천현우

module changed

Showing 303 changed files with 22767 additions and 1760 deletions
1 +import {voicoding} from './voicoding.js'
2 +
3 +const start = voicoding()
...\ No newline at end of file ...\ No newline at end of file
1 +#!/bin/sh
2 +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
3 +
4 +case `uname` in
5 + *CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;;
6 +esac
7 +
8 +if [ -x "$basedir/node" ]; then
9 + "$basedir/node" "$basedir/../mkdirp/bin/cmd.js" "$@"
10 + ret=$?
11 +else
12 + node "$basedir/../mkdirp/bin/cmd.js" "$@"
13 + ret=$?
14 +fi
15 +exit $ret
1 +@ECHO off
2 +SETLOCAL
3 +CALL :find_dp0
4 +
5 +IF EXIST "%dp0%\node.exe" (
6 + SET "_prog=%dp0%\node.exe"
7 +) ELSE (
8 + SET "_prog=node"
9 + SET PATHEXT=%PATHEXT:;.JS;=;%
10 +)
11 +
12 +"%_prog%" "%dp0%\..\mkdirp\bin\cmd.js" %*
13 +ENDLOCAL
14 +EXIT /b %errorlevel%
15 +:find_dp0
16 +SET dp0=%~dp0
17 +EXIT /b
1 +#!/usr/bin/env pwsh
2 +$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
3 +
4 +$exe=""
5 +if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
6 + # Fix case when both the Windows and Linux builds of Node
7 + # are installed in the same directory
8 + $exe=".exe"
9 +}
10 +$ret=0
11 +if (Test-Path "$basedir/node$exe") {
12 + & "$basedir/node$exe" "$basedir/../mkdirp/bin/cmd.js" $args
13 + $ret=$LASTEXITCODE
14 +} else {
15 + & "node$exe" "$basedir/../mkdirp/bin/cmd.js" $args
16 + $ret=$LASTEXITCODE
17 +}
18 +exit $ret
...@@ -8,7 +8,7 @@ This package contains type definitions for Node.js (http://nodejs.org/). ...@@ -8,7 +8,7 @@ This package contains type definitions for Node.js (http://nodejs.org/).
8 Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node. 8 Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node.
9 9
10 ### Additional Details 10 ### Additional Details
11 - * Last updated: Fri, 21 May 2021 10:32:02 GMT 11 + * Last updated: Wed, 02 Jun 2021 07:31:33 GMT
12 * Dependencies: none 12 * Dependencies: none
13 * Global values: `AbortController`, `AbortSignal`, `Buffer`, `__dirname`, `__filename`, `clearImmediate`, `clearInterval`, `clearTimeout`, `console`, `exports`, `global`, `module`, `process`, `queueMicrotask`, `require`, `setImmediate`, `setInterval`, `setTimeout` 13 * Global values: `AbortController`, `AbortSignal`, `Buffer`, `__dirname`, `__filename`, `clearImmediate`, `clearInterval`, `clearTimeout`, `console`, `exports`, `global`, `module`, `process`, `queueMicrotask`, `require`, `setImmediate`, `setInterval`, `setTimeout`
14 14
......
...@@ -167,7 +167,7 @@ declare module 'http' { ...@@ -167,7 +167,7 @@ declare module 'http' {
167 finished: boolean; 167 finished: boolean;
168 headersSent: boolean; 168 headersSent: boolean;
169 /** 169 /**
170 - * @deprecate Use `socket` instead. 170 + * @deprecated Use `socket` instead.
171 */ 171 */
172 connection: Socket | null; 172 connection: Socket | null;
173 socket: Socket | null; 173 socket: Socket | null;
......
1 { 1 {
2 "_from": "@types/node@*", 2 "_from": "@types/node@*",
3 - "_id": "@types/node@15.6.0", 3 + "_id": "@types/node@15.6.2",
4 "_inBundle": false, 4 "_inBundle": false,
5 - "_integrity": "sha512-gCYSfQpy+LYhOFTKAeE8BkyGqaxmlFxe+n4DKM6DR0wzw/HISUE/hAmkC/KT8Sw5PCJblqg062b3z9gucv3k0A==", 5 + "_integrity": "sha512-dxcOx8801kMo3KlU+C+/ctWrzREAH7YvoF3aoVpRdqgs+Kf7flp+PJDN/EX5bME3suDUZHsxes9hpvBmzYlWbA==",
6 "_location": "/@types/node", 6 "_location": "/@types/node",
7 "_phantomChildren": {}, 7 "_phantomChildren": {},
8 "_requested": { 8 "_requested": {
...@@ -22,8 +22,8 @@ ...@@ -22,8 +22,8 @@
22 "/@types/pumpify", 22 "/@types/pumpify",
23 "/protobufjs" 23 "/protobufjs"
24 ], 24 ],
25 - "_resolved": "https://registry.npmjs.org/@types/node/-/node-15.6.0.tgz", 25 + "_resolved": "https://registry.npmjs.org/@types/node/-/node-15.6.2.tgz",
26 - "_shasum": "f0ddca5a61e52627c9dcb771a6039d44694597bc", 26 + "_shasum": "c61d49f38af70da32424b5322eee21f97e627175",
27 "_spec": "@types/node@*", 27 "_spec": "@types/node@*",
28 "_where": "C:\\Users\\1000c\\이것저것\\옾소\\Voicoding\\node_modules\\@types\\pumpify", 28 "_where": "C:\\Users\\1000c\\이것저것\\옾소\\Voicoding\\node_modules\\@types\\pumpify",
29 "bugs": { 29 "bugs": {
...@@ -199,7 +199,7 @@ ...@@ -199,7 +199,7 @@
199 "dependencies": {}, 199 "dependencies": {},
200 "deprecated": false, 200 "deprecated": false,
201 "description": "TypeScript definitions for Node.js", 201 "description": "TypeScript definitions for Node.js",
202 - "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped#readme", 202 + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node",
203 "license": "MIT", 203 "license": "MIT",
204 "main": "", 204 "main": "",
205 "name": "@types/node", 205 "name": "@types/node",
...@@ -209,9 +209,9 @@ ...@@ -209,9 +209,9 @@
209 "directory": "types/node" 209 "directory": "types/node"
210 }, 210 },
211 "scripts": {}, 211 "scripts": {},
212 - "typeScriptVersion": "3.5", 212 + "typeScriptVersion": "3.6",
213 "types": "index.d.ts", 213 "types": "index.d.ts",
214 - "typesPublisherContentHash": "fe5d90fe4c06a65d482f400f205828b1280c7062026d5afdccc3b2bbccf4adcd", 214 + "typesPublisherContentHash": "f62422deccbd466260cb63740d207022259eb7fc7b6e7c406be463b9d1b0cd19",
215 "typesVersions": { 215 "typesVersions": {
216 "<=3.6": { 216 "<=3.6": {
217 "*": [ 217 "*": [
...@@ -219,5 +219,5 @@ ...@@ -219,5 +219,5 @@
219 ] 219 ]
220 } 220 }
221 }, 221 },
222 - "version": "15.6.0" 222 + "version": "15.6.2"
223 } 223 }
......
...@@ -88,7 +88,10 @@ declare module 'perf_hooks' { ...@@ -88,7 +88,10 @@ declare module 'perf_hooks' {
88 * @param util1 The result of a previous call to eventLoopUtilization() 88 * @param util1 The result of a previous call to eventLoopUtilization()
89 * @param util2 The result of a previous call to eventLoopUtilization() prior to util1 89 * @param util2 The result of a previous call to eventLoopUtilization() prior to util1
90 */ 90 */
91 - type EventLoopUtilityFunction = (util1?: EventLoopUtilization, util2?: EventLoopUtilization) => EventLoopUtilization; 91 + type EventLoopUtilityFunction = (
92 + util1?: EventLoopUtilization,
93 + util2?: EventLoopUtilization,
94 + ) => EventLoopUtilization;
92 95
93 interface Performance { 96 interface Performance {
94 /** 97 /**
...@@ -122,7 +125,7 @@ declare module 'perf_hooks' { ...@@ -122,7 +125,7 @@ declare module 'perf_hooks' {
122 * @param startMark 125 * @param startMark
123 * @param endMark 126 * @param endMark
124 */ 127 */
125 - measure(name: string, startMark: string, endMark: string): void; 128 + measure(name: string, startMark?: string, endMark?: string): void;
126 129
127 /** 130 /**
128 * An instance of the PerformanceNodeTiming class that provides performance metrics for specific Node.js operational milestones. 131 * An instance of the PerformanceNodeTiming class that provides performance metrics for specific Node.js operational milestones.
......
1 +The MIT License (MIT)
2 +
3 +Copyright (c) 2015 Linus Unnebäck
4 +
5 +Permission is hereby granted, free of charge, to any person obtaining a copy
6 +of this software and associated documentation files (the "Software"), to deal
7 +in the Software without restriction, including without limitation the rights
8 +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 +copies of the Software, and to permit persons to whom the Software is
10 +furnished to do so, subject to the following conditions:
11 +
12 +The above copyright notice and this permission notice shall be included in all
13 +copies or substantial portions of the Software.
14 +
15 +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 +SOFTWARE.
1 +# `append-field`
2 +
3 +A [W3C HTML JSON forms spec](http://www.w3.org/TR/html-json-forms/) compliant
4 +field appender (for lack of a better name). Useful for people implementing
5 +`application/x-www-form-urlencoded` and `multipart/form-data` parsers.
6 +
7 +It works best on objects created with `Object.create(null)`. Otherwise it might
8 +conflict with variables from the prototype (e.g. `hasOwnProperty`).
9 +
10 +## Installation
11 +
12 +```sh
13 +npm install --save append-field
14 +```
15 +
16 +## Usage
17 +
18 +```javascript
19 +var appendField = require('append-field')
20 +var obj = Object.create(null)
21 +
22 +appendField(obj, 'pets[0][species]', 'Dahut')
23 +appendField(obj, 'pets[0][name]', 'Hypatia')
24 +appendField(obj, 'pets[1][species]', 'Felis Stultus')
25 +appendField(obj, 'pets[1][name]', 'Billie')
26 +
27 +console.log(obj)
28 +```
29 +
30 +```text
31 +{ pets:
32 + [ { species: 'Dahut', name: 'Hypatia' },
33 + { species: 'Felis Stultus', name: 'Billie' } ] }
34 +```
35 +
36 +## API
37 +
38 +### `appendField(store, key, value)`
39 +
40 +Adds the field named `key` with the value `value` to the object `store`.
41 +
42 +## License
43 +
44 +MIT
1 +var parsePath = require('./lib/parse-path')
2 +var setValue = require('./lib/set-value')
3 +
4 +function appendField (store, key, value) {
5 + var steps = parsePath(key)
6 +
7 + steps.reduce(function (context, step) {
8 + return setValue(context, step, context[step.key], value)
9 + }, store)
10 +}
11 +
12 +module.exports = appendField
1 +var reFirstKey = /^[^\[]*/
2 +var reDigitPath = /^\[(\d+)\]/
3 +var reNormalPath = /^\[([^\]]+)\]/
4 +
5 +function parsePath (key) {
6 + function failure () {
7 + return [{ type: 'object', key: key, last: true }]
8 + }
9 +
10 + var firstKey = reFirstKey.exec(key)[0]
11 + if (!firstKey) return failure()
12 +
13 + var len = key.length
14 + var pos = firstKey.length
15 + var tail = { type: 'object', key: firstKey }
16 + var steps = [tail]
17 +
18 + while (pos < len) {
19 + var m
20 +
21 + if (key[pos] === '[' && key[pos + 1] === ']') {
22 + pos += 2
23 + tail.append = true
24 + if (pos !== len) return failure()
25 + continue
26 + }
27 +
28 + m = reDigitPath.exec(key.substring(pos))
29 + if (m !== null) {
30 + pos += m[0].length
31 + tail.nextType = 'array'
32 + tail = { type: 'array', key: parseInt(m[1], 10) }
33 + steps.push(tail)
34 + continue
35 + }
36 +
37 + m = reNormalPath.exec(key.substring(pos))
38 + if (m !== null) {
39 + pos += m[0].length
40 + tail.nextType = 'object'
41 + tail = { type: 'object', key: m[1] }
42 + steps.push(tail)
43 + continue
44 + }
45 +
46 + return failure()
47 + }
48 +
49 + tail.last = true
50 + return steps
51 +}
52 +
53 +module.exports = parsePath
1 +function valueType (value) {
2 + if (value === undefined) return 'undefined'
3 + if (Array.isArray(value)) return 'array'
4 + if (typeof value === 'object') return 'object'
5 + return 'scalar'
6 +}
7 +
8 +function setLastValue (context, step, currentValue, entryValue) {
9 + switch (valueType(currentValue)) {
10 + case 'undefined':
11 + if (step.append) {
12 + context[step.key] = [entryValue]
13 + } else {
14 + context[step.key] = entryValue
15 + }
16 + break
17 + case 'array':
18 + context[step.key].push(entryValue)
19 + break
20 + case 'object':
21 + return setLastValue(currentValue, { type: 'object', key: '', last: true }, currentValue[''], entryValue)
22 + case 'scalar':
23 + context[step.key] = [context[step.key], entryValue]
24 + break
25 + }
26 +
27 + return context
28 +}
29 +
30 +function setValue (context, step, currentValue, entryValue) {
31 + if (step.last) return setLastValue(context, step, currentValue, entryValue)
32 +
33 + var obj
34 + switch (valueType(currentValue)) {
35 + case 'undefined':
36 + if (step.nextType === 'array') {
37 + context[step.key] = []
38 + } else {
39 + context[step.key] = Object.create(null)
40 + }
41 + return context[step.key]
42 + case 'object':
43 + return context[step.key]
44 + case 'array':
45 + if (step.nextType === 'array') {
46 + return currentValue
47 + }
48 +
49 + obj = Object.create(null)
50 + context[step.key] = obj
51 + currentValue.forEach(function (item, i) {
52 + if (item !== undefined) obj['' + i] = item
53 + })
54 +
55 + return obj
56 + case 'scalar':
57 + obj = Object.create(null)
58 + obj[''] = currentValue
59 + context[step.key] = obj
60 + return obj
61 + }
62 +}
63 +
64 +module.exports = setValue
1 +{
2 + "_from": "append-field@^1.0.0",
3 + "_id": "append-field@1.0.0",
4 + "_inBundle": false,
5 + "_integrity": "sha1-HjRA6RXwsSA9I3SOeO3XubW0PlY=",
6 + "_location": "/append-field",
7 + "_phantomChildren": {},
8 + "_requested": {
9 + "type": "range",
10 + "registry": true,
11 + "raw": "append-field@^1.0.0",
12 + "name": "append-field",
13 + "escapedName": "append-field",
14 + "rawSpec": "^1.0.0",
15 + "saveSpec": null,
16 + "fetchSpec": "^1.0.0"
17 + },
18 + "_requiredBy": [
19 + "/multer"
20 + ],
21 + "_resolved": "https://registry.npmjs.org/append-field/-/append-field-1.0.0.tgz",
22 + "_shasum": "1e3440e915f0b1203d23748e78edd7b9b5b43e56",
23 + "_spec": "append-field@^1.0.0",
24 + "_where": "C:\\Users\\1000c\\이것저것\\옾소\\Voicoding\\node_modules\\multer",
25 + "author": {
26 + "name": "Linus Unnebäck",
27 + "email": "linus@folkdatorn.se"
28 + },
29 + "bugs": {
30 + "url": "https://github.com/LinusU/node-append-field/issues"
31 + },
32 + "bundleDependencies": false,
33 + "deprecated": false,
34 + "description": "A [W3C HTML JSON forms spec](http://www.w3.org/TR/html-json-forms/) compliant field appender (for lack of a better name). Useful for people implementing `application/x-www-form-urlencoded` and `multipart/form-data` parsers.",
35 + "devDependencies": {
36 + "mocha": "^2.2.4",
37 + "standard": "^6.0.5",
38 + "testdata-w3c-json-form": "^0.2.0"
39 + },
40 + "homepage": "https://github.com/LinusU/node-append-field#readme",
41 + "license": "MIT",
42 + "main": "index.js",
43 + "name": "append-field",
44 + "repository": {
45 + "type": "git",
46 + "url": "git+ssh://git@github.com/LinusU/node-append-field.git"
47 + },
48 + "scripts": {
49 + "test": "standard && mocha"
50 + },
51 + "version": "1.0.0"
52 +}
1 +/* eslint-env mocha */
2 +
3 +var assert = require('assert')
4 +var appendField = require('../')
5 +var testData = require('testdata-w3c-json-form')
6 +
7 +describe('Append Field', function () {
8 + for (var test of testData) {
9 + it('handles ' + test.name, function () {
10 + var store = Object.create(null)
11 +
12 + for (var field of test.fields) {
13 + appendField(store, field.key, field.value)
14 + }
15 +
16 + assert.deepEqual(store, test.expected)
17 + })
18 + }
19 +})
1 +MIT License
2 +
3 +Copyright (c) 2016, 2018 Linus Unnebäck
4 +
5 +Permission is hereby granted, free of charge, to any person obtaining a copy
6 +of this software and associated documentation files (the "Software"), to deal
7 +in the Software without restriction, including without limitation the rights
8 +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 +copies of the Software, and to permit persons to whom the Software is
10 +furnished to do so, subject to the following conditions:
11 +
12 +The above copyright notice and this permission notice shall be included in all
13 +copies or substantial portions of the Software.
14 +
15 +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 +SOFTWARE.
1 +var toString = Object.prototype.toString
2 +
3 +var isModern = (
4 + typeof Buffer.alloc === 'function' &&
5 + typeof Buffer.allocUnsafe === 'function' &&
6 + typeof Buffer.from === 'function'
7 +)
8 +
9 +function isArrayBuffer (input) {
10 + return toString.call(input).slice(8, -1) === 'ArrayBuffer'
11 +}
12 +
13 +function fromArrayBuffer (obj, byteOffset, length) {
14 + byteOffset >>>= 0
15 +
16 + var maxLength = obj.byteLength - byteOffset
17 +
18 + if (maxLength < 0) {
19 + throw new RangeError("'offset' is out of bounds")
20 + }
21 +
22 + if (length === undefined) {
23 + length = maxLength
24 + } else {
25 + length >>>= 0
26 +
27 + if (length > maxLength) {
28 + throw new RangeError("'length' is out of bounds")
29 + }
30 + }
31 +
32 + return isModern
33 + ? Buffer.from(obj.slice(byteOffset, byteOffset + length))
34 + : new Buffer(new Uint8Array(obj.slice(byteOffset, byteOffset + length)))
35 +}
36 +
37 +function fromString (string, encoding) {
38 + if (typeof encoding !== 'string' || encoding === '') {
39 + encoding = 'utf8'
40 + }
41 +
42 + if (!Buffer.isEncoding(encoding)) {
43 + throw new TypeError('"encoding" must be a valid string encoding')
44 + }
45 +
46 + return isModern
47 + ? Buffer.from(string, encoding)
48 + : new Buffer(string, encoding)
49 +}
50 +
51 +function bufferFrom (value, encodingOrOffset, length) {
52 + if (typeof value === 'number') {
53 + throw new TypeError('"value" argument must not be a number')
54 + }
55 +
56 + if (isArrayBuffer(value)) {
57 + return fromArrayBuffer(value, encodingOrOffset, length)
58 + }
59 +
60 + if (typeof value === 'string') {
61 + return fromString(value, encodingOrOffset)
62 + }
63 +
64 + return isModern
65 + ? Buffer.from(value)
66 + : new Buffer(value)
67 +}
68 +
69 +module.exports = bufferFrom
1 +{
2 + "_from": "buffer-from@^1.0.0",
3 + "_id": "buffer-from@1.1.1",
4 + "_inBundle": false,
5 + "_integrity": "sha512-MQcXEUbCKtEo7bhqEs6560Hyd4XaovZlO/k9V3hjVUF/zwW7KBVdSK4gIt/bzwS9MbR5qob+F5jusZsb0YQK2A==",
6 + "_location": "/buffer-from",
7 + "_phantomChildren": {},
8 + "_requested": {
9 + "type": "range",
10 + "registry": true,
11 + "raw": "buffer-from@^1.0.0",
12 + "name": "buffer-from",
13 + "escapedName": "buffer-from",
14 + "rawSpec": "^1.0.0",
15 + "saveSpec": null,
16 + "fetchSpec": "^1.0.0"
17 + },
18 + "_requiredBy": [
19 + "/concat-stream"
20 + ],
21 + "_resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.1.tgz",
22 + "_shasum": "32713bc028f75c02fdb710d7c7bcec1f2c6070ef",
23 + "_spec": "buffer-from@^1.0.0",
24 + "_where": "C:\\Users\\1000c\\이것저것\\옾소\\Voicoding\\node_modules\\concat-stream",
25 + "bugs": {
26 + "url": "https://github.com/LinusU/buffer-from/issues"
27 + },
28 + "bundleDependencies": false,
29 + "deprecated": false,
30 + "description": "A [ponyfill](https://ponyfill.com) for `Buffer.from`, uses native implementation if available.",
31 + "devDependencies": {
32 + "standard": "^7.1.2"
33 + },
34 + "files": [
35 + "index.js"
36 + ],
37 + "homepage": "https://github.com/LinusU/buffer-from#readme",
38 + "keywords": [
39 + "buffer",
40 + "buffer from"
41 + ],
42 + "license": "MIT",
43 + "name": "buffer-from",
44 + "repository": {
45 + "type": "git",
46 + "url": "git+https://github.com/LinusU/buffer-from.git"
47 + },
48 + "scripts": {
49 + "test": "standard && node test"
50 + },
51 + "version": "1.1.1"
52 +}
1 +# Buffer From
2 +
3 +A [ponyfill](https://ponyfill.com) for `Buffer.from`, uses native implementation if available.
4 +
5 +## Installation
6 +
7 +```sh
8 +npm install --save buffer-from
9 +```
10 +
11 +## Usage
12 +
13 +```js
14 +const bufferFrom = require('buffer-from')
15 +
16 +console.log(bufferFrom([1, 2, 3, 4]))
17 +//=> <Buffer 01 02 03 04>
18 +
19 +const arr = new Uint8Array([1, 2, 3, 4])
20 +console.log(bufferFrom(arr.buffer, 1, 2))
21 +//=> <Buffer 02 03>
22 +
23 +console.log(bufferFrom('test', 'utf8'))
24 +//=> <Buffer 74 65 73 74>
25 +
26 +const buf = bufferFrom('test')
27 +console.log(bufferFrom(buf))
28 +//=> <Buffer 74 65 73 74>
29 +```
30 +
31 +## API
32 +
33 +### bufferFrom(array)
34 +
35 +- `array` &lt;Array&gt;
36 +
37 +Allocates a new `Buffer` using an `array` of octets.
38 +
39 +### bufferFrom(arrayBuffer[, byteOffset[, length]])
40 +
41 +- `arrayBuffer` &lt;ArrayBuffer&gt; The `.buffer` property of a TypedArray or ArrayBuffer
42 +- `byteOffset` &lt;Integer&gt; Where to start copying from `arrayBuffer`. **Default:** `0`
43 +- `length` &lt;Integer&gt; How many bytes to copy from `arrayBuffer`. **Default:** `arrayBuffer.length - byteOffset`
44 +
45 +When passed a reference to the `.buffer` property of a TypedArray instance, the
46 +newly created `Buffer` will share the same allocated memory as the TypedArray.
47 +
48 +The optional `byteOffset` and `length` arguments specify a memory range within
49 +the `arrayBuffer` that will be shared by the `Buffer`.
50 +
51 +### bufferFrom(buffer)
52 +
53 +- `buffer` &lt;Buffer&gt; An existing `Buffer` to copy data from
54 +
55 +Copies the passed `buffer` data onto a new `Buffer` instance.
56 +
57 +### bufferFrom(string[, encoding])
58 +
59 +- `string` &lt;String&gt; A string to encode.
60 +- `encoding` &lt;String&gt; The encoding of `string`. **Default:** `'utf8'`
61 +
62 +Creates a new `Buffer` containing the given JavaScript string `string`. If
63 +provided, the `encoding` parameter identifies the character encoding of
64 +`string`.
65 +
66 +## See also
67 +
68 +- [buffer-alloc](https://github.com/LinusU/buffer-alloc) A ponyfill for `Buffer.alloc`
69 +- [buffer-alloc-unsafe](https://github.com/LinusU/buffer-alloc-unsafe) A ponyfill for `Buffer.allocUnsafe`
1 +sudo: false
2 +language: cpp
3 +notifications:
4 + email: false
5 +env:
6 + matrix:
7 + - TRAVIS_NODE_VERSION="0.10"
8 + - TRAVIS_NODE_VERSION="0.12"
9 + - TRAVIS_NODE_VERSION="4"
10 + - TRAVIS_NODE_VERSION="6"
11 + - TRAVIS_NODE_VERSION="7"
12 +install:
13 + - rm -rf ~/.nvm && git clone https://github.com/creationix/nvm.git ~/.nvm && source ~/.nvm/nvm.sh && nvm install $TRAVIS_NODE_VERSION
14 + - node --version
15 + - npm --version
16 + - npm install
17 +script: npm test
1 +Copyright Brian White. All rights reserved.
2 +
3 +Permission is hereby granted, free of charge, to any person obtaining a copy
4 +of this software and associated documentation files (the "Software"), to
5 +deal in the Software without restriction, including without limitation the
6 +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
7 +sell copies of the Software, and to permit persons to whom the Software is
8 +furnished to do so, subject to the following conditions:
9 +
10 +The above copyright notice and this permission notice shall be included in
11 +all copies or substantial portions of the Software.
12 +
13 +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
18 +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
19 +IN THE SOFTWARE.
...\ No newline at end of file ...\ No newline at end of file
1 +Description
2 +===========
3 +
4 +A node.js module for parsing incoming HTML form data.
5 +
6 +If you've found this module to be useful and wish to support it, you may do so by visiting this pledgie campaign:
7 +<a href='https://pledgie.com/campaigns/28774'><img alt='Click here to support busboy' src='https://pledgie.com/campaigns/28774.png?skin_name=chrome' border='0'></a>
8 +
9 +
10 +Requirements
11 +============
12 +
13 +* [node.js](http://nodejs.org/) -- v0.8.0 or newer
14 +
15 +
16 +Install
17 +=======
18 +
19 + npm install busboy
20 +
21 +
22 +Examples
23 +========
24 +
25 +* Parsing (multipart) with default options:
26 +
27 +```javascript
28 +var http = require('http'),
29 + inspect = require('util').inspect;
30 +
31 +var Busboy = require('busboy');
32 +
33 +http.createServer(function(req, res) {
34 + if (req.method === 'POST') {
35 + var busboy = new Busboy({ headers: req.headers });
36 + busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
37 + console.log('File [' + fieldname + ']: filename: ' + filename + ', encoding: ' + encoding + ', mimetype: ' + mimetype);
38 + file.on('data', function(data) {
39 + console.log('File [' + fieldname + '] got ' + data.length + ' bytes');
40 + });
41 + file.on('end', function() {
42 + console.log('File [' + fieldname + '] Finished');
43 + });
44 + });
45 + busboy.on('field', function(fieldname, val, fieldnameTruncated, valTruncated, encoding, mimetype) {
46 + console.log('Field [' + fieldname + ']: value: ' + inspect(val));
47 + });
48 + busboy.on('finish', function() {
49 + console.log('Done parsing form!');
50 + res.writeHead(303, { Connection: 'close', Location: '/' });
51 + res.end();
52 + });
53 + req.pipe(busboy);
54 + } else if (req.method === 'GET') {
55 + res.writeHead(200, { Connection: 'close' });
56 + res.end('<html><head></head><body>\
57 + <form method="POST" enctype="multipart/form-data">\
58 + <input type="text" name="textfield"><br />\
59 + <input type="file" name="filefield"><br />\
60 + <input type="submit">\
61 + </form>\
62 + </body></html>');
63 + }
64 +}).listen(8000, function() {
65 + console.log('Listening for requests');
66 +});
67 +
68 +// Example output, using http://nodejs.org/images/ryan-speaker.jpg as the file:
69 +//
70 +// Listening for requests
71 +// File [filefield]: filename: ryan-speaker.jpg, encoding: binary
72 +// File [filefield] got 11971 bytes
73 +// Field [textfield]: value: 'testing! :-)'
74 +// File [filefield] Finished
75 +// Done parsing form!
76 +```
77 +
78 +* Save all incoming files to disk:
79 +
80 +```javascript
81 +var http = require('http'),
82 + path = require('path'),
83 + os = require('os'),
84 + fs = require('fs');
85 +
86 +var Busboy = require('busboy');
87 +
88 +http.createServer(function(req, res) {
89 + if (req.method === 'POST') {
90 + var busboy = new Busboy({ headers: req.headers });
91 + busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
92 + var saveTo = path.join(os.tmpDir(), path.basename(fieldname));
93 + file.pipe(fs.createWriteStream(saveTo));
94 + });
95 + busboy.on('finish', function() {
96 + res.writeHead(200, { 'Connection': 'close' });
97 + res.end("That's all folks!");
98 + });
99 + return req.pipe(busboy);
100 + }
101 + res.writeHead(404);
102 + res.end();
103 +}).listen(8000, function() {
104 + console.log('Listening for requests');
105 +});
106 +```
107 +
108 +* Parsing (urlencoded) with default options:
109 +
110 +```javascript
111 +var http = require('http'),
112 + inspect = require('util').inspect;
113 +
114 +var Busboy = require('busboy');
115 +
116 +http.createServer(function(req, res) {
117 + if (req.method === 'POST') {
118 + var busboy = new Busboy({ headers: req.headers });
119 + busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
120 + console.log('File [' + fieldname + ']: filename: ' + filename);
121 + file.on('data', function(data) {
122 + console.log('File [' + fieldname + '] got ' + data.length + ' bytes');
123 + });
124 + file.on('end', function() {
125 + console.log('File [' + fieldname + '] Finished');
126 + });
127 + });
128 + busboy.on('field', function(fieldname, val, fieldnameTruncated, valTruncated) {
129 + console.log('Field [' + fieldname + ']: value: ' + inspect(val));
130 + });
131 + busboy.on('finish', function() {
132 + console.log('Done parsing form!');
133 + res.writeHead(303, { Connection: 'close', Location: '/' });
134 + res.end();
135 + });
136 + req.pipe(busboy);
137 + } else if (req.method === 'GET') {
138 + res.writeHead(200, { Connection: 'close' });
139 + res.end('<html><head></head><body>\
140 + <form method="POST">\
141 + <input type="text" name="textfield"><br />\
142 + <select name="selectfield">\
143 + <option value="1">1</option>\
144 + <option value="10">10</option>\
145 + <option value="100">100</option>\
146 + <option value="9001">9001</option>\
147 + </select><br />\
148 + <input type="checkbox" name="checkfield">Node.js rules!<br />\
149 + <input type="submit">\
150 + </form>\
151 + </body></html>');
152 + }
153 +}).listen(8000, function() {
154 + console.log('Listening for requests');
155 +});
156 +
157 +// Example output:
158 +//
159 +// Listening for requests
160 +// Field [textfield]: value: 'testing! :-)'
161 +// Field [selectfield]: value: '9001'
162 +// Field [checkfield]: value: 'on'
163 +// Done parsing form!
164 +```
165 +
166 +
167 +API
168 +===
169 +
170 +_Busboy_ is a _Writable_ stream
171 +
172 +Busboy (special) events
173 +-----------------------
174 +
175 +* **file**(< _string_ >fieldname, < _ReadableStream_ >stream, < _string_ >filename, < _string_ >transferEncoding, < _string_ >mimeType) - Emitted for each new file form field found. `transferEncoding` contains the 'Content-Transfer-Encoding' value for the file stream. `mimeType` contains the 'Content-Type' value for the file stream.
176 + * Note: if you listen for this event, you should always handle the `stream` no matter if you care about the file contents or not (e.g. you can simply just do `stream.resume();` if you want to discard the contents), otherwise the 'finish' event will never fire on the Busboy instance. However, if you don't care about **any** incoming files, you can simply not listen for the 'file' event at all and any/all files will be automatically and safely discarded (these discarded files do still count towards `files` and `parts` limits).
177 + * If a configured file size limit was reached, `stream` will both have a boolean property `truncated` (best checked at the end of the stream) and emit a 'limit' event to notify you when this happens.
178 +
179 +* **field**(< _string_ >fieldname, < _string_ >value, < _boolean_ >fieldnameTruncated, < _boolean_ >valueTruncated, < _string_ >transferEncoding, < _string_ >mimeType) - Emitted for each new non-file field found.
180 +
181 +* **partsLimit**() - Emitted when specified `parts` limit has been reached. No more 'file' or 'field' events will be emitted.
182 +
183 +* **filesLimit**() - Emitted when specified `files` limit has been reached. No more 'file' events will be emitted.
184 +
185 +* **fieldsLimit**() - Emitted when specified `fields` limit has been reached. No more 'field' events will be emitted.
186 +
187 +
188 +Busboy methods
189 +--------------
190 +
191 +* **(constructor)**(< _object_ >config) - Creates and returns a new Busboy instance.
192 +
193 + * The constructor takes the following valid `config` settings:
194 +
195 + * **headers** - _object_ - These are the HTTP headers of the incoming request, which are used by individual parsers.
196 +
197 + * **highWaterMark** - _integer_ - highWaterMark to use for this Busboy instance (Default: WritableStream default).
198 +
199 + * **fileHwm** - _integer_ - highWaterMark to use for file streams (Default: ReadableStream default).
200 +
201 + * **defCharset** - _string_ - Default character set to use when one isn't defined (Default: 'utf8').
202 +
203 + * **preservePath** - _boolean_ - If paths in the multipart 'filename' field shall be preserved. (Default: false).
204 +
205 + * **limits** - _object_ - Various limits on incoming data. Valid properties are:
206 +
207 + * **fieldNameSize** - _integer_ - Max field name size (in bytes) (Default: 100 bytes).
208 +
209 + * **fieldSize** - _integer_ - Max field value size (in bytes) (Default: 1MB).
210 +
211 + * **fields** - _integer_ - Max number of non-file fields (Default: Infinity).
212 +
213 + * **fileSize** - _integer_ - For multipart forms, the max file size (in bytes) (Default: Infinity).
214 +
215 + * **files** - _integer_ - For multipart forms, the max number of file fields (Default: Infinity).
216 +
217 + * **parts** - _integer_ - For multipart forms, the max number of parts (fields + files) (Default: Infinity).
218 +
219 + * **headerPairs** - _integer_ - For multipart forms, the max number of header key=>value pairs to parse **Default:** 2000 (same as node's http).
220 +
221 + * The constructor can throw errors:
222 +
223 + * **Unsupported content type: $type** - The `Content-Type` isn't one Busboy can parse.
224 +
225 + * **Missing Content-Type** - The provided headers don't include `Content-Type` at all.
This diff could not be displayed because it is too large.
1 +/*
2 + Modifications for better node.js integration:
3 + Copyright 2014 Brian White. All rights reserved.
4 +
5 + Permission is hereby granted, free of charge, to any person obtaining a copy
6 + of this software and associated documentation files (the "Software"), to
7 + deal in the Software without restriction, including without limitation the
8 + rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
9 + sell copies of the Software, and to permit persons to whom the Software is
10 + furnished to do so, subject to the following conditions:
11 +
12 + The above copyright notice and this permission notice shall be included in
13 + all copies or substantial portions of the Software.
14 +
15 + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20 + FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
21 + IN THE SOFTWARE.
22 +*/
23 +/*
24 + Original source code:
25 + Copyright 2014 Joshua Bell
26 +
27 + Licensed under the Apache License, Version 2.0 (the "License");
28 + you may not use this file except in compliance with the License.
29 + You may obtain a copy of the License at
30 +
31 + http://www.apache.org/licenses/LICENSE-2.0
32 +
33 + Unless required by applicable law or agreed to in writing, software
34 + distributed under the License is distributed on an "AS IS" BASIS,
35 + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
36 + See the License for the specific language governing permissions and
37 + limitations under the License.
38 +*/
39 +
40 +//
41 +// Utilities
42 +//
43 +
44 +/**
45 + * @param {number} a The number to test.
46 + * @param {number} min The minimum value in the range, inclusive.
47 + * @param {number} max The maximum value in the range, inclusive.
48 + * @return {boolean} True if a >= min and a <= max.
49 + */
50 +function inRange(a, min, max) {
51 + return min <= a && a <= max;
52 +}
53 +
54 +/**
55 + * @param {number} n The numerator.
56 + * @param {number} d The denominator.
57 + * @return {number} The result of the integer division of n by d.
58 + */
59 +function div(n, d) {
60 + return Math.floor(n / d);
61 +}
62 +
63 +
64 +//
65 +// Implementation of Encoding specification
66 +// http://dvcs.w3.org/hg/encoding/raw-file/tip/Overview.html
67 +//
68 +
69 +//
70 +// 3. Terminology
71 +//
72 +
73 +//
74 +// 4. Encodings
75 +//
76 +
77 +/** @const */ var EOF_byte = -1;
78 +/** @const */ var EOF_code_point = -1;
79 +
80 +/**
81 + * @constructor
82 + * @param {Buffer} bytes Array of bytes that provide the stream.
83 + */
84 +function ByteInputStream(bytes) {
85 + /** @type {number} */
86 + var pos = 0;
87 +
88 + /**
89 + * @this {ByteInputStream}
90 + * @return {number} Get the next byte from the stream.
91 + */
92 + this.get = function() {
93 + return (pos >= bytes.length) ? EOF_byte : Number(bytes[pos]);
94 + };
95 +
96 + /** @param {number} n Number (positive or negative) by which to
97 + * offset the byte pointer. */
98 + this.offset = function(n) {
99 + pos += n;
100 + if (pos < 0) {
101 + throw new Error('Seeking past start of the buffer');
102 + }
103 + if (pos > bytes.length) {
104 + throw new Error('Seeking past EOF');
105 + }
106 + };
107 +
108 + /**
109 + * @param {Array.<number>} test Array of bytes to compare against.
110 + * @return {boolean} True if the start of the stream matches the test
111 + * bytes.
112 + */
113 + this.match = function(test) {
114 + if (test.length > pos + bytes.length) {
115 + return false;
116 + }
117 + var i;
118 + for (i = 0; i < test.length; i += 1) {
119 + if (Number(bytes[pos + i]) !== test[i]) {
120 + return false;
121 + }
122 + }
123 + return true;
124 + };
125 +}
126 +
127 +/**
128 + * @constructor
129 + * @param {Array.<number>} bytes The array to write bytes into.
130 + */
131 +function ByteOutputStream(bytes) {
132 + /** @type {number} */
133 + var pos = 0;
134 +
135 + /**
136 + * @param {...number} var_args The byte or bytes to emit into the stream.
137 + * @return {number} The last byte emitted.
138 + */
139 + this.emit = function(var_args) {
140 + /** @type {number} */
141 + var last = EOF_byte;
142 + var i;
143 + for (i = 0; i < arguments.length; ++i) {
144 + last = Number(arguments[i]);
145 + bytes[pos++] = last;
146 + }
147 + return last;
148 + };
149 +}
150 +
151 +/**
152 + * @constructor
153 + * @param {string} string The source of code units for the stream.
154 + */
155 +function CodePointInputStream(string) {
156 + /**
157 + * @param {string} string Input string of UTF-16 code units.
158 + * @return {Array.<number>} Code points.
159 + */
160 + function stringToCodePoints(string) {
161 + /** @type {Array.<number>} */
162 + var cps = [];
163 + // Based on http://www.w3.org/TR/WebIDL/#idl-DOMString
164 + var i = 0, n = string.length;
165 + while (i < string.length) {
166 + var c = string.charCodeAt(i);
167 + if (!inRange(c, 0xD800, 0xDFFF)) {
168 + cps.push(c);
169 + } else if (inRange(c, 0xDC00, 0xDFFF)) {
170 + cps.push(0xFFFD);
171 + } else { // (inRange(cu, 0xD800, 0xDBFF))
172 + if (i === n - 1) {
173 + cps.push(0xFFFD);
174 + } else {
175 + var d = string.charCodeAt(i + 1);
176 + if (inRange(d, 0xDC00, 0xDFFF)) {
177 + var a = c & 0x3FF;
178 + var b = d & 0x3FF;
179 + i += 1;
180 + cps.push(0x10000 + (a << 10) + b);
181 + } else {
182 + cps.push(0xFFFD);
183 + }
184 + }
185 + }
186 + i += 1;
187 + }
188 + return cps;
189 + }
190 +
191 + /** @type {number} */
192 + var pos = 0;
193 + /** @type {Array.<number>} */
194 + var cps = stringToCodePoints(string);
195 +
196 + /** @param {number} n The number of bytes (positive or negative)
197 + * to advance the code point pointer by.*/
198 + this.offset = function(n) {
199 + pos += n;
200 + if (pos < 0) {
201 + throw new Error('Seeking past start of the buffer');
202 + }
203 + if (pos > cps.length) {
204 + throw new Error('Seeking past EOF');
205 + }
206 + };
207 +
208 +
209 + /** @return {number} Get the next code point from the stream. */
210 + this.get = function() {
211 + if (pos >= cps.length) {
212 + return EOF_code_point;
213 + }
214 + return cps[pos];
215 + };
216 +}
217 +
218 +/**
219 + * @constructor
220 + */
221 +function CodePointOutputStream() {
222 + /** @type {string} */
223 + var string = '';
224 +
225 + /** @return {string} The accumulated string. */
226 + this.string = function() {
227 + return string;
228 + };
229 +
230 + /** @param {number} c The code point to encode into the stream. */
231 + this.emit = function(c) {
232 + if (c <= 0xFFFF) {
233 + string += String.fromCharCode(c);
234 + } else {
235 + c -= 0x10000;
236 + string += String.fromCharCode(0xD800 + ((c >> 10) & 0x3ff));
237 + string += String.fromCharCode(0xDC00 + (c & 0x3ff));
238 + }
239 + };
240 +}
241 +
242 +/**
243 + * @constructor
244 + * @param {string} message Description of the error.
245 + */
246 +function EncodingError(message) {
247 + this.name = 'EncodingError';
248 + this.message = message;
249 + this.code = 0;
250 +}
251 +EncodingError.prototype = Error.prototype;
252 +
253 +/**
254 + * @param {boolean} fatal If true, decoding errors raise an exception.
255 + * @param {number=} opt_code_point Override the standard fallback code point.
256 + * @return {number} The code point to insert on a decoding error.
257 + */
258 +function decoderError(fatal, opt_code_point) {
259 + if (fatal) {
260 + throw new EncodingError('Decoder error');
261 + }
262 + return opt_code_point || 0xFFFD;
263 +}
264 +
265 +/**
266 + * @param {number} code_point The code point that could not be encoded.
267 + * @return {number} Always throws, no value is actually returned.
268 + */
269 +function encoderError(code_point) {
270 + throw new EncodingError('The code point ' + code_point +
271 + ' could not be encoded.');
272 +}
273 +
274 +/**
275 + * @param {string} label The encoding label.
276 + * @return {?{name:string,labels:Array.<string>}}
277 + */
278 +function getEncoding(label) {
279 + label = String(label).trim().toLowerCase();
280 + if (Object.prototype.hasOwnProperty.call(label_to_encoding, label)) {
281 + return label_to_encoding[label];
282 + }
283 + return null;
284 +}
285 +
286 +/** @type {Array.<{encodings: Array.<{name:string,labels:Array.<string>}>,
287 + * heading: string}>} */
288 +var encodings = [
289 + {
290 + "encodings": [
291 + {
292 + "labels": [
293 + "unicode-1-1-utf-8",
294 + "utf-8",
295 + "utf8"
296 + ],
297 + "name": "utf-8"
298 + }
299 + ],
300 + "heading": "The Encoding"
301 + },
302 + {
303 + "encodings": [
304 + {
305 + "labels": [
306 + "864",
307 + "cp864",
308 + "csibm864",
309 + "ibm864"
310 + ],
311 + "name": "ibm864"
312 + },
313 + {
314 + "labels": [
315 + "866",
316 + "cp866",
317 + "csibm866",
318 + "ibm866"
319 + ],
320 + "name": "ibm866"
321 + },
322 + {
323 + "labels": [
324 + "csisolatin2",
325 + "iso-8859-2",
326 + "iso-ir-101",
327 + "iso8859-2",
328 + "iso88592",
329 + "iso_8859-2",
330 + "iso_8859-2:1987",
331 + "l2",
332 + "latin2"
333 + ],
334 + "name": "iso-8859-2"
335 + },
336 + {
337 + "labels": [
338 + "csisolatin3",
339 + "iso-8859-3",
340 + "iso-ir-109",
341 + "iso8859-3",
342 + "iso88593",
343 + "iso_8859-3",
344 + "iso_8859-3:1988",
345 + "l3",
346 + "latin3"
347 + ],
348 + "name": "iso-8859-3"
349 + },
350 + {
351 + "labels": [
352 + "csisolatin4",
353 + "iso-8859-4",
354 + "iso-ir-110",
355 + "iso8859-4",
356 + "iso88594",
357 + "iso_8859-4",
358 + "iso_8859-4:1988",
359 + "l4",
360 + "latin4"
361 + ],
362 + "name": "iso-8859-4"
363 + },
364 + {
365 + "labels": [
366 + "csisolatincyrillic",
367 + "cyrillic",
368 + "iso-8859-5",
369 + "iso-ir-144",
370 + "iso8859-5",
371 + "iso88595",
372 + "iso_8859-5",
373 + "iso_8859-5:1988"
374 + ],
375 + "name": "iso-8859-5"
376 + },
377 + {
378 + "labels": [
379 + "arabic",
380 + "asmo-708",
381 + "csiso88596e",
382 + "csiso88596i",
383 + "csisolatinarabic",
384 + "ecma-114",
385 + "iso-8859-6",
386 + "iso-8859-6-e",
387 + "iso-8859-6-i",
388 + "iso-ir-127",
389 + "iso8859-6",
390 + "iso88596",
391 + "iso_8859-6",
392 + "iso_8859-6:1987"
393 + ],
394 + "name": "iso-8859-6"
395 + },
396 + {
397 + "labels": [
398 + "csisolatingreek",
399 + "ecma-118",
400 + "elot_928",
401 + "greek",
402 + "greek8",
403 + "iso-8859-7",
404 + "iso-ir-126",
405 + "iso8859-7",
406 + "iso88597",
407 + "iso_8859-7",
408 + "iso_8859-7:1987",
409 + "sun_eu_greek"
410 + ],
411 + "name": "iso-8859-7"
412 + },
413 + {
414 + "labels": [
415 + "csiso88598e",
416 + "csisolatinhebrew",
417 + "hebrew",
418 + "iso-8859-8",
419 + "iso-8859-8-e",
420 + "iso-ir-138",
421 + "iso8859-8",
422 + "iso88598",
423 + "iso_8859-8",
424 + "iso_8859-8:1988",
425 + "visual"
426 + ],
427 + "name": "iso-8859-8"
428 + },
429 + {
430 + "labels": [
431 + "csiso88598i",
432 + "iso-8859-8-i",
433 + "logical"
434 + ],
435 + "name": "iso-8859-8-i"
436 + },
437 + {
438 + "labels": [
439 + "csisolatin6",
440 + "iso-8859-10",
441 + "iso-ir-157",
442 + "iso8859-10",
443 + "iso885910",
444 + "l6",
445 + "latin6"
446 + ],
447 + "name": "iso-8859-10"
448 + },
449 + {
450 + "labels": [
451 + "iso-8859-13",
452 + "iso8859-13",
453 + "iso885913"
454 + ],
455 + "name": "iso-8859-13"
456 + },
457 + {
458 + "labels": [
459 + "iso-8859-14",
460 + "iso8859-14",
461 + "iso885914"
462 + ],
463 + "name": "iso-8859-14"
464 + },
465 + {
466 + "labels": [
467 + "csisolatin9",
468 + "iso-8859-15",
469 + "iso8859-15",
470 + "iso885915",
471 + "iso_8859-15",
472 + "l9"
473 + ],
474 + "name": "iso-8859-15"
475 + },
476 + {
477 + "labels": [
478 + "iso-8859-16"
479 + ],
480 + "name": "iso-8859-16"
481 + },
482 + {
483 + "labels": [
484 + "cskoi8r",
485 + "koi",
486 + "koi8",
487 + "koi8-r",
488 + "koi8_r"
489 + ],
490 + "name": "koi8-r"
491 + },
492 + {
493 + "labels": [
494 + "koi8-u"
495 + ],
496 + "name": "koi8-u"
497 + },
498 + {
499 + "labels": [
500 + "csmacintosh",
501 + "mac",
502 + "macintosh",
503 + "x-mac-roman"
504 + ],
505 + "name": "macintosh"
506 + },
507 + {
508 + "labels": [
509 + "dos-874",
510 + "iso-8859-11",
511 + "iso8859-11",
512 + "iso885911",
513 + "tis-620",
514 + "windows-874"
515 + ],
516 + "name": "windows-874"
517 + },
518 + {
519 + "labels": [
520 + "cp1250",
521 + "windows-1250",
522 + "x-cp1250"
523 + ],
524 + "name": "windows-1250"
525 + },
526 + {
527 + "labels": [
528 + "cp1251",
529 + "windows-1251",
530 + "x-cp1251"
531 + ],
532 + "name": "windows-1251"
533 + },
534 + {
535 + "labels": [
536 + "ansi_x3.4-1968",
537 + "ascii",
538 + "cp1252",
539 + "cp819",
540 + "csisolatin1",
541 + "ibm819",
542 + "iso-8859-1",
543 + "iso-ir-100",
544 + "iso8859-1",
545 + "iso88591",
546 + "iso_8859-1",
547 + "iso_8859-1:1987",
548 + "l1",
549 + "latin1",
550 + "us-ascii",
551 + "windows-1252",
552 + "x-cp1252"
553 + ],
554 + "name": "windows-1252"
555 + },
556 + {
557 + "labels": [
558 + "cp1253",
559 + "windows-1253",
560 + "x-cp1253"
561 + ],
562 + "name": "windows-1253"
563 + },
564 + {
565 + "labels": [
566 + "cp1254",
567 + "csisolatin5",
568 + "iso-8859-9",
569 + "iso-ir-148",
570 + "iso8859-9",
571 + "iso88599",
572 + "iso_8859-9",
573 + "iso_8859-9:1989",
574 + "l5",
575 + "latin5",
576 + "windows-1254",
577 + "x-cp1254"
578 + ],
579 + "name": "windows-1254"
580 + },
581 + {
582 + "labels": [
583 + "cp1255",
584 + "windows-1255",
585 + "x-cp1255"
586 + ],
587 + "name": "windows-1255"
588 + },
589 + {
590 + "labels": [
591 + "cp1256",
592 + "windows-1256",
593 + "x-cp1256"
594 + ],
595 + "name": "windows-1256"
596 + },
597 + {
598 + "labels": [
599 + "cp1257",
600 + "windows-1257",
601 + "x-cp1257"
602 + ],
603 + "name": "windows-1257"
604 + },
605 + {
606 + "labels": [
607 + "cp1258",
608 + "windows-1258",
609 + "x-cp1258"
610 + ],
611 + "name": "windows-1258"
612 + },
613 + {
614 + "labels": [
615 + "x-mac-cyrillic",
616 + "x-mac-ukrainian"
617 + ],
618 + "name": "x-mac-cyrillic"
619 + }
620 + ],
621 + "heading": "Legacy single-byte encodings"
622 + },
623 + {
624 + "encodings": [
625 + {
626 + "labels": [
627 + "chinese",
628 + "csgb2312",
629 + "csiso58gb231280",
630 + "gb2312",
631 + "gb_2312",
632 + "gb_2312-80",
633 + "gbk",
634 + "iso-ir-58",
635 + "x-gbk"
636 + ],
637 + "name": "gbk"
638 + },
639 + {
640 + "labels": [
641 + "gb18030"
642 + ],
643 + "name": "gb18030"
644 + },
645 + {
646 + "labels": [
647 + "hz-gb-2312"
648 + ],
649 + "name": "hz-gb-2312"
650 + }
651 + ],
652 + "heading": "Legacy multi-byte Chinese (simplified) encodings"
653 + },
654 + {
655 + "encodings": [
656 + {
657 + "labels": [
658 + "big5",
659 + "big5-hkscs",
660 + "cn-big5",
661 + "csbig5",
662 + "x-x-big5"
663 + ],
664 + "name": "big5"
665 + }
666 + ],
667 + "heading": "Legacy multi-byte Chinese (traditional) encodings"
668 + },
669 + {
670 + "encodings": [
671 + {
672 + "labels": [
673 + "cseucpkdfmtjapanese",
674 + "euc-jp",
675 + "x-euc-jp"
676 + ],
677 + "name": "euc-jp"
678 + },
679 + {
680 + "labels": [
681 + "csiso2022jp",
682 + "iso-2022-jp"
683 + ],
684 + "name": "iso-2022-jp"
685 + },
686 + {
687 + "labels": [
688 + "csshiftjis",
689 + "ms_kanji",
690 + "shift-jis",
691 + "shift_jis",
692 + "sjis",
693 + "windows-31j",
694 + "x-sjis"
695 + ],
696 + "name": "shift_jis"
697 + }
698 + ],
699 + "heading": "Legacy multi-byte Japanese encodings"
700 + },
701 + {
702 + "encodings": [
703 + {
704 + "labels": [
705 + "cseuckr",
706 + "csksc56011987",
707 + "euc-kr",
708 + "iso-ir-149",
709 + "korean",
710 + "ks_c_5601-1987",
711 + "ks_c_5601-1989",
712 + "ksc5601",
713 + "ksc_5601",
714 + "windows-949"
715 + ],
716 + "name": "euc-kr"
717 + }
718 + ],
719 + "heading": "Legacy multi-byte Korean encodings"
720 + },
721 + {
722 + "encodings": [
723 + {
724 + "labels": [
725 + "csiso2022kr",
726 + "iso-2022-cn",
727 + "iso-2022-cn-ext",
728 + "iso-2022-kr"
729 + ],
730 + "name": "replacement"
731 + },
732 + {
733 + "labels": [
734 + "utf-16be"
735 + ],
736 + "name": "utf-16be"
737 + },
738 + {
739 + "labels": [
740 + "utf-16",
741 + "utf-16le"
742 + ],
743 + "name": "utf-16le"
744 + },
745 + {
746 + "labels": [
747 + "x-user-defined"
748 + ],
749 + "name": "x-user-defined"
750 + }
751 + ],
752 + "heading": "Legacy miscellaneous encodings"
753 + }
754 +];
755 +
756 +var name_to_encoding = {};
757 +var label_to_encoding = {};
758 +encodings.forEach(function(category) {
759 + category.encodings.forEach(function(encoding) {
760 + name_to_encoding[encoding.name] = encoding;
761 + encoding.labels.forEach(function(label) {
762 + label_to_encoding[label] = encoding;
763 + });
764 + });
765 +});
766 +
767 +//
768 +// 5. Indexes
769 +//
770 +
771 +/**
772 + * @param {number} pointer The |pointer| to search for.
773 + * @param {Array.<?number>|undefined} index The |index| to search within.
774 + * @return {?number} The code point corresponding to |pointer| in |index|,
775 + * or null if |code point| is not in |index|.
776 + */
777 +function indexCodePointFor(pointer, index) {
778 + if (!index) return null;
779 + return index[pointer] || null;
780 +}
781 +
782 +/**
783 + * @param {number} code_point The |code point| to search for.
784 + * @param {Array.<?number>} index The |index| to search within.
785 + * @return {?number} The first pointer corresponding to |code point| in
786 + * |index|, or null if |code point| is not in |index|.
787 + */
788 +function indexPointerFor(code_point, index) {
789 + var pointer = index.indexOf(code_point);
790 + return pointer === -1 ? null : pointer;
791 +}
792 +
793 +/** @type {Object.<string, (Array.<number>|Array.<Array.<number>>)>} */
794 +var indexes = require('./encoding-indexes');
795 +
796 +/**
797 + * @param {number} pointer The |pointer| to search for in the gb18030 index.
798 + * @return {?number} The code point corresponding to |pointer| in |index|,
799 + * or null if |code point| is not in the gb18030 index.
800 + */
801 +function indexGB18030CodePointFor(pointer) {
802 + if ((pointer > 39419 && pointer < 189000) || (pointer > 1237575)) {
803 + return null;
804 + }
805 + var /** @type {number} */ offset = 0,
806 + /** @type {number} */ code_point_offset = 0,
807 + /** @type {Array.<Array.<number>>} */ idx = indexes['gb18030'];
808 + var i;
809 + for (i = 0; i < idx.length; ++i) {
810 + var entry = idx[i];
811 + if (entry[0] <= pointer) {
812 + offset = entry[0];
813 + code_point_offset = entry[1];
814 + } else {
815 + break;
816 + }
817 + }
818 + return code_point_offset + pointer - offset;
819 +}
820 +
821 +/**
822 + * @param {number} code_point The |code point| to locate in the gb18030 index.
823 + * @return {number} The first pointer corresponding to |code point| in the
824 + * gb18030 index.
825 + */
826 +function indexGB18030PointerFor(code_point) {
827 + var /** @type {number} */ offset = 0,
828 + /** @type {number} */ pointer_offset = 0,
829 + /** @type {Array.<Array.<number>>} */ idx = indexes['gb18030'];
830 + var i;
831 + for (i = 0; i < idx.length; ++i) {
832 + var entry = idx[i];
833 + if (entry[1] <= code_point) {
834 + offset = entry[1];
835 + pointer_offset = entry[0];
836 + } else {
837 + break;
838 + }
839 + }
840 + return pointer_offset + code_point - offset;
841 +}
842 +
843 +
844 +//
845 +// 7. API
846 +//
847 +
848 +/** @const */ var DEFAULT_ENCODING = 'utf-8';
849 +
850 +// 7.1 Interface TextDecoder
851 +
852 +/**
853 + * @constructor
854 + * @param {string=} opt_encoding The label of the encoding;
855 + * defaults to 'utf-8'.
856 + * @param {{fatal: boolean}=} options
857 + */
858 +function TextDecoder(opt_encoding, options) {
859 + if (!(this instanceof TextDecoder)) {
860 + return new TextDecoder(opt_encoding, options);
861 + }
862 + opt_encoding = opt_encoding ? String(opt_encoding) : DEFAULT_ENCODING;
863 + options = Object(options);
864 + /** @private */
865 + this._encoding = getEncoding(opt_encoding);
866 + if (this._encoding === null || this._encoding.name === 'replacement')
867 + throw new TypeError('Unknown encoding: ' + opt_encoding);
868 +
869 + /** @private @type {boolean} */
870 + this._streaming = false;
871 + /** @private @type {boolean} */
872 + this._BOMseen = false;
873 + /** @private */
874 + this._decoder = null;
875 + /** @private @type {{fatal: boolean}=} */
876 + this._options = { fatal: Boolean(options.fatal) };
877 +
878 + if (Object.defineProperty) {
879 + Object.defineProperty(
880 + this, 'encoding',
881 + { get: function() { return this._encoding.name; } });
882 + } else {
883 + this.encoding = this._encoding.name;
884 + }
885 +
886 + return this;
887 +}
888 +
889 +// TODO: Issue if input byte stream is offset by decoder
890 +// TODO: BOM detection will not work if stream header spans multiple calls
891 +// (last N bytes of previous stream may need to be retained?)
892 +TextDecoder.prototype = {
893 + /**
894 + * @param {Buffer=} bytes The buffer of bytes to decode.
895 + * @param {{stream: boolean}=} options
896 + */
897 + decode: function decode(bytes, options) {
898 + options = Object(options);
899 +
900 + if (!this._streaming) {
901 + this._decoder = this._encoding.getDecoder(this._options);
902 + this._BOMseen = false;
903 + }
904 + this._streaming = Boolean(options.stream);
905 +
906 + var input_stream = new ByteInputStream(bytes);
907 +
908 + var output_stream = new CodePointOutputStream();
909 +
910 + /** @type {number} */
911 + var code_point;
912 +
913 + while (input_stream.get() !== EOF_byte) {
914 + code_point = this._decoder.decode(input_stream);
915 + if (code_point !== null && code_point !== EOF_code_point) {
916 + output_stream.emit(code_point);
917 + }
918 + }
919 + if (!this._streaming) {
920 + do {
921 + code_point = this._decoder.decode(input_stream);
922 + if (code_point !== null && code_point !== EOF_code_point) {
923 + output_stream.emit(code_point);
924 + }
925 + } while (code_point !== EOF_code_point &&
926 + input_stream.get() != EOF_byte);
927 + this._decoder = null;
928 + }
929 +
930 + var result = output_stream.string();
931 + if (!this._BOMseen && result.length) {
932 + this._BOMseen = true;
933 + if (UTFs.indexOf(this.encoding) !== -1 &&
934 + result.charCodeAt(0) === 0xFEFF) {
935 + result = result.substring(1);
936 + }
937 + }
938 +
939 + return result;
940 + }
941 +};
942 +
943 +var UTFs = ['utf-8', 'utf-16le', 'utf-16be'];
944 +
945 +// 7.2 Interface TextEncoder
946 +
947 +/**
948 + * @constructor
949 + * @param {string=} opt_encoding The label of the encoding;
950 + * defaults to 'utf-8'.
951 + * @param {{fatal: boolean}=} options
952 + */
953 +function TextEncoder(opt_encoding, options) {
954 + if (!(this instanceof TextEncoder)) {
955 + return new TextEncoder(opt_encoding, options);
956 + }
957 + opt_encoding = opt_encoding ? String(opt_encoding) : DEFAULT_ENCODING;
958 + options = Object(options);
959 + /** @private */
960 + this._encoding = getEncoding(opt_encoding);
961 + if (this._encoding === null || (this._encoding.name !== 'utf-8' &&
962 + this._encoding.name !== 'utf-16le' &&
963 + this._encoding.name !== 'utf-16be'))
964 + throw new TypeError('Unknown encoding: ' + opt_encoding);
965 + /** @private @type {boolean} */
966 + this._streaming = false;
967 + /** @private */
968 + this._encoder = null;
969 + /** @private @type {{fatal: boolean}=} */
970 + this._options = { fatal: Boolean(options.fatal) };
971 +
972 + if (Object.defineProperty) {
973 + Object.defineProperty(
974 + this, 'encoding',
975 + { get: function() { return this._encoding.name; } });
976 + } else {
977 + this.encoding = this._encoding.name;
978 + }
979 +
980 + return this;
981 +}
982 +
983 +TextEncoder.prototype = {
984 + /**
985 + * @param {string=} opt_string The string to encode.
986 + * @param {{stream: boolean}=} options
987 + */
988 + encode: function encode(opt_string, options) {
989 + opt_string = opt_string ? String(opt_string) : '';
990 + options = Object(options);
991 + // TODO: any options?
992 + if (!this._streaming) {
993 + this._encoder = this._encoding.getEncoder(this._options);
994 + }
995 + this._streaming = Boolean(options.stream);
996 +
997 + var bytes = [];
998 + var output_stream = new ByteOutputStream(bytes);
999 + var input_stream = new CodePointInputStream(opt_string);
1000 + while (input_stream.get() !== EOF_code_point) {
1001 + this._encoder.encode(output_stream, input_stream);
1002 + }
1003 + if (!this._streaming) {
1004 + /** @type {number} */
1005 + var last_byte;
1006 + do {
1007 + last_byte = this._encoder.encode(output_stream, input_stream);
1008 + } while (last_byte !== EOF_byte);
1009 + this._encoder = null;
1010 + }
1011 + return new Buffer(bytes);
1012 + }
1013 +};
1014 +
1015 +
1016 +//
1017 +// 8. The encoding
1018 +//
1019 +
1020 +// 8.1 utf-8
1021 +
1022 +/**
1023 + * @constructor
1024 + * @param {{fatal: boolean}} options
1025 + */
1026 +function UTF8Decoder(options) {
1027 + var fatal = options.fatal;
1028 + var /** @type {number} */ utf8_code_point = 0,
1029 + /** @type {number} */ utf8_bytes_needed = 0,
1030 + /** @type {number} */ utf8_bytes_seen = 0,
1031 + /** @type {number} */ utf8_lower_boundary = 0;
1032 +
1033 + /**
1034 + * @param {ByteInputStream} byte_pointer The byte stream to decode.
1035 + * @return {?number} The next code point decoded, or null if not enough
1036 + * data exists in the input stream to decode a complete code point.
1037 + */
1038 + this.decode = function(byte_pointer) {
1039 + var bite = byte_pointer.get();
1040 + if (bite === EOF_byte) {
1041 + if (utf8_bytes_needed !== 0) {
1042 + return decoderError(fatal);
1043 + }
1044 + return EOF_code_point;
1045 + }
1046 + byte_pointer.offset(1);
1047 +
1048 + if (utf8_bytes_needed === 0) {
1049 + if (inRange(bite, 0x00, 0x7F)) {
1050 + return bite;
1051 + }
1052 + if (inRange(bite, 0xC2, 0xDF)) {
1053 + utf8_bytes_needed = 1;
1054 + utf8_lower_boundary = 0x80;
1055 + utf8_code_point = bite - 0xC0;
1056 + } else if (inRange(bite, 0xE0, 0xEF)) {
1057 + utf8_bytes_needed = 2;
1058 + utf8_lower_boundary = 0x800;
1059 + utf8_code_point = bite - 0xE0;
1060 + } else if (inRange(bite, 0xF0, 0xF4)) {
1061 + utf8_bytes_needed = 3;
1062 + utf8_lower_boundary = 0x10000;
1063 + utf8_code_point = bite - 0xF0;
1064 + } else {
1065 + return decoderError(fatal);
1066 + }
1067 + utf8_code_point = utf8_code_point * Math.pow(64, utf8_bytes_needed);
1068 + return null;
1069 + }
1070 + if (!inRange(bite, 0x80, 0xBF)) {
1071 + utf8_code_point = 0;
1072 + utf8_bytes_needed = 0;
1073 + utf8_bytes_seen = 0;
1074 + utf8_lower_boundary = 0;
1075 + byte_pointer.offset(-1);
1076 + return decoderError(fatal);
1077 + }
1078 + utf8_bytes_seen += 1;
1079 + utf8_code_point = utf8_code_point + (bite - 0x80) *
1080 + Math.pow(64, utf8_bytes_needed - utf8_bytes_seen);
1081 + if (utf8_bytes_seen !== utf8_bytes_needed) {
1082 + return null;
1083 + }
1084 + var code_point = utf8_code_point;
1085 + var lower_boundary = utf8_lower_boundary;
1086 + utf8_code_point = 0;
1087 + utf8_bytes_needed = 0;
1088 + utf8_bytes_seen = 0;
1089 + utf8_lower_boundary = 0;
1090 + if (inRange(code_point, lower_boundary, 0x10FFFF) &&
1091 + !inRange(code_point, 0xD800, 0xDFFF)) {
1092 + return code_point;
1093 + }
1094 + return decoderError(fatal);
1095 + };
1096 +}
1097 +
1098 +/**
1099 + * @constructor
1100 + * @param {{fatal: boolean}} options
1101 + */
1102 +function UTF8Encoder(options) {
1103 + var fatal = options.fatal;
1104 + /**
1105 + * @param {ByteOutputStream} output_byte_stream Output byte stream.
1106 + * @param {CodePointInputStream} code_point_pointer Input stream.
1107 + * @return {number} The last byte emitted.
1108 + */
1109 + this.encode = function(output_byte_stream, code_point_pointer) {
1110 + /** @type {number} */
1111 + var code_point = code_point_pointer.get();
1112 + if (code_point === EOF_code_point) {
1113 + return EOF_byte;
1114 + }
1115 + code_point_pointer.offset(1);
1116 + if (inRange(code_point, 0xD800, 0xDFFF)) {
1117 + return encoderError(code_point);
1118 + }
1119 + if (inRange(code_point, 0x0000, 0x007f)) {
1120 + return output_byte_stream.emit(code_point);
1121 + }
1122 + var count, offset;
1123 + if (inRange(code_point, 0x0080, 0x07FF)) {
1124 + count = 1;
1125 + offset = 0xC0;
1126 + } else if (inRange(code_point, 0x0800, 0xFFFF)) {
1127 + count = 2;
1128 + offset = 0xE0;
1129 + } else if (inRange(code_point, 0x10000, 0x10FFFF)) {
1130 + count = 3;
1131 + offset = 0xF0;
1132 + }
1133 + var result = output_byte_stream.emit(
1134 + div(code_point, Math.pow(64, count)) + offset);
1135 + while (count > 0) {
1136 + var temp = div(code_point, Math.pow(64, count - 1));
1137 + result = output_byte_stream.emit(0x80 + (temp % 64));
1138 + count -= 1;
1139 + }
1140 + return result;
1141 + };
1142 +}
1143 +
1144 +/** @param {{fatal: boolean}} options */
1145 +name_to_encoding['utf-8'].getEncoder = function(options) {
1146 + return new UTF8Encoder(options);
1147 +};
1148 +/** @param {{fatal: boolean}} options */
1149 +name_to_encoding['utf-8'].getDecoder = function(options) {
1150 + return new UTF8Decoder(options);
1151 +};
1152 +
1153 +//
1154 +// 9. Legacy single-byte encodings
1155 +//
1156 +
1157 +/**
1158 + * @constructor
1159 + * @param {Array.<number>} index The encoding index.
1160 + * @param {{fatal: boolean}} options
1161 + */
1162 +function SingleByteDecoder(index, options) {
1163 + var fatal = options.fatal;
1164 + /**
1165 + * @param {ByteInputStream} byte_pointer The byte stream to decode.
1166 + * @return {?number} The next code point decoded, or null if not enough
1167 + * data exists in the input stream to decode a complete code point.
1168 + */
1169 + this.decode = function(byte_pointer) {
1170 + var bite = byte_pointer.get();
1171 + if (bite === EOF_byte) {
1172 + return EOF_code_point;
1173 + }
1174 + byte_pointer.offset(1);
1175 + if (inRange(bite, 0x00, 0x7F)) {
1176 + return bite;
1177 + }
1178 + var code_point = index[bite - 0x80];
1179 + if (code_point === null) {
1180 + return decoderError(fatal);
1181 + }
1182 + return code_point;
1183 + };
1184 +}
1185 +
1186 +/**
1187 + * @constructor
1188 + * @param {Array.<?number>} index The encoding index.
1189 + * @param {{fatal: boolean}} options
1190 + */
1191 +function SingleByteEncoder(index, options) {
1192 + var fatal = options.fatal;
1193 + /**
1194 + * @param {ByteOutputStream} output_byte_stream Output byte stream.
1195 + * @param {CodePointInputStream} code_point_pointer Input stream.
1196 + * @return {number} The last byte emitted.
1197 + */
1198 + this.encode = function(output_byte_stream, code_point_pointer) {
1199 + var code_point = code_point_pointer.get();
1200 + if (code_point === EOF_code_point) {
1201 + return EOF_byte;
1202 + }
1203 + code_point_pointer.offset(1);
1204 + if (inRange(code_point, 0x0000, 0x007F)) {
1205 + return output_byte_stream.emit(code_point);
1206 + }
1207 + var pointer = indexPointerFor(code_point, index);
1208 + if (pointer === null) {
1209 + encoderError(code_point);
1210 + }
1211 + return output_byte_stream.emit(pointer + 0x80);
1212 + };
1213 +}
1214 +
1215 +(function() {
1216 + encodings.forEach(function(category) {
1217 + if (category.heading !== 'Legacy single-byte encodings')
1218 + return;
1219 + category.encodings.forEach(function(encoding) {
1220 + var idx = indexes[encoding.name];
1221 + /** @param {{fatal: boolean}} options */
1222 + encoding.getDecoder = function(options) {
1223 + return new SingleByteDecoder(idx, options);
1224 + };
1225 + /** @param {{fatal: boolean}} options */
1226 + encoding.getEncoder = function(options) {
1227 + return new SingleByteEncoder(idx, options);
1228 + };
1229 + });
1230 + });
1231 +}());
1232 +
1233 +//
1234 +// 10. Legacy multi-byte Chinese (simplified) encodings
1235 +//
1236 +
1237 +// 9.1 gbk
1238 +
1239 +/**
1240 + * @constructor
1241 + * @param {boolean} gb18030 True if decoding gb18030, false otherwise.
1242 + * @param {{fatal: boolean}} options
1243 + */
1244 +function GBKDecoder(gb18030, options) {
1245 + var fatal = options.fatal;
1246 + var /** @type {number} */ gbk_first = 0x00,
1247 + /** @type {number} */ gbk_second = 0x00,
1248 + /** @type {number} */ gbk_third = 0x00;
1249 + /**
1250 + * @param {ByteInputStream} byte_pointer The byte stream to decode.
1251 + * @return {?number} The next code point decoded, or null if not enough
1252 + * data exists in the input stream to decode a complete code point.
1253 + */
1254 + this.decode = function(byte_pointer) {
1255 + var bite = byte_pointer.get();
1256 + if (bite === EOF_byte && gbk_first === 0x00 &&
1257 + gbk_second === 0x00 && gbk_third === 0x00) {
1258 + return EOF_code_point;
1259 + }
1260 + if (bite === EOF_byte &&
1261 + (gbk_first !== 0x00 || gbk_second !== 0x00 || gbk_third !== 0x00)) {
1262 + gbk_first = 0x00;
1263 + gbk_second = 0x00;
1264 + gbk_third = 0x00;
1265 + decoderError(fatal);
1266 + }
1267 + byte_pointer.offset(1);
1268 + var code_point;
1269 + if (gbk_third !== 0x00) {
1270 + code_point = null;
1271 + if (inRange(bite, 0x30, 0x39)) {
1272 + code_point = indexGB18030CodePointFor(
1273 + (((gbk_first - 0x81) * 10 + (gbk_second - 0x30)) * 126 +
1274 + (gbk_third - 0x81)) * 10 + bite - 0x30);
1275 + }
1276 + gbk_first = 0x00;
1277 + gbk_second = 0x00;
1278 + gbk_third = 0x00;
1279 + if (code_point === null) {
1280 + byte_pointer.offset(-3);
1281 + return decoderError(fatal);
1282 + }
1283 + return code_point;
1284 + }
1285 + if (gbk_second !== 0x00) {
1286 + if (inRange(bite, 0x81, 0xFE)) {
1287 + gbk_third = bite;
1288 + return null;
1289 + }
1290 + byte_pointer.offset(-2);
1291 + gbk_first = 0x00;
1292 + gbk_second = 0x00;
1293 + return decoderError(fatal);
1294 + }
1295 + if (gbk_first !== 0x00) {
1296 + if (inRange(bite, 0x30, 0x39) && gb18030) {
1297 + gbk_second = bite;
1298 + return null;
1299 + }
1300 + var lead = gbk_first;
1301 + var pointer = null;
1302 + gbk_first = 0x00;
1303 + var offset = bite < 0x7F ? 0x40 : 0x41;
1304 + if (inRange(bite, 0x40, 0x7E) || inRange(bite, 0x80, 0xFE)) {
1305 + pointer = (lead - 0x81) * 190 + (bite - offset);
1306 + }
1307 + code_point = pointer === null ? null :
1308 + indexCodePointFor(pointer, indexes['gbk']);
1309 + if (pointer === null) {
1310 + byte_pointer.offset(-1);
1311 + }
1312 + if (code_point === null) {
1313 + return decoderError(fatal);
1314 + }
1315 + return code_point;
1316 + }
1317 + if (inRange(bite, 0x00, 0x7F)) {
1318 + return bite;
1319 + }
1320 + if (bite === 0x80) {
1321 + return 0x20AC;
1322 + }
1323 + if (inRange(bite, 0x81, 0xFE)) {
1324 + gbk_first = bite;
1325 + return null;
1326 + }
1327 + return decoderError(fatal);
1328 + };
1329 +}
1330 +
1331 +/**
1332 + * @constructor
1333 + * @param {boolean} gb18030 True if decoding gb18030, false otherwise.
1334 + * @param {{fatal: boolean}} options
1335 + */
1336 +function GBKEncoder(gb18030, options) {
1337 + var fatal = options.fatal;
1338 + /**
1339 + * @param {ByteOutputStream} output_byte_stream Output byte stream.
1340 + * @param {CodePointInputStream} code_point_pointer Input stream.
1341 + * @return {number} The last byte emitted.
1342 + */
1343 + this.encode = function(output_byte_stream, code_point_pointer) {
1344 + var code_point = code_point_pointer.get();
1345 + if (code_point === EOF_code_point) {
1346 + return EOF_byte;
1347 + }
1348 + code_point_pointer.offset(1);
1349 + if (inRange(code_point, 0x0000, 0x007F)) {
1350 + return output_byte_stream.emit(code_point);
1351 + }
1352 + var pointer = indexPointerFor(code_point, indexes['gbk']);
1353 + if (pointer !== null) {
1354 + var lead = div(pointer, 190) + 0x81;
1355 + var trail = pointer % 190;
1356 + var offset = trail < 0x3F ? 0x40 : 0x41;
1357 + return output_byte_stream.emit(lead, trail + offset);
1358 + }
1359 + if (pointer === null && !gb18030) {
1360 + return encoderError(code_point);
1361 + }
1362 + pointer = indexGB18030PointerFor(code_point);
1363 + var byte1 = div(div(div(pointer, 10), 126), 10);
1364 + pointer = pointer - byte1 * 10 * 126 * 10;
1365 + var byte2 = div(div(pointer, 10), 126);
1366 + pointer = pointer - byte2 * 10 * 126;
1367 + var byte3 = div(pointer, 10);
1368 + var byte4 = pointer - byte3 * 10;
1369 + return output_byte_stream.emit(byte1 + 0x81,
1370 + byte2 + 0x30,
1371 + byte3 + 0x81,
1372 + byte4 + 0x30);
1373 + };
1374 +}
1375 +
1376 +name_to_encoding['gbk'].getEncoder = function(options) {
1377 + return new GBKEncoder(false, options);
1378 +};
1379 +name_to_encoding['gbk'].getDecoder = function(options) {
1380 + return new GBKDecoder(false, options);
1381 +};
1382 +
1383 +// 9.2 gb18030
1384 +name_to_encoding['gb18030'].getEncoder = function(options) {
1385 + return new GBKEncoder(true, options);
1386 +};
1387 +name_to_encoding['gb18030'].getDecoder = function(options) {
1388 + return new GBKDecoder(true, options);
1389 +};
1390 +
1391 +// 10.2 hz-gb-2312
1392 +
1393 +/**
1394 + * @constructor
1395 + * @param {{fatal: boolean}} options
1396 + */
1397 +function HZGB2312Decoder(options) {
1398 + var fatal = options.fatal;
1399 + var /** @type {boolean} */ hzgb2312 = false,
1400 + /** @type {number} */ hzgb2312_lead = 0x00;
1401 + /**
1402 + * @param {ByteInputStream} byte_pointer The byte stream to decode.
1403 + * @return {?number} The next code point decoded, or null if not enough
1404 + * data exists in the input stream to decode a complete code point.
1405 + */
1406 + this.decode = function(byte_pointer) {
1407 + var bite = byte_pointer.get();
1408 + if (bite === EOF_byte && hzgb2312_lead === 0x00) {
1409 + return EOF_code_point;
1410 + }
1411 + if (bite === EOF_byte && hzgb2312_lead !== 0x00) {
1412 + hzgb2312_lead = 0x00;
1413 + return decoderError(fatal);
1414 + }
1415 + byte_pointer.offset(1);
1416 + if (hzgb2312_lead === 0x7E) {
1417 + hzgb2312_lead = 0x00;
1418 + if (bite === 0x7B) {
1419 + hzgb2312 = true;
1420 + return null;
1421 + }
1422 + if (bite === 0x7D) {
1423 + hzgb2312 = false;
1424 + return null;
1425 + }
1426 + if (bite === 0x7E) {
1427 + return 0x007E;
1428 + }
1429 + if (bite === 0x0A) {
1430 + return null;
1431 + }
1432 + byte_pointer.offset(-1);
1433 + return decoderError(fatal);
1434 + }
1435 + if (hzgb2312_lead !== 0x00) {
1436 + var lead = hzgb2312_lead;
1437 + hzgb2312_lead = 0x00;
1438 + var code_point = null;
1439 + if (inRange(bite, 0x21, 0x7E)) {
1440 + code_point = indexCodePointFor((lead - 1) * 190 +
1441 + (bite + 0x3F), indexes['gbk']);
1442 + }
1443 + if (bite === 0x0A) {
1444 + hzgb2312 = false;
1445 + }
1446 + if (code_point === null) {
1447 + return decoderError(fatal);
1448 + }
1449 + return code_point;
1450 + }
1451 + if (bite === 0x7E) {
1452 + hzgb2312_lead = 0x7E;
1453 + return null;
1454 + }
1455 + if (hzgb2312) {
1456 + if (inRange(bite, 0x20, 0x7F)) {
1457 + hzgb2312_lead = bite;
1458 + return null;
1459 + }
1460 + if (bite === 0x0A) {
1461 + hzgb2312 = false;
1462 + }
1463 + return decoderError(fatal);
1464 + }
1465 + if (inRange(bite, 0x00, 0x7F)) {
1466 + return bite;
1467 + }
1468 + return decoderError(fatal);
1469 + };
1470 +}
1471 +
1472 +/**
1473 + * @constructor
1474 + * @param {{fatal: boolean}} options
1475 + */
1476 +function HZGB2312Encoder(options) {
1477 + var fatal = options.fatal;
1478 + /** @type {boolean} */
1479 + var hzgb2312 = false;
1480 + /**
1481 + * @param {ByteOutputStream} output_byte_stream Output byte stream.
1482 + * @param {CodePointInputStream} code_point_pointer Input stream.
1483 + * @return {number} The last byte emitted.
1484 + */
1485 + this.encode = function(output_byte_stream, code_point_pointer) {
1486 + var code_point = code_point_pointer.get();
1487 + if (code_point === EOF_code_point) {
1488 + return EOF_byte;
1489 + }
1490 + code_point_pointer.offset(1);
1491 + if (inRange(code_point, 0x0000, 0x007F) && hzgb2312) {
1492 + code_point_pointer.offset(-1);
1493 + hzgb2312 = false;
1494 + return output_byte_stream.emit(0x7E, 0x7D);
1495 + }
1496 + if (code_point === 0x007E) {
1497 + return output_byte_stream.emit(0x7E, 0x7E);
1498 + }
1499 + if (inRange(code_point, 0x0000, 0x007F)) {
1500 + return output_byte_stream.emit(code_point);
1501 + }
1502 + if (!hzgb2312) {
1503 + code_point_pointer.offset(-1);
1504 + hzgb2312 = true;
1505 + return output_byte_stream.emit(0x7E, 0x7B);
1506 + }
1507 + var pointer = indexPointerFor(code_point, indexes['gbk']);
1508 + if (pointer === null) {
1509 + return encoderError(code_point);
1510 + }
1511 + var lead = div(pointer, 190) + 1;
1512 + var trail = pointer % 190 - 0x3F;
1513 + if (!inRange(lead, 0x21, 0x7E) || !inRange(trail, 0x21, 0x7E)) {
1514 + return encoderError(code_point);
1515 + }
1516 + return output_byte_stream.emit(lead, trail);
1517 + };
1518 +}
1519 +
1520 +/** @param {{fatal: boolean}} options */
1521 +name_to_encoding['hz-gb-2312'].getEncoder = function(options) {
1522 + return new HZGB2312Encoder(options);
1523 +};
1524 +/** @param {{fatal: boolean}} options */
1525 +name_to_encoding['hz-gb-2312'].getDecoder = function(options) {
1526 + return new HZGB2312Decoder(options);
1527 +};
1528 +
1529 +//
1530 +// 11. Legacy multi-byte Chinese (traditional) encodings
1531 +//
1532 +
1533 +// 11.1 big5
1534 +
1535 +/**
1536 + * @constructor
1537 + * @param {{fatal: boolean}} options
1538 + */
1539 +function Big5Decoder(options) {
1540 + var fatal = options.fatal;
1541 + var /** @type {number} */ big5_lead = 0x00,
1542 + /** @type {?number} */ big5_pending = null;
1543 +
1544 + /**
1545 + * @param {ByteInputStream} byte_pointer The byte steram to decode.
1546 + * @return {?number} The next code point decoded, or null if not enough
1547 + * data exists in the input stream to decode a complete code point.
1548 + */
1549 + this.decode = function(byte_pointer) {
1550 + // NOTE: Hack to support emitting two code points
1551 + if (big5_pending !== null) {
1552 + var pending = big5_pending;
1553 + big5_pending = null;
1554 + return pending;
1555 + }
1556 + var bite = byte_pointer.get();
1557 + if (bite === EOF_byte && big5_lead === 0x00) {
1558 + return EOF_code_point;
1559 + }
1560 + if (bite === EOF_byte && big5_lead !== 0x00) {
1561 + big5_lead = 0x00;
1562 + return decoderError(fatal);
1563 + }
1564 + byte_pointer.offset(1);
1565 + if (big5_lead !== 0x00) {
1566 + var lead = big5_lead;
1567 + var pointer = null;
1568 + big5_lead = 0x00;
1569 + var offset = bite < 0x7F ? 0x40 : 0x62;
1570 + if (inRange(bite, 0x40, 0x7E) || inRange(bite, 0xA1, 0xFE)) {
1571 + pointer = (lead - 0x81) * 157 + (bite - offset);
1572 + }
1573 + if (pointer === 1133) {
1574 + big5_pending = 0x0304;
1575 + return 0x00CA;
1576 + }
1577 + if (pointer === 1135) {
1578 + big5_pending = 0x030C;
1579 + return 0x00CA;
1580 + }
1581 + if (pointer === 1164) {
1582 + big5_pending = 0x0304;
1583 + return 0x00EA;
1584 + }
1585 + if (pointer === 1166) {
1586 + big5_pending = 0x030C;
1587 + return 0x00EA;
1588 + }
1589 + var code_point = (pointer === null) ? null :
1590 + indexCodePointFor(pointer, indexes['big5']);
1591 + if (pointer === null) {
1592 + byte_pointer.offset(-1);
1593 + }
1594 + if (code_point === null) {
1595 + return decoderError(fatal);
1596 + }
1597 + return code_point;
1598 + }
1599 + if (inRange(bite, 0x00, 0x7F)) {
1600 + return bite;
1601 + }
1602 + if (inRange(bite, 0x81, 0xFE)) {
1603 + big5_lead = bite;
1604 + return null;
1605 + }
1606 + return decoderError(fatal);
1607 + };
1608 +}
1609 +
1610 +/**
1611 + * @constructor
1612 + * @param {{fatal: boolean}} options
1613 + */
1614 +function Big5Encoder(options) {
1615 + var fatal = options.fatal;
1616 + /**
1617 + * @param {ByteOutputStream} output_byte_stream Output byte stream.
1618 + * @param {CodePointInputStream} code_point_pointer Input stream.
1619 + * @return {number} The last byte emitted.
1620 + */
1621 + this.encode = function(output_byte_stream, code_point_pointer) {
1622 + var code_point = code_point_pointer.get();
1623 + if (code_point === EOF_code_point) {
1624 + return EOF_byte;
1625 + }
1626 + code_point_pointer.offset(1);
1627 + if (inRange(code_point, 0x0000, 0x007F)) {
1628 + return output_byte_stream.emit(code_point);
1629 + }
1630 + var pointer = indexPointerFor(code_point, indexes['big5']);
1631 + if (pointer === null) {
1632 + return encoderError(code_point);
1633 + }
1634 + var lead = div(pointer, 157) + 0x81;
1635 + //if (lead < 0xA1) {
1636 + // return encoderError(code_point);
1637 + //}
1638 + var trail = pointer % 157;
1639 + var offset = trail < 0x3F ? 0x40 : 0x62;
1640 + return output_byte_stream.emit(lead, trail + offset);
1641 + };
1642 +}
1643 +
1644 +/** @param {{fatal: boolean}} options */
1645 +name_to_encoding['big5'].getEncoder = function(options) {
1646 + return new Big5Encoder(options);
1647 +};
1648 +/** @param {{fatal: boolean}} options */
1649 +name_to_encoding['big5'].getDecoder = function(options) {
1650 + return new Big5Decoder(options);
1651 +};
1652 +
1653 +
1654 +//
1655 +// 12. Legacy multi-byte Japanese encodings
1656 +//
1657 +
1658 +// 12.1 euc.jp
1659 +
1660 +/**
1661 + * @constructor
1662 + * @param {{fatal: boolean}} options
1663 + */
1664 +function EUCJPDecoder(options) {
1665 + var fatal = options.fatal;
1666 + var /** @type {number} */ eucjp_first = 0x00,
1667 + /** @type {number} */ eucjp_second = 0x00;
1668 + /**
1669 + * @param {ByteInputStream} byte_pointer The byte stream to decode.
1670 + * @return {?number} The next code point decoded, or null if not enough
1671 + * data exists in the input stream to decode a complete code point.
1672 + */
1673 + this.decode = function(byte_pointer) {
1674 + var bite = byte_pointer.get();
1675 + if (bite === EOF_byte) {
1676 + if (eucjp_first === 0x00 && eucjp_second === 0x00) {
1677 + return EOF_code_point;
1678 + }
1679 + eucjp_first = 0x00;
1680 + eucjp_second = 0x00;
1681 + return decoderError(fatal);
1682 + }
1683 + byte_pointer.offset(1);
1684 +
1685 + var lead, code_point;
1686 + if (eucjp_second !== 0x00) {
1687 + lead = eucjp_second;
1688 + eucjp_second = 0x00;
1689 + code_point = null;
1690 + if (inRange(lead, 0xA1, 0xFE) && inRange(bite, 0xA1, 0xFE)) {
1691 + code_point = indexCodePointFor((lead - 0xA1) * 94 + bite - 0xA1,
1692 + indexes['jis0212']);
1693 + }
1694 + if (!inRange(bite, 0xA1, 0xFE)) {
1695 + byte_pointer.offset(-1);
1696 + }
1697 + if (code_point === null) {
1698 + return decoderError(fatal);
1699 + }
1700 + return code_point;
1701 + }
1702 + if (eucjp_first === 0x8E && inRange(bite, 0xA1, 0xDF)) {
1703 + eucjp_first = 0x00;
1704 + return 0xFF61 + bite - 0xA1;
1705 + }
1706 + if (eucjp_first === 0x8F && inRange(bite, 0xA1, 0xFE)) {
1707 + eucjp_first = 0x00;
1708 + eucjp_second = bite;
1709 + return null;
1710 + }
1711 + if (eucjp_first !== 0x00) {
1712 + lead = eucjp_first;
1713 + eucjp_first = 0x00;
1714 + code_point = null;
1715 + if (inRange(lead, 0xA1, 0xFE) && inRange(bite, 0xA1, 0xFE)) {
1716 + code_point = indexCodePointFor((lead - 0xA1) * 94 + bite - 0xA1,
1717 + indexes['jis0208']);
1718 + }
1719 + if (!inRange(bite, 0xA1, 0xFE)) {
1720 + byte_pointer.offset(-1);
1721 + }
1722 + if (code_point === null) {
1723 + return decoderError(fatal);
1724 + }
1725 + return code_point;
1726 + }
1727 + if (inRange(bite, 0x00, 0x7F)) {
1728 + return bite;
1729 + }
1730 + if (bite === 0x8E || bite === 0x8F || (inRange(bite, 0xA1, 0xFE))) {
1731 + eucjp_first = bite;
1732 + return null;
1733 + }
1734 + return decoderError(fatal);
1735 + };
1736 +}
1737 +
1738 +/**
1739 + * @constructor
1740 + * @param {{fatal: boolean}} options
1741 + */
1742 +function EUCJPEncoder(options) {
1743 + var fatal = options.fatal;
1744 + /**
1745 + * @param {ByteOutputStream} output_byte_stream Output byte stream.
1746 + * @param {CodePointInputStream} code_point_pointer Input stream.
1747 + * @return {number} The last byte emitted.
1748 + */
1749 + this.encode = function(output_byte_stream, code_point_pointer) {
1750 + var code_point = code_point_pointer.get();
1751 + if (code_point === EOF_code_point) {
1752 + return EOF_byte;
1753 + }
1754 + code_point_pointer.offset(1);
1755 + if (inRange(code_point, 0x0000, 0x007F)) {
1756 + return output_byte_stream.emit(code_point);
1757 + }
1758 + if (code_point === 0x00A5) {
1759 + return output_byte_stream.emit(0x5C);
1760 + }
1761 + if (code_point === 0x203E) {
1762 + return output_byte_stream.emit(0x7E);
1763 + }
1764 + if (inRange(code_point, 0xFF61, 0xFF9F)) {
1765 + return output_byte_stream.emit(0x8E, code_point - 0xFF61 + 0xA1);
1766 + }
1767 +
1768 + var pointer = indexPointerFor(code_point, indexes['jis0208']);
1769 + if (pointer === null) {
1770 + return encoderError(code_point);
1771 + }
1772 + var lead = div(pointer, 94) + 0xA1;
1773 + var trail = pointer % 94 + 0xA1;
1774 + return output_byte_stream.emit(lead, trail);
1775 + };
1776 +}
1777 +
1778 +/** @param {{fatal: boolean}} options */
1779 +name_to_encoding['euc-jp'].getEncoder = function(options) {
1780 + return new EUCJPEncoder(options);
1781 +};
1782 +/** @param {{fatal: boolean}} options */
1783 +name_to_encoding['euc-jp'].getDecoder = function(options) {
1784 + return new EUCJPDecoder(options);
1785 +};
1786 +
1787 +// 12.2 iso-2022-jp
1788 +
1789 +/**
1790 + * @constructor
1791 + * @param {{fatal: boolean}} options
1792 + */
1793 +function ISO2022JPDecoder(options) {
1794 + var fatal = options.fatal;
1795 + /** @enum */
1796 + var state = {
1797 + ASCII: 0,
1798 + escape_start: 1,
1799 + escape_middle: 2,
1800 + escape_final: 3,
1801 + lead: 4,
1802 + trail: 5,
1803 + Katakana: 6
1804 + };
1805 + var /** @type {number} */ iso2022jp_state = state.ASCII,
1806 + /** @type {boolean} */ iso2022jp_jis0212 = false,
1807 + /** @type {number} */ iso2022jp_lead = 0x00;
1808 + /**
1809 + * @param {ByteInputStream} byte_pointer The byte stream to decode.
1810 + * @return {?number} The next code point decoded, or null if not enough
1811 + * data exists in the input stream to decode a complete code point.
1812 + */
1813 + this.decode = function(byte_pointer) {
1814 + var bite = byte_pointer.get();
1815 + if (bite !== EOF_byte) {
1816 + byte_pointer.offset(1);
1817 + }
1818 + switch (iso2022jp_state) {
1819 + default:
1820 + case state.ASCII:
1821 + if (bite === 0x1B) {
1822 + iso2022jp_state = state.escape_start;
1823 + return null;
1824 + }
1825 + if (inRange(bite, 0x00, 0x7F)) {
1826 + return bite;
1827 + }
1828 + if (bite === EOF_byte) {
1829 + return EOF_code_point;
1830 + }
1831 + return decoderError(fatal);
1832 +
1833 + case state.escape_start:
1834 + if (bite === 0x24 || bite === 0x28) {
1835 + iso2022jp_lead = bite;
1836 + iso2022jp_state = state.escape_middle;
1837 + return null;
1838 + }
1839 + if (bite !== EOF_byte) {
1840 + byte_pointer.offset(-1);
1841 + }
1842 + iso2022jp_state = state.ASCII;
1843 + return decoderError(fatal);
1844 +
1845 + case state.escape_middle:
1846 + var lead = iso2022jp_lead;
1847 + iso2022jp_lead = 0x00;
1848 + if (lead === 0x24 && (bite === 0x40 || bite === 0x42)) {
1849 + iso2022jp_jis0212 = false;
1850 + iso2022jp_state = state.lead;
1851 + return null;
1852 + }
1853 + if (lead === 0x24 && bite === 0x28) {
1854 + iso2022jp_state = state.escape_final;
1855 + return null;
1856 + }
1857 + if (lead === 0x28 && (bite === 0x42 || bite === 0x4A)) {
1858 + iso2022jp_state = state.ASCII;
1859 + return null;
1860 + }
1861 + if (lead === 0x28 && bite === 0x49) {
1862 + iso2022jp_state = state.Katakana;
1863 + return null;
1864 + }
1865 + if (bite === EOF_byte) {
1866 + byte_pointer.offset(-1);
1867 + } else {
1868 + byte_pointer.offset(-2);
1869 + }
1870 + iso2022jp_state = state.ASCII;
1871 + return decoderError(fatal);
1872 +
1873 + case state.escape_final:
1874 + if (bite === 0x44) {
1875 + iso2022jp_jis0212 = true;
1876 + iso2022jp_state = state.lead;
1877 + return null;
1878 + }
1879 + if (bite === EOF_byte) {
1880 + byte_pointer.offset(-2);
1881 + } else {
1882 + byte_pointer.offset(-3);
1883 + }
1884 + iso2022jp_state = state.ASCII;
1885 + return decoderError(fatal);
1886 +
1887 + case state.lead:
1888 + if (bite === 0x0A) {
1889 + iso2022jp_state = state.ASCII;
1890 + return decoderError(fatal, 0x000A);
1891 + }
1892 + if (bite === 0x1B) {
1893 + iso2022jp_state = state.escape_start;
1894 + return null;
1895 + }
1896 + if (bite === EOF_byte) {
1897 + return EOF_code_point;
1898 + }
1899 + iso2022jp_lead = bite;
1900 + iso2022jp_state = state.trail;
1901 + return null;
1902 +
1903 + case state.trail:
1904 + iso2022jp_state = state.lead;
1905 + if (bite === EOF_byte) {
1906 + return decoderError(fatal);
1907 + }
1908 + var code_point = null;
1909 + var pointer = (iso2022jp_lead - 0x21) * 94 + bite - 0x21;
1910 + if (inRange(iso2022jp_lead, 0x21, 0x7E) &&
1911 + inRange(bite, 0x21, 0x7E)) {
1912 + code_point = (iso2022jp_jis0212 === false) ?
1913 + indexCodePointFor(pointer, indexes['jis0208']) :
1914 + indexCodePointFor(pointer, indexes['jis0212']);
1915 + }
1916 + if (code_point === null) {
1917 + return decoderError(fatal);
1918 + }
1919 + return code_point;
1920 +
1921 + case state.Katakana:
1922 + if (bite === 0x1B) {
1923 + iso2022jp_state = state.escape_start;
1924 + return null;
1925 + }
1926 + if (inRange(bite, 0x21, 0x5F)) {
1927 + return 0xFF61 + bite - 0x21;
1928 + }
1929 + if (bite === EOF_byte) {
1930 + return EOF_code_point;
1931 + }
1932 + return decoderError(fatal);
1933 + }
1934 + };
1935 +}
1936 +
1937 +/**
1938 + * @constructor
1939 + * @param {{fatal: boolean}} options
1940 + */
1941 +function ISO2022JPEncoder(options) {
1942 + var fatal = options.fatal;
1943 + /** @enum */
1944 + var state = {
1945 + ASCII: 0,
1946 + lead: 1,
1947 + Katakana: 2
1948 + };
1949 + var /** @type {number} */ iso2022jp_state = state.ASCII;
1950 + /**
1951 + * @param {ByteOutputStream} output_byte_stream Output byte stream.
1952 + * @param {CodePointInputStream} code_point_pointer Input stream.
1953 + * @return {number} The last byte emitted.
1954 + */
1955 + this.encode = function(output_byte_stream, code_point_pointer) {
1956 + var code_point = code_point_pointer.get();
1957 + if (code_point === EOF_code_point) {
1958 + return EOF_byte;
1959 + }
1960 + code_point_pointer.offset(1);
1961 + if ((inRange(code_point, 0x0000, 0x007F) ||
1962 + code_point === 0x00A5 || code_point === 0x203E) &&
1963 + iso2022jp_state !== state.ASCII) {
1964 + code_point_pointer.offset(-1);
1965 + iso2022jp_state = state.ASCII;
1966 + return output_byte_stream.emit(0x1B, 0x28, 0x42);
1967 + }
1968 + if (inRange(code_point, 0x0000, 0x007F)) {
1969 + return output_byte_stream.emit(code_point);
1970 + }
1971 + if (code_point === 0x00A5) {
1972 + return output_byte_stream.emit(0x5C);
1973 + }
1974 + if (code_point === 0x203E) {
1975 + return output_byte_stream.emit(0x7E);
1976 + }
1977 + if (inRange(code_point, 0xFF61, 0xFF9F) &&
1978 + iso2022jp_state !== state.Katakana) {
1979 + code_point_pointer.offset(-1);
1980 + iso2022jp_state = state.Katakana;
1981 + return output_byte_stream.emit(0x1B, 0x28, 0x49);
1982 + }
1983 + if (inRange(code_point, 0xFF61, 0xFF9F)) {
1984 + return output_byte_stream.emit(code_point - 0xFF61 - 0x21);
1985 + }
1986 + if (iso2022jp_state !== state.lead) {
1987 + code_point_pointer.offset(-1);
1988 + iso2022jp_state = state.lead;
1989 + return output_byte_stream.emit(0x1B, 0x24, 0x42);
1990 + }
1991 + var pointer = indexPointerFor(code_point, indexes['jis0208']);
1992 + if (pointer === null) {
1993 + return encoderError(code_point);
1994 + }
1995 + var lead = div(pointer, 94) + 0x21;
1996 + var trail = pointer % 94 + 0x21;
1997 + return output_byte_stream.emit(lead, trail);
1998 + };
1999 +}
2000 +
2001 +/** @param {{fatal: boolean}} options */
2002 +name_to_encoding['iso-2022-jp'].getEncoder = function(options) {
2003 + return new ISO2022JPEncoder(options);
2004 +};
2005 +/** @param {{fatal: boolean}} options */
2006 +name_to_encoding['iso-2022-jp'].getDecoder = function(options) {
2007 + return new ISO2022JPDecoder(options);
2008 +};
2009 +
2010 +// 12.3 shift_jis
2011 +
2012 +/**
2013 + * @constructor
2014 + * @param {{fatal: boolean}} options
2015 + */
2016 +function ShiftJISDecoder(options) {
2017 + var fatal = options.fatal;
2018 + var /** @type {number} */ shiftjis_lead = 0x00;
2019 + /**
2020 + * @param {ByteInputStream} byte_pointer The byte stream to decode.
2021 + * @return {?number} The next code point decoded, or null if not enough
2022 + * data exists in the input stream to decode a complete code point.
2023 + */
2024 + this.decode = function(byte_pointer) {
2025 + var bite = byte_pointer.get();
2026 + if (bite === EOF_byte && shiftjis_lead === 0x00) {
2027 + return EOF_code_point;
2028 + }
2029 + if (bite === EOF_byte && shiftjis_lead !== 0x00) {
2030 + shiftjis_lead = 0x00;
2031 + return decoderError(fatal);
2032 + }
2033 + byte_pointer.offset(1);
2034 + if (shiftjis_lead !== 0x00) {
2035 + var lead = shiftjis_lead;
2036 + shiftjis_lead = 0x00;
2037 + if (inRange(bite, 0x40, 0x7E) || inRange(bite, 0x80, 0xFC)) {
2038 + var offset = (bite < 0x7F) ? 0x40 : 0x41;
2039 + var lead_offset = (lead < 0xA0) ? 0x81 : 0xC1;
2040 + var code_point = indexCodePointFor((lead - lead_offset) * 188 +
2041 + bite - offset, indexes['jis0208']);
2042 + if (code_point === null) {
2043 + return decoderError(fatal);
2044 + }
2045 + return code_point;
2046 + }
2047 + byte_pointer.offset(-1);
2048 + return decoderError(fatal);
2049 + }
2050 + if (inRange(bite, 0x00, 0x80)) {
2051 + return bite;
2052 + }
2053 + if (inRange(bite, 0xA1, 0xDF)) {
2054 + return 0xFF61 + bite - 0xA1;
2055 + }
2056 + if (inRange(bite, 0x81, 0x9F) || inRange(bite, 0xE0, 0xFC)) {
2057 + shiftjis_lead = bite;
2058 + return null;
2059 + }
2060 + return decoderError(fatal);
2061 + };
2062 +}
2063 +
2064 +/**
2065 + * @constructor
2066 + * @param {{fatal: boolean}} options
2067 + */
2068 +function ShiftJISEncoder(options) {
2069 + var fatal = options.fatal;
2070 + /**
2071 + * @param {ByteOutputStream} output_byte_stream Output byte stream.
2072 + * @param {CodePointInputStream} code_point_pointer Input stream.
2073 + * @return {number} The last byte emitted.
2074 + */
2075 + this.encode = function(output_byte_stream, code_point_pointer) {
2076 + var code_point = code_point_pointer.get();
2077 + if (code_point === EOF_code_point) {
2078 + return EOF_byte;
2079 + }
2080 + code_point_pointer.offset(1);
2081 + if (inRange(code_point, 0x0000, 0x0080)) {
2082 + return output_byte_stream.emit(code_point);
2083 + }
2084 + if (code_point === 0x00A5) {
2085 + return output_byte_stream.emit(0x5C);
2086 + }
2087 + if (code_point === 0x203E) {
2088 + return output_byte_stream.emit(0x7E);
2089 + }
2090 + if (inRange(code_point, 0xFF61, 0xFF9F)) {
2091 + return output_byte_stream.emit(code_point - 0xFF61 + 0xA1);
2092 + }
2093 + var pointer = indexPointerFor(code_point, indexes['jis0208']);
2094 + if (pointer === null) {
2095 + return encoderError(code_point);
2096 + }
2097 + var lead = div(pointer, 188);
2098 + var lead_offset = lead < 0x1F ? 0x81 : 0xC1;
2099 + var trail = pointer % 188;
2100 + var offset = trail < 0x3F ? 0x40 : 0x41;
2101 + return output_byte_stream.emit(lead + lead_offset, trail + offset);
2102 + };
2103 +}
2104 +
2105 +/** @param {{fatal: boolean}} options */
2106 +name_to_encoding['shift_jis'].getEncoder = function(options) {
2107 + return new ShiftJISEncoder(options);
2108 +};
2109 +/** @param {{fatal: boolean}} options */
2110 +name_to_encoding['shift_jis'].getDecoder = function(options) {
2111 + return new ShiftJISDecoder(options);
2112 +};
2113 +
2114 +//
2115 +// 13. Legacy multi-byte Korean encodings
2116 +//
2117 +
2118 +// 13.1 euc-kr
2119 +
2120 +/**
2121 + * @constructor
2122 + * @param {{fatal: boolean}} options
2123 + */
2124 +function EUCKRDecoder(options) {
2125 + var fatal = options.fatal;
2126 + var /** @type {number} */ euckr_lead = 0x00;
2127 + /**
2128 + * @param {ByteInputStream} byte_pointer The byte stream to decode.
2129 + * @return {?number} The next code point decoded, or null if not enough
2130 + * data exists in the input stream to decode a complete code point.
2131 + */
2132 + this.decode = function(byte_pointer) {
2133 + var bite = byte_pointer.get();
2134 + if (bite === EOF_byte && euckr_lead === 0) {
2135 + return EOF_code_point;
2136 + }
2137 + if (bite === EOF_byte && euckr_lead !== 0) {
2138 + euckr_lead = 0x00;
2139 + return decoderError(fatal);
2140 + }
2141 + byte_pointer.offset(1);
2142 + if (euckr_lead !== 0x00) {
2143 + var lead = euckr_lead;
2144 + var pointer = null;
2145 + euckr_lead = 0x00;
2146 +
2147 + if (inRange(lead, 0x81, 0xC6)) {
2148 + var temp = (26 + 26 + 126) * (lead - 0x81);
2149 + if (inRange(bite, 0x41, 0x5A)) {
2150 + pointer = temp + bite - 0x41;
2151 + } else if (inRange(bite, 0x61, 0x7A)) {
2152 + pointer = temp + 26 + bite - 0x61;
2153 + } else if (inRange(bite, 0x81, 0xFE)) {
2154 + pointer = temp + 26 + 26 + bite - 0x81;
2155 + }
2156 + }
2157 +
2158 + if (inRange(lead, 0xC7, 0xFD) && inRange(bite, 0xA1, 0xFE)) {
2159 + pointer = (26 + 26 + 126) * (0xC7 - 0x81) + (lead - 0xC7) * 94 +
2160 + (bite - 0xA1);
2161 + }
2162 +
2163 + var code_point = (pointer === null) ? null :
2164 + indexCodePointFor(pointer, indexes['euc-kr']);
2165 + if (pointer === null) {
2166 + byte_pointer.offset(-1);
2167 + }
2168 + if (code_point === null) {
2169 + return decoderError(fatal);
2170 + }
2171 + return code_point;
2172 + }
2173 +
2174 + if (inRange(bite, 0x00, 0x7F)) {
2175 + return bite;
2176 + }
2177 +
2178 + if (inRange(bite, 0x81, 0xFD)) {
2179 + euckr_lead = bite;
2180 + return null;
2181 + }
2182 +
2183 + return decoderError(fatal);
2184 + };
2185 +}
2186 +
2187 +/**
2188 + * @constructor
2189 + * @param {{fatal: boolean}} options
2190 + */
2191 +function EUCKREncoder(options) {
2192 + var fatal = options.fatal;
2193 + /**
2194 + * @param {ByteOutputStream} output_byte_stream Output byte stream.
2195 + * @param {CodePointInputStream} code_point_pointer Input stream.
2196 + * @return {number} The last byte emitted.
2197 + */
2198 + this.encode = function(output_byte_stream, code_point_pointer) {
2199 + var code_point = code_point_pointer.get();
2200 + if (code_point === EOF_code_point) {
2201 + return EOF_byte;
2202 + }
2203 + code_point_pointer.offset(1);
2204 + if (inRange(code_point, 0x0000, 0x007F)) {
2205 + return output_byte_stream.emit(code_point);
2206 + }
2207 + var pointer = indexPointerFor(code_point, indexes['euc-kr']);
2208 + if (pointer === null) {
2209 + return encoderError(code_point);
2210 + }
2211 + var lead, trail;
2212 + if (pointer < ((26 + 26 + 126) * (0xC7 - 0x81))) {
2213 + lead = div(pointer, (26 + 26 + 126)) + 0x81;
2214 + trail = pointer % (26 + 26 + 126);
2215 + var offset = trail < 26 ? 0x41 : trail < 26 + 26 ? 0x47 : 0x4D;
2216 + return output_byte_stream.emit(lead, trail + offset);
2217 + }
2218 + pointer = pointer - (26 + 26 + 126) * (0xC7 - 0x81);
2219 + lead = div(pointer, 94) + 0xC7;
2220 + trail = pointer % 94 + 0xA1;
2221 + return output_byte_stream.emit(lead, trail);
2222 + };
2223 +}
2224 +
2225 +/** @param {{fatal: boolean}} options */
2226 +name_to_encoding['euc-kr'].getEncoder = function(options) {
2227 + return new EUCKREncoder(options);
2228 +};
2229 +/** @param {{fatal: boolean}} options */
2230 +name_to_encoding['euc-kr'].getDecoder = function(options) {
2231 + return new EUCKRDecoder(options);
2232 +};
2233 +
2234 +
2235 +//
2236 +// 14. Legacy miscellaneous encodings
2237 +//
2238 +
2239 +// 14.1 replacement
2240 +
2241 +// Not needed - API throws TypeError
2242 +
2243 +// 14.2 utf-16
2244 +
2245 +/**
2246 + * @constructor
2247 + * @param {boolean} utf16_be True if big-endian, false if little-endian.
2248 + * @param {{fatal: boolean}} options
2249 + */
2250 +function UTF16Decoder(utf16_be, options) {
2251 + var fatal = options.fatal;
2252 + var /** @type {?number} */ utf16_lead_byte = null,
2253 + /** @type {?number} */ utf16_lead_surrogate = null;
2254 + /**
2255 + * @param {ByteInputStream} byte_pointer The byte stream to decode.
2256 + * @return {?number} The next code point decoded, or null if not enough
2257 + * data exists in the input stream to decode a complete code point.
2258 + */
2259 + this.decode = function(byte_pointer) {
2260 + var bite = byte_pointer.get();
2261 + if (bite === EOF_byte && utf16_lead_byte === null &&
2262 + utf16_lead_surrogate === null) {
2263 + return EOF_code_point;
2264 + }
2265 + if (bite === EOF_byte && (utf16_lead_byte !== null ||
2266 + utf16_lead_surrogate !== null)) {
2267 + return decoderError(fatal);
2268 + }
2269 + byte_pointer.offset(1);
2270 + if (utf16_lead_byte === null) {
2271 + utf16_lead_byte = bite;
2272 + return null;
2273 + }
2274 + var code_point;
2275 + if (utf16_be) {
2276 + code_point = (utf16_lead_byte << 8) + bite;
2277 + } else {
2278 + code_point = (bite << 8) + utf16_lead_byte;
2279 + }
2280 + utf16_lead_byte = null;
2281 + if (utf16_lead_surrogate !== null) {
2282 + var lead_surrogate = utf16_lead_surrogate;
2283 + utf16_lead_surrogate = null;
2284 + if (inRange(code_point, 0xDC00, 0xDFFF)) {
2285 + return 0x10000 + (lead_surrogate - 0xD800) * 0x400 +
2286 + (code_point - 0xDC00);
2287 + }
2288 + byte_pointer.offset(-2);
2289 + return decoderError(fatal);
2290 + }
2291 + if (inRange(code_point, 0xD800, 0xDBFF)) {
2292 + utf16_lead_surrogate = code_point;
2293 + return null;
2294 + }
2295 + if (inRange(code_point, 0xDC00, 0xDFFF)) {
2296 + return decoderError(fatal);
2297 + }
2298 + return code_point;
2299 + };
2300 +}
2301 +
2302 +/**
2303 + * @constructor
2304 + * @param {boolean} utf16_be True if big-endian, false if little-endian.
2305 + * @param {{fatal: boolean}} options
2306 + */
2307 +function UTF16Encoder(utf16_be, options) {
2308 + var fatal = options.fatal;
2309 + /**
2310 + * @param {ByteOutputStream} output_byte_stream Output byte stream.
2311 + * @param {CodePointInputStream} code_point_pointer Input stream.
2312 + * @return {number} The last byte emitted.
2313 + */
2314 + this.encode = function(output_byte_stream, code_point_pointer) {
2315 + /**
2316 + * @param {number} code_unit
2317 + * @return {number} last byte emitted
2318 + */
2319 + function convert_to_bytes(code_unit) {
2320 + var byte1 = code_unit >> 8;
2321 + var byte2 = code_unit & 0x00FF;
2322 + if (utf16_be) {
2323 + return output_byte_stream.emit(byte1, byte2);
2324 + }
2325 + return output_byte_stream.emit(byte2, byte1);
2326 + }
2327 + var code_point = code_point_pointer.get();
2328 + if (code_point === EOF_code_point) {
2329 + return EOF_byte;
2330 + }
2331 + code_point_pointer.offset(1);
2332 + if (inRange(code_point, 0xD800, 0xDFFF)) {
2333 + encoderError(code_point);
2334 + }
2335 + if (code_point <= 0xFFFF) {
2336 + return convert_to_bytes(code_point);
2337 + }
2338 + var lead = div((code_point - 0x10000), 0x400) + 0xD800;
2339 + var trail = ((code_point - 0x10000) % 0x400) + 0xDC00;
2340 + convert_to_bytes(lead);
2341 + return convert_to_bytes(trail);
2342 + };
2343 +}
2344 +
2345 +// 14.3 utf-16be
2346 +/** @param {{fatal: boolean}} options */
2347 +name_to_encoding['utf-16be'].getEncoder = function(options) {
2348 + return new UTF16Encoder(true, options);
2349 +};
2350 +/** @param {{fatal: boolean}} options */
2351 +name_to_encoding['utf-16be'].getDecoder = function(options) {
2352 + return new UTF16Decoder(true, options);
2353 +};
2354 +
2355 +// 14.4 utf-16le
2356 +/** @param {{fatal: boolean}} options */
2357 +name_to_encoding['utf-16le'].getEncoder = function(options) {
2358 + return new UTF16Encoder(false, options);
2359 +};
2360 +/** @param {{fatal: boolean}} options */
2361 +name_to_encoding['utf-16le'].getDecoder = function(options) {
2362 + return new UTF16Decoder(false, options);
2363 +};
2364 +
2365 +// 14.5 x-user-defined
2366 +// TODO: Implement this encoding.
2367 +
2368 +// NOTE: currently unused
2369 +/**
2370 + * @param {string} label The encoding label.
2371 + * @param {ByteInputStream} input_stream The byte stream to test.
2372 + */
2373 +function detectEncoding(label, input_stream) {
2374 + if (input_stream.match([0xFF, 0xFE])) {
2375 + input_stream.offset(2);
2376 + return 'utf-16le';
2377 + }
2378 + if (input_stream.match([0xFE, 0xFF])) {
2379 + input_stream.offset(2);
2380 + return 'utf-16be';
2381 + }
2382 + if (input_stream.match([0xEF, 0xBB, 0xBF])) {
2383 + input_stream.offset(3);
2384 + return 'utf-8';
2385 + }
2386 + return label;
2387 +}
2388 +
2389 +exports.TextEncoder = TextEncoder;
2390 +exports.TextDecoder = TextDecoder;
2391 +exports.encodingExists = getEncoding;
1 +var fs = require('fs'),
2 + WritableStream = require('stream').Writable
3 + || require('readable-stream').Writable,
4 + inherits = require('util').inherits;
5 +
6 +var parseParams = require('./utils').parseParams;
7 +
8 +function Busboy(opts) {
9 + if (!(this instanceof Busboy))
10 + return new Busboy(opts);
11 + if (opts.highWaterMark !== undefined)
12 + WritableStream.call(this, { highWaterMark: opts.highWaterMark });
13 + else
14 + WritableStream.call(this);
15 +
16 + this._done = false;
17 + this._parser = undefined;
18 + this._finished = false;
19 +
20 + this.opts = opts;
21 + if (opts.headers && typeof opts.headers['content-type'] === 'string')
22 + this.parseHeaders(opts.headers);
23 + else
24 + throw new Error('Missing Content-Type');
25 +}
26 +inherits(Busboy, WritableStream);
27 +
28 +Busboy.prototype.emit = function(ev) {
29 + if (ev === 'finish') {
30 + if (!this._done) {
31 + this._parser && this._parser.end();
32 + return;
33 + } else if (this._finished) {
34 + return;
35 + }
36 + this._finished = true;
37 + }
38 + WritableStream.prototype.emit.apply(this, arguments);
39 +};
40 +
41 +Busboy.prototype.parseHeaders = function(headers) {
42 + this._parser = undefined;
43 + if (headers['content-type']) {
44 + var parsed = parseParams(headers['content-type']),
45 + matched, type;
46 + for (var i = 0; i < TYPES.length; ++i) {
47 + type = TYPES[i];
48 + if (typeof type.detect === 'function')
49 + matched = type.detect(parsed);
50 + else
51 + matched = type.detect.test(parsed[0]);
52 + if (matched)
53 + break;
54 + }
55 + if (matched) {
56 + var cfg = {
57 + limits: this.opts.limits,
58 + headers: headers,
59 + parsedConType: parsed,
60 + highWaterMark: undefined,
61 + fileHwm: undefined,
62 + defCharset: undefined,
63 + preservePath: false
64 + };
65 + if (this.opts.highWaterMark)
66 + cfg.highWaterMark = this.opts.highWaterMark;
67 + if (this.opts.fileHwm)
68 + cfg.fileHwm = this.opts.fileHwm;
69 + cfg.defCharset = this.opts.defCharset;
70 + cfg.preservePath = this.opts.preservePath;
71 + this._parser = type(this, cfg);
72 + return;
73 + }
74 + }
75 + throw new Error('Unsupported content type: ' + headers['content-type']);
76 +};
77 +
78 +Busboy.prototype._write = function(chunk, encoding, cb) {
79 + if (!this._parser)
80 + return cb(new Error('Not ready to parse. Missing Content-Type?'));
81 + this._parser.write(chunk, cb);
82 +};
83 +
84 +var TYPES = [
85 + require('./types/multipart'),
86 + require('./types/urlencoded'),
87 +];
88 +
89 +module.exports = Busboy;
1 +// TODO:
2 +// * support 1 nested multipart level
3 +// (see second multipart example here:
4 +// http://www.w3.org/TR/html401/interact/forms.html#didx-multipartform-data)
5 +// * support limits.fieldNameSize
6 +// -- this will require modifications to utils.parseParams
7 +
8 +var ReadableStream = require('stream').Readable || require('readable-stream'),
9 + inherits = require('util').inherits;
10 +
11 +var Dicer = require('dicer');
12 +
13 +var parseParams = require('../utils').parseParams,
14 + decodeText = require('../utils').decodeText,
15 + basename = require('../utils').basename;
16 +
17 +var RE_BOUNDARY = /^boundary$/i,
18 + RE_FIELD = /^form-data$/i,
19 + RE_CHARSET = /^charset$/i,
20 + RE_FILENAME = /^filename$/i,
21 + RE_NAME = /^name$/i;
22 +
23 +Multipart.detect = /^multipart\/form-data/i;
24 +function Multipart(boy, cfg) {
25 + if (!(this instanceof Multipart))
26 + return new Multipart(boy, cfg);
27 + var i,
28 + len,
29 + self = this,
30 + boundary,
31 + limits = cfg.limits,
32 + parsedConType = cfg.parsedConType || [],
33 + defCharset = cfg.defCharset || 'utf8',
34 + preservePath = cfg.preservePath,
35 + fileopts = (typeof cfg.fileHwm === 'number'
36 + ? { highWaterMark: cfg.fileHwm }
37 + : {});
38 +
39 + for (i = 0, len = parsedConType.length; i < len; ++i) {
40 + if (Array.isArray(parsedConType[i])
41 + && RE_BOUNDARY.test(parsedConType[i][0])) {
42 + boundary = parsedConType[i][1];
43 + break;
44 + }
45 + }
46 +
47 + function checkFinished() {
48 + if (nends === 0 && finished && !boy._done) {
49 + finished = false;
50 + process.nextTick(function() {
51 + boy._done = true;
52 + boy.emit('finish');
53 + });
54 + }
55 + }
56 +
57 + if (typeof boundary !== 'string')
58 + throw new Error('Multipart: Boundary not found');
59 +
60 + var fieldSizeLimit = (limits && typeof limits.fieldSize === 'number'
61 + ? limits.fieldSize
62 + : 1 * 1024 * 1024),
63 + fileSizeLimit = (limits && typeof limits.fileSize === 'number'
64 + ? limits.fileSize
65 + : Infinity),
66 + filesLimit = (limits && typeof limits.files === 'number'
67 + ? limits.files
68 + : Infinity),
69 + fieldsLimit = (limits && typeof limits.fields === 'number'
70 + ? limits.fields
71 + : Infinity),
72 + partsLimit = (limits && typeof limits.parts === 'number'
73 + ? limits.parts
74 + : Infinity);
75 +
76 + var nfiles = 0,
77 + nfields = 0,
78 + nends = 0,
79 + curFile,
80 + curField,
81 + finished = false;
82 +
83 + this._needDrain = false;
84 + this._pause = false;
85 + this._cb = undefined;
86 + this._nparts = 0;
87 + this._boy = boy;
88 +
89 + var parserCfg = {
90 + boundary: boundary,
91 + maxHeaderPairs: (limits && limits.headerPairs)
92 + };
93 + if (fileopts.highWaterMark)
94 + parserCfg.partHwm = fileopts.highWaterMark;
95 + if (cfg.highWaterMark)
96 + parserCfg.highWaterMark = cfg.highWaterMark;
97 +
98 + this.parser = new Dicer(parserCfg);
99 + this.parser.on('drain', function() {
100 + self._needDrain = false;
101 + if (self._cb && !self._pause) {
102 + var cb = self._cb;
103 + self._cb = undefined;
104 + cb();
105 + }
106 + }).on('part', function onPart(part) {
107 + if (++self._nparts > partsLimit) {
108 + self.parser.removeListener('part', onPart);
109 + self.parser.on('part', skipPart);
110 + boy.hitPartsLimit = true;
111 + boy.emit('partsLimit');
112 + return skipPart(part);
113 + }
114 +
115 + // hack because streams2 _always_ doesn't emit 'end' until nextTick, so let
116 + // us emit 'end' early since we know the part has ended if we are already
117 + // seeing the next part
118 + if (curField) {
119 + var field = curField;
120 + field.emit('end');
121 + field.removeAllListeners('end');
122 + }
123 +
124 + part.on('header', function(header) {
125 + var contype,
126 + fieldname,
127 + parsed,
128 + charset,
129 + encoding,
130 + filename,
131 + nsize = 0;
132 +
133 + if (header['content-type']) {
134 + parsed = parseParams(header['content-type'][0]);
135 + if (parsed[0]) {
136 + contype = parsed[0].toLowerCase();
137 + for (i = 0, len = parsed.length; i < len; ++i) {
138 + if (RE_CHARSET.test(parsed[i][0])) {
139 + charset = parsed[i][1].toLowerCase();
140 + break;
141 + }
142 + }
143 + }
144 + }
145 +
146 + if (contype === undefined)
147 + contype = 'text/plain';
148 + if (charset === undefined)
149 + charset = defCharset;
150 +
151 + if (header['content-disposition']) {
152 + parsed = parseParams(header['content-disposition'][0]);
153 + if (!RE_FIELD.test(parsed[0]))
154 + return skipPart(part);
155 + for (i = 0, len = parsed.length; i < len; ++i) {
156 + if (RE_NAME.test(parsed[i][0])) {
157 + fieldname = decodeText(parsed[i][1], 'binary', 'utf8');
158 + } else if (RE_FILENAME.test(parsed[i][0])) {
159 + filename = decodeText(parsed[i][1], 'binary', 'utf8');
160 + if (!preservePath)
161 + filename = basename(filename);
162 + }
163 + }
164 + } else
165 + return skipPart(part);
166 +
167 + if (header['content-transfer-encoding'])
168 + encoding = header['content-transfer-encoding'][0].toLowerCase();
169 + else
170 + encoding = '7bit';
171 +
172 + var onData,
173 + onEnd;
174 + if (contype === 'application/octet-stream' || filename !== undefined) {
175 + // file/binary field
176 + if (nfiles === filesLimit) {
177 + if (!boy.hitFilesLimit) {
178 + boy.hitFilesLimit = true;
179 + boy.emit('filesLimit');
180 + }
181 + return skipPart(part);
182 + }
183 +
184 + ++nfiles;
185 +
186 + if (!boy._events.file) {
187 + self.parser._ignore();
188 + return;
189 + }
190 +
191 + ++nends;
192 + var file = new FileStream(fileopts);
193 + curFile = file;
194 + file.on('end', function() {
195 + --nends;
196 + checkFinished();
197 + if (self._cb && !self._needDrain) {
198 + var cb = self._cb;
199 + self._cb = undefined;
200 + cb();
201 + }
202 + });
203 + file._read = function(n) {
204 + if (!self._pause)
205 + return;
206 + self._pause = false;
207 + if (self._cb && !self._needDrain) {
208 + var cb = self._cb;
209 + self._cb = undefined;
210 + cb();
211 + }
212 + };
213 + boy.emit('file', fieldname, file, filename, encoding, contype);
214 +
215 + onData = function(data) {
216 + if ((nsize += data.length) > fileSizeLimit) {
217 + var extralen = (fileSizeLimit - (nsize - data.length));
218 + if (extralen > 0)
219 + file.push(data.slice(0, extralen));
220 + file.emit('limit');
221 + file.truncated = true;
222 + part.removeAllListeners('data');
223 + } else if (!file.push(data))
224 + self._pause = true;
225 + };
226 +
227 + onEnd = function() {
228 + curFile = undefined;
229 + file.push(null);
230 + };
231 + } else {
232 + // non-file field
233 + if (nfields === fieldsLimit) {
234 + if (!boy.hitFieldsLimit) {
235 + boy.hitFieldsLimit = true;
236 + boy.emit('fieldsLimit');
237 + }
238 + return skipPart(part);
239 + }
240 +
241 + ++nfields;
242 + ++nends;
243 + var buffer = '',
244 + truncated = false;
245 + curField = part;
246 +
247 + onData = function(data) {
248 + if ((nsize += data.length) > fieldSizeLimit) {
249 + var extralen = (fieldSizeLimit - (nsize - data.length));
250 + buffer += data.toString('binary', 0, extralen);
251 + truncated = true;
252 + part.removeAllListeners('data');
253 + } else
254 + buffer += data.toString('binary');
255 + };
256 +
257 + onEnd = function() {
258 + curField = undefined;
259 + if (buffer.length)
260 + buffer = decodeText(buffer, 'binary', charset);
261 + boy.emit('field', fieldname, buffer, false, truncated, encoding, contype);
262 + --nends;
263 + checkFinished();
264 + };
265 + }
266 +
267 + /* As of node@2efe4ab761666 (v0.10.29+/v0.11.14+), busboy had become
268 + broken. Streams2/streams3 is a huge black box of confusion, but
269 + somehow overriding the sync state seems to fix things again (and still
270 + seems to work for previous node versions).
271 + */
272 + part._readableState.sync = false;
273 +
274 + part.on('data', onData);
275 + part.on('end', onEnd);
276 + }).on('error', function(err) {
277 + if (curFile)
278 + curFile.emit('error', err);
279 + });
280 + }).on('error', function(err) {
281 + boy.emit('error', err);
282 + }).on('finish', function() {
283 + finished = true;
284 + checkFinished();
285 + });
286 +}
287 +
288 +Multipart.prototype.write = function(chunk, cb) {
289 + var r;
290 + if ((r = this.parser.write(chunk)) && !this._pause)
291 + cb();
292 + else {
293 + this._needDrain = !r;
294 + this._cb = cb;
295 + }
296 +};
297 +
298 +Multipart.prototype.end = function() {
299 + var self = this;
300 + if (this._nparts === 0 && !self._boy._done) {
301 + process.nextTick(function() {
302 + self._boy._done = true;
303 + self._boy.emit('finish');
304 + });
305 + } else if (this.parser.writable)
306 + this.parser.end();
307 +};
308 +
309 +function skipPart(part) {
310 + part.resume();
311 +}
312 +
313 +function FileStream(opts) {
314 + if (!(this instanceof FileStream))
315 + return new FileStream(opts);
316 + ReadableStream.call(this, opts);
317 +
318 + this.truncated = false;
319 +}
320 +inherits(FileStream, ReadableStream);
321 +
322 +FileStream.prototype._read = function(n) {};
323 +
324 +module.exports = Multipart;
1 +var Decoder = require('../utils').Decoder,
2 + decodeText = require('../utils').decodeText;
3 +
4 +var RE_CHARSET = /^charset$/i;
5 +
6 +UrlEncoded.detect = /^application\/x-www-form-urlencoded/i;
7 +function UrlEncoded(boy, cfg) {
8 + if (!(this instanceof UrlEncoded))
9 + return new UrlEncoded(boy, cfg);
10 + var limits = cfg.limits,
11 + headers = cfg.headers,
12 + parsedConType = cfg.parsedConType;
13 + this.boy = boy;
14 +
15 + this.fieldSizeLimit = (limits && typeof limits.fieldSize === 'number'
16 + ? limits.fieldSize
17 + : 1 * 1024 * 1024);
18 + this.fieldNameSizeLimit = (limits && typeof limits.fieldNameSize === 'number'
19 + ? limits.fieldNameSize
20 + : 100);
21 + this.fieldsLimit = (limits && typeof limits.fields === 'number'
22 + ? limits.fields
23 + : Infinity);
24 +
25 + var charset;
26 + for (var i = 0, len = parsedConType.length; i < len; ++i) {
27 + if (Array.isArray(parsedConType[i])
28 + && RE_CHARSET.test(parsedConType[i][0])) {
29 + charset = parsedConType[i][1].toLowerCase();
30 + break;
31 + }
32 + }
33 +
34 + if (charset === undefined)
35 + charset = cfg.defCharset || 'utf8';
36 +
37 + this.decoder = new Decoder();
38 + this.charset = charset;
39 + this._fields = 0;
40 + this._state = 'key';
41 + this._checkingBytes = true;
42 + this._bytesKey = 0;
43 + this._bytesVal = 0;
44 + this._key = '';
45 + this._val = '';
46 + this._keyTrunc = false;
47 + this._valTrunc = false;
48 + this._hitlimit = false;
49 +}
50 +
51 +UrlEncoded.prototype.write = function(data, cb) {
52 + if (this._fields === this.fieldsLimit) {
53 + if (!this.boy.hitFieldsLimit) {
54 + this.boy.hitFieldsLimit = true;
55 + this.boy.emit('fieldsLimit');
56 + }
57 + return cb();
58 + }
59 +
60 + var idxeq, idxamp, i, p = 0, len = data.length;
61 +
62 + while (p < len) {
63 + if (this._state === 'key') {
64 + idxeq = idxamp = undefined;
65 + for (i = p; i < len; ++i) {
66 + if (!this._checkingBytes)
67 + ++p;
68 + if (data[i] === 0x3D/*=*/) {
69 + idxeq = i;
70 + break;
71 + } else if (data[i] === 0x26/*&*/) {
72 + idxamp = i;
73 + break;
74 + }
75 + if (this._checkingBytes && this._bytesKey === this.fieldNameSizeLimit) {
76 + this._hitLimit = true;
77 + break;
78 + } else if (this._checkingBytes)
79 + ++this._bytesKey;
80 + }
81 +
82 + if (idxeq !== undefined) {
83 + // key with assignment
84 + if (idxeq > p)
85 + this._key += this.decoder.write(data.toString('binary', p, idxeq));
86 + this._state = 'val';
87 +
88 + this._hitLimit = false;
89 + this._checkingBytes = true;
90 + this._val = '';
91 + this._bytesVal = 0;
92 + this._valTrunc = false;
93 + this.decoder.reset();
94 +
95 + p = idxeq + 1;
96 + } else if (idxamp !== undefined) {
97 + // key with no assignment
98 + ++this._fields;
99 + var key, keyTrunc = this._keyTrunc;
100 + if (idxamp > p)
101 + key = (this._key += this.decoder.write(data.toString('binary', p, idxamp)));
102 + else
103 + key = this._key;
104 +
105 + this._hitLimit = false;
106 + this._checkingBytes = true;
107 + this._key = '';
108 + this._bytesKey = 0;
109 + this._keyTrunc = false;
110 + this.decoder.reset();
111 +
112 + if (key.length) {
113 + this.boy.emit('field', decodeText(key, 'binary', this.charset),
114 + '',
115 + keyTrunc,
116 + false);
117 + }
118 +
119 + p = idxamp + 1;
120 + if (this._fields === this.fieldsLimit)
121 + return cb();
122 + } else if (this._hitLimit) {
123 + // we may not have hit the actual limit if there are encoded bytes...
124 + if (i > p)
125 + this._key += this.decoder.write(data.toString('binary', p, i));
126 + p = i;
127 + if ((this._bytesKey = this._key.length) === this.fieldNameSizeLimit) {
128 + // yep, we actually did hit the limit
129 + this._checkingBytes = false;
130 + this._keyTrunc = true;
131 + }
132 + } else {
133 + if (p < len)
134 + this._key += this.decoder.write(data.toString('binary', p));
135 + p = len;
136 + }
137 + } else {
138 + idxamp = undefined;
139 + for (i = p; i < len; ++i) {
140 + if (!this._checkingBytes)
141 + ++p;
142 + if (data[i] === 0x26/*&*/) {
143 + idxamp = i;
144 + break;
145 + }
146 + if (this._checkingBytes && this._bytesVal === this.fieldSizeLimit) {
147 + this._hitLimit = true;
148 + break;
149 + }
150 + else if (this._checkingBytes)
151 + ++this._bytesVal;
152 + }
153 +
154 + if (idxamp !== undefined) {
155 + ++this._fields;
156 + if (idxamp > p)
157 + this._val += this.decoder.write(data.toString('binary', p, idxamp));
158 + this.boy.emit('field', decodeText(this._key, 'binary', this.charset),
159 + decodeText(this._val, 'binary', this.charset),
160 + this._keyTrunc,
161 + this._valTrunc);
162 + this._state = 'key';
163 +
164 + this._hitLimit = false;
165 + this._checkingBytes = true;
166 + this._key = '';
167 + this._bytesKey = 0;
168 + this._keyTrunc = false;
169 + this.decoder.reset();
170 +
171 + p = idxamp + 1;
172 + if (this._fields === this.fieldsLimit)
173 + return cb();
174 + } else if (this._hitLimit) {
175 + // we may not have hit the actual limit if there are encoded bytes...
176 + if (i > p)
177 + this._val += this.decoder.write(data.toString('binary', p, i));
178 + p = i;
179 + if ((this._val === '' && this.fieldSizeLimit === 0)
180 + || (this._bytesVal = this._val.length) === this.fieldSizeLimit) {
181 + // yep, we actually did hit the limit
182 + this._checkingBytes = false;
183 + this._valTrunc = true;
184 + }
185 + } else {
186 + if (p < len)
187 + this._val += this.decoder.write(data.toString('binary', p));
188 + p = len;
189 + }
190 + }
191 + }
192 + cb();
193 +};
194 +
195 +UrlEncoded.prototype.end = function() {
196 + if (this.boy._done)
197 + return;
198 +
199 + if (this._state === 'key' && this._key.length > 0) {
200 + this.boy.emit('field', decodeText(this._key, 'binary', this.charset),
201 + '',
202 + this._keyTrunc,
203 + false);
204 + } else if (this._state === 'val') {
205 + this.boy.emit('field', decodeText(this._key, 'binary', this.charset),
206 + decodeText(this._val, 'binary', this.charset),
207 + this._keyTrunc,
208 + this._valTrunc);
209 + }
210 + this.boy._done = true;
211 + this.boy.emit('finish');
212 +};
213 +
214 +module.exports = UrlEncoded;
1 +var jsencoding = require('../deps/encoding/encoding');
2 +
3 +var RE_ENCODED = /%([a-fA-F0-9]{2})/g;
4 +function encodedReplacer(match, byte) {
5 + return String.fromCharCode(parseInt(byte, 16));
6 +}
7 +function parseParams(str) {
8 + var res = [],
9 + state = 'key',
10 + charset = '',
11 + inquote = false,
12 + escaping = false,
13 + p = 0,
14 + tmp = '';
15 +
16 + for (var i = 0, len = str.length; i < len; ++i) {
17 + if (str[i] === '\\' && inquote) {
18 + if (escaping)
19 + escaping = false;
20 + else {
21 + escaping = true;
22 + continue;
23 + }
24 + } else if (str[i] === '"') {
25 + if (!escaping) {
26 + if (inquote) {
27 + inquote = false;
28 + state = 'key';
29 + } else
30 + inquote = true;
31 + continue;
32 + } else
33 + escaping = false;
34 + } else {
35 + if (escaping && inquote)
36 + tmp += '\\';
37 + escaping = false;
38 + if ((state === 'charset' || state === 'lang') && str[i] === "'") {
39 + if (state === 'charset') {
40 + state = 'lang';
41 + charset = tmp.substring(1);
42 + } else
43 + state = 'value';
44 + tmp = '';
45 + continue;
46 + } else if (state === 'key'
47 + && (str[i] === '*' || str[i] === '=')
48 + && res.length) {
49 + if (str[i] === '*')
50 + state = 'charset';
51 + else
52 + state = 'value';
53 + res[p] = [tmp, undefined];
54 + tmp = '';
55 + continue;
56 + } else if (!inquote && str[i] === ';') {
57 + state = 'key';
58 + if (charset) {
59 + if (tmp.length) {
60 + tmp = decodeText(tmp.replace(RE_ENCODED, encodedReplacer),
61 + 'binary',
62 + charset);
63 + }
64 + charset = '';
65 + }
66 + if (res[p] === undefined)
67 + res[p] = tmp;
68 + else
69 + res[p][1] = tmp;
70 + tmp = '';
71 + ++p;
72 + continue;
73 + } else if (!inquote && (str[i] === ' ' || str[i] === '\t'))
74 + continue;
75 + }
76 + tmp += str[i];
77 + }
78 + if (charset && tmp.length) {
79 + tmp = decodeText(tmp.replace(RE_ENCODED, encodedReplacer),
80 + 'binary',
81 + charset);
82 + }
83 +
84 + if (res[p] === undefined) {
85 + if (tmp)
86 + res[p] = tmp;
87 + } else
88 + res[p][1] = tmp;
89 +
90 + return res;
91 +};
92 +exports.parseParams = parseParams;
93 +
94 +
95 +function decodeText(text, textEncoding, destEncoding) {
96 + var ret;
97 + if (text && jsencoding.encodingExists(destEncoding)) {
98 + try {
99 + ret = jsencoding.TextDecoder(destEncoding)
100 + .decode(new Buffer(text, textEncoding));
101 + } catch(e) {}
102 + }
103 + return (typeof ret === 'string' ? ret : text);
104 +}
105 +exports.decodeText = decodeText;
106 +
107 +
108 +var HEX = [
109 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
110 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
111 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
112 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,
113 + 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0,
114 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
115 + 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0,
116 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
117 +], RE_PLUS = /\+/g;
118 +function Decoder() {
119 + this.buffer = undefined;
120 +}
121 +Decoder.prototype.write = function(str) {
122 + // Replace '+' with ' ' before decoding
123 + str = str.replace(RE_PLUS, ' ');
124 + var res = '';
125 + var i = 0, p = 0, len = str.length;
126 + for (; i < len; ++i) {
127 + if (this.buffer !== undefined) {
128 + if (!HEX[str.charCodeAt(i)]) {
129 + res += '%' + this.buffer;
130 + this.buffer = undefined;
131 + --i; // retry character
132 + } else {
133 + this.buffer += str[i];
134 + ++p;
135 + if (this.buffer.length === 2) {
136 + res += String.fromCharCode(parseInt(this.buffer, 16));
137 + this.buffer = undefined;
138 + }
139 + }
140 + } else if (str[i] === '%') {
141 + if (i > p) {
142 + res += str.substring(p, i);
143 + p = i;
144 + }
145 + this.buffer = '';
146 + ++p;
147 + }
148 + }
149 + if (p < len && this.buffer === undefined)
150 + res += str.substring(p);
151 + return res;
152 +};
153 +Decoder.prototype.reset = function() {
154 + this.buffer = undefined;
155 +};
156 +exports.Decoder = Decoder;
157 +
158 +
159 +var RE_SPLIT_POSIX =
160 + /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/,
161 + RE_SPLIT_DEVICE =
162 + /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/,
163 + RE_SPLIT_WINDOWS =
164 + /^([\s\S]*?)((?:\.{1,2}|[^\\\/]+?|)(\.[^.\/\\]*|))(?:[\\\/]*)$/;
165 +function splitPathPosix(filename) {
166 + return RE_SPLIT_POSIX.exec(filename).slice(1);
167 +}
168 +function splitPathWindows(filename) {
169 + // Separate device+slash from tail
170 + var result = RE_SPLIT_DEVICE.exec(filename),
171 + device = (result[1] || '') + (result[2] || ''),
172 + tail = result[3] || '';
173 + // Split the tail into dir, basename and extension
174 + var result2 = RE_SPLIT_WINDOWS.exec(tail),
175 + dir = result2[1],
176 + basename = result2[2],
177 + ext = result2[3];
178 + return [device, dir, basename, ext];
179 +}
180 +function basename(path) {
181 + var f = splitPathPosix(path)[2];
182 + if (f === path)
183 + f = splitPathWindows(path)[2];
184 + return f;
185 +}
186 +exports.basename = basename;
...\ No newline at end of file ...\ No newline at end of file
1 +{
2 + "_from": "busboy@^0.2.11",
3 + "_id": "busboy@0.2.14",
4 + "_inBundle": false,
5 + "_integrity": "sha1-bCpiLvz0fFe7vh4qnDetNseSVFM=",
6 + "_location": "/busboy",
7 + "_phantomChildren": {},
8 + "_requested": {
9 + "type": "range",
10 + "registry": true,
11 + "raw": "busboy@^0.2.11",
12 + "name": "busboy",
13 + "escapedName": "busboy",
14 + "rawSpec": "^0.2.11",
15 + "saveSpec": null,
16 + "fetchSpec": "^0.2.11"
17 + },
18 + "_requiredBy": [
19 + "/multer"
20 + ],
21 + "_resolved": "https://registry.npmjs.org/busboy/-/busboy-0.2.14.tgz",
22 + "_shasum": "6c2a622efcf47c57bbbe1e2a9c37ad36c7925453",
23 + "_spec": "busboy@^0.2.11",
24 + "_where": "C:\\Users\\1000c\\이것저것\\옾소\\Voicoding\\node_modules\\multer",
25 + "author": {
26 + "name": "Brian White",
27 + "email": "mscdex@mscdex.net"
28 + },
29 + "bugs": {
30 + "url": "https://github.com/mscdex/busboy/issues"
31 + },
32 + "bundleDependencies": false,
33 + "dependencies": {
34 + "dicer": "0.2.5",
35 + "readable-stream": "1.1.x"
36 + },
37 + "deprecated": false,
38 + "description": "A streaming parser for HTML form data for node.js",
39 + "engines": {
40 + "node": ">=0.8.0"
41 + },
42 + "homepage": "https://github.com/mscdex/busboy#readme",
43 + "keywords": [
44 + "uploads",
45 + "forms",
46 + "multipart",
47 + "form-data"
48 + ],
49 + "licenses": [
50 + {
51 + "type": "MIT",
52 + "url": "http://github.com/mscdex/busboy/raw/master/LICENSE"
53 + }
54 + ],
55 + "main": "./lib/main",
56 + "name": "busboy",
57 + "repository": {
58 + "type": "git",
59 + "url": "git+ssh://git@github.com/mscdex/busboy.git"
60 + },
61 + "scripts": {
62 + "test": "node test/test.js"
63 + },
64 + "version": "0.2.14"
65 +}
1 +var Busboy = require('..');
2 +
3 +var path = require('path'),
4 + inspect = require('util').inspect,
5 + assert = require('assert');
6 +
7 +var EMPTY_FN = function() {};
8 +
9 +var t = 0,
10 + group = path.basename(__filename, '.js') + '/';
11 +var tests = [
12 + { source: [
13 + ['-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k',
14 + 'Content-Disposition: form-data; name="file_name_0"',
15 + '',
16 + 'super alpha file',
17 + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k',
18 + 'Content-Disposition: form-data; name="file_name_1"',
19 + '',
20 + 'super beta file',
21 + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k',
22 + 'Content-Disposition: form-data; name="upload_file_0"; filename="1k_a.dat"',
23 + 'Content-Type: application/octet-stream',
24 + '',
25 + 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA',
26 + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k',
27 + 'Content-Disposition: form-data; name="upload_file_1"; filename="1k_b.dat"',
28 + 'Content-Type: application/octet-stream',
29 + '',
30 + 'BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB',
31 + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k--'
32 + ].join('\r\n')
33 + ],
34 + boundary: '---------------------------paZqsnEHRufoShdX6fh0lUhXBP4k',
35 + expected: [
36 + ['field', 'file_name_0', 'super alpha file', false, false, '7bit', 'text/plain'],
37 + ['field', 'file_name_1', 'super beta file', false, false, '7bit', 'text/plain'],
38 + ['file', 'upload_file_0', 1023, 0, '1k_a.dat', '7bit', 'application/octet-stream'],
39 + ['file', 'upload_file_1', 1023, 0, '1k_b.dat', '7bit', 'application/octet-stream']
40 + ],
41 + what: 'Fields and files'
42 + },
43 + { source: [
44 + ['------WebKitFormBoundaryTB2MiQ36fnSJlrhY',
45 + 'Content-Disposition: form-data; name="cont"',
46 + '',
47 + 'some random content',
48 + '------WebKitFormBoundaryTB2MiQ36fnSJlrhY',
49 + 'Content-Disposition: form-data; name="pass"',
50 + '',
51 + 'some random pass',
52 + '------WebKitFormBoundaryTB2MiQ36fnSJlrhY',
53 + 'Content-Disposition: form-data; name="bit"',
54 + '',
55 + '2',
56 + '------WebKitFormBoundaryTB2MiQ36fnSJlrhY--'
57 + ].join('\r\n')
58 + ],
59 + boundary: '----WebKitFormBoundaryTB2MiQ36fnSJlrhY',
60 + expected: [
61 + ['field', 'cont', 'some random content', false, false, '7bit', 'text/plain'],
62 + ['field', 'pass', 'some random pass', false, false, '7bit', 'text/plain'],
63 + ['field', 'bit', '2', false, false, '7bit', 'text/plain']
64 + ],
65 + what: 'Fields only'
66 + },
67 + { source: [
68 + ''
69 + ],
70 + boundary: '----WebKitFormBoundaryTB2MiQ36fnSJlrhY',
71 + expected: [],
72 + what: 'No fields and no files'
73 + },
74 + { source: [
75 + ['-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k',
76 + 'Content-Disposition: form-data; name="file_name_0"',
77 + '',
78 + 'super alpha file',
79 + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k',
80 + 'Content-Disposition: form-data; name="upload_file_0"; filename="1k_a.dat"',
81 + 'Content-Type: application/octet-stream',
82 + '',
83 + 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
84 + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k--'
85 + ].join('\r\n')
86 + ],
87 + boundary: '---------------------------paZqsnEHRufoShdX6fh0lUhXBP4k',
88 + limits: {
89 + fileSize: 13,
90 + fieldSize: 5
91 + },
92 + expected: [
93 + ['field', 'file_name_0', 'super', false, true, '7bit', 'text/plain'],
94 + ['file', 'upload_file_0', 13, 2, '1k_a.dat', '7bit', 'application/octet-stream']
95 + ],
96 + what: 'Fields and files (limits)'
97 + },
98 + { source: [
99 + ['-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k',
100 + 'Content-Disposition: form-data; name="file_name_0"',
101 + '',
102 + 'super alpha file',
103 + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k',
104 + 'Content-Disposition: form-data; name="upload_file_0"; filename="1k_a.dat"',
105 + 'Content-Type: application/octet-stream',
106 + '',
107 + 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
108 + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k--'
109 + ].join('\r\n')
110 + ],
111 + boundary: '---------------------------paZqsnEHRufoShdX6fh0lUhXBP4k',
112 + limits: {
113 + files: 0
114 + },
115 + expected: [
116 + ['field', 'file_name_0', 'super alpha file', false, false, '7bit', 'text/plain']
117 + ],
118 + what: 'Fields and files (limits: 0 files)'
119 + },
120 + { source: [
121 + ['-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k',
122 + 'Content-Disposition: form-data; name="file_name_0"',
123 + '',
124 + 'super alpha file',
125 + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k',
126 + 'Content-Disposition: form-data; name="file_name_1"',
127 + '',
128 + 'super beta file',
129 + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k',
130 + 'Content-Disposition: form-data; name="upload_file_0"; filename="1k_a.dat"',
131 + 'Content-Type: application/octet-stream',
132 + '',
133 + 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA',
134 + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k',
135 + 'Content-Disposition: form-data; name="upload_file_1"; filename="1k_b.dat"',
136 + 'Content-Type: application/octet-stream',
137 + '',
138 + 'BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB',
139 + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k--'
140 + ].join('\r\n')
141 + ],
142 + boundary: '---------------------------paZqsnEHRufoShdX6fh0lUhXBP4k',
143 + expected: [
144 + ['field', 'file_name_0', 'super alpha file', false, false, '7bit', 'text/plain'],
145 + ['field', 'file_name_1', 'super beta file', false, false, '7bit', 'text/plain'],
146 + ],
147 + events: ['field'],
148 + what: 'Fields and (ignored) files'
149 + },
150 + { source: [
151 + ['-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k',
152 + 'Content-Disposition: form-data; name="upload_file_0"; filename="/tmp/1k_a.dat"',
153 + 'Content-Type: application/octet-stream',
154 + '',
155 + 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
156 + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k',
157 + 'Content-Disposition: form-data; name="upload_file_1"; filename="C:\\files\\1k_b.dat"',
158 + 'Content-Type: application/octet-stream',
159 + '',
160 + 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
161 + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k',
162 + 'Content-Disposition: form-data; name="upload_file_2"; filename="relative/1k_c.dat"',
163 + 'Content-Type: application/octet-stream',
164 + '',
165 + 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
166 + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k--'
167 + ].join('\r\n')
168 + ],
169 + boundary: '---------------------------paZqsnEHRufoShdX6fh0lUhXBP4k',
170 + expected: [
171 + ['file', 'upload_file_0', 26, 0, '1k_a.dat', '7bit', 'application/octet-stream'],
172 + ['file', 'upload_file_1', 26, 0, '1k_b.dat', '7bit', 'application/octet-stream'],
173 + ['file', 'upload_file_2', 26, 0, '1k_c.dat', '7bit', 'application/octet-stream']
174 + ],
175 + what: 'Files with filenames containing paths'
176 + },
177 + { source: [
178 + ['-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k',
179 + 'Content-Disposition: form-data; name="upload_file_0"; filename="/absolute/1k_a.dat"',
180 + 'Content-Type: application/octet-stream',
181 + '',
182 + 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
183 + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k',
184 + 'Content-Disposition: form-data; name="upload_file_1"; filename="C:\\absolute\\1k_b.dat"',
185 + 'Content-Type: application/octet-stream',
186 + '',
187 + 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
188 + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k',
189 + 'Content-Disposition: form-data; name="upload_file_2"; filename="relative/1k_c.dat"',
190 + 'Content-Type: application/octet-stream',
191 + '',
192 + 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
193 + '-----------------------------paZqsnEHRufoShdX6fh0lUhXBP4k--'
194 + ].join('\r\n')
195 + ],
196 + boundary: '---------------------------paZqsnEHRufoShdX6fh0lUhXBP4k',
197 + preservePath: true,
198 + expected: [
199 + ['file', 'upload_file_0', 26, 0, '/absolute/1k_a.dat', '7bit', 'application/octet-stream'],
200 + ['file', 'upload_file_1', 26, 0, 'C:\\absolute\\1k_b.dat', '7bit', 'application/octet-stream'],
201 + ['file', 'upload_file_2', 26, 0, 'relative/1k_c.dat', '7bit', 'application/octet-stream']
202 + ],
203 + what: 'Paths to be preserved through the preservePath option'
204 + },
205 + { source: [
206 + ['------WebKitFormBoundaryTB2MiQ36fnSJlrhY',
207 + 'Content-Disposition: form-data; name="cont"',
208 + 'Content-Type: ',
209 + '',
210 + 'some random content',
211 + '------WebKitFormBoundaryTB2MiQ36fnSJlrhY',
212 + 'Content-Disposition: ',
213 + '',
214 + 'some random pass',
215 + '------WebKitFormBoundaryTB2MiQ36fnSJlrhY--'
216 + ].join('\r\n')
217 + ],
218 + boundary: '----WebKitFormBoundaryTB2MiQ36fnSJlrhY',
219 + expected: [
220 + ['field', 'cont', 'some random content', false, false, '7bit', 'text/plain']
221 + ],
222 + what: 'Empty content-type and empty content-disposition'
223 + },
224 + { source: [
225 + ['--asdasdasdasd\r\n',
226 + 'Content-Type: text/plain\r\n',
227 + 'Content-Disposition: form-data; name="foo"\r\n',
228 + '\r\n',
229 + 'asd\r\n',
230 + '--asdasdasdasd--'
231 + ].join(':)')
232 + ],
233 + boundary: 'asdasdasdasd',
234 + expected: [],
235 + shouldError: 'Unexpected end of multipart data',
236 + what: 'Stopped mid-header'
237 + },
238 + { source: [
239 + ['------WebKitFormBoundaryTB2MiQ36fnSJlrhY',
240 + 'Content-Disposition: form-data; name="cont"',
241 + 'Content-Type: application/json',
242 + '',
243 + '{}',
244 + '------WebKitFormBoundaryTB2MiQ36fnSJlrhY--',
245 + ].join('\r\n')
246 + ],
247 + boundary: '----WebKitFormBoundaryTB2MiQ36fnSJlrhY',
248 + expected: [
249 + ['field', 'cont', '{}', false, false, '7bit', 'application/json']
250 + ],
251 + what: 'content-type for fields'
252 + },
253 + { source: [
254 + '------WebKitFormBoundaryTB2MiQ36fnSJlrhY--\r\n'
255 + ],
256 + boundary: '----WebKitFormBoundaryTB2MiQ36fnSJlrhY',
257 + expected: [],
258 + what: 'empty form'
259 + }
260 +];
261 +
262 +function next() {
263 + if (t === tests.length)
264 + return;
265 +
266 + var v = tests[t];
267 +
268 + var busboy = new Busboy({
269 + limits: v.limits,
270 + preservePath: v.preservePath,
271 + headers: {
272 + 'content-type': 'multipart/form-data; boundary=' + v.boundary
273 + }
274 + }),
275 + finishes = 0,
276 + results = [];
277 +
278 + if (v.events === undefined || v.events.indexOf('field') > -1) {
279 + busboy.on('field', function(key, val, keyTrunc, valTrunc, encoding, contype) {
280 + results.push(['field', key, val, keyTrunc, valTrunc, encoding, contype]);
281 + });
282 + }
283 + if (v.events === undefined || v.events.indexOf('file') > -1) {
284 + busboy.on('file', function(fieldname, stream, filename, encoding, mimeType) {
285 + var nb = 0,
286 + info = ['file',
287 + fieldname,
288 + nb,
289 + 0,
290 + filename,
291 + encoding,
292 + mimeType];
293 + results.push(info);
294 + stream.on('data', function(d) {
295 + nb += d.length;
296 + }).on('limit', function() {
297 + ++info[3];
298 + }).on('end', function() {
299 + info[2] = nb;
300 + if (stream.truncated)
301 + ++info[3];
302 + });
303 + });
304 + }
305 + busboy.on('finish', function() {
306 + assert(finishes++ === 0, makeMsg(v.what, 'finish emitted multiple times'));
307 + assert.deepEqual(results.length,
308 + v.expected.length,
309 + makeMsg(v.what, 'Parsed result count mismatch. Saw '
310 + + results.length
311 + + '. Expected: ' + v.expected.length));
312 +
313 + results.forEach(function(result, i) {
314 + assert.deepEqual(result,
315 + v.expected[i],
316 + makeMsg(v.what,
317 + 'Result mismatch:\nParsed: ' + inspect(result)
318 + + '\nExpected: ' + inspect(v.expected[i]))
319 + );
320 + });
321 + ++t;
322 + next();
323 + }).on('error', function(err) {
324 + if (!v.shouldError || v.shouldError !== err.message)
325 + assert(false, makeMsg(v.what, 'Unexpected error: ' + err));
326 + });
327 +
328 + v.source.forEach(function(s) {
329 + busboy.write(new Buffer(s, 'utf8'), EMPTY_FN);
330 + });
331 + busboy.end();
332 +}
333 +next();
334 +
335 +function makeMsg(what, msg) {
336 + return '[' + group + what + ']: ' + msg;
337 +}
338 +
339 +process.on('exit', function() {
340 + assert(t === tests.length,
341 + makeMsg('_exit',
342 + 'Only finished ' + t + '/' + tests.length + ' tests'));
343 +});
1 +var Busboy = require('..');
2 +
3 +var path = require('path'),
4 + inspect = require('util').inspect,
5 + assert = require('assert');
6 +
7 +var EMPTY_FN = function() {};
8 +
9 +var t = 0,
10 + group = path.basename(__filename, '.js') + '/';
11 +
12 +var tests = [
13 + { source: ['foo'],
14 + expected: [['foo', '', false, false]],
15 + what: 'Unassigned value'
16 + },
17 + { source: ['foo=bar'],
18 + expected: [['foo', 'bar', false, false]],
19 + what: 'Assigned value'
20 + },
21 + { source: ['foo&bar=baz'],
22 + expected: [['foo', '', false, false],
23 + ['bar', 'baz', false, false]],
24 + what: 'Unassigned and assigned value'
25 + },
26 + { source: ['foo=bar&baz'],
27 + expected: [['foo', 'bar', false, false],
28 + ['baz', '', false, false]],
29 + what: 'Assigned and unassigned value'
30 + },
31 + { source: ['foo=bar&baz=bla'],
32 + expected: [['foo', 'bar', false, false],
33 + ['baz', 'bla', false, false]],
34 + what: 'Two assigned values'
35 + },
36 + { source: ['foo&bar'],
37 + expected: [['foo', '', false, false],
38 + ['bar', '', false, false]],
39 + what: 'Two unassigned values'
40 + },
41 + { source: ['foo&bar&'],
42 + expected: [['foo', '', false, false],
43 + ['bar', '', false, false]],
44 + what: 'Two unassigned values and ampersand'
45 + },
46 + { source: ['foo=bar+baz%2Bquux'],
47 + expected: [['foo', 'bar baz+quux', false, false]],
48 + what: 'Assigned value with (plus) space'
49 + },
50 + { source: ['foo=bar%20baz%21'],
51 + expected: [['foo', 'bar baz!', false, false]],
52 + what: 'Assigned value with encoded bytes'
53 + },
54 + { source: ['foo%20bar=baz%20bla%21'],
55 + expected: [['foo bar', 'baz bla!', false, false]],
56 + what: 'Assigned value with encoded bytes #2'
57 + },
58 + { source: ['foo=bar%20baz%21&num=1000'],
59 + expected: [['foo', 'bar baz!', false, false],
60 + ['num', '1000', false, false]],
61 + what: 'Two assigned values, one with encoded bytes'
62 + },
63 + { source: ['foo=bar&baz=bla'],
64 + expected: [],
65 + what: 'Limits: zero fields',
66 + limits: { fields: 0 }
67 + },
68 + { source: ['foo=bar&baz=bla'],
69 + expected: [['foo', 'bar', false, false]],
70 + what: 'Limits: one field',
71 + limits: { fields: 1 }
72 + },
73 + { source: ['foo=bar&baz=bla'],
74 + expected: [['foo', 'bar', false, false],
75 + ['baz', 'bla', false, false]],
76 + what: 'Limits: field part lengths match limits',
77 + limits: { fieldNameSize: 3, fieldSize: 3 }
78 + },
79 + { source: ['foo=bar&baz=bla'],
80 + expected: [['fo', 'bar', true, false],
81 + ['ba', 'bla', true, false]],
82 + what: 'Limits: truncated field name',
83 + limits: { fieldNameSize: 2 }
84 + },
85 + { source: ['foo=bar&baz=bla'],
86 + expected: [['foo', 'ba', false, true],
87 + ['baz', 'bl', false, true]],
88 + what: 'Limits: truncated field value',
89 + limits: { fieldSize: 2 }
90 + },
91 + { source: ['foo=bar&baz=bla'],
92 + expected: [['fo', 'ba', true, true],
93 + ['ba', 'bl', true, true]],
94 + what: 'Limits: truncated field name and value',
95 + limits: { fieldNameSize: 2, fieldSize: 2 }
96 + },
97 + { source: ['foo=bar&baz=bla'],
98 + expected: [['fo', '', true, true],
99 + ['ba', '', true, true]],
100 + what: 'Limits: truncated field name and zero value limit',
101 + limits: { fieldNameSize: 2, fieldSize: 0 }
102 + },
103 + { source: ['foo=bar&baz=bla'],
104 + expected: [['', '', true, true],
105 + ['', '', true, true]],
106 + what: 'Limits: truncated zero field name and zero value limit',
107 + limits: { fieldNameSize: 0, fieldSize: 0 }
108 + },
109 + { source: ['&'],
110 + expected: [],
111 + what: 'Ampersand'
112 + },
113 + { source: ['&&&&&'],
114 + expected: [],
115 + what: 'Many ampersands'
116 + },
117 + { source: ['='],
118 + expected: [['', '', false, false]],
119 + what: 'Assigned value, empty name and value'
120 + },
121 + { source: [''],
122 + expected: [],
123 + what: 'Nothing'
124 + },
125 +];
126 +
127 +function next() {
128 + if (t === tests.length)
129 + return;
130 +
131 + var v = tests[t];
132 +
133 + var busboy = new Busboy({
134 + limits: v.limits,
135 + headers: {
136 + 'content-type': 'application/x-www-form-urlencoded; charset=utf-8'
137 + }
138 + }),
139 + finishes = 0,
140 + results = [];
141 +
142 + busboy.on('field', function(key, val, keyTrunc, valTrunc) {
143 + results.push([key, val, keyTrunc, valTrunc]);
144 + });
145 + busboy.on('file', function() {
146 + throw new Error(makeMsg(v.what, 'Unexpected file'));
147 + });
148 + busboy.on('finish', function() {
149 + assert(finishes++ === 0, makeMsg(v.what, 'finish emitted multiple times'));
150 + assert.deepEqual(results.length,
151 + v.expected.length,
152 + makeMsg(v.what, 'Parsed result count mismatch. Saw '
153 + + results.length
154 + + '. Expected: ' + v.expected.length));
155 +
156 + var i = 0;
157 + results.forEach(function(result) {
158 + assert.deepEqual(result,
159 + v.expected[i],
160 + makeMsg(v.what,
161 + 'Result mismatch:\nParsed: ' + inspect(result)
162 + + '\nExpected: ' + inspect(v.expected[i]))
163 + );
164 + ++i;
165 + });
166 + ++t;
167 + next();
168 + });
169 +
170 + v.source.forEach(function(s) {
171 + busboy.write(new Buffer(s, 'utf8'), EMPTY_FN);
172 + });
173 + busboy.end();
174 +}
175 +next();
176 +
177 +function makeMsg(what, msg) {
178 + return '[' + group + what + ']: ' + msg;
179 +}
180 +
181 +process.on('exit', function() {
182 + assert(t === tests.length, makeMsg('_exit', 'Only finished ' + t + '/' + tests.length + ' tests'));
183 +});
1 +var Decoder = require('../lib/utils').Decoder;
2 +
3 +var path = require('path'),
4 + assert = require('assert');
5 +
6 +var group = path.basename(__filename, '.js') + '/';
7 +
8 +[
9 + { source: ['Hello world'],
10 + expected: 'Hello world',
11 + what: 'No encoded bytes'
12 + },
13 + { source: ['Hello%20world'],
14 + expected: 'Hello world',
15 + what: 'One full encoded byte'
16 + },
17 + { source: ['Hello%20world%21'],
18 + expected: 'Hello world!',
19 + what: 'Two full encoded bytes'
20 + },
21 + { source: ['Hello%', '20world'],
22 + expected: 'Hello world',
23 + what: 'One full encoded byte split #1'
24 + },
25 + { source: ['Hello%2', '0world'],
26 + expected: 'Hello world',
27 + what: 'One full encoded byte split #2'
28 + },
29 + { source: ['Hello%20', 'world'],
30 + expected: 'Hello world',
31 + what: 'One full encoded byte (concat)'
32 + },
33 + { source: ['Hello%2Qworld'],
34 + expected: 'Hello%2Qworld',
35 + what: 'Malformed encoded byte #1'
36 + },
37 + { source: ['Hello%world'],
38 + expected: 'Hello%world',
39 + what: 'Malformed encoded byte #2'
40 + },
41 + { source: ['Hello+world'],
42 + expected: 'Hello world',
43 + what: 'Plus to space'
44 + },
45 + { source: ['Hello+world%21'],
46 + expected: 'Hello world!',
47 + what: 'Plus and encoded byte'
48 + },
49 + { source: ['5%2B5%3D10'],
50 + expected: '5+5=10',
51 + what: 'Encoded plus'
52 + },
53 + { source: ['5+%2B+5+%3D+10'],
54 + expected: '5 + 5 = 10',
55 + what: 'Spaces and encoded plus'
56 + },
57 +].forEach(function(v) {
58 + var dec = new Decoder(), result = '';
59 + v.source.forEach(function(s) {
60 + result += dec.write(s);
61 + });
62 + var msg = '[' + group + v.what + ']: decoded string mismatch.\n'
63 + + 'Saw: ' + result + '\n'
64 + + 'Expected: ' + v.expected;
65 + assert.deepEqual(result, v.expected, msg);
66 +});
1 +var parseParams = require('../lib/utils').parseParams;
2 +
3 +var path = require('path'),
4 + assert = require('assert'),
5 + inspect = require('util').inspect;
6 +
7 +var group = path.basename(__filename, '.js') + '/';
8 +
9 +[
10 + { source: 'video/ogg',
11 + expected: ['video/ogg'],
12 + what: 'No parameters'
13 + },
14 + { source: 'video/ogg;',
15 + expected: ['video/ogg'],
16 + what: 'No parameters (with separator)'
17 + },
18 + { source: 'video/ogg; ',
19 + expected: ['video/ogg'],
20 + what: 'No parameters (with separator followed by whitespace)'
21 + },
22 + { source: ';video/ogg',
23 + expected: ['', 'video/ogg'],
24 + what: 'Empty parameter'
25 + },
26 + { source: 'video/*',
27 + expected: ['video/*'],
28 + what: 'Subtype with asterisk'
29 + },
30 + { source: 'text/plain; encoding=utf8',
31 + expected: ['text/plain', ['encoding', 'utf8']],
32 + what: 'Unquoted'
33 + },
34 + { source: 'text/plain; encoding=',
35 + expected: ['text/plain', ['encoding', '']],
36 + what: 'Unquoted empty string'
37 + },
38 + { source: 'text/plain; encoding="utf8"',
39 + expected: ['text/plain', ['encoding', 'utf8']],
40 + what: 'Quoted'
41 + },
42 + { source: 'text/plain; greeting="hello \\"world\\""',
43 + expected: ['text/plain', ['greeting', 'hello "world"']],
44 + what: 'Quotes within quoted'
45 + },
46 + { source: 'text/plain; encoding=""',
47 + expected: ['text/plain', ['encoding', '']],
48 + what: 'Quoted empty string'
49 + },
50 + { source: 'text/plain; encoding="utf8";\t foo=bar;test',
51 + expected: ['text/plain', ['encoding', 'utf8'], ['foo', 'bar'], 'test'],
52 + what: 'Multiple params with various spacing'
53 + },
54 + { source: "text/plain; filename*=iso-8859-1'en'%A3%20rates",
55 + expected: ['text/plain', ['filename', '£ rates']],
56 + what: 'Extended parameter (RFC 5987) with language'
57 + },
58 + { source: "text/plain; filename*=utf-8''%c2%a3%20and%20%e2%82%ac%20rates",
59 + expected: ['text/plain', ['filename', '£ and € rates']],
60 + what: 'Extended parameter (RFC 5987) without language'
61 + },
62 + { source: "text/plain; filename*=utf-8''%E6%B5%8B%E8%AF%95%E6%96%87%E6%A1%A3",
63 + expected: ['text/plain', ['filename', '测试文档']],
64 + what: 'Extended parameter (RFC 5987) without language #2'
65 + },
66 + { source: "text/plain; filename*=iso-8859-1'en'%A3%20rates; altfilename*=utf-8''%c2%a3%20and%20%e2%82%ac%20rates",
67 + expected: ['text/plain', ['filename', '£ rates'], ['altfilename', '£ and € rates']],
68 + what: 'Multiple extended parameters (RFC 5987) with mixed charsets'
69 + },
70 + { source: "text/plain; filename*=iso-8859-1'en'%A3%20rates; altfilename=\"foobarbaz\"",
71 + expected: ['text/plain', ['filename', '£ rates'], ['altfilename', 'foobarbaz']],
72 + what: 'Mixed regular and extended parameters (RFC 5987)'
73 + },
74 + { source: "text/plain; filename=\"foobarbaz\"; altfilename*=iso-8859-1'en'%A3%20rates",
75 + expected: ['text/plain', ['filename', 'foobarbaz'], ['altfilename', '£ rates']],
76 + what: 'Mixed regular and extended parameters (RFC 5987) #2'
77 + },
78 + { source: 'text/plain; filename="C:\\folder\\test.png"',
79 + expected: ['text/plain', ['filename', 'C:\\folder\\test.png']],
80 + what: 'Unescaped backslashes should be considered backslashes'
81 + },
82 + { source: 'text/plain; filename="John \\"Magic\\" Smith.png"',
83 + expected: ['text/plain', ['filename', 'John "Magic" Smith.png']],
84 + what: 'Escaped double-quotes should be considered double-quotes'
85 + },
86 + { source: 'multipart/form-data; charset=utf-8; boundary=0xKhTmLbOuNdArY',
87 + expected: ['multipart/form-data', ['charset', 'utf-8'], ['boundary', '0xKhTmLbOuNdArY']],
88 + what: 'Multiple non-quoted parameters'
89 + },
90 +].forEach(function(v) {
91 + var result = parseParams(v.source),
92 + msg = '[' + group + v.what + ']: parsed parameters mismatch.\n'
93 + + 'Saw: ' + inspect(result) + '\n'
94 + + 'Expected: ' + inspect(v.expected);
95 + assert.deepEqual(result, v.expected, msg);
96 +});
1 +require('fs').readdirSync(__dirname).forEach(function(f) {
2 + if (f.substr(0, 5) === 'test-')
3 + require('./' + f);
4 +});
...\ No newline at end of file ...\ No newline at end of file
1 +The MIT License
2 +
3 +Copyright (c) 2013 Max Ogden
4 +
5 +Permission is hereby granted, free of charge,
6 +to any person obtaining a copy of this software and
7 +associated documentation files (the "Software"), to
8 +deal in the Software without restriction, including
9 +without limitation the rights to use, copy, modify,
10 +merge, publish, distribute, sublicense, and/or sell
11 +copies of the Software, and to permit persons to whom
12 +the Software is furnished to do so,
13 +subject to the following conditions:
14 +
15 +The above copyright notice and this permission notice
16 +shall be included in all copies or substantial portions of the Software.
17 +
18 +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
19 +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
20 +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
21 +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
22 +ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
23 +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
24 +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
...\ No newline at end of file ...\ No newline at end of file
1 +var Writable = require('readable-stream').Writable
2 +var inherits = require('inherits')
3 +var bufferFrom = require('buffer-from')
4 +
5 +if (typeof Uint8Array === 'undefined') {
6 + var U8 = require('typedarray').Uint8Array
7 +} else {
8 + var U8 = Uint8Array
9 +}
10 +
11 +function ConcatStream(opts, cb) {
12 + if (!(this instanceof ConcatStream)) return new ConcatStream(opts, cb)
13 +
14 + if (typeof opts === 'function') {
15 + cb = opts
16 + opts = {}
17 + }
18 + if (!opts) opts = {}
19 +
20 + var encoding = opts.encoding
21 + var shouldInferEncoding = false
22 +
23 + if (!encoding) {
24 + shouldInferEncoding = true
25 + } else {
26 + encoding = String(encoding).toLowerCase()
27 + if (encoding === 'u8' || encoding === 'uint8') {
28 + encoding = 'uint8array'
29 + }
30 + }
31 +
32 + Writable.call(this, { objectMode: true })
33 +
34 + this.encoding = encoding
35 + this.shouldInferEncoding = shouldInferEncoding
36 +
37 + if (cb) this.on('finish', function () { cb(this.getBody()) })
38 + this.body = []
39 +}
40 +
41 +module.exports = ConcatStream
42 +inherits(ConcatStream, Writable)
43 +
44 +ConcatStream.prototype._write = function(chunk, enc, next) {
45 + this.body.push(chunk)
46 + next()
47 +}
48 +
49 +ConcatStream.prototype.inferEncoding = function (buff) {
50 + var firstBuffer = buff === undefined ? this.body[0] : buff;
51 + if (Buffer.isBuffer(firstBuffer)) return 'buffer'
52 + if (typeof Uint8Array !== 'undefined' && firstBuffer instanceof Uint8Array) return 'uint8array'
53 + if (Array.isArray(firstBuffer)) return 'array'
54 + if (typeof firstBuffer === 'string') return 'string'
55 + if (Object.prototype.toString.call(firstBuffer) === "[object Object]") return 'object'
56 + return 'buffer'
57 +}
58 +
59 +ConcatStream.prototype.getBody = function () {
60 + if (!this.encoding && this.body.length === 0) return []
61 + if (this.shouldInferEncoding) this.encoding = this.inferEncoding()
62 + if (this.encoding === 'array') return arrayConcat(this.body)
63 + if (this.encoding === 'string') return stringConcat(this.body)
64 + if (this.encoding === 'buffer') return bufferConcat(this.body)
65 + if (this.encoding === 'uint8array') return u8Concat(this.body)
66 + return this.body
67 +}
68 +
69 +var isArray = Array.isArray || function (arr) {
70 + return Object.prototype.toString.call(arr) == '[object Array]'
71 +}
72 +
73 +function isArrayish (arr) {
74 + return /Array\]$/.test(Object.prototype.toString.call(arr))
75 +}
76 +
77 +function isBufferish (p) {
78 + return typeof p === 'string' || isArrayish(p) || (p && typeof p.subarray === 'function')
79 +}
80 +
81 +function stringConcat (parts) {
82 + var strings = []
83 + var needsToString = false
84 + for (var i = 0; i < parts.length; i++) {
85 + var p = parts[i]
86 + if (typeof p === 'string') {
87 + strings.push(p)
88 + } else if (Buffer.isBuffer(p)) {
89 + strings.push(p)
90 + } else if (isBufferish(p)) {
91 + strings.push(bufferFrom(p))
92 + } else {
93 + strings.push(bufferFrom(String(p)))
94 + }
95 + }
96 + if (Buffer.isBuffer(parts[0])) {
97 + strings = Buffer.concat(strings)
98 + strings = strings.toString('utf8')
99 + } else {
100 + strings = strings.join('')
101 + }
102 + return strings
103 +}
104 +
105 +function bufferConcat (parts) {
106 + var bufs = []
107 + for (var i = 0; i < parts.length; i++) {
108 + var p = parts[i]
109 + if (Buffer.isBuffer(p)) {
110 + bufs.push(p)
111 + } else if (isBufferish(p)) {
112 + bufs.push(bufferFrom(p))
113 + } else {
114 + bufs.push(bufferFrom(String(p)))
115 + }
116 + }
117 + return Buffer.concat(bufs)
118 +}
119 +
120 +function arrayConcat (parts) {
121 + var res = []
122 + for (var i = 0; i < parts.length; i++) {
123 + res.push.apply(res, parts[i])
124 + }
125 + return res
126 +}
127 +
128 +function u8Concat (parts) {
129 + var len = 0
130 + for (var i = 0; i < parts.length; i++) {
131 + if (typeof parts[i] === 'string') {
132 + parts[i] = bufferFrom(parts[i])
133 + }
134 + len += parts[i].length
135 + }
136 + var u8 = new U8(len)
137 + for (var i = 0, offset = 0; i < parts.length; i++) {
138 + var part = parts[i]
139 + for (var j = 0; j < part.length; j++) {
140 + u8[offset++] = part[j]
141 + }
142 + }
143 + return u8
144 +}
1 +language: node_js
2 +node_js:
3 + - "0.8"
4 + - "0.10"
1 +
2 +test:
3 + @node_modules/.bin/tape test.js
4 +
5 +.PHONY: test
6 +
1 +
2 +# isarray
3 +
4 +`Array#isArray` for older browsers.
5 +
6 +[![build status](https://secure.travis-ci.org/juliangruber/isarray.svg)](http://travis-ci.org/juliangruber/isarray)
7 +[![downloads](https://img.shields.io/npm/dm/isarray.svg)](https://www.npmjs.org/package/isarray)
8 +
9 +[![browser support](https://ci.testling.com/juliangruber/isarray.png)
10 +](https://ci.testling.com/juliangruber/isarray)
11 +
12 +## Usage
13 +
14 +```js
15 +var isArray = require('isarray');
16 +
17 +console.log(isArray([])); // => true
18 +console.log(isArray({})); // => false
19 +```
20 +
21 +## Installation
22 +
23 +With [npm](http://npmjs.org) do
24 +
25 +```bash
26 +$ npm install isarray
27 +```
28 +
29 +Then bundle for the browser with
30 +[browserify](https://github.com/substack/browserify).
31 +
32 +With [component](http://component.io) do
33 +
34 +```bash
35 +$ component install juliangruber/isarray
36 +```
37 +
38 +## License
39 +
40 +(MIT)
41 +
42 +Copyright (c) 2013 Julian Gruber &lt;julian@juliangruber.com&gt;
43 +
44 +Permission is hereby granted, free of charge, to any person obtaining a copy of
45 +this software and associated documentation files (the "Software"), to deal in
46 +the Software without restriction, including without limitation the rights to
47 +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
48 +of the Software, and to permit persons to whom the Software is furnished to do
49 +so, subject to the following conditions:
50 +
51 +The above copyright notice and this permission notice shall be included in all
52 +copies or substantial portions of the Software.
53 +
54 +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
55 +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
56 +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
57 +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
58 +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
59 +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
60 +SOFTWARE.
1 +{
2 + "name" : "isarray",
3 + "description" : "Array#isArray for older browsers",
4 + "version" : "0.0.1",
5 + "repository" : "juliangruber/isarray",
6 + "homepage": "https://github.com/juliangruber/isarray",
7 + "main" : "index.js",
8 + "scripts" : [
9 + "index.js"
10 + ],
11 + "dependencies" : {},
12 + "keywords": ["browser","isarray","array"],
13 + "author": {
14 + "name": "Julian Gruber",
15 + "email": "mail@juliangruber.com",
16 + "url": "http://juliangruber.com"
17 + },
18 + "license": "MIT"
19 +}
1 +var toString = {}.toString;
2 +
3 +module.exports = Array.isArray || function (arr) {
4 + return toString.call(arr) == '[object Array]';
5 +};
1 +{
2 + "_from": "isarray@~1.0.0",
3 + "_id": "isarray@1.0.0",
4 + "_inBundle": false,
5 + "_integrity": "sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE=",
6 + "_location": "/concat-stream/isarray",
7 + "_phantomChildren": {},
8 + "_requested": {
9 + "type": "range",
10 + "registry": true,
11 + "raw": "isarray@~1.0.0",
12 + "name": "isarray",
13 + "escapedName": "isarray",
14 + "rawSpec": "~1.0.0",
15 + "saveSpec": null,
16 + "fetchSpec": "~1.0.0"
17 + },
18 + "_requiredBy": [
19 + "/concat-stream/readable-stream"
20 + ],
21 + "_resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz",
22 + "_shasum": "bb935d48582cba168c06834957a54a3e07124f11",
23 + "_spec": "isarray@~1.0.0",
24 + "_where": "C:\\Users\\1000c\\이것저것\\옾소\\Voicoding\\node_modules\\concat-stream\\node_modules\\readable-stream",
25 + "author": {
26 + "name": "Julian Gruber",
27 + "email": "mail@juliangruber.com",
28 + "url": "http://juliangruber.com"
29 + },
30 + "bugs": {
31 + "url": "https://github.com/juliangruber/isarray/issues"
32 + },
33 + "bundleDependencies": false,
34 + "dependencies": {},
35 + "deprecated": false,
36 + "description": "Array#isArray for older browsers",
37 + "devDependencies": {
38 + "tape": "~2.13.4"
39 + },
40 + "homepage": "https://github.com/juliangruber/isarray",
41 + "keywords": [
42 + "browser",
43 + "isarray",
44 + "array"
45 + ],
46 + "license": "MIT",
47 + "main": "index.js",
48 + "name": "isarray",
49 + "repository": {
50 + "type": "git",
51 + "url": "git://github.com/juliangruber/isarray.git"
52 + },
53 + "scripts": {
54 + "test": "tape test.js"
55 + },
56 + "testling": {
57 + "files": "test.js",
58 + "browsers": [
59 + "ie/8..latest",
60 + "firefox/17..latest",
61 + "firefox/nightly",
62 + "chrome/22..latest",
63 + "chrome/canary",
64 + "opera/12..latest",
65 + "opera/next",
66 + "safari/5.1..latest",
67 + "ipad/6.0..latest",
68 + "iphone/6.0..latest",
69 + "android-browser/4.2..latest"
70 + ]
71 + },
72 + "version": "1.0.0"
73 +}
1 +var isArray = require('./');
2 +var test = require('tape');
3 +
4 +test('is array', function(t){
5 + t.ok(isArray([]));
6 + t.notOk(isArray({}));
7 + t.notOk(isArray(null));
8 + t.notOk(isArray(false));
9 +
10 + var obj = {};
11 + obj[0] = true;
12 + t.notOk(isArray(obj));
13 +
14 + var arr = [];
15 + arr.foo = 'bar';
16 + t.ok(isArray(arr));
17 +
18 + t.end();
19 +});
20 +
1 +sudo: false
2 +language: node_js
3 +before_install:
4 + - (test $NPM_LEGACY && npm install -g npm@2 && npm install -g npm@3) || true
5 +notifications:
6 + email: false
7 +matrix:
8 + fast_finish: true
9 + include:
10 + - node_js: '0.8'
11 + env: NPM_LEGACY=true
12 + - node_js: '0.10'
13 + env: NPM_LEGACY=true
14 + - node_js: '0.11'
15 + env: NPM_LEGACY=true
16 + - node_js: '0.12'
17 + env: NPM_LEGACY=true
18 + - node_js: 1
19 + env: NPM_LEGACY=true
20 + - node_js: 2
21 + env: NPM_LEGACY=true
22 + - node_js: 3
23 + env: NPM_LEGACY=true
24 + - node_js: 4
25 + - node_js: 5
26 + - node_js: 6
27 + - node_js: 7
28 + - node_js: 8
29 + - node_js: 9
30 +script: "npm run test"
31 +env:
32 + global:
33 + - secure: rE2Vvo7vnjabYNULNyLFxOyt98BoJexDqsiOnfiD6kLYYsiQGfr/sbZkPMOFm9qfQG7pjqx+zZWZjGSswhTt+626C0t/njXqug7Yps4c3dFblzGfreQHp7wNX5TFsvrxd6dAowVasMp61sJcRnB2w8cUzoe3RAYUDHyiHktwqMc=
34 + - secure: g9YINaKAdMatsJ28G9jCGbSaguXCyxSTy+pBO6Ch0Cf57ZLOTka3HqDj8p3nV28LUIHZ3ut5WO43CeYKwt4AUtLpBS3a0dndHdY6D83uY6b2qh5hXlrcbeQTq2cvw2y95F7hm4D1kwrgZ7ViqaKggRcEupAL69YbJnxeUDKWEdI=
1 +Node.js is licensed for use as follows:
2 +
3 +"""
4 +Copyright Node.js contributors. All rights reserved.
5 +
6 +Permission is hereby granted, free of charge, to any person obtaining a copy
7 +of this software and associated documentation files (the "Software"), to
8 +deal in the Software without restriction, including without limitation the
9 +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
10 +sell copies of the Software, and to permit persons to whom the Software is
11 +furnished to do so, subject to the following conditions:
12 +
13 +The above copyright notice and this permission notice shall be included in
14 +all copies or substantial portions of the Software.
15 +
16 +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21 +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
22 +IN THE SOFTWARE.
23 +"""
24 +
25 +This license applies to parts of Node.js originating from the
26 +https://github.com/joyent/node repository:
27 +
28 +"""
29 +Copyright Joyent, Inc. and other Node contributors. All rights reserved.
30 +Permission is hereby granted, free of charge, to any person obtaining a copy
31 +of this software and associated documentation files (the "Software"), to
32 +deal in the Software without restriction, including without limitation the
33 +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
34 +sell copies of the Software, and to permit persons to whom the Software is
35 +furnished to do so, subject to the following conditions:
36 +
37 +The above copyright notice and this permission notice shall be included in
38 +all copies or substantial portions of the Software.
39 +
40 +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
41 +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
42 +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
43 +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
44 +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
45 +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
46 +IN THE SOFTWARE.
47 +"""
1 +# readable-stream
2 +
3 +***Node-core v8.11.1 streams for userland*** [![Build Status](https://travis-ci.org/nodejs/readable-stream.svg?branch=master)](https://travis-ci.org/nodejs/readable-stream)
4 +
5 +
6 +[![NPM](https://nodei.co/npm/readable-stream.png?downloads=true&downloadRank=true)](https://nodei.co/npm/readable-stream/)
7 +[![NPM](https://nodei.co/npm-dl/readable-stream.png?&months=6&height=3)](https://nodei.co/npm/readable-stream/)
8 +
9 +
10 +[![Sauce Test Status](https://saucelabs.com/browser-matrix/readable-stream.svg)](https://saucelabs.com/u/readable-stream)
11 +
12 +```bash
13 +npm install --save readable-stream
14 +```
15 +
16 +***Node-core streams for userland***
17 +
18 +This package is a mirror of the Streams2 and Streams3 implementations in
19 +Node-core.
20 +
21 +Full documentation may be found on the [Node.js website](https://nodejs.org/dist/v8.11.1/docs/api/stream.html).
22 +
23 +If you want to guarantee a stable streams base, regardless of what version of
24 +Node you, or the users of your libraries are using, use **readable-stream** *only* and avoid the *"stream"* module in Node-core, for background see [this blogpost](http://r.va.gg/2014/06/why-i-dont-use-nodes-core-stream-module.html).
25 +
26 +As of version 2.0.0 **readable-stream** uses semantic versioning.
27 +
28 +# Streams Working Group
29 +
30 +`readable-stream` is maintained by the Streams Working Group, which
31 +oversees the development and maintenance of the Streams API within
32 +Node.js. The responsibilities of the Streams Working Group include:
33 +
34 +* Addressing stream issues on the Node.js issue tracker.
35 +* Authoring and editing stream documentation within the Node.js project.
36 +* Reviewing changes to stream subclasses within the Node.js project.
37 +* Redirecting changes to streams from the Node.js project to this
38 + project.
39 +* Assisting in the implementation of stream providers within Node.js.
40 +* Recommending versions of `readable-stream` to be included in Node.js.
41 +* Messaging about the future of streams to give the community advance
42 + notice of changes.
43 +
44 +<a name="members"></a>
45 +## Team Members
46 +
47 +* **Chris Dickinson** ([@chrisdickinson](https://github.com/chrisdickinson)) &lt;christopher.s.dickinson@gmail.com&gt;
48 + - Release GPG key: 9554F04D7259F04124DE6B476D5A82AC7E37093B
49 +* **Calvin Metcalf** ([@calvinmetcalf](https://github.com/calvinmetcalf)) &lt;calvin.metcalf@gmail.com&gt;
50 + - Release GPG key: F3EF5F62A87FC27A22E643F714CE4FF5015AA242
51 +* **Rod Vagg** ([@rvagg](https://github.com/rvagg)) &lt;rod@vagg.org&gt;
52 + - Release GPG key: DD8F2338BAE7501E3DD5AC78C273792F7D83545D
53 +* **Sam Newman** ([@sonewman](https://github.com/sonewman)) &lt;newmansam@outlook.com&gt;
54 +* **Mathias Buus** ([@mafintosh](https://github.com/mafintosh)) &lt;mathiasbuus@gmail.com&gt;
55 +* **Domenic Denicola** ([@domenic](https://github.com/domenic)) &lt;d@domenic.me&gt;
56 +* **Matteo Collina** ([@mcollina](https://github.com/mcollina)) &lt;matteo.collina@gmail.com&gt;
57 + - Release GPG key: 3ABC01543F22DD2239285CDD818674489FBC127E
58 +* **Irina Shestak** ([@lrlna](https://github.com/lrlna)) &lt;shestak.irina@gmail.com&gt;
1 +# streams WG Meeting 2015-01-30
2 +
3 +## Links
4 +
5 +* **Google Hangouts Video**: http://www.youtube.com/watch?v=I9nDOSGfwZg
6 +* **GitHub Issue**: https://github.com/iojs/readable-stream/issues/106
7 +* **Original Minutes Google Doc**: https://docs.google.com/document/d/17aTgLnjMXIrfjgNaTUnHQO7m3xgzHR2VXBTmi03Qii4/
8 +
9 +## Agenda
10 +
11 +Extracted from https://github.com/iojs/readable-stream/labels/wg-agenda prior to meeting.
12 +
13 +* adopt a charter [#105](https://github.com/iojs/readable-stream/issues/105)
14 +* release and versioning strategy [#101](https://github.com/iojs/readable-stream/issues/101)
15 +* simpler stream creation [#102](https://github.com/iojs/readable-stream/issues/102)
16 +* proposal: deprecate implicit flowing of streams [#99](https://github.com/iojs/readable-stream/issues/99)
17 +
18 +## Minutes
19 +
20 +### adopt a charter
21 +
22 +* group: +1's all around
23 +
24 +### What versioning scheme should be adopted?
25 +* group: +1’s 3.0.0
26 +* domenic+group: pulling in patches from other sources where appropriate
27 +* mikeal: version independently, suggesting versions for io.js
28 +* mikeal+domenic: work with TC to notify in advance of changes
29 +simpler stream creation
30 +
31 +### streamline creation of streams
32 +* sam: streamline creation of streams
33 +* domenic: nice simple solution posted
34 + but, we lose the opportunity to change the model
35 + may not be backwards incompatible (double check keys)
36 +
37 + **action item:** domenic will check
38 +
39 +### remove implicit flowing of streams on(‘data’)
40 +* add isFlowing / isPaused
41 +* mikeal: worrying that we’re documenting polyfill methods – confuses users
42 +* domenic: more reflective API is probably good, with warning labels for users
43 +* new section for mad scientists (reflective stream access)
44 +* calvin: name the “third state”
45 +* mikeal: maybe borrow the name from whatwg?
46 +* domenic: we’re missing the “third state”
47 +* consensus: kind of difficult to name the third state
48 +* mikeal: figure out differences in states / compat
49 +* mathias: always flow on data – eliminates third state
50 + * explore what it breaks
51 +
52 +**action items:**
53 +* ask isaac for ability to list packages by what public io.js APIs they use (esp. Stream)
54 +* ask rod/build for infrastructure
55 +* **chris**: explore the “flow on data” approach
56 +* add isPaused/isFlowing
57 +* add new docs section
58 +* move isPaused to that section
59 +
60 +
1 +module.exports = require('./lib/_stream_duplex.js');
1 +module.exports = require('./readable').Duplex
1 +// Copyright Joyent, Inc. and other Node contributors.
2 +//
3 +// Permission is hereby granted, free of charge, to any person obtaining a
4 +// copy of this software and associated documentation files (the
5 +// "Software"), to deal in the Software without restriction, including
6 +// without limitation the rights to use, copy, modify, merge, publish,
7 +// distribute, sublicense, and/or sell copies of the Software, and to permit
8 +// persons to whom the Software is furnished to do so, subject to the
9 +// following conditions:
10 +//
11 +// The above copyright notice and this permission notice shall be included
12 +// in all copies or substantial portions of the Software.
13 +//
14 +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15 +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17 +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18 +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19 +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20 +// USE OR OTHER DEALINGS IN THE SOFTWARE.
21 +
22 +// a duplex stream is just a stream that is both readable and writable.
23 +// Since JS doesn't have multiple prototypal inheritance, this class
24 +// prototypally inherits from Readable, and then parasitically from
25 +// Writable.
26 +
27 +'use strict';
28 +
29 +/*<replacement>*/
30 +
31 +var pna = require('process-nextick-args');
32 +/*</replacement>*/
33 +
34 +/*<replacement>*/
35 +var objectKeys = Object.keys || function (obj) {
36 + var keys = [];
37 + for (var key in obj) {
38 + keys.push(key);
39 + }return keys;
40 +};
41 +/*</replacement>*/
42 +
43 +module.exports = Duplex;
44 +
45 +/*<replacement>*/
46 +var util = Object.create(require('core-util-is'));
47 +util.inherits = require('inherits');
48 +/*</replacement>*/
49 +
50 +var Readable = require('./_stream_readable');
51 +var Writable = require('./_stream_writable');
52 +
53 +util.inherits(Duplex, Readable);
54 +
55 +{
56 + // avoid scope creep, the keys array can then be collected
57 + var keys = objectKeys(Writable.prototype);
58 + for (var v = 0; v < keys.length; v++) {
59 + var method = keys[v];
60 + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
61 + }
62 +}
63 +
64 +function Duplex(options) {
65 + if (!(this instanceof Duplex)) return new Duplex(options);
66 +
67 + Readable.call(this, options);
68 + Writable.call(this, options);
69 +
70 + if (options && options.readable === false) this.readable = false;
71 +
72 + if (options && options.writable === false) this.writable = false;
73 +
74 + this.allowHalfOpen = true;
75 + if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
76 +
77 + this.once('end', onend);
78 +}
79 +
80 +Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
81 + // making it explicit this property is not enumerable
82 + // because otherwise some prototype manipulation in
83 + // userland will fail
84 + enumerable: false,
85 + get: function () {
86 + return this._writableState.highWaterMark;
87 + }
88 +});
89 +
90 +// the no-half-open enforcer
91 +function onend() {
92 + // if we allow half-open state, or if the writable side ended,
93 + // then we're ok.
94 + if (this.allowHalfOpen || this._writableState.ended) return;
95 +
96 + // no more data can be written.
97 + // But allow more writes to happen in this tick.
98 + pna.nextTick(onEndNT, this);
99 +}
100 +
101 +function onEndNT(self) {
102 + self.end();
103 +}
104 +
105 +Object.defineProperty(Duplex.prototype, 'destroyed', {
106 + get: function () {
107 + if (this._readableState === undefined || this._writableState === undefined) {
108 + return false;
109 + }
110 + return this._readableState.destroyed && this._writableState.destroyed;
111 + },
112 + set: function (value) {
113 + // we ignore the value if the stream
114 + // has not been initialized yet
115 + if (this._readableState === undefined || this._writableState === undefined) {
116 + return;
117 + }
118 +
119 + // backward compatibility, the user is explicitly
120 + // managing destroyed
121 + this._readableState.destroyed = value;
122 + this._writableState.destroyed = value;
123 + }
124 +});
125 +
126 +Duplex.prototype._destroy = function (err, cb) {
127 + this.push(null);
128 + this.end();
129 +
130 + pna.nextTick(cb, err);
131 +};
...\ No newline at end of file ...\ No newline at end of file
1 +// Copyright Joyent, Inc. and other Node contributors.
2 +//
3 +// Permission is hereby granted, free of charge, to any person obtaining a
4 +// copy of this software and associated documentation files (the
5 +// "Software"), to deal in the Software without restriction, including
6 +// without limitation the rights to use, copy, modify, merge, publish,
7 +// distribute, sublicense, and/or sell copies of the Software, and to permit
8 +// persons to whom the Software is furnished to do so, subject to the
9 +// following conditions:
10 +//
11 +// The above copyright notice and this permission notice shall be included
12 +// in all copies or substantial portions of the Software.
13 +//
14 +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15 +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17 +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18 +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19 +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20 +// USE OR OTHER DEALINGS IN THE SOFTWARE.
21 +
22 +// a passthrough stream.
23 +// basically just the most minimal sort of Transform stream.
24 +// Every written chunk gets output as-is.
25 +
26 +'use strict';
27 +
28 +module.exports = PassThrough;
29 +
30 +var Transform = require('./_stream_transform');
31 +
32 +/*<replacement>*/
33 +var util = Object.create(require('core-util-is'));
34 +util.inherits = require('inherits');
35 +/*</replacement>*/
36 +
37 +util.inherits(PassThrough, Transform);
38 +
39 +function PassThrough(options) {
40 + if (!(this instanceof PassThrough)) return new PassThrough(options);
41 +
42 + Transform.call(this, options);
43 +}
44 +
45 +PassThrough.prototype._transform = function (chunk, encoding, cb) {
46 + cb(null, chunk);
47 +};
...\ No newline at end of file ...\ No newline at end of file
1 +// Copyright Joyent, Inc. and other Node contributors.
2 +//
3 +// Permission is hereby granted, free of charge, to any person obtaining a
4 +// copy of this software and associated documentation files (the
5 +// "Software"), to deal in the Software without restriction, including
6 +// without limitation the rights to use, copy, modify, merge, publish,
7 +// distribute, sublicense, and/or sell copies of the Software, and to permit
8 +// persons to whom the Software is furnished to do so, subject to the
9 +// following conditions:
10 +//
11 +// The above copyright notice and this permission notice shall be included
12 +// in all copies or substantial portions of the Software.
13 +//
14 +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15 +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17 +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18 +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19 +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20 +// USE OR OTHER DEALINGS IN THE SOFTWARE.
21 +
22 +'use strict';
23 +
24 +/*<replacement>*/
25 +
26 +var pna = require('process-nextick-args');
27 +/*</replacement>*/
28 +
29 +module.exports = Readable;
30 +
31 +/*<replacement>*/
32 +var isArray = require('isarray');
33 +/*</replacement>*/
34 +
35 +/*<replacement>*/
36 +var Duplex;
37 +/*</replacement>*/
38 +
39 +Readable.ReadableState = ReadableState;
40 +
41 +/*<replacement>*/
42 +var EE = require('events').EventEmitter;
43 +
44 +var EElistenerCount = function (emitter, type) {
45 + return emitter.listeners(type).length;
46 +};
47 +/*</replacement>*/
48 +
49 +/*<replacement>*/
50 +var Stream = require('./internal/streams/stream');
51 +/*</replacement>*/
52 +
53 +/*<replacement>*/
54 +
55 +var Buffer = require('safe-buffer').Buffer;
56 +var OurUint8Array = global.Uint8Array || function () {};
57 +function _uint8ArrayToBuffer(chunk) {
58 + return Buffer.from(chunk);
59 +}
60 +function _isUint8Array(obj) {
61 + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
62 +}
63 +
64 +/*</replacement>*/
65 +
66 +/*<replacement>*/
67 +var util = Object.create(require('core-util-is'));
68 +util.inherits = require('inherits');
69 +/*</replacement>*/
70 +
71 +/*<replacement>*/
72 +var debugUtil = require('util');
73 +var debug = void 0;
74 +if (debugUtil && debugUtil.debuglog) {
75 + debug = debugUtil.debuglog('stream');
76 +} else {
77 + debug = function () {};
78 +}
79 +/*</replacement>*/
80 +
81 +var BufferList = require('./internal/streams/BufferList');
82 +var destroyImpl = require('./internal/streams/destroy');
83 +var StringDecoder;
84 +
85 +util.inherits(Readable, Stream);
86 +
87 +var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
88 +
89 +function prependListener(emitter, event, fn) {
90 + // Sadly this is not cacheable as some libraries bundle their own
91 + // event emitter implementation with them.
92 + if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn);
93 +
94 + // This is a hack to make sure that our error handler is attached before any
95 + // userland ones. NEVER DO THIS. This is here only because this code needs
96 + // to continue to work with older versions of Node.js that do not include
97 + // the prependListener() method. The goal is to eventually remove this hack.
98 + if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];
99 +}
100 +
101 +function ReadableState(options, stream) {
102 + Duplex = Duplex || require('./_stream_duplex');
103 +
104 + options = options || {};
105 +
106 + // Duplex streams are both readable and writable, but share
107 + // the same options object.
108 + // However, some cases require setting options to different
109 + // values for the readable and the writable sides of the duplex stream.
110 + // These options can be provided separately as readableXXX and writableXXX.
111 + var isDuplex = stream instanceof Duplex;
112 +
113 + // object stream flag. Used to make read(n) ignore n and to
114 + // make all the buffer merging and length checks go away
115 + this.objectMode = !!options.objectMode;
116 +
117 + if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
118 +
119 + // the point at which it stops calling _read() to fill the buffer
120 + // Note: 0 is a valid value, means "don't call _read preemptively ever"
121 + var hwm = options.highWaterMark;
122 + var readableHwm = options.readableHighWaterMark;
123 + var defaultHwm = this.objectMode ? 16 : 16 * 1024;
124 +
125 + if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm;
126 +
127 + // cast to ints.
128 + this.highWaterMark = Math.floor(this.highWaterMark);
129 +
130 + // A linked list is used to store data chunks instead of an array because the
131 + // linked list can remove elements from the beginning faster than
132 + // array.shift()
133 + this.buffer = new BufferList();
134 + this.length = 0;
135 + this.pipes = null;
136 + this.pipesCount = 0;
137 + this.flowing = null;
138 + this.ended = false;
139 + this.endEmitted = false;
140 + this.reading = false;
141 +
142 + // a flag to be able to tell if the event 'readable'/'data' is emitted
143 + // immediately, or on a later tick. We set this to true at first, because
144 + // any actions that shouldn't happen until "later" should generally also
145 + // not happen before the first read call.
146 + this.sync = true;
147 +
148 + // whenever we return null, then we set a flag to say
149 + // that we're awaiting a 'readable' event emission.
150 + this.needReadable = false;
151 + this.emittedReadable = false;
152 + this.readableListening = false;
153 + this.resumeScheduled = false;
154 +
155 + // has it been destroyed
156 + this.destroyed = false;
157 +
158 + // Crypto is kind of old and crusty. Historically, its default string
159 + // encoding is 'binary' so we have to make this configurable.
160 + // Everything else in the universe uses 'utf8', though.
161 + this.defaultEncoding = options.defaultEncoding || 'utf8';
162 +
163 + // the number of writers that are awaiting a drain event in .pipe()s
164 + this.awaitDrain = 0;
165 +
166 + // if true, a maybeReadMore has been scheduled
167 + this.readingMore = false;
168 +
169 + this.decoder = null;
170 + this.encoding = null;
171 + if (options.encoding) {
172 + if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
173 + this.decoder = new StringDecoder(options.encoding);
174 + this.encoding = options.encoding;
175 + }
176 +}
177 +
178 +function Readable(options) {
179 + Duplex = Duplex || require('./_stream_duplex');
180 +
181 + if (!(this instanceof Readable)) return new Readable(options);
182 +
183 + this._readableState = new ReadableState(options, this);
184 +
185 + // legacy
186 + this.readable = true;
187 +
188 + if (options) {
189 + if (typeof options.read === 'function') this._read = options.read;
190 +
191 + if (typeof options.destroy === 'function') this._destroy = options.destroy;
192 + }
193 +
194 + Stream.call(this);
195 +}
196 +
197 +Object.defineProperty(Readable.prototype, 'destroyed', {
198 + get: function () {
199 + if (this._readableState === undefined) {
200 + return false;
201 + }
202 + return this._readableState.destroyed;
203 + },
204 + set: function (value) {
205 + // we ignore the value if the stream
206 + // has not been initialized yet
207 + if (!this._readableState) {
208 + return;
209 + }
210 +
211 + // backward compatibility, the user is explicitly
212 + // managing destroyed
213 + this._readableState.destroyed = value;
214 + }
215 +});
216 +
217 +Readable.prototype.destroy = destroyImpl.destroy;
218 +Readable.prototype._undestroy = destroyImpl.undestroy;
219 +Readable.prototype._destroy = function (err, cb) {
220 + this.push(null);
221 + cb(err);
222 +};
223 +
224 +// Manually shove something into the read() buffer.
225 +// This returns true if the highWaterMark has not been hit yet,
226 +// similar to how Writable.write() returns true if you should
227 +// write() some more.
228 +Readable.prototype.push = function (chunk, encoding) {
229 + var state = this._readableState;
230 + var skipChunkCheck;
231 +
232 + if (!state.objectMode) {
233 + if (typeof chunk === 'string') {
234 + encoding = encoding || state.defaultEncoding;
235 + if (encoding !== state.encoding) {
236 + chunk = Buffer.from(chunk, encoding);
237 + encoding = '';
238 + }
239 + skipChunkCheck = true;
240 + }
241 + } else {
242 + skipChunkCheck = true;
243 + }
244 +
245 + return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
246 +};
247 +
248 +// Unshift should *always* be something directly out of read()
249 +Readable.prototype.unshift = function (chunk) {
250 + return readableAddChunk(this, chunk, null, true, false);
251 +};
252 +
253 +function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
254 + var state = stream._readableState;
255 + if (chunk === null) {
256 + state.reading = false;
257 + onEofChunk(stream, state);
258 + } else {
259 + var er;
260 + if (!skipChunkCheck) er = chunkInvalid(state, chunk);
261 + if (er) {
262 + stream.emit('error', er);
263 + } else if (state.objectMode || chunk && chunk.length > 0) {
264 + if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
265 + chunk = _uint8ArrayToBuffer(chunk);
266 + }
267 +
268 + if (addToFront) {
269 + if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true);
270 + } else if (state.ended) {
271 + stream.emit('error', new Error('stream.push() after EOF'));
272 + } else {
273 + state.reading = false;
274 + if (state.decoder && !encoding) {
275 + chunk = state.decoder.write(chunk);
276 + if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
277 + } else {
278 + addChunk(stream, state, chunk, false);
279 + }
280 + }
281 + } else if (!addToFront) {
282 + state.reading = false;
283 + }
284 + }
285 +
286 + return needMoreData(state);
287 +}
288 +
289 +function addChunk(stream, state, chunk, addToFront) {
290 + if (state.flowing && state.length === 0 && !state.sync) {
291 + stream.emit('data', chunk);
292 + stream.read(0);
293 + } else {
294 + // update the buffer info.
295 + state.length += state.objectMode ? 1 : chunk.length;
296 + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
297 +
298 + if (state.needReadable) emitReadable(stream);
299 + }
300 + maybeReadMore(stream, state);
301 +}
302 +
303 +function chunkInvalid(state, chunk) {
304 + var er;
305 + if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
306 + er = new TypeError('Invalid non-string/buffer chunk');
307 + }
308 + return er;
309 +}
310 +
311 +// if it's past the high water mark, we can push in some more.
312 +// Also, if we have no data yet, we can stand some
313 +// more bytes. This is to work around cases where hwm=0,
314 +// such as the repl. Also, if the push() triggered a
315 +// readable event, and the user called read(largeNumber) such that
316 +// needReadable was set, then we ought to push more, so that another
317 +// 'readable' event will be triggered.
318 +function needMoreData(state) {
319 + return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
320 +}
321 +
322 +Readable.prototype.isPaused = function () {
323 + return this._readableState.flowing === false;
324 +};
325 +
326 +// backwards compatibility.
327 +Readable.prototype.setEncoding = function (enc) {
328 + if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
329 + this._readableState.decoder = new StringDecoder(enc);
330 + this._readableState.encoding = enc;
331 + return this;
332 +};
333 +
334 +// Don't raise the hwm > 8MB
335 +var MAX_HWM = 0x800000;
336 +function computeNewHighWaterMark(n) {
337 + if (n >= MAX_HWM) {
338 + n = MAX_HWM;
339 + } else {
340 + // Get the next highest power of 2 to prevent increasing hwm excessively in
341 + // tiny amounts
342 + n--;
343 + n |= n >>> 1;
344 + n |= n >>> 2;
345 + n |= n >>> 4;
346 + n |= n >>> 8;
347 + n |= n >>> 16;
348 + n++;
349 + }
350 + return n;
351 +}
352 +
353 +// This function is designed to be inlinable, so please take care when making
354 +// changes to the function body.
355 +function howMuchToRead(n, state) {
356 + if (n <= 0 || state.length === 0 && state.ended) return 0;
357 + if (state.objectMode) return 1;
358 + if (n !== n) {
359 + // Only flow one buffer at a time
360 + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
361 + }
362 + // If we're asking for more than the current hwm, then raise the hwm.
363 + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
364 + if (n <= state.length) return n;
365 + // Don't have enough
366 + if (!state.ended) {
367 + state.needReadable = true;
368 + return 0;
369 + }
370 + return state.length;
371 +}
372 +
373 +// you can override either this method, or the async _read(n) below.
374 +Readable.prototype.read = function (n) {
375 + debug('read', n);
376 + n = parseInt(n, 10);
377 + var state = this._readableState;
378 + var nOrig = n;
379 +
380 + if (n !== 0) state.emittedReadable = false;
381 +
382 + // if we're doing read(0) to trigger a readable event, but we
383 + // already have a bunch of data in the buffer, then just trigger
384 + // the 'readable' event and move on.
385 + if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {
386 + debug('read: emitReadable', state.length, state.ended);
387 + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
388 + return null;
389 + }
390 +
391 + n = howMuchToRead(n, state);
392 +
393 + // if we've ended, and we're now clear, then finish it up.
394 + if (n === 0 && state.ended) {
395 + if (state.length === 0) endReadable(this);
396 + return null;
397 + }
398 +
399 + // All the actual chunk generation logic needs to be
400 + // *below* the call to _read. The reason is that in certain
401 + // synthetic stream cases, such as passthrough streams, _read
402 + // may be a completely synchronous operation which may change
403 + // the state of the read buffer, providing enough data when
404 + // before there was *not* enough.
405 + //
406 + // So, the steps are:
407 + // 1. Figure out what the state of things will be after we do
408 + // a read from the buffer.
409 + //
410 + // 2. If that resulting state will trigger a _read, then call _read.
411 + // Note that this may be asynchronous, or synchronous. Yes, it is
412 + // deeply ugly to write APIs this way, but that still doesn't mean
413 + // that the Readable class should behave improperly, as streams are
414 + // designed to be sync/async agnostic.
415 + // Take note if the _read call is sync or async (ie, if the read call
416 + // has returned yet), so that we know whether or not it's safe to emit
417 + // 'readable' etc.
418 + //
419 + // 3. Actually pull the requested chunks out of the buffer and return.
420 +
421 + // if we need a readable event, then we need to do some reading.
422 + var doRead = state.needReadable;
423 + debug('need readable', doRead);
424 +
425 + // if we currently have less than the highWaterMark, then also read some
426 + if (state.length === 0 || state.length - n < state.highWaterMark) {
427 + doRead = true;
428 + debug('length less than watermark', doRead);
429 + }
430 +
431 + // however, if we've ended, then there's no point, and if we're already
432 + // reading, then it's unnecessary.
433 + if (state.ended || state.reading) {
434 + doRead = false;
435 + debug('reading or ended', doRead);
436 + } else if (doRead) {
437 + debug('do read');
438 + state.reading = true;
439 + state.sync = true;
440 + // if the length is currently zero, then we *need* a readable event.
441 + if (state.length === 0) state.needReadable = true;
442 + // call internal read method
443 + this._read(state.highWaterMark);
444 + state.sync = false;
445 + // If _read pushed data synchronously, then `reading` will be false,
446 + // and we need to re-evaluate how much data we can return to the user.
447 + if (!state.reading) n = howMuchToRead(nOrig, state);
448 + }
449 +
450 + var ret;
451 + if (n > 0) ret = fromList(n, state);else ret = null;
452 +
453 + if (ret === null) {
454 + state.needReadable = true;
455 + n = 0;
456 + } else {
457 + state.length -= n;
458 + }
459 +
460 + if (state.length === 0) {
461 + // If we have nothing in the buffer, then we want to know
462 + // as soon as we *do* get something into the buffer.
463 + if (!state.ended) state.needReadable = true;
464 +
465 + // If we tried to read() past the EOF, then emit end on the next tick.
466 + if (nOrig !== n && state.ended) endReadable(this);
467 + }
468 +
469 + if (ret !== null) this.emit('data', ret);
470 +
471 + return ret;
472 +};
473 +
474 +function onEofChunk(stream, state) {
475 + if (state.ended) return;
476 + if (state.decoder) {
477 + var chunk = state.decoder.end();
478 + if (chunk && chunk.length) {
479 + state.buffer.push(chunk);
480 + state.length += state.objectMode ? 1 : chunk.length;
481 + }
482 + }
483 + state.ended = true;
484 +
485 + // emit 'readable' now to make sure it gets picked up.
486 + emitReadable(stream);
487 +}
488 +
489 +// Don't emit readable right away in sync mode, because this can trigger
490 +// another read() call => stack overflow. This way, it might trigger
491 +// a nextTick recursion warning, but that's not so bad.
492 +function emitReadable(stream) {
493 + var state = stream._readableState;
494 + state.needReadable = false;
495 + if (!state.emittedReadable) {
496 + debug('emitReadable', state.flowing);
497 + state.emittedReadable = true;
498 + if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream);
499 + }
500 +}
501 +
502 +function emitReadable_(stream) {
503 + debug('emit readable');
504 + stream.emit('readable');
505 + flow(stream);
506 +}
507 +
508 +// at this point, the user has presumably seen the 'readable' event,
509 +// and called read() to consume some data. that may have triggered
510 +// in turn another _read(n) call, in which case reading = true if
511 +// it's in progress.
512 +// However, if we're not ended, or reading, and the length < hwm,
513 +// then go ahead and try to read some more preemptively.
514 +function maybeReadMore(stream, state) {
515 + if (!state.readingMore) {
516 + state.readingMore = true;
517 + pna.nextTick(maybeReadMore_, stream, state);
518 + }
519 +}
520 +
521 +function maybeReadMore_(stream, state) {
522 + var len = state.length;
523 + while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
524 + debug('maybeReadMore read 0');
525 + stream.read(0);
526 + if (len === state.length)
527 + // didn't get any data, stop spinning.
528 + break;else len = state.length;
529 + }
530 + state.readingMore = false;
531 +}
532 +
533 +// abstract method. to be overridden in specific implementation classes.
534 +// call cb(er, data) where data is <= n in length.
535 +// for virtual (non-string, non-buffer) streams, "length" is somewhat
536 +// arbitrary, and perhaps not very meaningful.
537 +Readable.prototype._read = function (n) {
538 + this.emit('error', new Error('_read() is not implemented'));
539 +};
540 +
541 +Readable.prototype.pipe = function (dest, pipeOpts) {
542 + var src = this;
543 + var state = this._readableState;
544 +
545 + switch (state.pipesCount) {
546 + case 0:
547 + state.pipes = dest;
548 + break;
549 + case 1:
550 + state.pipes = [state.pipes, dest];
551 + break;
552 + default:
553 + state.pipes.push(dest);
554 + break;
555 + }
556 + state.pipesCount += 1;
557 + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
558 +
559 + var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
560 +
561 + var endFn = doEnd ? onend : unpipe;
562 + if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn);
563 +
564 + dest.on('unpipe', onunpipe);
565 + function onunpipe(readable, unpipeInfo) {
566 + debug('onunpipe');
567 + if (readable === src) {
568 + if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
569 + unpipeInfo.hasUnpiped = true;
570 + cleanup();
571 + }
572 + }
573 + }
574 +
575 + function onend() {
576 + debug('onend');
577 + dest.end();
578 + }
579 +
580 + // when the dest drains, it reduces the awaitDrain counter
581 + // on the source. This would be more elegant with a .once()
582 + // handler in flow(), but adding and removing repeatedly is
583 + // too slow.
584 + var ondrain = pipeOnDrain(src);
585 + dest.on('drain', ondrain);
586 +
587 + var cleanedUp = false;
588 + function cleanup() {
589 + debug('cleanup');
590 + // cleanup event handlers once the pipe is broken
591 + dest.removeListener('close', onclose);
592 + dest.removeListener('finish', onfinish);
593 + dest.removeListener('drain', ondrain);
594 + dest.removeListener('error', onerror);
595 + dest.removeListener('unpipe', onunpipe);
596 + src.removeListener('end', onend);
597 + src.removeListener('end', unpipe);
598 + src.removeListener('data', ondata);
599 +
600 + cleanedUp = true;
601 +
602 + // if the reader is waiting for a drain event from this
603 + // specific writer, then it would cause it to never start
604 + // flowing again.
605 + // So, if this is awaiting a drain, then we just call it now.
606 + // If we don't know, then assume that we are waiting for one.
607 + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
608 + }
609 +
610 + // If the user pushes more data while we're writing to dest then we'll end up
611 + // in ondata again. However, we only want to increase awaitDrain once because
612 + // dest will only emit one 'drain' event for the multiple writes.
613 + // => Introduce a guard on increasing awaitDrain.
614 + var increasedAwaitDrain = false;
615 + src.on('data', ondata);
616 + function ondata(chunk) {
617 + debug('ondata');
618 + increasedAwaitDrain = false;
619 + var ret = dest.write(chunk);
620 + if (false === ret && !increasedAwaitDrain) {
621 + // If the user unpiped during `dest.write()`, it is possible
622 + // to get stuck in a permanently paused state if that write
623 + // also returned false.
624 + // => Check whether `dest` is still a piping destination.
625 + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
626 + debug('false write response, pause', src._readableState.awaitDrain);
627 + src._readableState.awaitDrain++;
628 + increasedAwaitDrain = true;
629 + }
630 + src.pause();
631 + }
632 + }
633 +
634 + // if the dest has an error, then stop piping into it.
635 + // however, don't suppress the throwing behavior for this.
636 + function onerror(er) {
637 + debug('onerror', er);
638 + unpipe();
639 + dest.removeListener('error', onerror);
640 + if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
641 + }
642 +
643 + // Make sure our error handler is attached before userland ones.
644 + prependListener(dest, 'error', onerror);
645 +
646 + // Both close and finish should trigger unpipe, but only once.
647 + function onclose() {
648 + dest.removeListener('finish', onfinish);
649 + unpipe();
650 + }
651 + dest.once('close', onclose);
652 + function onfinish() {
653 + debug('onfinish');
654 + dest.removeListener('close', onclose);
655 + unpipe();
656 + }
657 + dest.once('finish', onfinish);
658 +
659 + function unpipe() {
660 + debug('unpipe');
661 + src.unpipe(dest);
662 + }
663 +
664 + // tell the dest that it's being piped to
665 + dest.emit('pipe', src);
666 +
667 + // start the flow if it hasn't been started already.
668 + if (!state.flowing) {
669 + debug('pipe resume');
670 + src.resume();
671 + }
672 +
673 + return dest;
674 +};
675 +
676 +function pipeOnDrain(src) {
677 + return function () {
678 + var state = src._readableState;
679 + debug('pipeOnDrain', state.awaitDrain);
680 + if (state.awaitDrain) state.awaitDrain--;
681 + if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
682 + state.flowing = true;
683 + flow(src);
684 + }
685 + };
686 +}
687 +
688 +Readable.prototype.unpipe = function (dest) {
689 + var state = this._readableState;
690 + var unpipeInfo = { hasUnpiped: false };
691 +
692 + // if we're not piping anywhere, then do nothing.
693 + if (state.pipesCount === 0) return this;
694 +
695 + // just one destination. most common case.
696 + if (state.pipesCount === 1) {
697 + // passed in one, but it's not the right one.
698 + if (dest && dest !== state.pipes) return this;
699 +
700 + if (!dest) dest = state.pipes;
701 +
702 + // got a match.
703 + state.pipes = null;
704 + state.pipesCount = 0;
705 + state.flowing = false;
706 + if (dest) dest.emit('unpipe', this, unpipeInfo);
707 + return this;
708 + }
709 +
710 + // slow case. multiple pipe destinations.
711 +
712 + if (!dest) {
713 + // remove all.
714 + var dests = state.pipes;
715 + var len = state.pipesCount;
716 + state.pipes = null;
717 + state.pipesCount = 0;
718 + state.flowing = false;
719 +
720 + for (var i = 0; i < len; i++) {
721 + dests[i].emit('unpipe', this, unpipeInfo);
722 + }return this;
723 + }
724 +
725 + // try to find the right one.
726 + var index = indexOf(state.pipes, dest);
727 + if (index === -1) return this;
728 +
729 + state.pipes.splice(index, 1);
730 + state.pipesCount -= 1;
731 + if (state.pipesCount === 1) state.pipes = state.pipes[0];
732 +
733 + dest.emit('unpipe', this, unpipeInfo);
734 +
735 + return this;
736 +};
737 +
738 +// set up data events if they are asked for
739 +// Ensure readable listeners eventually get something
740 +Readable.prototype.on = function (ev, fn) {
741 + var res = Stream.prototype.on.call(this, ev, fn);
742 +
743 + if (ev === 'data') {
744 + // Start flowing on next tick if stream isn't explicitly paused
745 + if (this._readableState.flowing !== false) this.resume();
746 + } else if (ev === 'readable') {
747 + var state = this._readableState;
748 + if (!state.endEmitted && !state.readableListening) {
749 + state.readableListening = state.needReadable = true;
750 + state.emittedReadable = false;
751 + if (!state.reading) {
752 + pna.nextTick(nReadingNextTick, this);
753 + } else if (state.length) {
754 + emitReadable(this);
755 + }
756 + }
757 + }
758 +
759 + return res;
760 +};
761 +Readable.prototype.addListener = Readable.prototype.on;
762 +
763 +function nReadingNextTick(self) {
764 + debug('readable nexttick read 0');
765 + self.read(0);
766 +}
767 +
768 +// pause() and resume() are remnants of the legacy readable stream API
769 +// If the user uses them, then switch into old mode.
770 +Readable.prototype.resume = function () {
771 + var state = this._readableState;
772 + if (!state.flowing) {
773 + debug('resume');
774 + state.flowing = true;
775 + resume(this, state);
776 + }
777 + return this;
778 +};
779 +
780 +function resume(stream, state) {
781 + if (!state.resumeScheduled) {
782 + state.resumeScheduled = true;
783 + pna.nextTick(resume_, stream, state);
784 + }
785 +}
786 +
787 +function resume_(stream, state) {
788 + if (!state.reading) {
789 + debug('resume read 0');
790 + stream.read(0);
791 + }
792 +
793 + state.resumeScheduled = false;
794 + state.awaitDrain = 0;
795 + stream.emit('resume');
796 + flow(stream);
797 + if (state.flowing && !state.reading) stream.read(0);
798 +}
799 +
800 +Readable.prototype.pause = function () {
801 + debug('call pause flowing=%j', this._readableState.flowing);
802 + if (false !== this._readableState.flowing) {
803 + debug('pause');
804 + this._readableState.flowing = false;
805 + this.emit('pause');
806 + }
807 + return this;
808 +};
809 +
810 +function flow(stream) {
811 + var state = stream._readableState;
812 + debug('flow', state.flowing);
813 + while (state.flowing && stream.read() !== null) {}
814 +}
815 +
816 +// wrap an old-style stream as the async data source.
817 +// This is *not* part of the readable stream interface.
818 +// It is an ugly unfortunate mess of history.
819 +Readable.prototype.wrap = function (stream) {
820 + var _this = this;
821 +
822 + var state = this._readableState;
823 + var paused = false;
824 +
825 + stream.on('end', function () {
826 + debug('wrapped end');
827 + if (state.decoder && !state.ended) {
828 + var chunk = state.decoder.end();
829 + if (chunk && chunk.length) _this.push(chunk);
830 + }
831 +
832 + _this.push(null);
833 + });
834 +
835 + stream.on('data', function (chunk) {
836 + debug('wrapped data');
837 + if (state.decoder) chunk = state.decoder.write(chunk);
838 +
839 + // don't skip over falsy values in objectMode
840 + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
841 +
842 + var ret = _this.push(chunk);
843 + if (!ret) {
844 + paused = true;
845 + stream.pause();
846 + }
847 + });
848 +
849 + // proxy all the other methods.
850 + // important when wrapping filters and duplexes.
851 + for (var i in stream) {
852 + if (this[i] === undefined && typeof stream[i] === 'function') {
853 + this[i] = function (method) {
854 + return function () {
855 + return stream[method].apply(stream, arguments);
856 + };
857 + }(i);
858 + }
859 + }
860 +
861 + // proxy certain important events.
862 + for (var n = 0; n < kProxyEvents.length; n++) {
863 + stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));
864 + }
865 +
866 + // when we try to consume some more bytes, simply unpause the
867 + // underlying stream.
868 + this._read = function (n) {
869 + debug('wrapped _read', n);
870 + if (paused) {
871 + paused = false;
872 + stream.resume();
873 + }
874 + };
875 +
876 + return this;
877 +};
878 +
879 +Object.defineProperty(Readable.prototype, 'readableHighWaterMark', {
880 + // making it explicit this property is not enumerable
881 + // because otherwise some prototype manipulation in
882 + // userland will fail
883 + enumerable: false,
884 + get: function () {
885 + return this._readableState.highWaterMark;
886 + }
887 +});
888 +
889 +// exposed for testing purposes only.
890 +Readable._fromList = fromList;
891 +
892 +// Pluck off n bytes from an array of buffers.
893 +// Length is the combined lengths of all the buffers in the list.
894 +// This function is designed to be inlinable, so please take care when making
895 +// changes to the function body.
896 +function fromList(n, state) {
897 + // nothing buffered
898 + if (state.length === 0) return null;
899 +
900 + var ret;
901 + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
902 + // read it all, truncate the list
903 + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length);
904 + state.buffer.clear();
905 + } else {
906 + // read part of list
907 + ret = fromListPartial(n, state.buffer, state.decoder);
908 + }
909 +
910 + return ret;
911 +}
912 +
913 +// Extracts only enough buffered data to satisfy the amount requested.
914 +// This function is designed to be inlinable, so please take care when making
915 +// changes to the function body.
916 +function fromListPartial(n, list, hasStrings) {
917 + var ret;
918 + if (n < list.head.data.length) {
919 + // slice is the same for buffers and strings
920 + ret = list.head.data.slice(0, n);
921 + list.head.data = list.head.data.slice(n);
922 + } else if (n === list.head.data.length) {
923 + // first chunk is a perfect match
924 + ret = list.shift();
925 + } else {
926 + // result spans more than one buffer
927 + ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
928 + }
929 + return ret;
930 +}
931 +
932 +// Copies a specified amount of characters from the list of buffered data
933 +// chunks.
934 +// This function is designed to be inlinable, so please take care when making
935 +// changes to the function body.
936 +function copyFromBufferString(n, list) {
937 + var p = list.head;
938 + var c = 1;
939 + var ret = p.data;
940 + n -= ret.length;
941 + while (p = p.next) {
942 + var str = p.data;
943 + var nb = n > str.length ? str.length : n;
944 + if (nb === str.length) ret += str;else ret += str.slice(0, n);
945 + n -= nb;
946 + if (n === 0) {
947 + if (nb === str.length) {
948 + ++c;
949 + if (p.next) list.head = p.next;else list.head = list.tail = null;
950 + } else {
951 + list.head = p;
952 + p.data = str.slice(nb);
953 + }
954 + break;
955 + }
956 + ++c;
957 + }
958 + list.length -= c;
959 + return ret;
960 +}
961 +
962 +// Copies a specified amount of bytes from the list of buffered data chunks.
963 +// This function is designed to be inlinable, so please take care when making
964 +// changes to the function body.
965 +function copyFromBuffer(n, list) {
966 + var ret = Buffer.allocUnsafe(n);
967 + var p = list.head;
968 + var c = 1;
969 + p.data.copy(ret);
970 + n -= p.data.length;
971 + while (p = p.next) {
972 + var buf = p.data;
973 + var nb = n > buf.length ? buf.length : n;
974 + buf.copy(ret, ret.length - n, 0, nb);
975 + n -= nb;
976 + if (n === 0) {
977 + if (nb === buf.length) {
978 + ++c;
979 + if (p.next) list.head = p.next;else list.head = list.tail = null;
980 + } else {
981 + list.head = p;
982 + p.data = buf.slice(nb);
983 + }
984 + break;
985 + }
986 + ++c;
987 + }
988 + list.length -= c;
989 + return ret;
990 +}
991 +
992 +function endReadable(stream) {
993 + var state = stream._readableState;
994 +
995 + // If we get here before consuming all the bytes, then that is a
996 + // bug in node. Should never happen.
997 + if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream');
998 +
999 + if (!state.endEmitted) {
1000 + state.ended = true;
1001 + pna.nextTick(endReadableNT, state, stream);
1002 + }
1003 +}
1004 +
1005 +function endReadableNT(state, stream) {
1006 + // Check that we didn't get one last unshift.
1007 + if (!state.endEmitted && state.length === 0) {
1008 + state.endEmitted = true;
1009 + stream.readable = false;
1010 + stream.emit('end');
1011 + }
1012 +}
1013 +
1014 +function indexOf(xs, x) {
1015 + for (var i = 0, l = xs.length; i < l; i++) {
1016 + if (xs[i] === x) return i;
1017 + }
1018 + return -1;
1019 +}
...\ No newline at end of file ...\ No newline at end of file
1 +// Copyright Joyent, Inc. and other Node contributors.
2 +//
3 +// Permission is hereby granted, free of charge, to any person obtaining a
4 +// copy of this software and associated documentation files (the
5 +// "Software"), to deal in the Software without restriction, including
6 +// without limitation the rights to use, copy, modify, merge, publish,
7 +// distribute, sublicense, and/or sell copies of the Software, and to permit
8 +// persons to whom the Software is furnished to do so, subject to the
9 +// following conditions:
10 +//
11 +// The above copyright notice and this permission notice shall be included
12 +// in all copies or substantial portions of the Software.
13 +//
14 +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15 +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17 +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18 +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19 +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20 +// USE OR OTHER DEALINGS IN THE SOFTWARE.
21 +
22 +// a transform stream is a readable/writable stream where you do
23 +// something with the data. Sometimes it's called a "filter",
24 +// but that's not a great name for it, since that implies a thing where
25 +// some bits pass through, and others are simply ignored. (That would
26 +// be a valid example of a transform, of course.)
27 +//
28 +// While the output is causally related to the input, it's not a
29 +// necessarily symmetric or synchronous transformation. For example,
30 +// a zlib stream might take multiple plain-text writes(), and then
31 +// emit a single compressed chunk some time in the future.
32 +//
33 +// Here's how this works:
34 +//
35 +// The Transform stream has all the aspects of the readable and writable
36 +// stream classes. When you write(chunk), that calls _write(chunk,cb)
37 +// internally, and returns false if there's a lot of pending writes
38 +// buffered up. When you call read(), that calls _read(n) until
39 +// there's enough pending readable data buffered up.
40 +//
41 +// In a transform stream, the written data is placed in a buffer. When
42 +// _read(n) is called, it transforms the queued up data, calling the
43 +// buffered _write cb's as it consumes chunks. If consuming a single
44 +// written chunk would result in multiple output chunks, then the first
45 +// outputted bit calls the readcb, and subsequent chunks just go into
46 +// the read buffer, and will cause it to emit 'readable' if necessary.
47 +//
48 +// This way, back-pressure is actually determined by the reading side,
49 +// since _read has to be called to start processing a new chunk. However,
50 +// a pathological inflate type of transform can cause excessive buffering
51 +// here. For example, imagine a stream where every byte of input is
52 +// interpreted as an integer from 0-255, and then results in that many
53 +// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
54 +// 1kb of data being output. In this case, you could write a very small
55 +// amount of input, and end up with a very large amount of output. In
56 +// such a pathological inflating mechanism, there'd be no way to tell
57 +// the system to stop doing the transform. A single 4MB write could
58 +// cause the system to run out of memory.
59 +//
60 +// However, even in such a pathological case, only a single written chunk
61 +// would be consumed, and then the rest would wait (un-transformed) until
62 +// the results of the previous transformed chunk were consumed.
63 +
64 +'use strict';
65 +
66 +module.exports = Transform;
67 +
68 +var Duplex = require('./_stream_duplex');
69 +
70 +/*<replacement>*/
71 +var util = Object.create(require('core-util-is'));
72 +util.inherits = require('inherits');
73 +/*</replacement>*/
74 +
75 +util.inherits(Transform, Duplex);
76 +
77 +function afterTransform(er, data) {
78 + var ts = this._transformState;
79 + ts.transforming = false;
80 +
81 + var cb = ts.writecb;
82 +
83 + if (!cb) {
84 + return this.emit('error', new Error('write callback called multiple times'));
85 + }
86 +
87 + ts.writechunk = null;
88 + ts.writecb = null;
89 +
90 + if (data != null) // single equals check for both `null` and `undefined`
91 + this.push(data);
92 +
93 + cb(er);
94 +
95 + var rs = this._readableState;
96 + rs.reading = false;
97 + if (rs.needReadable || rs.length < rs.highWaterMark) {
98 + this._read(rs.highWaterMark);
99 + }
100 +}
101 +
102 +function Transform(options) {
103 + if (!(this instanceof Transform)) return new Transform(options);
104 +
105 + Duplex.call(this, options);
106 +
107 + this._transformState = {
108 + afterTransform: afterTransform.bind(this),
109 + needTransform: false,
110 + transforming: false,
111 + writecb: null,
112 + writechunk: null,
113 + writeencoding: null
114 + };
115 +
116 + // start out asking for a readable event once data is transformed.
117 + this._readableState.needReadable = true;
118 +
119 + // we have implemented the _read method, and done the other things
120 + // that Readable wants before the first _read call, so unset the
121 + // sync guard flag.
122 + this._readableState.sync = false;
123 +
124 + if (options) {
125 + if (typeof options.transform === 'function') this._transform = options.transform;
126 +
127 + if (typeof options.flush === 'function') this._flush = options.flush;
128 + }
129 +
130 + // When the writable side finishes, then flush out anything remaining.
131 + this.on('prefinish', prefinish);
132 +}
133 +
134 +function prefinish() {
135 + var _this = this;
136 +
137 + if (typeof this._flush === 'function') {
138 + this._flush(function (er, data) {
139 + done(_this, er, data);
140 + });
141 + } else {
142 + done(this, null, null);
143 + }
144 +}
145 +
146 +Transform.prototype.push = function (chunk, encoding) {
147 + this._transformState.needTransform = false;
148 + return Duplex.prototype.push.call(this, chunk, encoding);
149 +};
150 +
151 +// This is the part where you do stuff!
152 +// override this function in implementation classes.
153 +// 'chunk' is an input chunk.
154 +//
155 +// Call `push(newChunk)` to pass along transformed output
156 +// to the readable side. You may call 'push' zero or more times.
157 +//
158 +// Call `cb(err)` when you are done with this chunk. If you pass
159 +// an error, then that'll put the hurt on the whole operation. If you
160 +// never call cb(), then you'll never get another chunk.
161 +Transform.prototype._transform = function (chunk, encoding, cb) {
162 + throw new Error('_transform() is not implemented');
163 +};
164 +
165 +Transform.prototype._write = function (chunk, encoding, cb) {
166 + var ts = this._transformState;
167 + ts.writecb = cb;
168 + ts.writechunk = chunk;
169 + ts.writeencoding = encoding;
170 + if (!ts.transforming) {
171 + var rs = this._readableState;
172 + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
173 + }
174 +};
175 +
176 +// Doesn't matter what the args are here.
177 +// _transform does all the work.
178 +// That we got here means that the readable side wants more data.
179 +Transform.prototype._read = function (n) {
180 + var ts = this._transformState;
181 +
182 + if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
183 + ts.transforming = true;
184 + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
185 + } else {
186 + // mark that we need a transform, so that any data that comes in
187 + // will get processed, now that we've asked for it.
188 + ts.needTransform = true;
189 + }
190 +};
191 +
192 +Transform.prototype._destroy = function (err, cb) {
193 + var _this2 = this;
194 +
195 + Duplex.prototype._destroy.call(this, err, function (err2) {
196 + cb(err2);
197 + _this2.emit('close');
198 + });
199 +};
200 +
201 +function done(stream, er, data) {
202 + if (er) return stream.emit('error', er);
203 +
204 + if (data != null) // single equals check for both `null` and `undefined`
205 + stream.push(data);
206 +
207 + // if there's nothing in the write buffer, then that means
208 + // that nothing more will ever be provided
209 + if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0');
210 +
211 + if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming');
212 +
213 + return stream.push(null);
214 +}
...\ No newline at end of file ...\ No newline at end of file
1 +// Copyright Joyent, Inc. and other Node contributors.
2 +//
3 +// Permission is hereby granted, free of charge, to any person obtaining a
4 +// copy of this software and associated documentation files (the
5 +// "Software"), to deal in the Software without restriction, including
6 +// without limitation the rights to use, copy, modify, merge, publish,
7 +// distribute, sublicense, and/or sell copies of the Software, and to permit
8 +// persons to whom the Software is furnished to do so, subject to the
9 +// following conditions:
10 +//
11 +// The above copyright notice and this permission notice shall be included
12 +// in all copies or substantial portions of the Software.
13 +//
14 +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15 +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17 +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18 +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19 +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20 +// USE OR OTHER DEALINGS IN THE SOFTWARE.
21 +
22 +// A bit simpler than readable streams.
23 +// Implement an async ._write(chunk, encoding, cb), and it'll handle all
24 +// the drain event emission and buffering.
25 +
26 +'use strict';
27 +
28 +/*<replacement>*/
29 +
30 +var pna = require('process-nextick-args');
31 +/*</replacement>*/
32 +
33 +module.exports = Writable;
34 +
35 +/* <replacement> */
36 +function WriteReq(chunk, encoding, cb) {
37 + this.chunk = chunk;
38 + this.encoding = encoding;
39 + this.callback = cb;
40 + this.next = null;
41 +}
42 +
43 +// It seems a linked list but it is not
44 +// there will be only 2 of these for each stream
45 +function CorkedRequest(state) {
46 + var _this = this;
47 +
48 + this.next = null;
49 + this.entry = null;
50 + this.finish = function () {
51 + onCorkedFinish(_this, state);
52 + };
53 +}
54 +/* </replacement> */
55 +
56 +/*<replacement>*/
57 +var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick;
58 +/*</replacement>*/
59 +
60 +/*<replacement>*/
61 +var Duplex;
62 +/*</replacement>*/
63 +
64 +Writable.WritableState = WritableState;
65 +
66 +/*<replacement>*/
67 +var util = Object.create(require('core-util-is'));
68 +util.inherits = require('inherits');
69 +/*</replacement>*/
70 +
71 +/*<replacement>*/
72 +var internalUtil = {
73 + deprecate: require('util-deprecate')
74 +};
75 +/*</replacement>*/
76 +
77 +/*<replacement>*/
78 +var Stream = require('./internal/streams/stream');
79 +/*</replacement>*/
80 +
81 +/*<replacement>*/
82 +
83 +var Buffer = require('safe-buffer').Buffer;
84 +var OurUint8Array = global.Uint8Array || function () {};
85 +function _uint8ArrayToBuffer(chunk) {
86 + return Buffer.from(chunk);
87 +}
88 +function _isUint8Array(obj) {
89 + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
90 +}
91 +
92 +/*</replacement>*/
93 +
94 +var destroyImpl = require('./internal/streams/destroy');
95 +
96 +util.inherits(Writable, Stream);
97 +
98 +function nop() {}
99 +
100 +function WritableState(options, stream) {
101 + Duplex = Duplex || require('./_stream_duplex');
102 +
103 + options = options || {};
104 +
105 + // Duplex streams are both readable and writable, but share
106 + // the same options object.
107 + // However, some cases require setting options to different
108 + // values for the readable and the writable sides of the duplex stream.
109 + // These options can be provided separately as readableXXX and writableXXX.
110 + var isDuplex = stream instanceof Duplex;
111 +
112 + // object stream flag to indicate whether or not this stream
113 + // contains buffers or objects.
114 + this.objectMode = !!options.objectMode;
115 +
116 + if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
117 +
118 + // the point at which write() starts returning false
119 + // Note: 0 is a valid value, means that we always return false if
120 + // the entire buffer is not flushed immediately on write()
121 + var hwm = options.highWaterMark;
122 + var writableHwm = options.writableHighWaterMark;
123 + var defaultHwm = this.objectMode ? 16 : 16 * 1024;
124 +
125 + if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm;
126 +
127 + // cast to ints.
128 + this.highWaterMark = Math.floor(this.highWaterMark);
129 +
130 + // if _final has been called
131 + this.finalCalled = false;
132 +
133 + // drain event flag.
134 + this.needDrain = false;
135 + // at the start of calling end()
136 + this.ending = false;
137 + // when end() has been called, and returned
138 + this.ended = false;
139 + // when 'finish' is emitted
140 + this.finished = false;
141 +
142 + // has it been destroyed
143 + this.destroyed = false;
144 +
145 + // should we decode strings into buffers before passing to _write?
146 + // this is here so that some node-core streams can optimize string
147 + // handling at a lower level.
148 + var noDecode = options.decodeStrings === false;
149 + this.decodeStrings = !noDecode;
150 +
151 + // Crypto is kind of old and crusty. Historically, its default string
152 + // encoding is 'binary' so we have to make this configurable.
153 + // Everything else in the universe uses 'utf8', though.
154 + this.defaultEncoding = options.defaultEncoding || 'utf8';
155 +
156 + // not an actual buffer we keep track of, but a measurement
157 + // of how much we're waiting to get pushed to some underlying
158 + // socket or file.
159 + this.length = 0;
160 +
161 + // a flag to see when we're in the middle of a write.
162 + this.writing = false;
163 +
164 + // when true all writes will be buffered until .uncork() call
165 + this.corked = 0;
166 +
167 + // a flag to be able to tell if the onwrite cb is called immediately,
168 + // or on a later tick. We set this to true at first, because any
169 + // actions that shouldn't happen until "later" should generally also
170 + // not happen before the first write call.
171 + this.sync = true;
172 +
173 + // a flag to know if we're processing previously buffered items, which
174 + // may call the _write() callback in the same tick, so that we don't
175 + // end up in an overlapped onwrite situation.
176 + this.bufferProcessing = false;
177 +
178 + // the callback that's passed to _write(chunk,cb)
179 + this.onwrite = function (er) {
180 + onwrite(stream, er);
181 + };
182 +
183 + // the callback that the user supplies to write(chunk,encoding,cb)
184 + this.writecb = null;
185 +
186 + // the amount that is being written when _write is called.
187 + this.writelen = 0;
188 +
189 + this.bufferedRequest = null;
190 + this.lastBufferedRequest = null;
191 +
192 + // number of pending user-supplied write callbacks
193 + // this must be 0 before 'finish' can be emitted
194 + this.pendingcb = 0;
195 +
196 + // emit prefinish if the only thing we're waiting for is _write cbs
197 + // This is relevant for synchronous Transform streams
198 + this.prefinished = false;
199 +
200 + // True if the error was already emitted and should not be thrown again
201 + this.errorEmitted = false;
202 +
203 + // count buffered requests
204 + this.bufferedRequestCount = 0;
205 +
206 + // allocate the first CorkedRequest, there is always
207 + // one allocated and free to use, and we maintain at most two
208 + this.corkedRequestsFree = new CorkedRequest(this);
209 +}
210 +
211 +WritableState.prototype.getBuffer = function getBuffer() {
212 + var current = this.bufferedRequest;
213 + var out = [];
214 + while (current) {
215 + out.push(current);
216 + current = current.next;
217 + }
218 + return out;
219 +};
220 +
221 +(function () {
222 + try {
223 + Object.defineProperty(WritableState.prototype, 'buffer', {
224 + get: internalUtil.deprecate(function () {
225 + return this.getBuffer();
226 + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
227 + });
228 + } catch (_) {}
229 +})();
230 +
231 +// Test _writableState for inheritance to account for Duplex streams,
232 +// whose prototype chain only points to Readable.
233 +var realHasInstance;
234 +if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
235 + realHasInstance = Function.prototype[Symbol.hasInstance];
236 + Object.defineProperty(Writable, Symbol.hasInstance, {
237 + value: function (object) {
238 + if (realHasInstance.call(this, object)) return true;
239 + if (this !== Writable) return false;
240 +
241 + return object && object._writableState instanceof WritableState;
242 + }
243 + });
244 +} else {
245 + realHasInstance = function (object) {
246 + return object instanceof this;
247 + };
248 +}
249 +
250 +function Writable(options) {
251 + Duplex = Duplex || require('./_stream_duplex');
252 +
253 + // Writable ctor is applied to Duplexes, too.
254 + // `realHasInstance` is necessary because using plain `instanceof`
255 + // would return false, as no `_writableState` property is attached.
256 +
257 + // Trying to use the custom `instanceof` for Writable here will also break the
258 + // Node.js LazyTransform implementation, which has a non-trivial getter for
259 + // `_writableState` that would lead to infinite recursion.
260 + if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {
261 + return new Writable(options);
262 + }
263 +
264 + this._writableState = new WritableState(options, this);
265 +
266 + // legacy.
267 + this.writable = true;
268 +
269 + if (options) {
270 + if (typeof options.write === 'function') this._write = options.write;
271 +
272 + if (typeof options.writev === 'function') this._writev = options.writev;
273 +
274 + if (typeof options.destroy === 'function') this._destroy = options.destroy;
275 +
276 + if (typeof options.final === 'function') this._final = options.final;
277 + }
278 +
279 + Stream.call(this);
280 +}
281 +
282 +// Otherwise people can pipe Writable streams, which is just wrong.
283 +Writable.prototype.pipe = function () {
284 + this.emit('error', new Error('Cannot pipe, not readable'));
285 +};
286 +
287 +function writeAfterEnd(stream, cb) {
288 + var er = new Error('write after end');
289 + // TODO: defer error events consistently everywhere, not just the cb
290 + stream.emit('error', er);
291 + pna.nextTick(cb, er);
292 +}
293 +
294 +// Checks that a user-supplied chunk is valid, especially for the particular
295 +// mode the stream is in. Currently this means that `null` is never accepted
296 +// and undefined/non-string values are only allowed in object mode.
297 +function validChunk(stream, state, chunk, cb) {
298 + var valid = true;
299 + var er = false;
300 +
301 + if (chunk === null) {
302 + er = new TypeError('May not write null values to stream');
303 + } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
304 + er = new TypeError('Invalid non-string/buffer chunk');
305 + }
306 + if (er) {
307 + stream.emit('error', er);
308 + pna.nextTick(cb, er);
309 + valid = false;
310 + }
311 + return valid;
312 +}
313 +
314 +Writable.prototype.write = function (chunk, encoding, cb) {
315 + var state = this._writableState;
316 + var ret = false;
317 + var isBuf = !state.objectMode && _isUint8Array(chunk);
318 +
319 + if (isBuf && !Buffer.isBuffer(chunk)) {
320 + chunk = _uint8ArrayToBuffer(chunk);
321 + }
322 +
323 + if (typeof encoding === 'function') {
324 + cb = encoding;
325 + encoding = null;
326 + }
327 +
328 + if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
329 +
330 + if (typeof cb !== 'function') cb = nop;
331 +
332 + if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
333 + state.pendingcb++;
334 + ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
335 + }
336 +
337 + return ret;
338 +};
339 +
340 +Writable.prototype.cork = function () {
341 + var state = this._writableState;
342 +
343 + state.corked++;
344 +};
345 +
346 +Writable.prototype.uncork = function () {
347 + var state = this._writableState;
348 +
349 + if (state.corked) {
350 + state.corked--;
351 +
352 + if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
353 + }
354 +};
355 +
356 +Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
357 + // node::ParseEncoding() requires lower case.
358 + if (typeof encoding === 'string') encoding = encoding.toLowerCase();
359 + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding);
360 + this._writableState.defaultEncoding = encoding;
361 + return this;
362 +};
363 +
364 +function decodeChunk(state, chunk, encoding) {
365 + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
366 + chunk = Buffer.from(chunk, encoding);
367 + }
368 + return chunk;
369 +}
370 +
371 +Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
372 + // making it explicit this property is not enumerable
373 + // because otherwise some prototype manipulation in
374 + // userland will fail
375 + enumerable: false,
376 + get: function () {
377 + return this._writableState.highWaterMark;
378 + }
379 +});
380 +
381 +// if we're already writing something, then just put this
382 +// in the queue, and wait our turn. Otherwise, call _write
383 +// If we return false, then we need a drain event, so set that flag.
384 +function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
385 + if (!isBuf) {
386 + var newChunk = decodeChunk(state, chunk, encoding);
387 + if (chunk !== newChunk) {
388 + isBuf = true;
389 + encoding = 'buffer';
390 + chunk = newChunk;
391 + }
392 + }
393 + var len = state.objectMode ? 1 : chunk.length;
394 +
395 + state.length += len;
396 +
397 + var ret = state.length < state.highWaterMark;
398 + // we must ensure that previous needDrain will not be reset to false.
399 + if (!ret) state.needDrain = true;
400 +
401 + if (state.writing || state.corked) {
402 + var last = state.lastBufferedRequest;
403 + state.lastBufferedRequest = {
404 + chunk: chunk,
405 + encoding: encoding,
406 + isBuf: isBuf,
407 + callback: cb,
408 + next: null
409 + };
410 + if (last) {
411 + last.next = state.lastBufferedRequest;
412 + } else {
413 + state.bufferedRequest = state.lastBufferedRequest;
414 + }
415 + state.bufferedRequestCount += 1;
416 + } else {
417 + doWrite(stream, state, false, len, chunk, encoding, cb);
418 + }
419 +
420 + return ret;
421 +}
422 +
423 +function doWrite(stream, state, writev, len, chunk, encoding, cb) {
424 + state.writelen = len;
425 + state.writecb = cb;
426 + state.writing = true;
427 + state.sync = true;
428 + if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
429 + state.sync = false;
430 +}
431 +
432 +function onwriteError(stream, state, sync, er, cb) {
433 + --state.pendingcb;
434 +
435 + if (sync) {
436 + // defer the callback if we are being called synchronously
437 + // to avoid piling up things on the stack
438 + pna.nextTick(cb, er);
439 + // this can emit finish, and it will always happen
440 + // after error
441 + pna.nextTick(finishMaybe, stream, state);
442 + stream._writableState.errorEmitted = true;
443 + stream.emit('error', er);
444 + } else {
445 + // the caller expect this to happen before if
446 + // it is async
447 + cb(er);
448 + stream._writableState.errorEmitted = true;
449 + stream.emit('error', er);
450 + // this can emit finish, but finish must
451 + // always follow error
452 + finishMaybe(stream, state);
453 + }
454 +}
455 +
456 +function onwriteStateUpdate(state) {
457 + state.writing = false;
458 + state.writecb = null;
459 + state.length -= state.writelen;
460 + state.writelen = 0;
461 +}
462 +
463 +function onwrite(stream, er) {
464 + var state = stream._writableState;
465 + var sync = state.sync;
466 + var cb = state.writecb;
467 +
468 + onwriteStateUpdate(state);
469 +
470 + if (er) onwriteError(stream, state, sync, er, cb);else {
471 + // Check if we're actually ready to finish, but don't emit yet
472 + var finished = needFinish(state);
473 +
474 + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
475 + clearBuffer(stream, state);
476 + }
477 +
478 + if (sync) {
479 + /*<replacement>*/
480 + asyncWrite(afterWrite, stream, state, finished, cb);
481 + /*</replacement>*/
482 + } else {
483 + afterWrite(stream, state, finished, cb);
484 + }
485 + }
486 +}
487 +
488 +function afterWrite(stream, state, finished, cb) {
489 + if (!finished) onwriteDrain(stream, state);
490 + state.pendingcb--;
491 + cb();
492 + finishMaybe(stream, state);
493 +}
494 +
495 +// Must force callback to be called on nextTick, so that we don't
496 +// emit 'drain' before the write() consumer gets the 'false' return
497 +// value, and has a chance to attach a 'drain' listener.
498 +function onwriteDrain(stream, state) {
499 + if (state.length === 0 && state.needDrain) {
500 + state.needDrain = false;
501 + stream.emit('drain');
502 + }
503 +}
504 +
505 +// if there's something in the buffer waiting, then process it
506 +function clearBuffer(stream, state) {
507 + state.bufferProcessing = true;
508 + var entry = state.bufferedRequest;
509 +
510 + if (stream._writev && entry && entry.next) {
511 + // Fast case, write everything using _writev()
512 + var l = state.bufferedRequestCount;
513 + var buffer = new Array(l);
514 + var holder = state.corkedRequestsFree;
515 + holder.entry = entry;
516 +
517 + var count = 0;
518 + var allBuffers = true;
519 + while (entry) {
520 + buffer[count] = entry;
521 + if (!entry.isBuf) allBuffers = false;
522 + entry = entry.next;
523 + count += 1;
524 + }
525 + buffer.allBuffers = allBuffers;
526 +
527 + doWrite(stream, state, true, state.length, buffer, '', holder.finish);
528 +
529 + // doWrite is almost always async, defer these to save a bit of time
530 + // as the hot path ends with doWrite
531 + state.pendingcb++;
532 + state.lastBufferedRequest = null;
533 + if (holder.next) {
534 + state.corkedRequestsFree = holder.next;
535 + holder.next = null;
536 + } else {
537 + state.corkedRequestsFree = new CorkedRequest(state);
538 + }
539 + state.bufferedRequestCount = 0;
540 + } else {
541 + // Slow case, write chunks one-by-one
542 + while (entry) {
543 + var chunk = entry.chunk;
544 + var encoding = entry.encoding;
545 + var cb = entry.callback;
546 + var len = state.objectMode ? 1 : chunk.length;
547 +
548 + doWrite(stream, state, false, len, chunk, encoding, cb);
549 + entry = entry.next;
550 + state.bufferedRequestCount--;
551 + // if we didn't call the onwrite immediately, then
552 + // it means that we need to wait until it does.
553 + // also, that means that the chunk and cb are currently
554 + // being processed, so move the buffer counter past them.
555 + if (state.writing) {
556 + break;
557 + }
558 + }
559 +
560 + if (entry === null) state.lastBufferedRequest = null;
561 + }
562 +
563 + state.bufferedRequest = entry;
564 + state.bufferProcessing = false;
565 +}
566 +
567 +Writable.prototype._write = function (chunk, encoding, cb) {
568 + cb(new Error('_write() is not implemented'));
569 +};
570 +
571 +Writable.prototype._writev = null;
572 +
573 +Writable.prototype.end = function (chunk, encoding, cb) {
574 + var state = this._writableState;
575 +
576 + if (typeof chunk === 'function') {
577 + cb = chunk;
578 + chunk = null;
579 + encoding = null;
580 + } else if (typeof encoding === 'function') {
581 + cb = encoding;
582 + encoding = null;
583 + }
584 +
585 + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
586 +
587 + // .end() fully uncorks
588 + if (state.corked) {
589 + state.corked = 1;
590 + this.uncork();
591 + }
592 +
593 + // ignore unnecessary end() calls.
594 + if (!state.ending && !state.finished) endWritable(this, state, cb);
595 +};
596 +
597 +function needFinish(state) {
598 + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
599 +}
600 +function callFinal(stream, state) {
601 + stream._final(function (err) {
602 + state.pendingcb--;
603 + if (err) {
604 + stream.emit('error', err);
605 + }
606 + state.prefinished = true;
607 + stream.emit('prefinish');
608 + finishMaybe(stream, state);
609 + });
610 +}
611 +function prefinish(stream, state) {
612 + if (!state.prefinished && !state.finalCalled) {
613 + if (typeof stream._final === 'function') {
614 + state.pendingcb++;
615 + state.finalCalled = true;
616 + pna.nextTick(callFinal, stream, state);
617 + } else {
618 + state.prefinished = true;
619 + stream.emit('prefinish');
620 + }
621 + }
622 +}
623 +
624 +function finishMaybe(stream, state) {
625 + var need = needFinish(state);
626 + if (need) {
627 + prefinish(stream, state);
628 + if (state.pendingcb === 0) {
629 + state.finished = true;
630 + stream.emit('finish');
631 + }
632 + }
633 + return need;
634 +}
635 +
636 +function endWritable(stream, state, cb) {
637 + state.ending = true;
638 + finishMaybe(stream, state);
639 + if (cb) {
640 + if (state.finished) pna.nextTick(cb);else stream.once('finish', cb);
641 + }
642 + state.ended = true;
643 + stream.writable = false;
644 +}
645 +
646 +function onCorkedFinish(corkReq, state, err) {
647 + var entry = corkReq.entry;
648 + corkReq.entry = null;
649 + while (entry) {
650 + var cb = entry.callback;
651 + state.pendingcb--;
652 + cb(err);
653 + entry = entry.next;
654 + }
655 + if (state.corkedRequestsFree) {
656 + state.corkedRequestsFree.next = corkReq;
657 + } else {
658 + state.corkedRequestsFree = corkReq;
659 + }
660 +}
661 +
662 +Object.defineProperty(Writable.prototype, 'destroyed', {
663 + get: function () {
664 + if (this._writableState === undefined) {
665 + return false;
666 + }
667 + return this._writableState.destroyed;
668 + },
669 + set: function (value) {
670 + // we ignore the value if the stream
671 + // has not been initialized yet
672 + if (!this._writableState) {
673 + return;
674 + }
675 +
676 + // backward compatibility, the user is explicitly
677 + // managing destroyed
678 + this._writableState.destroyed = value;
679 + }
680 +});
681 +
682 +Writable.prototype.destroy = destroyImpl.destroy;
683 +Writable.prototype._undestroy = destroyImpl.undestroy;
684 +Writable.prototype._destroy = function (err, cb) {
685 + this.end();
686 + cb(err);
687 +};
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
4 +
5 +var Buffer = require('safe-buffer').Buffer;
6 +var util = require('util');
7 +
8 +function copyBuffer(src, target, offset) {
9 + src.copy(target, offset);
10 +}
11 +
12 +module.exports = function () {
13 + function BufferList() {
14 + _classCallCheck(this, BufferList);
15 +
16 + this.head = null;
17 + this.tail = null;
18 + this.length = 0;
19 + }
20 +
21 + BufferList.prototype.push = function push(v) {
22 + var entry = { data: v, next: null };
23 + if (this.length > 0) this.tail.next = entry;else this.head = entry;
24 + this.tail = entry;
25 + ++this.length;
26 + };
27 +
28 + BufferList.prototype.unshift = function unshift(v) {
29 + var entry = { data: v, next: this.head };
30 + if (this.length === 0) this.tail = entry;
31 + this.head = entry;
32 + ++this.length;
33 + };
34 +
35 + BufferList.prototype.shift = function shift() {
36 + if (this.length === 0) return;
37 + var ret = this.head.data;
38 + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
39 + --this.length;
40 + return ret;
41 + };
42 +
43 + BufferList.prototype.clear = function clear() {
44 + this.head = this.tail = null;
45 + this.length = 0;
46 + };
47 +
48 + BufferList.prototype.join = function join(s) {
49 + if (this.length === 0) return '';
50 + var p = this.head;
51 + var ret = '' + p.data;
52 + while (p = p.next) {
53 + ret += s + p.data;
54 + }return ret;
55 + };
56 +
57 + BufferList.prototype.concat = function concat(n) {
58 + if (this.length === 0) return Buffer.alloc(0);
59 + if (this.length === 1) return this.head.data;
60 + var ret = Buffer.allocUnsafe(n >>> 0);
61 + var p = this.head;
62 + var i = 0;
63 + while (p) {
64 + copyBuffer(p.data, ret, i);
65 + i += p.data.length;
66 + p = p.next;
67 + }
68 + return ret;
69 + };
70 +
71 + return BufferList;
72 +}();
73 +
74 +if (util && util.inspect && util.inspect.custom) {
75 + module.exports.prototype[util.inspect.custom] = function () {
76 + var obj = util.inspect({ length: this.length });
77 + return this.constructor.name + ' ' + obj;
78 + };
79 +}
...\ No newline at end of file ...\ No newline at end of file
1 +'use strict';
2 +
3 +/*<replacement>*/
4 +
5 +var pna = require('process-nextick-args');
6 +/*</replacement>*/
7 +
8 +// undocumented cb() API, needed for core, not for public API
9 +function destroy(err, cb) {
10 + var _this = this;
11 +
12 + var readableDestroyed = this._readableState && this._readableState.destroyed;
13 + var writableDestroyed = this._writableState && this._writableState.destroyed;
14 +
15 + if (readableDestroyed || writableDestroyed) {
16 + if (cb) {
17 + cb(err);
18 + } else if (err && (!this._writableState || !this._writableState.errorEmitted)) {
19 + pna.nextTick(emitErrorNT, this, err);
20 + }
21 + return this;
22 + }
23 +
24 + // we set destroyed to true before firing error callbacks in order
25 + // to make it re-entrance safe in case destroy() is called within callbacks
26 +
27 + if (this._readableState) {
28 + this._readableState.destroyed = true;
29 + }
30 +
31 + // if this is a duplex stream mark the writable part as destroyed as well
32 + if (this._writableState) {
33 + this._writableState.destroyed = true;
34 + }
35 +
36 + this._destroy(err || null, function (err) {
37 + if (!cb && err) {
38 + pna.nextTick(emitErrorNT, _this, err);
39 + if (_this._writableState) {
40 + _this._writableState.errorEmitted = true;
41 + }
42 + } else if (cb) {
43 + cb(err);
44 + }
45 + });
46 +
47 + return this;
48 +}
49 +
50 +function undestroy() {
51 + if (this._readableState) {
52 + this._readableState.destroyed = false;
53 + this._readableState.reading = false;
54 + this._readableState.ended = false;
55 + this._readableState.endEmitted = false;
56 + }
57 +
58 + if (this._writableState) {
59 + this._writableState.destroyed = false;
60 + this._writableState.ended = false;
61 + this._writableState.ending = false;
62 + this._writableState.finished = false;
63 + this._writableState.errorEmitted = false;
64 + }
65 +}
66 +
67 +function emitErrorNT(self, err) {
68 + self.emit('error', err);
69 +}
70 +
71 +module.exports = {
72 + destroy: destroy,
73 + undestroy: undestroy
74 +};
...\ No newline at end of file ...\ No newline at end of file
1 +{
2 + "_from": "readable-stream@^2.2.2",
3 + "_id": "readable-stream@2.3.7",
4 + "_inBundle": false,
5 + "_integrity": "sha512-Ebho8K4jIbHAxnuxi7o42OrZgF/ZTNcsZj6nRKyUmkhLFq8CHItp/fy6hQZuZmP/n3yZ9VBUbp4zz/mX8hmYPw==",
6 + "_location": "/concat-stream/readable-stream",
7 + "_phantomChildren": {},
8 + "_requested": {
9 + "type": "range",
10 + "registry": true,
11 + "raw": "readable-stream@^2.2.2",
12 + "name": "readable-stream",
13 + "escapedName": "readable-stream",
14 + "rawSpec": "^2.2.2",
15 + "saveSpec": null,
16 + "fetchSpec": "^2.2.2"
17 + },
18 + "_requiredBy": [
19 + "/concat-stream"
20 + ],
21 + "_resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.7.tgz",
22 + "_shasum": "1eca1cf711aef814c04f62252a36a62f6cb23b57",
23 + "_spec": "readable-stream@^2.2.2",
24 + "_where": "C:\\Users\\1000c\\이것저것\\옾소\\Voicoding\\node_modules\\concat-stream",
25 + "browser": {
26 + "util": false,
27 + "./readable.js": "./readable-browser.js",
28 + "./writable.js": "./writable-browser.js",
29 + "./duplex.js": "./duplex-browser.js",
30 + "./lib/internal/streams/stream.js": "./lib/internal/streams/stream-browser.js"
31 + },
32 + "bugs": {
33 + "url": "https://github.com/nodejs/readable-stream/issues"
34 + },
35 + "bundleDependencies": false,
36 + "dependencies": {
37 + "core-util-is": "~1.0.0",
38 + "inherits": "~2.0.3",
39 + "isarray": "~1.0.0",
40 + "process-nextick-args": "~2.0.0",
41 + "safe-buffer": "~5.1.1",
42 + "string_decoder": "~1.1.1",
43 + "util-deprecate": "~1.0.1"
44 + },
45 + "deprecated": false,
46 + "description": "Streams3, a user-land copy of the stream library from Node.js",
47 + "devDependencies": {
48 + "assert": "^1.4.0",
49 + "babel-polyfill": "^6.9.1",
50 + "buffer": "^4.9.0",
51 + "lolex": "^2.3.2",
52 + "nyc": "^6.4.0",
53 + "tap": "^0.7.0",
54 + "tape": "^4.8.0"
55 + },
56 + "homepage": "https://github.com/nodejs/readable-stream#readme",
57 + "keywords": [
58 + "readable",
59 + "stream",
60 + "pipe"
61 + ],
62 + "license": "MIT",
63 + "main": "readable.js",
64 + "name": "readable-stream",
65 + "nyc": {
66 + "include": [
67 + "lib/**.js"
68 + ]
69 + },
70 + "repository": {
71 + "type": "git",
72 + "url": "git://github.com/nodejs/readable-stream.git"
73 + },
74 + "scripts": {
75 + "ci": "tap test/parallel/*.js test/ours/*.js --tap | tee test.tap && node test/verify-dependencies.js",
76 + "cover": "nyc npm test",
77 + "report": "nyc report --reporter=lcov",
78 + "test": "tap test/parallel/*.js test/ours/*.js && node test/verify-dependencies.js"
79 + },
80 + "version": "2.3.7"
81 +}
1 +module.exports = require('./readable').PassThrough
1 +exports = module.exports = require('./lib/_stream_readable.js');
2 +exports.Stream = exports;
3 +exports.Readable = exports;
4 +exports.Writable = require('./lib/_stream_writable.js');
5 +exports.Duplex = require('./lib/_stream_duplex.js');
6 +exports.Transform = require('./lib/_stream_transform.js');
7 +exports.PassThrough = require('./lib/_stream_passthrough.js');
1 +var Stream = require('stream');
2 +if (process.env.READABLE_STREAM === 'disable' && Stream) {
3 + module.exports = Stream;
4 + exports = module.exports = Stream.Readable;
5 + exports.Readable = Stream.Readable;
6 + exports.Writable = Stream.Writable;
7 + exports.Duplex = Stream.Duplex;
8 + exports.Transform = Stream.Transform;
9 + exports.PassThrough = Stream.PassThrough;
10 + exports.Stream = Stream;
11 +} else {
12 + exports = module.exports = require('./lib/_stream_readable.js');
13 + exports.Stream = Stream || exports;
14 + exports.Readable = exports;
15 + exports.Writable = require('./lib/_stream_writable.js');
16 + exports.Duplex = require('./lib/_stream_duplex.js');
17 + exports.Transform = require('./lib/_stream_transform.js');
18 + exports.PassThrough = require('./lib/_stream_passthrough.js');
19 +}
1 +module.exports = require('./readable').Transform
1 +module.exports = require('./lib/_stream_writable.js');
1 +var Stream = require("stream")
2 +var Writable = require("./lib/_stream_writable.js")
3 +
4 +if (process.env.READABLE_STREAM === 'disable') {
5 + module.exports = Stream && Stream.Writable || Writable
6 +} else {
7 + module.exports = Writable
8 +}
1 +sudo: false
2 +language: node_js
3 +before_install:
4 + - npm install -g npm@2
5 + - test $NPM_LEGACY && npm install -g npm@latest-3 || npm install npm -g
6 +notifications:
7 + email: false
8 +matrix:
9 + fast_finish: true
10 + include:
11 + - node_js: '0.8'
12 + env:
13 + - TASK=test
14 + - NPM_LEGACY=true
15 + - node_js: '0.10'
16 + env:
17 + - TASK=test
18 + - NPM_LEGACY=true
19 + - node_js: '0.11'
20 + env:
21 + - TASK=test
22 + - NPM_LEGACY=true
23 + - node_js: '0.12'
24 + env:
25 + - TASK=test
26 + - NPM_LEGACY=true
27 + - node_js: 1
28 + env:
29 + - TASK=test
30 + - NPM_LEGACY=true
31 + - node_js: 2
32 + env:
33 + - TASK=test
34 + - NPM_LEGACY=true
35 + - node_js: 3
36 + env:
37 + - TASK=test
38 + - NPM_LEGACY=true
39 + - node_js: 4
40 + env: TASK=test
41 + - node_js: 5
42 + env: TASK=test
43 + - node_js: 6
44 + env: TASK=test
45 + - node_js: 7
46 + env: TASK=test
47 + - node_js: 8
48 + env: TASK=test
49 + - node_js: 9
50 + env: TASK=test
1 +Node.js is licensed for use as follows:
2 +
3 +"""
4 +Copyright Node.js contributors. All rights reserved.
5 +
6 +Permission is hereby granted, free of charge, to any person obtaining a copy
7 +of this software and associated documentation files (the "Software"), to
8 +deal in the Software without restriction, including without limitation the
9 +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
10 +sell copies of the Software, and to permit persons to whom the Software is
11 +furnished to do so, subject to the following conditions:
12 +
13 +The above copyright notice and this permission notice shall be included in
14 +all copies or substantial portions of the Software.
15 +
16 +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21 +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
22 +IN THE SOFTWARE.
23 +"""
24 +
25 +This license applies to parts of Node.js originating from the
26 +https://github.com/joyent/node repository:
27 +
28 +"""
29 +Copyright Joyent, Inc. and other Node contributors. All rights reserved.
30 +Permission is hereby granted, free of charge, to any person obtaining a copy
31 +of this software and associated documentation files (the "Software"), to
32 +deal in the Software without restriction, including without limitation the
33 +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
34 +sell copies of the Software, and to permit persons to whom the Software is
35 +furnished to do so, subject to the following conditions:
36 +
37 +The above copyright notice and this permission notice shall be included in
38 +all copies or substantial portions of the Software.
39 +
40 +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
41 +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
42 +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
43 +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
44 +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
45 +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
46 +IN THE SOFTWARE.
47 +"""
48 +
1 +# string_decoder
2 +
3 +***Node-core v8.9.4 string_decoder for userland***
4 +
5 +
6 +[![NPM](https://nodei.co/npm/string_decoder.png?downloads=true&downloadRank=true)](https://nodei.co/npm/string_decoder/)
7 +[![NPM](https://nodei.co/npm-dl/string_decoder.png?&months=6&height=3)](https://nodei.co/npm/string_decoder/)
8 +
9 +
10 +```bash
11 +npm install --save string_decoder
12 +```
13 +
14 +***Node-core string_decoder for userland***
15 +
16 +This package is a mirror of the string_decoder implementation in Node-core.
17 +
18 +Full documentation may be found on the [Node.js website](https://nodejs.org/dist/v8.9.4/docs/api/).
19 +
20 +As of version 1.0.0 **string_decoder** uses semantic versioning.
21 +
22 +## Previous versions
23 +
24 +Previous version numbers match the versions found in Node core, e.g. 0.10.24 matches Node 0.10.24, likewise 0.11.10 matches Node 0.11.10.
25 +
26 +## Update
27 +
28 +The *build/* directory contains a build script that will scrape the source from the [nodejs/node](https://github.com/nodejs/node) repo given a specific Node version.
29 +
30 +## Streams Working Group
31 +
32 +`string_decoder` is maintained by the Streams Working Group, which
33 +oversees the development and maintenance of the Streams API within
34 +Node.js. The responsibilities of the Streams Working Group include:
35 +
36 +* Addressing stream issues on the Node.js issue tracker.
37 +* Authoring and editing stream documentation within the Node.js project.
38 +* Reviewing changes to stream subclasses within the Node.js project.
39 +* Redirecting changes to streams from the Node.js project to this
40 + project.
41 +* Assisting in the implementation of stream providers within Node.js.
42 +* Recommending versions of `readable-stream` to be included in Node.js.
43 +* Messaging about the future of streams to give the community advance
44 + notice of changes.
45 +
46 +See [readable-stream](https://github.com/nodejs/readable-stream) for
47 +more details.
1 +{
2 + "_from": "string_decoder@~1.1.1",
3 + "_id": "string_decoder@1.1.1",
4 + "_inBundle": false,
5 + "_integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==",
6 + "_location": "/concat-stream/string_decoder",
7 + "_phantomChildren": {},
8 + "_requested": {
9 + "type": "range",
10 + "registry": true,
11 + "raw": "string_decoder@~1.1.1",
12 + "name": "string_decoder",
13 + "escapedName": "string_decoder",
14 + "rawSpec": "~1.1.1",
15 + "saveSpec": null,
16 + "fetchSpec": "~1.1.1"
17 + },
18 + "_requiredBy": [
19 + "/concat-stream/readable-stream"
20 + ],
21 + "_resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz",
22 + "_shasum": "9cf1611ba62685d7030ae9e4ba34149c3af03fc8",
23 + "_spec": "string_decoder@~1.1.1",
24 + "_where": "C:\\Users\\1000c\\이것저것\\옾소\\Voicoding\\node_modules\\concat-stream\\node_modules\\readable-stream",
25 + "bugs": {
26 + "url": "https://github.com/nodejs/string_decoder/issues"
27 + },
28 + "bundleDependencies": false,
29 + "dependencies": {
30 + "safe-buffer": "~5.1.0"
31 + },
32 + "deprecated": false,
33 + "description": "The string_decoder module from Node core",
34 + "devDependencies": {
35 + "babel-polyfill": "^6.23.0",
36 + "core-util-is": "^1.0.2",
37 + "inherits": "^2.0.3",
38 + "tap": "~0.4.8"
39 + },
40 + "homepage": "https://github.com/nodejs/string_decoder",
41 + "keywords": [
42 + "string",
43 + "decoder",
44 + "browser",
45 + "browserify"
46 + ],
47 + "license": "MIT",
48 + "main": "lib/string_decoder.js",
49 + "name": "string_decoder",
50 + "repository": {
51 + "type": "git",
52 + "url": "git://github.com/nodejs/string_decoder.git"
53 + },
54 + "scripts": {
55 + "ci": "tap test/parallel/*.js test/ours/*.js --tap | tee test.tap && node test/verify-dependencies.js",
56 + "test": "tap test/parallel/*.js && node test/verify-dependencies"
57 + },
58 + "version": "1.1.1"
59 +}
1 +{
2 + "_from": "concat-stream@^1.5.2",
3 + "_id": "concat-stream@1.6.2",
4 + "_inBundle": false,
5 + "_integrity": "sha512-27HBghJxjiZtIk3Ycvn/4kbJk/1uZuJFfuPEns6LaEvpvG1f0hTea8lilrouyo9mVc2GWdcEZ8OLoGmSADlrCw==",
6 + "_location": "/concat-stream",
7 + "_phantomChildren": {
8 + "core-util-is": "1.0.2",
9 + "inherits": "2.0.4",
10 + "process-nextick-args": "2.0.1",
11 + "safe-buffer": "5.1.2",
12 + "util-deprecate": "1.0.2"
13 + },
14 + "_requested": {
15 + "type": "range",
16 + "registry": true,
17 + "raw": "concat-stream@^1.5.2",
18 + "name": "concat-stream",
19 + "escapedName": "concat-stream",
20 + "rawSpec": "^1.5.2",
21 + "saveSpec": null,
22 + "fetchSpec": "^1.5.2"
23 + },
24 + "_requiredBy": [
25 + "/multer"
26 + ],
27 + "_resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-1.6.2.tgz",
28 + "_shasum": "904bdf194cd3122fc675c77fc4ac3d4ff0fd1a34",
29 + "_spec": "concat-stream@^1.5.2",
30 + "_where": "C:\\Users\\1000c\\이것저것\\옾소\\Voicoding\\node_modules\\multer",
31 + "author": {
32 + "name": "Max Ogden",
33 + "email": "max@maxogden.com"
34 + },
35 + "bugs": {
36 + "url": "http://github.com/maxogden/concat-stream/issues"
37 + },
38 + "bundleDependencies": false,
39 + "dependencies": {
40 + "buffer-from": "^1.0.0",
41 + "inherits": "^2.0.3",
42 + "readable-stream": "^2.2.2",
43 + "typedarray": "^0.0.6"
44 + },
45 + "deprecated": false,
46 + "description": "writable stream that concatenates strings or binary data and calls a callback with the result",
47 + "devDependencies": {
48 + "tape": "^4.6.3"
49 + },
50 + "engines": [
51 + "node >= 0.8"
52 + ],
53 + "files": [
54 + "index.js"
55 + ],
56 + "homepage": "https://github.com/maxogden/concat-stream#readme",
57 + "license": "MIT",
58 + "main": "index.js",
59 + "name": "concat-stream",
60 + "repository": {
61 + "type": "git",
62 + "url": "git+ssh://git@github.com/maxogden/concat-stream.git"
63 + },
64 + "scripts": {
65 + "test": "tape test/*.js test/server/*.js"
66 + },
67 + "tags": [
68 + "stream",
69 + "simple",
70 + "util",
71 + "utility"
72 + ],
73 + "testling": {
74 + "files": "test/*.js",
75 + "browsers": [
76 + "ie/8..latest",
77 + "firefox/17..latest",
78 + "firefox/nightly",
79 + "chrome/22..latest",
80 + "chrome/canary",
81 + "opera/12..latest",
82 + "opera/next",
83 + "safari/5.1..latest",
84 + "ipad/6.0..latest",
85 + "iphone/6.0..latest",
86 + "android-browser/4.2..latest"
87 + ]
88 + },
89 + "version": "1.6.2"
90 +}
1 +# concat-stream
2 +
3 +Writable stream that concatenates all the data from a stream and calls a callback with the result. Use this when you want to collect all the data from a stream into a single buffer.
4 +
5 +[![Build Status](https://travis-ci.org/maxogden/concat-stream.svg?branch=master)](https://travis-ci.org/maxogden/concat-stream)
6 +
7 +[![NPM](https://nodei.co/npm/concat-stream.png)](https://nodei.co/npm/concat-stream/)
8 +
9 +### description
10 +
11 +Streams emit many buffers. If you want to collect all of the buffers, and when the stream ends concatenate all of the buffers together and receive a single buffer then this is the module for you.
12 +
13 +Only use this if you know you can fit all of the output of your stream into a single Buffer (e.g. in RAM).
14 +
15 +There are also `objectMode` streams that emit things other than Buffers, and you can concatenate these too. See below for details.
16 +
17 +## Related
18 +
19 +`concat-stream` is part of the [mississippi stream utility collection](https://github.com/maxogden/mississippi) which includes more useful stream modules similar to this one.
20 +
21 +### examples
22 +
23 +#### Buffers
24 +
25 +```js
26 +var fs = require('fs')
27 +var concat = require('concat-stream')
28 +
29 +var readStream = fs.createReadStream('cat.png')
30 +var concatStream = concat(gotPicture)
31 +
32 +readStream.on('error', handleError)
33 +readStream.pipe(concatStream)
34 +
35 +function gotPicture(imageBuffer) {
36 + // imageBuffer is all of `cat.png` as a node.js Buffer
37 +}
38 +
39 +function handleError(err) {
40 + // handle your error appropriately here, e.g.:
41 + console.error(err) // print the error to STDERR
42 + process.exit(1) // exit program with non-zero exit code
43 +}
44 +
45 +```
46 +
47 +#### Arrays
48 +
49 +```js
50 +var write = concat(function(data) {})
51 +write.write([1,2,3])
52 +write.write([4,5,6])
53 +write.end()
54 +// data will be [1,2,3,4,5,6] in the above callback
55 +```
56 +
57 +#### Uint8Arrays
58 +
59 +```js
60 +var write = concat(function(data) {})
61 +var a = new Uint8Array(3)
62 +a[0] = 97; a[1] = 98; a[2] = 99
63 +write.write(a)
64 +write.write('!')
65 +write.end(Buffer.from('!!1'))
66 +```
67 +
68 +See `test/` for more examples
69 +
70 +# methods
71 +
72 +```js
73 +var concat = require('concat-stream')
74 +```
75 +
76 +## var writable = concat(opts={}, cb)
77 +
78 +Return a `writable` stream that will fire `cb(data)` with all of the data that
79 +was written to the stream. Data can be written to `writable` as strings,
80 +Buffers, arrays of byte integers, and Uint8Arrays.
81 +
82 +By default `concat-stream` will give you back the same data type as the type of the first buffer written to the stream. Use `opts.encoding` to set what format `data` should be returned as, e.g. if you if you don't want to rely on the built-in type checking or for some other reason.
83 +
84 +* `string` - get a string
85 +* `buffer` - get back a Buffer
86 +* `array` - get an array of byte integers
87 +* `uint8array`, `u8`, `uint8` - get back a Uint8Array
88 +* `object`, get back an array of Objects
89 +
90 +If you don't specify an encoding, and the types can't be inferred (e.g. you write things that aren't in the list above), it will try to convert concat them into a `Buffer`.
91 +
92 +If nothing is written to `writable` then `data` will be an empty array `[]`.
93 +
94 +# error handling
95 +
96 +`concat-stream` does not handle errors for you, so you must handle errors on whatever streams you pipe into `concat-stream`. This is a general rule when programming with node.js streams: always handle errors on each and every stream. Since `concat-stream` is not itself a stream it does not emit errors.
97 +
98 +We recommend using [`end-of-stream`](https://npmjs.org/end-of-stream) or [`pump`](https://npmjs.org/pump) for writing error tolerant stream code.
99 +
100 +# license
101 +
102 +MIT LICENSE
1 +Copyright Node.js contributors. All rights reserved.
2 +
3 +Permission is hereby granted, free of charge, to any person obtaining a copy
4 +of this software and associated documentation files (the "Software"), to
5 +deal in the Software without restriction, including without limitation the
6 +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
7 +sell copies of the Software, and to permit persons to whom the Software is
8 +furnished to do so, subject to the following conditions:
9 +
10 +The above copyright notice and this permission notice shall be included in
11 +all copies or substantial portions of the Software.
12 +
13 +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
18 +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
19 +IN THE SOFTWARE.
1 +# core-util-is
2 +
3 +The `util.is*` functions introduced in Node v0.12.
1 +diff --git a/lib/util.js b/lib/util.js
2 +index a03e874..9074e8e 100644
3 +--- a/lib/util.js
4 ++++ b/lib/util.js
5 +@@ -19,430 +19,6 @@
6 + // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
7 + // USE OR OTHER DEALINGS IN THE SOFTWARE.
8 +
9 +-var formatRegExp = /%[sdj%]/g;
10 +-exports.format = function(f) {
11 +- if (!isString(f)) {
12 +- var objects = [];
13 +- for (var i = 0; i < arguments.length; i++) {
14 +- objects.push(inspect(arguments[i]));
15 +- }
16 +- return objects.join(' ');
17 +- }
18 +-
19 +- var i = 1;
20 +- var args = arguments;
21 +- var len = args.length;
22 +- var str = String(f).replace(formatRegExp, function(x) {
23 +- if (x === '%%') return '%';
24 +- if (i >= len) return x;
25 +- switch (x) {
26 +- case '%s': return String(args[i++]);
27 +- case '%d': return Number(args[i++]);
28 +- case '%j':
29 +- try {
30 +- return JSON.stringify(args[i++]);
31 +- } catch (_) {
32 +- return '[Circular]';
33 +- }
34 +- default:
35 +- return x;
36 +- }
37 +- });
38 +- for (var x = args[i]; i < len; x = args[++i]) {
39 +- if (isNull(x) || !isObject(x)) {
40 +- str += ' ' + x;
41 +- } else {
42 +- str += ' ' + inspect(x);
43 +- }
44 +- }
45 +- return str;
46 +-};
47 +-
48 +-
49 +-// Mark that a method should not be used.
50 +-// Returns a modified function which warns once by default.
51 +-// If --no-deprecation is set, then it is a no-op.
52 +-exports.deprecate = function(fn, msg) {
53 +- // Allow for deprecating things in the process of starting up.
54 +- if (isUndefined(global.process)) {
55 +- return function() {
56 +- return exports.deprecate(fn, msg).apply(this, arguments);
57 +- };
58 +- }
59 +-
60 +- if (process.noDeprecation === true) {
61 +- return fn;
62 +- }
63 +-
64 +- var warned = false;
65 +- function deprecated() {
66 +- if (!warned) {
67 +- if (process.throwDeprecation) {
68 +- throw new Error(msg);
69 +- } else if (process.traceDeprecation) {
70 +- console.trace(msg);
71 +- } else {
72 +- console.error(msg);
73 +- }
74 +- warned = true;
75 +- }
76 +- return fn.apply(this, arguments);
77 +- }
78 +-
79 +- return deprecated;
80 +-};
81 +-
82 +-
83 +-var debugs = {};
84 +-var debugEnviron;
85 +-exports.debuglog = function(set) {
86 +- if (isUndefined(debugEnviron))
87 +- debugEnviron = process.env.NODE_DEBUG || '';
88 +- set = set.toUpperCase();
89 +- if (!debugs[set]) {
90 +- if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
91 +- var pid = process.pid;
92 +- debugs[set] = function() {
93 +- var msg = exports.format.apply(exports, arguments);
94 +- console.error('%s %d: %s', set, pid, msg);
95 +- };
96 +- } else {
97 +- debugs[set] = function() {};
98 +- }
99 +- }
100 +- return debugs[set];
101 +-};
102 +-
103 +-
104 +-/**
105 +- * Echos the value of a value. Trys to print the value out
106 +- * in the best way possible given the different types.
107 +- *
108 +- * @param {Object} obj The object to print out.
109 +- * @param {Object} opts Optional options object that alters the output.
110 +- */
111 +-/* legacy: obj, showHidden, depth, colors*/
112 +-function inspect(obj, opts) {
113 +- // default options
114 +- var ctx = {
115 +- seen: [],
116 +- stylize: stylizeNoColor
117 +- };
118 +- // legacy...
119 +- if (arguments.length >= 3) ctx.depth = arguments[2];
120 +- if (arguments.length >= 4) ctx.colors = arguments[3];
121 +- if (isBoolean(opts)) {
122 +- // legacy...
123 +- ctx.showHidden = opts;
124 +- } else if (opts) {
125 +- // got an "options" object
126 +- exports._extend(ctx, opts);
127 +- }
128 +- // set default options
129 +- if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
130 +- if (isUndefined(ctx.depth)) ctx.depth = 2;
131 +- if (isUndefined(ctx.colors)) ctx.colors = false;
132 +- if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
133 +- if (ctx.colors) ctx.stylize = stylizeWithColor;
134 +- return formatValue(ctx, obj, ctx.depth);
135 +-}
136 +-exports.inspect = inspect;
137 +-
138 +-
139 +-// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
140 +-inspect.colors = {
141 +- 'bold' : [1, 22],
142 +- 'italic' : [3, 23],
143 +- 'underline' : [4, 24],
144 +- 'inverse' : [7, 27],
145 +- 'white' : [37, 39],
146 +- 'grey' : [90, 39],
147 +- 'black' : [30, 39],
148 +- 'blue' : [34, 39],
149 +- 'cyan' : [36, 39],
150 +- 'green' : [32, 39],
151 +- 'magenta' : [35, 39],
152 +- 'red' : [31, 39],
153 +- 'yellow' : [33, 39]
154 +-};
155 +-
156 +-// Don't use 'blue' not visible on cmd.exe
157 +-inspect.styles = {
158 +- 'special': 'cyan',
159 +- 'number': 'yellow',
160 +- 'boolean': 'yellow',
161 +- 'undefined': 'grey',
162 +- 'null': 'bold',
163 +- 'string': 'green',
164 +- 'date': 'magenta',
165 +- // "name": intentionally not styling
166 +- 'regexp': 'red'
167 +-};
168 +-
169 +-
170 +-function stylizeWithColor(str, styleType) {
171 +- var style = inspect.styles[styleType];
172 +-
173 +- if (style) {
174 +- return '\u001b[' + inspect.colors[style][0] + 'm' + str +
175 +- '\u001b[' + inspect.colors[style][1] + 'm';
176 +- } else {
177 +- return str;
178 +- }
179 +-}
180 +-
181 +-
182 +-function stylizeNoColor(str, styleType) {
183 +- return str;
184 +-}
185 +-
186 +-
187 +-function arrayToHash(array) {
188 +- var hash = {};
189 +-
190 +- array.forEach(function(val, idx) {
191 +- hash[val] = true;
192 +- });
193 +-
194 +- return hash;
195 +-}
196 +-
197 +-
198 +-function formatValue(ctx, value, recurseTimes) {
199 +- // Provide a hook for user-specified inspect functions.
200 +- // Check that value is an object with an inspect function on it
201 +- if (ctx.customInspect &&
202 +- value &&
203 +- isFunction(value.inspect) &&
204 +- // Filter out the util module, it's inspect function is special
205 +- value.inspect !== exports.inspect &&
206 +- // Also filter out any prototype objects using the circular check.
207 +- !(value.constructor && value.constructor.prototype === value)) {
208 +- var ret = value.inspect(recurseTimes, ctx);
209 +- if (!isString(ret)) {
210 +- ret = formatValue(ctx, ret, recurseTimes);
211 +- }
212 +- return ret;
213 +- }
214 +-
215 +- // Primitive types cannot have properties
216 +- var primitive = formatPrimitive(ctx, value);
217 +- if (primitive) {
218 +- return primitive;
219 +- }
220 +-
221 +- // Look up the keys of the object.
222 +- var keys = Object.keys(value);
223 +- var visibleKeys = arrayToHash(keys);
224 +-
225 +- if (ctx.showHidden) {
226 +- keys = Object.getOwnPropertyNames(value);
227 +- }
228 +-
229 +- // Some type of object without properties can be shortcutted.
230 +- if (keys.length === 0) {
231 +- if (isFunction(value)) {
232 +- var name = value.name ? ': ' + value.name : '';
233 +- return ctx.stylize('[Function' + name + ']', 'special');
234 +- }
235 +- if (isRegExp(value)) {
236 +- return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
237 +- }
238 +- if (isDate(value)) {
239 +- return ctx.stylize(Date.prototype.toString.call(value), 'date');
240 +- }
241 +- if (isError(value)) {
242 +- return formatError(value);
243 +- }
244 +- }
245 +-
246 +- var base = '', array = false, braces = ['{', '}'];
247 +-
248 +- // Make Array say that they are Array
249 +- if (isArray(value)) {
250 +- array = true;
251 +- braces = ['[', ']'];
252 +- }
253 +-
254 +- // Make functions say that they are functions
255 +- if (isFunction(value)) {
256 +- var n = value.name ? ': ' + value.name : '';
257 +- base = ' [Function' + n + ']';
258 +- }
259 +-
260 +- // Make RegExps say that they are RegExps
261 +- if (isRegExp(value)) {
262 +- base = ' ' + RegExp.prototype.toString.call(value);
263 +- }
264 +-
265 +- // Make dates with properties first say the date
266 +- if (isDate(value)) {
267 +- base = ' ' + Date.prototype.toUTCString.call(value);
268 +- }
269 +-
270 +- // Make error with message first say the error
271 +- if (isError(value)) {
272 +- base = ' ' + formatError(value);
273 +- }
274 +-
275 +- if (keys.length === 0 && (!array || value.length == 0)) {
276 +- return braces[0] + base + braces[1];
277 +- }
278 +-
279 +- if (recurseTimes < 0) {
280 +- if (isRegExp(value)) {
281 +- return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
282 +- } else {
283 +- return ctx.stylize('[Object]', 'special');
284 +- }
285 +- }
286 +-
287 +- ctx.seen.push(value);
288 +-
289 +- var output;
290 +- if (array) {
291 +- output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
292 +- } else {
293 +- output = keys.map(function(key) {
294 +- return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
295 +- });
296 +- }
297 +-
298 +- ctx.seen.pop();
299 +-
300 +- return reduceToSingleString(output, base, braces);
301 +-}
302 +-
303 +-
304 +-function formatPrimitive(ctx, value) {
305 +- if (isUndefined(value))
306 +- return ctx.stylize('undefined', 'undefined');
307 +- if (isString(value)) {
308 +- var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
309 +- .replace(/'/g, "\\'")
310 +- .replace(/\\"/g, '"') + '\'';
311 +- return ctx.stylize(simple, 'string');
312 +- }
313 +- if (isNumber(value)) {
314 +- // Format -0 as '-0'. Strict equality won't distinguish 0 from -0,
315 +- // so instead we use the fact that 1 / -0 < 0 whereas 1 / 0 > 0 .
316 +- if (value === 0 && 1 / value < 0)
317 +- return ctx.stylize('-0', 'number');
318 +- return ctx.stylize('' + value, 'number');
319 +- }
320 +- if (isBoolean(value))
321 +- return ctx.stylize('' + value, 'boolean');
322 +- // For some reason typeof null is "object", so special case here.
323 +- if (isNull(value))
324 +- return ctx.stylize('null', 'null');
325 +-}
326 +-
327 +-
328 +-function formatError(value) {
329 +- return '[' + Error.prototype.toString.call(value) + ']';
330 +-}
331 +-
332 +-
333 +-function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
334 +- var output = [];
335 +- for (var i = 0, l = value.length; i < l; ++i) {
336 +- if (hasOwnProperty(value, String(i))) {
337 +- output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
338 +- String(i), true));
339 +- } else {
340 +- output.push('');
341 +- }
342 +- }
343 +- keys.forEach(function(key) {
344 +- if (!key.match(/^\d+$/)) {
345 +- output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
346 +- key, true));
347 +- }
348 +- });
349 +- return output;
350 +-}
351 +-
352 +-
353 +-function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
354 +- var name, str, desc;
355 +- desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
356 +- if (desc.get) {
357 +- if (desc.set) {
358 +- str = ctx.stylize('[Getter/Setter]', 'special');
359 +- } else {
360 +- str = ctx.stylize('[Getter]', 'special');
361 +- }
362 +- } else {
363 +- if (desc.set) {
364 +- str = ctx.stylize('[Setter]', 'special');
365 +- }
366 +- }
367 +- if (!hasOwnProperty(visibleKeys, key)) {
368 +- name = '[' + key + ']';
369 +- }
370 +- if (!str) {
371 +- if (ctx.seen.indexOf(desc.value) < 0) {
372 +- if (isNull(recurseTimes)) {
373 +- str = formatValue(ctx, desc.value, null);
374 +- } else {
375 +- str = formatValue(ctx, desc.value, recurseTimes - 1);
376 +- }
377 +- if (str.indexOf('\n') > -1) {
378 +- if (array) {
379 +- str = str.split('\n').map(function(line) {
380 +- return ' ' + line;
381 +- }).join('\n').substr(2);
382 +- } else {
383 +- str = '\n' + str.split('\n').map(function(line) {
384 +- return ' ' + line;
385 +- }).join('\n');
386 +- }
387 +- }
388 +- } else {
389 +- str = ctx.stylize('[Circular]', 'special');
390 +- }
391 +- }
392 +- if (isUndefined(name)) {
393 +- if (array && key.match(/^\d+$/)) {
394 +- return str;
395 +- }
396 +- name = JSON.stringify('' + key);
397 +- if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
398 +- name = name.substr(1, name.length - 2);
399 +- name = ctx.stylize(name, 'name');
400 +- } else {
401 +- name = name.replace(/'/g, "\\'")
402 +- .replace(/\\"/g, '"')
403 +- .replace(/(^"|"$)/g, "'");
404 +- name = ctx.stylize(name, 'string');
405 +- }
406 +- }
407 +-
408 +- return name + ': ' + str;
409 +-}
410 +-
411 +-
412 +-function reduceToSingleString(output, base, braces) {
413 +- var numLinesEst = 0;
414 +- var length = output.reduce(function(prev, cur) {
415 +- numLinesEst++;
416 +- if (cur.indexOf('\n') >= 0) numLinesEst++;
417 +- return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
418 +- }, 0);
419 +-
420 +- if (length > 60) {
421 +- return braces[0] +
422 +- (base === '' ? '' : base + '\n ') +
423 +- ' ' +
424 +- output.join(',\n ') +
425 +- ' ' +
426 +- braces[1];
427 +- }
428 +-
429 +- return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
430 +-}
431 +-
432 +-
433 + // NOTE: These type checking functions intentionally don't use `instanceof`
434 + // because it is fragile and can be easily faked with `Object.create()`.
435 + function isArray(ar) {
436 +@@ -522,166 +98,10 @@ function isPrimitive(arg) {
437 + exports.isPrimitive = isPrimitive;
438 +
439 + function isBuffer(arg) {
440 +- return arg instanceof Buffer;
441 ++ return Buffer.isBuffer(arg);
442 + }
443 + exports.isBuffer = isBuffer;
444 +
445 + function objectToString(o) {
446 + return Object.prototype.toString.call(o);
447 +-}
448 +-
449 +-
450 +-function pad(n) {
451 +- return n < 10 ? '0' + n.toString(10) : n.toString(10);
452 +-}
453 +-
454 +-
455 +-var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
456 +- 'Oct', 'Nov', 'Dec'];
457 +-
458 +-// 26 Feb 16:19:34
459 +-function timestamp() {
460 +- var d = new Date();
461 +- var time = [pad(d.getHours()),
462 +- pad(d.getMinutes()),
463 +- pad(d.getSeconds())].join(':');
464 +- return [d.getDate(), months[d.getMonth()], time].join(' ');
465 +-}
466 +-
467 +-
468 +-// log is just a thin wrapper to console.log that prepends a timestamp
469 +-exports.log = function() {
470 +- console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
471 +-};
472 +-
473 +-
474 +-/**
475 +- * Inherit the prototype methods from one constructor into another.
476 +- *
477 +- * The Function.prototype.inherits from lang.js rewritten as a standalone
478 +- * function (not on Function.prototype). NOTE: If this file is to be loaded
479 +- * during bootstrapping this function needs to be rewritten using some native
480 +- * functions as prototype setup using normal JavaScript does not work as
481 +- * expected during bootstrapping (see mirror.js in r114903).
482 +- *
483 +- * @param {function} ctor Constructor function which needs to inherit the
484 +- * prototype.
485 +- * @param {function} superCtor Constructor function to inherit prototype from.
486 +- */
487 +-exports.inherits = function(ctor, superCtor) {
488 +- ctor.super_ = superCtor;
489 +- ctor.prototype = Object.create(superCtor.prototype, {
490 +- constructor: {
491 +- value: ctor,
492 +- enumerable: false,
493 +- writable: true,
494 +- configurable: true
495 +- }
496 +- });
497 +-};
498 +-
499 +-exports._extend = function(origin, add) {
500 +- // Don't do anything if add isn't an object
501 +- if (!add || !isObject(add)) return origin;
502 +-
503 +- var keys = Object.keys(add);
504 +- var i = keys.length;
505 +- while (i--) {
506 +- origin[keys[i]] = add[keys[i]];
507 +- }
508 +- return origin;
509 +-};
510 +-
511 +-function hasOwnProperty(obj, prop) {
512 +- return Object.prototype.hasOwnProperty.call(obj, prop);
513 +-}
514 +-
515 +-
516 +-// Deprecated old stuff.
517 +-
518 +-exports.p = exports.deprecate(function() {
519 +- for (var i = 0, len = arguments.length; i < len; ++i) {
520 +- console.error(exports.inspect(arguments[i]));
521 +- }
522 +-}, 'util.p: Use console.error() instead');
523 +-
524 +-
525 +-exports.exec = exports.deprecate(function() {
526 +- return require('child_process').exec.apply(this, arguments);
527 +-}, 'util.exec is now called `child_process.exec`.');
528 +-
529 +-
530 +-exports.print = exports.deprecate(function() {
531 +- for (var i = 0, len = arguments.length; i < len; ++i) {
532 +- process.stdout.write(String(arguments[i]));
533 +- }
534 +-}, 'util.print: Use console.log instead');
535 +-
536 +-
537 +-exports.puts = exports.deprecate(function() {
538 +- for (var i = 0, len = arguments.length; i < len; ++i) {
539 +- process.stdout.write(arguments[i] + '\n');
540 +- }
541 +-}, 'util.puts: Use console.log instead');
542 +-
543 +-
544 +-exports.debug = exports.deprecate(function(x) {
545 +- process.stderr.write('DEBUG: ' + x + '\n');
546 +-}, 'util.debug: Use console.error instead');
547 +-
548 +-
549 +-exports.error = exports.deprecate(function(x) {
550 +- for (var i = 0, len = arguments.length; i < len; ++i) {
551 +- process.stderr.write(arguments[i] + '\n');
552 +- }
553 +-}, 'util.error: Use console.error instead');
554 +-
555 +-
556 +-exports.pump = exports.deprecate(function(readStream, writeStream, callback) {
557 +- var callbackCalled = false;
558 +-
559 +- function call(a, b, c) {
560 +- if (callback && !callbackCalled) {
561 +- callback(a, b, c);
562 +- callbackCalled = true;
563 +- }
564 +- }
565 +-
566 +- readStream.addListener('data', function(chunk) {
567 +- if (writeStream.write(chunk) === false) readStream.pause();
568 +- });
569 +-
570 +- writeStream.addListener('drain', function() {
571 +- readStream.resume();
572 +- });
573 +-
574 +- readStream.addListener('end', function() {
575 +- writeStream.end();
576 +- });
577 +-
578 +- readStream.addListener('close', function() {
579 +- call();
580 +- });
581 +-
582 +- readStream.addListener('error', function(err) {
583 +- writeStream.end();
584 +- call(err);
585 +- });
586 +-
587 +- writeStream.addListener('error', function(err) {
588 +- readStream.destroy();
589 +- call(err);
590 +- });
591 +-}, 'util.pump(): Use readableStream.pipe() instead');
592 +-
593 +-
594 +-var uv;
595 +-exports._errnoException = function(err, syscall) {
596 +- if (isUndefined(uv)) uv = process.binding('uv');
597 +- var errname = uv.errname(err);
598 +- var e = new Error(syscall + ' ' + errname);
599 +- e.code = errname;
600 +- e.errno = errname;
601 +- e.syscall = syscall;
602 +- return e;
603 +-};
604 ++}
...\ No newline at end of file ...\ No newline at end of file
1 +// Copyright Joyent, Inc. and other Node contributors.
2 +//
3 +// Permission is hereby granted, free of charge, to any person obtaining a
4 +// copy of this software and associated documentation files (the
5 +// "Software"), to deal in the Software without restriction, including
6 +// without limitation the rights to use, copy, modify, merge, publish,
7 +// distribute, sublicense, and/or sell copies of the Software, and to permit
8 +// persons to whom the Software is furnished to do so, subject to the
9 +// following conditions:
10 +//
11 +// The above copyright notice and this permission notice shall be included
12 +// in all copies or substantial portions of the Software.
13 +//
14 +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15 +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17 +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18 +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19 +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20 +// USE OR OTHER DEALINGS IN THE SOFTWARE.
21 +
22 +// NOTE: These type checking functions intentionally don't use `instanceof`
23 +// because it is fragile and can be easily faked with `Object.create()`.
24 +
25 +function isArray(arg) {
26 + if (Array.isArray) {
27 + return Array.isArray(arg);
28 + }
29 + return objectToString(arg) === '[object Array]';
30 +}
31 +exports.isArray = isArray;
32 +
33 +function isBoolean(arg) {
34 + return typeof arg === 'boolean';
35 +}
36 +exports.isBoolean = isBoolean;
37 +
38 +function isNull(arg) {
39 + return arg === null;
40 +}
41 +exports.isNull = isNull;
42 +
43 +function isNullOrUndefined(arg) {
44 + return arg == null;
45 +}
46 +exports.isNullOrUndefined = isNullOrUndefined;
47 +
48 +function isNumber(arg) {
49 + return typeof arg === 'number';
50 +}
51 +exports.isNumber = isNumber;
52 +
53 +function isString(arg) {
54 + return typeof arg === 'string';
55 +}
56 +exports.isString = isString;
57 +
58 +function isSymbol(arg) {
59 + return typeof arg === 'symbol';
60 +}
61 +exports.isSymbol = isSymbol;
62 +
63 +function isUndefined(arg) {
64 + return arg === void 0;
65 +}
66 +exports.isUndefined = isUndefined;
67 +
68 +function isRegExp(re) {
69 + return objectToString(re) === '[object RegExp]';
70 +}
71 +exports.isRegExp = isRegExp;
72 +
73 +function isObject(arg) {
74 + return typeof arg === 'object' && arg !== null;
75 +}
76 +exports.isObject = isObject;
77 +
78 +function isDate(d) {
79 + return objectToString(d) === '[object Date]';
80 +}
81 +exports.isDate = isDate;
82 +
83 +function isError(e) {
84 + return (objectToString(e) === '[object Error]' || e instanceof Error);
85 +}
86 +exports.isError = isError;
87 +
88 +function isFunction(arg) {
89 + return typeof arg === 'function';
90 +}
91 +exports.isFunction = isFunction;
92 +
93 +function isPrimitive(arg) {
94 + return arg === null ||
95 + typeof arg === 'boolean' ||
96 + typeof arg === 'number' ||
97 + typeof arg === 'string' ||
98 + typeof arg === 'symbol' || // ES6 symbol
99 + typeof arg === 'undefined';
100 +}
101 +exports.isPrimitive = isPrimitive;
102 +
103 +exports.isBuffer = Buffer.isBuffer;
104 +
105 +function objectToString(o) {
106 + return Object.prototype.toString.call(o);
107 +}
1 +{
2 + "_from": "core-util-is@~1.0.0",
3 + "_id": "core-util-is@1.0.2",
4 + "_inBundle": false,
5 + "_integrity": "sha1-tf1UIgqivFq1eqtxQMlAdUUDwac=",
6 + "_location": "/core-util-is",
7 + "_phantomChildren": {},
8 + "_requested": {
9 + "type": "range",
10 + "registry": true,
11 + "raw": "core-util-is@~1.0.0",
12 + "name": "core-util-is",
13 + "escapedName": "core-util-is",
14 + "rawSpec": "~1.0.0",
15 + "saveSpec": null,
16 + "fetchSpec": "~1.0.0"
17 + },
18 + "_requiredBy": [
19 + "/concat-stream/readable-stream",
20 + "/readable-stream"
21 + ],
22 + "_resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz",
23 + "_shasum": "b5fd54220aa2bc5ab57aab7140c940754503c1a7",
24 + "_spec": "core-util-is@~1.0.0",
25 + "_where": "C:\\Users\\1000c\\이것저것\\옾소\\Voicoding\\node_modules\\readable-stream",
26 + "author": {
27 + "name": "Isaac Z. Schlueter",
28 + "email": "i@izs.me",
29 + "url": "http://blog.izs.me/"
30 + },
31 + "bugs": {
32 + "url": "https://github.com/isaacs/core-util-is/issues"
33 + },
34 + "bundleDependencies": false,
35 + "deprecated": false,
36 + "description": "The `util.is*` functions introduced in Node v0.12.",
37 + "devDependencies": {
38 + "tap": "^2.3.0"
39 + },
40 + "homepage": "https://github.com/isaacs/core-util-is#readme",
41 + "keywords": [
42 + "util",
43 + "isBuffer",
44 + "isArray",
45 + "isNumber",
46 + "isString",
47 + "isRegExp",
48 + "isThis",
49 + "isThat",
50 + "polyfill"
51 + ],
52 + "license": "MIT",
53 + "main": "lib/util.js",
54 + "name": "core-util-is",
55 + "repository": {
56 + "type": "git",
57 + "url": "git://github.com/isaacs/core-util-is.git"
58 + },
59 + "scripts": {
60 + "test": "tap test.js"
61 + },
62 + "version": "1.0.2"
63 +}
1 +var assert = require('tap');
2 +
3 +var t = require('./lib/util');
4 +
5 +assert.equal(t.isArray([]), true);
6 +assert.equal(t.isArray({}), false);
7 +
8 +assert.equal(t.isBoolean(null), false);
9 +assert.equal(t.isBoolean(true), true);
10 +assert.equal(t.isBoolean(false), true);
11 +
12 +assert.equal(t.isNull(null), true);
13 +assert.equal(t.isNull(undefined), false);
14 +assert.equal(t.isNull(false), false);
15 +assert.equal(t.isNull(), false);
16 +
17 +assert.equal(t.isNullOrUndefined(null), true);
18 +assert.equal(t.isNullOrUndefined(undefined), true);
19 +assert.equal(t.isNullOrUndefined(false), false);
20 +assert.equal(t.isNullOrUndefined(), true);
21 +
22 +assert.equal(t.isNumber(null), false);
23 +assert.equal(t.isNumber('1'), false);
24 +assert.equal(t.isNumber(1), true);
25 +
26 +assert.equal(t.isString(null), false);
27 +assert.equal(t.isString('1'), true);
28 +assert.equal(t.isString(1), false);
29 +
30 +assert.equal(t.isSymbol(null), false);
31 +assert.equal(t.isSymbol('1'), false);
32 +assert.equal(t.isSymbol(1), false);
33 +assert.equal(t.isSymbol(Symbol()), true);
34 +
35 +assert.equal(t.isUndefined(null), false);
36 +assert.equal(t.isUndefined(undefined), true);
37 +assert.equal(t.isUndefined(false), false);
38 +assert.equal(t.isUndefined(), true);
39 +
40 +assert.equal(t.isRegExp(null), false);
41 +assert.equal(t.isRegExp('1'), false);
42 +assert.equal(t.isRegExp(new RegExp()), true);
43 +
44 +assert.equal(t.isObject({}), true);
45 +assert.equal(t.isObject([]), true);
46 +assert.equal(t.isObject(new RegExp()), true);
47 +assert.equal(t.isObject(new Date()), true);
48 +
49 +assert.equal(t.isDate(null), false);
50 +assert.equal(t.isDate('1'), false);
51 +assert.equal(t.isDate(new Date()), true);
52 +
53 +assert.equal(t.isError(null), false);
54 +assert.equal(t.isError({ err: true }), false);
55 +assert.equal(t.isError(new Error()), true);
56 +
57 +assert.equal(t.isFunction(null), false);
58 +assert.equal(t.isFunction({ }), false);
59 +assert.equal(t.isFunction(function() {}), true);
60 +
61 +assert.equal(t.isPrimitive(null), true);
62 +assert.equal(t.isPrimitive(''), true);
63 +assert.equal(t.isPrimitive(0), true);
64 +assert.equal(t.isPrimitive(new Date()), false);
65 +
66 +assert.equal(t.isBuffer(null), false);
67 +assert.equal(t.isBuffer({}), false);
68 +assert.equal(t.isBuffer(new Buffer(0)), true);
1 +sudo: false
2 +language: cpp
3 +notifications:
4 + email: false
5 +env:
6 + matrix:
7 + - TRAVIS_NODE_VERSION="0.10"
8 + - TRAVIS_NODE_VERSION="0.12"
9 + - TRAVIS_NODE_VERSION="4"
10 + - TRAVIS_NODE_VERSION="5"
11 +install:
12 + - rm -rf ~/.nvm && git clone https://github.com/creationix/nvm.git ~/.nvm && source ~/.nvm/nvm.sh && nvm install $TRAVIS_NODE_VERSION
13 + - node --version
14 + - npm --version
15 + - npm install
16 +script: npm test
1 +Copyright Brian White. All rights reserved.
2 +
3 +Permission is hereby granted, free of charge, to any person obtaining a copy
4 +of this software and associated documentation files (the "Software"), to
5 +deal in the Software without restriction, including without limitation the
6 +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
7 +sell copies of the Software, and to permit persons to whom the Software is
8 +furnished to do so, subject to the following conditions:
9 +
10 +The above copyright notice and this permission notice shall be included in
11 +all copies or substantial portions of the Software.
12 +
13 +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
18 +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
19 +IN THE SOFTWARE.
...\ No newline at end of file ...\ No newline at end of file
1 +
2 +Description
3 +===========
4 +
5 +A very fast streaming multipart parser for node.js.
6 +
7 +Benchmarks can be found [here](https://github.com/mscdex/dicer/wiki/Benchmarks).
8 +
9 +
10 +Requirements
11 +============
12 +
13 +* [node.js](http://nodejs.org/) -- v0.8.0 or newer
14 +
15 +
16 +Install
17 +============
18 +
19 + npm install dicer
20 +
21 +
22 +Examples
23 +========
24 +
25 +* Parse an HTTP form upload
26 +
27 +```javascript
28 +var inspect = require('util').inspect,
29 + http = require('http');
30 +
31 +var Dicer = require('dicer');
32 +
33 + // quick and dirty way to parse multipart boundary
34 +var RE_BOUNDARY = /^multipart\/.+?(?:; boundary=(?:(?:"(.+)")|(?:([^\s]+))))$/i,
35 + HTML = new Buffer('<html><head></head><body>\
36 + <form method="POST" enctype="multipart/form-data">\
37 + <input type="text" name="textfield"><br />\
38 + <input type="file" name="filefield"><br />\
39 + <input type="submit">\
40 + </form>\
41 + </body></html>'),
42 + PORT = 8080;
43 +
44 +http.createServer(function(req, res) {
45 + var m;
46 + if (req.method === 'POST'
47 + && req.headers['content-type']
48 + && (m = RE_BOUNDARY.exec(req.headers['content-type']))) {
49 + var d = new Dicer({ boundary: m[1] || m[2] });
50 +
51 + d.on('part', function(p) {
52 + console.log('New part!');
53 + p.on('header', function(header) {
54 + for (var h in header) {
55 + console.log('Part header: k: ' + inspect(h)
56 + + ', v: ' + inspect(header[h]));
57 + }
58 + });
59 + p.on('data', function(data) {
60 + console.log('Part data: ' + inspect(data.toString()));
61 + });
62 + p.on('end', function() {
63 + console.log('End of part\n');
64 + });
65 + });
66 + d.on('finish', function() {
67 + console.log('End of parts');
68 + res.writeHead(200);
69 + res.end('Form submission successful!');
70 + });
71 + req.pipe(d);
72 + } else if (req.method === 'GET' && req.url === '/') {
73 + res.writeHead(200);
74 + res.end(HTML);
75 + } else {
76 + res.writeHead(404);
77 + res.end();
78 + }
79 +}).listen(PORT, function() {
80 + console.log('Listening for requests on port ' + PORT);
81 +});
82 +```
83 +
84 +
85 +API
86 +===
87 +
88 +_Dicer_ is a _WritableStream_
89 +
90 +Dicer (special) events
91 +----------------------
92 +
93 +* **finish**() - Emitted when all parts have been parsed and the Dicer instance has been ended.
94 +
95 +* **part**(< _PartStream_ >stream) - Emitted when a new part has been found.
96 +
97 +* **preamble**(< _PartStream_ >stream) - Emitted for preamble if you should happen to need it (can usually be ignored).
98 +
99 +* **trailer**(< _Buffer_ >data) - Emitted when trailing data was found after the terminating boundary (as with the preamble, this can usually be ignored too).
100 +
101 +
102 +Dicer methods
103 +-------------
104 +
105 +* **(constructor)**(< _object_ >config) - Creates and returns a new Dicer instance with the following valid `config` settings:
106 +
107 + * **boundary** - _string_ - This is the boundary used to detect the beginning of a new part.
108 +
109 + * **headerFirst** - _boolean_ - If true, preamble header parsing will be performed first.
110 +
111 + * **maxHeaderPairs** - _integer_ - The maximum number of header key=>value pairs to parse **Default:** 2000 (same as node's http).
112 +
113 +* **setBoundary**(< _string_ >boundary) - _(void)_ - Sets the boundary to use for parsing and performs some initialization needed for parsing. You should only need to use this if you set `headerFirst` to true in the constructor and are parsing the boundary from the preamble header.
114 +
115 +
116 +
117 +_PartStream_ is a _ReadableStream_
118 +
119 +PartStream (special) events
120 +---------------------------
121 +
122 +* **header**(< _object_ >header) - An object containing the header for this particular part. Each property value is an _array_ of one or more string values.
1 +var assert = require('assert');
2 +var Dicer = require('..'),
3 + boundary = '-----------------------------168072824752491622650073',
4 + d = new Dicer({ boundary: boundary }),
5 + mb = 100,
6 + buffer = createMultipartBuffer(boundary, mb * 1024 * 1024),
7 + callbacks =
8 + { partBegin: -1,
9 + partEnd: -1,
10 + headerField: -1,
11 + headerValue: -1,
12 + partData: -1,
13 + end: -1,
14 + };
15 +
16 +
17 +d.on('part', function(p) {
18 + callbacks.partBegin++;
19 + p.on('header', function(header) {
20 + /*for (var h in header)
21 + console.log('Part header: k: ' + inspect(h) + ', v: ' + inspect(header[h]));*/
22 + });
23 + p.on('data', function(data) {
24 + callbacks.partData++;
25 + //console.log('Part data: ' + inspect(data.toString()));
26 + });
27 + p.on('end', function() {
28 + //console.log('End of part\n');
29 + callbacks.partEnd++;
30 + });
31 +});
32 +d.on('end', function() {
33 + //console.log('End of parts');
34 + callbacks.end++;
35 +});
36 +
37 +var start = +new Date(),
38 + nparsed = d.write(buffer),
39 + duration = +new Date - start,
40 + mbPerSec = (mb / (duration / 1000)).toFixed(2);
41 +
42 +console.log(mbPerSec+' mb/sec');
43 +
44 +//assert.equal(nparsed, buffer.length);
45 +
46 +function createMultipartBuffer(boundary, size) {
47 + var head =
48 + '--'+boundary+'\r\n'
49 + + 'content-disposition: form-data; name="field1"\r\n'
50 + + '\r\n'
51 + , tail = '\r\n--'+boundary+'--\r\n'
52 + , buffer = new Buffer(size);
53 +
54 + buffer.write(head, 'ascii', 0);
55 + buffer.write(tail, 'ascii', buffer.length - tail.length);
56 + return buffer;
57 +}
58 +
59 +process.on('exit', function() {
60 + /*for (var k in callbacks) {
61 + assert.equal(0, callbacks[k], k+' count off by '+callbacks[k]);
62 + }*/
63 +});
1 +var assert = require('assert');
2 +require('../node_modules/formidable/test/common');
3 +var multipartParser = require('../node_modules/formidable/lib/multipart_parser'),
4 + MultipartParser = multipartParser.MultipartParser,
5 + parser = new MultipartParser(),
6 + boundary = '-----------------------------168072824752491622650073',
7 + mb = 100,
8 + buffer = createMultipartBuffer(boundary, mb * 1024 * 1024),
9 + callbacks =
10 + { partBegin: -1,
11 + partEnd: -1,
12 + headerField: -1,
13 + headerValue: -1,
14 + partData: -1,
15 + end: -1,
16 + };
17 +
18 +
19 +parser.initWithBoundary(boundary);
20 +parser.onHeaderField = function() {
21 + callbacks.headerField++;
22 +};
23 +
24 +parser.onHeaderValue = function() {
25 + callbacks.headerValue++;
26 +};
27 +
28 +parser.onPartBegin = function() {
29 + callbacks.partBegin++;
30 +};
31 +
32 +parser.onPartData = function() {
33 + callbacks.partData++;
34 +};
35 +
36 +parser.onPartEnd = function() {
37 + callbacks.partEnd++;
38 +};
39 +
40 +parser.onEnd = function() {
41 + callbacks.end++;
42 +};
43 +
44 +var start = +new Date(),
45 + nparsed = parser.write(buffer),
46 + duration = +new Date - start,
47 + mbPerSec = (mb / (duration / 1000)).toFixed(2);
48 +
49 +console.log(mbPerSec+' mb/sec');
50 +
51 +//assert.equal(nparsed, buffer.length);
52 +
53 +function createMultipartBuffer(boundary, size) {
54 + var head =
55 + '--'+boundary+'\r\n'
56 + + 'content-disposition: form-data; name="field1"\r\n'
57 + + '\r\n'
58 + , tail = '\r\n--'+boundary+'--\r\n'
59 + , buffer = new Buffer(size);
60 +
61 + buffer.write(head, 'ascii', 0);
62 + buffer.write(tail, 'ascii', buffer.length - tail.length);
63 + return buffer;
64 +}
65 +
66 +process.on('exit', function() {
67 + /*for (var k in callbacks) {
68 + assert.equal(0, callbacks[k], k+' count off by '+callbacks[k]);
69 + }*/
70 +});
1 +var assert = require('assert');
2 +var multipartser = require('multipartser'),
3 + boundary = '-----------------------------168072824752491622650073',
4 + parser = multipartser(),
5 + mb = 100,
6 + buffer = createMultipartBuffer(boundary, mb * 1024 * 1024),
7 + callbacks =
8 + { partBegin: -1,
9 + partEnd: -1,
10 + headerField: -1,
11 + headerValue: -1,
12 + partData: -1,
13 + end: -1,
14 + };
15 +
16 +parser.boundary( boundary );
17 +
18 +parser.on( 'part', function ( part ) {
19 +});
20 +
21 +parser.on( 'end', function () {
22 + //console.log( 'completed parsing' );
23 +});
24 +
25 +parser.on( 'error', function ( error ) {
26 + console.error( error );
27 +});
28 +
29 +var start = +new Date(),
30 + nparsed = parser.data(buffer),
31 + nend = parser.end(),
32 + duration = +new Date - start,
33 + mbPerSec = (mb / (duration / 1000)).toFixed(2);
34 +
35 +console.log(mbPerSec+' mb/sec');
36 +
37 +//assert.equal(nparsed, buffer.length);
38 +
39 +function createMultipartBuffer(boundary, size) {
40 + var head =
41 + '--'+boundary+'\r\n'
42 + + 'content-disposition: form-data; name="field1"\r\n'
43 + + '\r\n'
44 + , tail = '\r\n--'+boundary+'--\r\n'
45 + , buffer = new Buffer(size);
46 +
47 + buffer.write(head, 'ascii', 0);
48 + buffer.write(tail, 'ascii', buffer.length - tail.length);
49 + return buffer;
50 +}
51 +
52 +process.on('exit', function() {
53 + /*for (var k in callbacks) {
54 + assert.equal(0, callbacks[k], k+' count off by '+callbacks[k]);
55 + }*/
56 +});
1 +var assert = require('assert'),
2 + Form = require('multiparty').Form,
3 + boundary = '-----------------------------168072824752491622650073',
4 + mb = 100,
5 + buffer = createMultipartBuffer(boundary, mb * 1024 * 1024),
6 + callbacks =
7 + { partBegin: -1,
8 + partEnd: -1,
9 + headerField: -1,
10 + headerValue: -1,
11 + partData: -1,
12 + end: -1,
13 + };
14 +
15 +var form = new Form({ boundary: boundary });
16 +
17 +hijack('onParseHeaderField', function() {
18 + callbacks.headerField++;
19 +});
20 +
21 +hijack('onParseHeaderValue', function() {
22 + callbacks.headerValue++;
23 +});
24 +
25 +hijack('onParsePartBegin', function() {
26 + callbacks.partBegin++;
27 +});
28 +
29 +hijack('onParsePartData', function() {
30 + callbacks.partData++;
31 +});
32 +
33 +hijack('onParsePartEnd', function() {
34 + callbacks.partEnd++;
35 +});
36 +
37 +form.on('finish', function() {
38 + callbacks.end++;
39 +});
40 +
41 +var start = new Date();
42 +form.write(buffer, function(err) {
43 + var duration = new Date() - start;
44 + assert.ifError(err);
45 + var mbPerSec = (mb / (duration / 1000)).toFixed(2);
46 + console.log(mbPerSec+' mb/sec');
47 +});
48 +
49 +//assert.equal(nparsed, buffer.length);
50 +
51 +function createMultipartBuffer(boundary, size) {
52 + var head =
53 + '--'+boundary+'\r\n'
54 + + 'content-disposition: form-data; name="field1"\r\n'
55 + + '\r\n'
56 + , tail = '\r\n--'+boundary+'--\r\n'
57 + , buffer = new Buffer(size);
58 +
59 + buffer.write(head, 'ascii', 0);
60 + buffer.write(tail, 'ascii', buffer.length - tail.length);
61 + return buffer;
62 +}
63 +
64 +process.on('exit', function() {
65 + /*for (var k in callbacks) {
66 + assert.equal(0, callbacks[k], k+' count off by '+callbacks[k]);
67 + }*/
68 +});
69 +
70 +function hijack(name, fn) {
71 + var oldFn = form[name];
72 + form[name] = function() {
73 + fn();
74 + return oldFn.apply(this, arguments);
75 + };
76 +}
1 +// A special, edited version of the multipart parser from parted is needed here
2 +// because otherwise it attempts to do some things above and beyond just parsing
3 +// -- like saving to disk and whatnot
4 +
5 +var assert = require('assert');
6 +var Parser = require('./parted-multipart'),
7 + boundary = '-----------------------------168072824752491622650073',
8 + parser = new Parser('boundary=' + boundary),
9 + mb = 100,
10 + buffer = createMultipartBuffer(boundary, mb * 1024 * 1024),
11 + callbacks =
12 + { partBegin: -1,
13 + partEnd: -1,
14 + headerField: -1,
15 + headerValue: -1,
16 + partData: -1,
17 + end: -1,
18 + };
19 +
20 +
21 +parser.on('header', function() {
22 + //callbacks.headerField++;
23 +});
24 +
25 +parser.on('data', function() {
26 + //callbacks.partBegin++;
27 +});
28 +
29 +parser.on('part', function() {
30 +
31 +});
32 +
33 +parser.on('end', function() {
34 + //callbacks.end++;
35 +});
36 +
37 +var start = +new Date(),
38 + nparsed = parser.write(buffer),
39 + duration = +new Date - start,
40 + mbPerSec = (mb / (duration / 1000)).toFixed(2);
41 +
42 +console.log(mbPerSec+' mb/sec');
43 +
44 +//assert.equal(nparsed, buffer.length);
45 +
46 +function createMultipartBuffer(boundary, size) {
47 + var head =
48 + '--'+boundary+'\r\n'
49 + + 'content-disposition: form-data; name="field1"\r\n'
50 + + '\r\n'
51 + , tail = '\r\n--'+boundary+'--\r\n'
52 + , buffer = new Buffer(size);
53 +
54 + buffer.write(head, 'ascii', 0);
55 + buffer.write(tail, 'ascii', buffer.length - tail.length);
56 + return buffer;
57 +}
58 +
59 +process.on('exit', function() {
60 + /*for (var k in callbacks) {
61 + assert.equal(0, callbacks[k], k+' count off by '+callbacks[k]);
62 + }*/
63 +});
1 +/**
2 + * Parted (https://github.com/chjj/parted)
3 + * A streaming multipart state parser.
4 + * Copyright (c) 2011, Christopher Jeffrey. (MIT Licensed)
5 + */
6 +
7 +var fs = require('fs')
8 + , path = require('path')
9 + , EventEmitter = require('events').EventEmitter
10 + , StringDecoder = require('string_decoder').StringDecoder
11 + , set = require('qs').set
12 + , each = Array.prototype.forEach;
13 +
14 +/**
15 + * Character Constants
16 + */
17 +
18 +var DASH = '-'.charCodeAt(0)
19 + , CR = '\r'.charCodeAt(0)
20 + , LF = '\n'.charCodeAt(0)
21 + , COLON = ':'.charCodeAt(0)
22 + , SPACE = ' '.charCodeAt(0);
23 +
24 +/**
25 + * Parser
26 + */
27 +
28 +var Parser = function(type, options) {
29 + if (!(this instanceof Parser)) {
30 + return new Parser(type, options);
31 + }
32 +
33 + EventEmitter.call(this);
34 +
35 + this.writable = true;
36 + this.readable = true;
37 +
38 + this.options = options || {};
39 +
40 + var key = grab(type, 'boundary');
41 + if (!key) {
42 + return this._error('No boundary key found.');
43 + }
44 +
45 + this.key = new Buffer('\r\n--' + key);
46 +
47 + this._key = {};
48 + each.call(this.key, function(ch) {
49 + this._key[ch] = true;
50 + }, this);
51 +
52 + this.state = 'start';
53 + this.pending = 0;
54 + this.written = 0;
55 + this.writtenDisk = 0;
56 + this.buff = new Buffer(200);
57 +
58 + this.preamble = true;
59 + this.epilogue = false;
60 +
61 + this._reset();
62 +};
63 +
64 +Parser.prototype.__proto__ = EventEmitter.prototype;
65 +
66 +/**
67 + * Parsing
68 + */
69 +
70 +Parser.prototype.write = function(data) {
71 + if (!this.writable
72 + || this.epilogue) return;
73 +
74 + try {
75 + this._parse(data);
76 + } catch (e) {
77 + this._error(e);
78 + }
79 +
80 + return true;
81 +};
82 +
83 +Parser.prototype.end = function(data) {
84 + if (!this.writable) return;
85 +
86 + if (data) this.write(data);
87 +
88 + if (!this.epilogue) {
89 + return this._error('Message underflow.');
90 + }
91 +
92 + return true;
93 +};
94 +
95 +Parser.prototype._parse = function(data) {
96 + var i = 0
97 + , len = data.length
98 + , buff = this.buff
99 + , key = this.key
100 + , ch
101 + , val
102 + , j;
103 +
104 + for (; i < len; i++) {
105 + if (this.pos >= 200) {
106 + return this._error('Potential buffer overflow.');
107 + }
108 +
109 + ch = data[i];
110 +
111 + switch (this.state) {
112 + case 'start':
113 + switch (ch) {
114 + case DASH:
115 + this.pos = 3;
116 + this.state = 'key';
117 + break;
118 + default:
119 + break;
120 + }
121 + break;
122 + case 'key':
123 + if (this.pos === key.length) {
124 + this.state = 'key_end';
125 + i--;
126 + } else if (ch !== key[this.pos]) {
127 + if (this.preamble) {
128 + this.state = 'start';
129 + i--;
130 + } else {
131 + this.state = 'body';
132 + val = this.pos - i;
133 + if (val > 0) {
134 + this._write(key.slice(0, val));
135 + }
136 + i--;
137 + }
138 + } else {
139 + this.pos++;
140 + }
141 + break;
142 + case 'key_end':
143 + switch (ch) {
144 + case CR:
145 + this.state = 'key_line_end';
146 + break;
147 + case DASH:
148 + this.state = 'key_dash_end';
149 + break;
150 + default:
151 + return this._error('Expected CR or DASH.');
152 + }
153 + break;
154 + case 'key_line_end':
155 + switch (ch) {
156 + case LF:
157 + if (this.preamble) {
158 + this.preamble = false;
159 + } else {
160 + this._finish();
161 + }
162 + this.state = 'header_name';
163 + this.pos = 0;
164 + break;
165 + default:
166 + return this._error('Expected CR.');
167 + }
168 + break;
169 + case 'key_dash_end':
170 + switch (ch) {
171 + case DASH:
172 + this.epilogue = true;
173 + this._finish();
174 + return;
175 + default:
176 + return this._error('Expected DASH.');
177 + }
178 + break;
179 + case 'header_name':
180 + switch (ch) {
181 + case COLON:
182 + this.header = buff.toString('ascii', 0, this.pos);
183 + this.pos = 0;
184 + this.state = 'header_val';
185 + break;
186 + default:
187 + buff[this.pos++] = ch | 32;
188 + break;
189 + }
190 + break;
191 + case 'header_val':
192 + switch (ch) {
193 + case CR:
194 + this.state = 'header_val_end';
195 + break;
196 + case SPACE:
197 + if (this.pos === 0) {
198 + break;
199 + }
200 + ; // FALL-THROUGH
201 + default:
202 + buff[this.pos++] = ch;
203 + break;
204 + }
205 + break;
206 + case 'header_val_end':
207 + switch (ch) {
208 + case LF:
209 + val = buff.toString('ascii', 0, this.pos);
210 + this._header(this.header, val);
211 + this.pos = 0;
212 + this.state = 'header_end';
213 + break;
214 + default:
215 + return this._error('Expected LF.');
216 + }
217 + break;
218 + case 'header_end':
219 + switch (ch) {
220 + case CR:
221 + this.state = 'head_end';
222 + break;
223 + default:
224 + this.state = 'header_name';
225 + i--;
226 + break;
227 + }
228 + break;
229 + case 'head_end':
230 + switch (ch) {
231 + case LF:
232 + this.state = 'body';
233 + i++;
234 + if (i >= len) return;
235 + data = data.slice(i);
236 + i = -1;
237 + len = data.length;
238 + break;
239 + default:
240 + return this._error('Expected LF.');
241 + }
242 + break;
243 + case 'body':
244 + switch (ch) {
245 + case CR:
246 + if (i > 0) {
247 + this._write(data.slice(0, i));
248 + }
249 + this.pos = 1;
250 + this.state = 'key';
251 + data = data.slice(i);
252 + i = 0;
253 + len = data.length;
254 + break;
255 + default:
256 + // boyer-moore-like algorithm
257 + // at felixge's suggestion
258 + while ((j = i + key.length - 1) < len) {
259 + if (this._key[data[j]]) break;
260 + i = j;
261 + }
262 + break;
263 + }
264 + break;
265 + }
266 + }
267 +
268 + if (this.state === 'body') {
269 + this._write(data);
270 + }
271 +};
272 +
273 +Parser.prototype._header = function(name, val) {
274 + /*if (name === 'content-disposition') {
275 + this.field = grab(val, 'name');
276 + this.file = grab(val, 'filename');
277 +
278 + if (this.file) {
279 + this.data = stream(this.file, this.options.path);
280 + } else {
281 + this.decode = new StringDecoder('utf8');
282 + this.data = '';
283 + }
284 + }*/
285 +
286 + return this.emit('header', name, val);
287 +};
288 +
289 +Parser.prototype._write = function(data) {
290 + /*if (this.data == null) {
291 + return this._error('No disposition.');
292 + }
293 +
294 + if (this.file) {
295 + this.data.write(data);
296 + this.writtenDisk += data.length;
297 + } else {
298 + this.data += this.decode.write(data);
299 + this.written += data.length;
300 + }*/
301 +
302 + this.emit('data', data);
303 +};
304 +
305 +Parser.prototype._reset = function() {
306 + this.pos = 0;
307 + this.decode = null;
308 + this.field = null;
309 + this.data = null;
310 + this.file = null;
311 + this.header = null;
312 +};
313 +
314 +Parser.prototype._error = function(err) {
315 + this.destroy();
316 + this.emit('error', typeof err === 'string'
317 + ? new Error(err)
318 + : err);
319 +};
320 +
321 +Parser.prototype.destroy = function(err) {
322 + this.writable = false;
323 + this.readable = false;
324 + this._reset();
325 +};
326 +
327 +Parser.prototype._finish = function() {
328 + var self = this
329 + , field = this.field
330 + , data = this.data
331 + , file = this.file
332 + , part;
333 +
334 + this.pending++;
335 +
336 + this._reset();
337 +
338 + if (data && data.path) {
339 + part = data.path;
340 + data.end(next);
341 + } else {
342 + part = data;
343 + next();
344 + }
345 +
346 + function next() {
347 + if (!self.readable) return;
348 +
349 + self.pending--;
350 +
351 + self.emit('part', field, part);
352 +
353 + if (data && data.path) {
354 + self.emit('file', field, part, file);
355 + }
356 +
357 + if (self.epilogue && !self.pending) {
358 + self.emit('end');
359 + self.destroy();
360 + }
361 + }
362 +};
363 +
364 +/**
365 + * Uploads
366 + */
367 +
368 +Parser.root = process.platform === 'win32'
369 + ? 'C:/Temp'
370 + : '/tmp';
371 +
372 +/**
373 + * Middleware
374 + */
375 +
376 +Parser.middleware = function(options) {
377 + options = options || {};
378 + return function(req, res, next) {
379 + if (options.ensureBody) {
380 + req.body = {};
381 + }
382 +
383 + if (req.method === 'GET'
384 + || req.method === 'HEAD'
385 + || req._multipart) return next();
386 +
387 + req._multipart = true;
388 +
389 + var type = req.headers['content-type'];
390 +
391 + if (type) type = type.split(';')[0].trim().toLowerCase();
392 +
393 + if (type === 'multipart/form-data') {
394 + Parser.handle(req, res, next, options);
395 + } else {
396 + next();
397 + }
398 + };
399 +};
400 +
401 +/**
402 + * Handler
403 + */
404 +
405 +Parser.handle = function(req, res, next, options) {
406 + var parser = new Parser(req.headers['content-type'], options)
407 + , diskLimit = options.diskLimit
408 + , limit = options.limit
409 + , parts = {}
410 + , files = {};
411 +
412 + parser.on('error', function(err) {
413 + req.destroy();
414 + next(err);
415 + });
416 +
417 + parser.on('part', function(field, part) {
418 + set(parts, field, part);
419 + });
420 +
421 + parser.on('file', function(field, path, name) {
422 + set(files, field, {
423 + path: path,
424 + name: name,
425 + toString: function() {
426 + return path;
427 + }
428 + });
429 + });
430 +
431 + parser.on('data', function() {
432 + if (this.writtenDisk > diskLimit || this.written > limit) {
433 + this.emit('error', new Error('Overflow.'));
434 + this.destroy();
435 + }
436 + });
437 +
438 + parser.on('end', next);
439 +
440 + req.body = parts;
441 + req.files = files;
442 + req.pipe(parser);
443 +};
444 +
445 +/**
446 + * Helpers
447 + */
448 +
449 +var isWindows = process.platform === 'win32';
450 +
451 +var stream = function(name, dir) {
452 + var ext = path.extname(name) || ''
453 + , name = path.basename(name, ext) || ''
454 + , dir = dir || Parser.root
455 + , tag;
456 +
457 + tag = Math.random().toString(36).substring(2);
458 +
459 + name = name.substring(0, 200) + '.' + tag;
460 + name = path.join(dir, name) + ext.substring(0, 6);
461 + name = name.replace(/\0/g, '');
462 +
463 + if (isWindows) {
464 + name = name.replace(/[:*<>|"?]/g, '');
465 + }
466 +
467 + return fs.createWriteStream(name);
468 +};
469 +
470 +var grab = function(str, name) {
471 + if (!str) return;
472 +
473 + var rx = new RegExp('\\b' + name + '\\s*=\\s*("[^"]+"|\'[^\']+\'|[^;,]+)', 'i')
474 + , cap = rx.exec(str);
475 +
476 + if (cap) {
477 + return cap[1].trim().replace(/^['"]|['"]$/g, '');
478 + }
479 +};
480 +
481 +/**
482 + * Expose
483 + */
484 +
485 +module.exports = Parser;
...\ No newline at end of file ...\ No newline at end of file
1 +var WritableStream = require('stream').Writable
2 + || require('readable-stream').Writable,
3 + inherits = require('util').inherits;
4 +
5 +var StreamSearch = require('streamsearch');
6 +
7 +var PartStream = require('./PartStream'),
8 + HeaderParser = require('./HeaderParser');
9 +
10 +var DASH = 45,
11 + B_ONEDASH = new Buffer('-'),
12 + B_CRLF = new Buffer('\r\n'),
13 + EMPTY_FN = function() {};
14 +
15 +function Dicer(cfg) {
16 + if (!(this instanceof Dicer))
17 + return new Dicer(cfg);
18 + WritableStream.call(this, cfg);
19 +
20 + if (!cfg || (!cfg.headerFirst && typeof cfg.boundary !== 'string'))
21 + throw new TypeError('Boundary required');
22 +
23 + if (typeof cfg.boundary === 'string')
24 + this.setBoundary(cfg.boundary);
25 + else
26 + this._bparser = undefined;
27 +
28 + this._headerFirst = cfg.headerFirst;
29 +
30 + var self = this;
31 +
32 + this._dashes = 0;
33 + this._parts = 0;
34 + this._finished = false;
35 + this._realFinish = false;
36 + this._isPreamble = true;
37 + this._justMatched = false;
38 + this._firstWrite = true;
39 + this._inHeader = true;
40 + this._part = undefined;
41 + this._cb = undefined;
42 + this._ignoreData = false;
43 + this._partOpts = (typeof cfg.partHwm === 'number'
44 + ? { highWaterMark: cfg.partHwm }
45 + : {});
46 + this._pause = false;
47 +
48 + this._hparser = new HeaderParser(cfg);
49 + this._hparser.on('header', function(header) {
50 + self._inHeader = false;
51 + self._part.emit('header', header);
52 + });
53 +
54 +}
55 +inherits(Dicer, WritableStream);
56 +
57 +Dicer.prototype.emit = function(ev) {
58 + if (ev === 'finish' && !this._realFinish) {
59 + if (!this._finished) {
60 + var self = this;
61 + process.nextTick(function() {
62 + self.emit('error', new Error('Unexpected end of multipart data'));
63 + if (self._part && !self._ignoreData) {
64 + var type = (self._isPreamble ? 'Preamble' : 'Part');
65 + self._part.emit('error', new Error(type + ' terminated early due to unexpected end of multipart data'));
66 + self._part.push(null);
67 + process.nextTick(function() {
68 + self._realFinish = true;
69 + self.emit('finish');
70 + self._realFinish = false;
71 + });
72 + return;
73 + }
74 + self._realFinish = true;
75 + self.emit('finish');
76 + self._realFinish = false;
77 + });
78 + }
79 + } else
80 + WritableStream.prototype.emit.apply(this, arguments);
81 +};
82 +
83 +Dicer.prototype._write = function(data, encoding, cb) {
84 + // ignore unexpected data (e.g. extra trailer data after finished)
85 + if (!this._hparser && !this._bparser)
86 + return cb();
87 +
88 + if (this._headerFirst && this._isPreamble) {
89 + if (!this._part) {
90 + this._part = new PartStream(this._partOpts);
91 + if (this._events.preamble)
92 + this.emit('preamble', this._part);
93 + else
94 + this._ignore();
95 + }
96 + var r = this._hparser.push(data);
97 + if (!this._inHeader && r !== undefined && r < data.length)
98 + data = data.slice(r);
99 + else
100 + return cb();
101 + }
102 +
103 + // allows for "easier" testing
104 + if (this._firstWrite) {
105 + this._bparser.push(B_CRLF);
106 + this._firstWrite = false;
107 + }
108 +
109 + this._bparser.push(data);
110 +
111 + if (this._pause)
112 + this._cb = cb;
113 + else
114 + cb();
115 +};
116 +
117 +Dicer.prototype.reset = function() {
118 + this._part = undefined;
119 + this._bparser = undefined;
120 + this._hparser = undefined;
121 +};
122 +
123 +Dicer.prototype.setBoundary = function(boundary) {
124 + var self = this;
125 + this._bparser = new StreamSearch('\r\n--' + boundary);
126 + this._bparser.on('info', function(isMatch, data, start, end) {
127 + self._oninfo(isMatch, data, start, end);
128 + });
129 +};
130 +
131 +Dicer.prototype._ignore = function() {
132 + if (this._part && !this._ignoreData) {
133 + this._ignoreData = true;
134 + this._part.on('error', EMPTY_FN);
135 + // we must perform some kind of read on the stream even though we are
136 + // ignoring the data, otherwise node's Readable stream will not emit 'end'
137 + // after pushing null to the stream
138 + this._part.resume();
139 + }
140 +};
141 +
142 +Dicer.prototype._oninfo = function(isMatch, data, start, end) {
143 + var buf, self = this, i = 0, r, ev, shouldWriteMore = true;
144 +
145 + if (!this._part && this._justMatched && data) {
146 + while (this._dashes < 2 && (start + i) < end) {
147 + if (data[start + i] === DASH) {
148 + ++i;
149 + ++this._dashes;
150 + } else {
151 + if (this._dashes)
152 + buf = B_ONEDASH;
153 + this._dashes = 0;
154 + break;
155 + }
156 + }
157 + if (this._dashes === 2) {
158 + if ((start + i) < end && this._events.trailer)
159 + this.emit('trailer', data.slice(start + i, end));
160 + this.reset();
161 + this._finished = true;
162 + // no more parts will be added
163 + if (self._parts === 0) {
164 + self._realFinish = true;
165 + self.emit('finish');
166 + self._realFinish = false;
167 + }
168 + }
169 + if (this._dashes)
170 + return;
171 + }
172 + if (this._justMatched)
173 + this._justMatched = false;
174 + if (!this._part) {
175 + this._part = new PartStream(this._partOpts);
176 + this._part._read = function(n) {
177 + self._unpause();
178 + };
179 + ev = this._isPreamble ? 'preamble' : 'part';
180 + if (this._events[ev])
181 + this.emit(ev, this._part);
182 + else
183 + this._ignore();
184 + if (!this._isPreamble)
185 + this._inHeader = true;
186 + }
187 + if (data && start < end && !this._ignoreData) {
188 + if (this._isPreamble || !this._inHeader) {
189 + if (buf)
190 + shouldWriteMore = this._part.push(buf);
191 + shouldWriteMore = this._part.push(data.slice(start, end));
192 + if (!shouldWriteMore)
193 + this._pause = true;
194 + } else if (!this._isPreamble && this._inHeader) {
195 + if (buf)
196 + this._hparser.push(buf);
197 + r = this._hparser.push(data.slice(start, end));
198 + if (!this._inHeader && r !== undefined && r < end)
199 + this._oninfo(false, data, start + r, end);
200 + }
201 + }
202 + if (isMatch) {
203 + this._hparser.reset();
204 + if (this._isPreamble)
205 + this._isPreamble = false;
206 + else {
207 + ++this._parts;
208 + this._part.on('end', function() {
209 + if (--self._parts === 0) {
210 + if (self._finished) {
211 + self._realFinish = true;
212 + self.emit('finish');
213 + self._realFinish = false;
214 + } else {
215 + self._unpause();
216 + }
217 + }
218 + });
219 + }
220 + this._part.push(null);
221 + this._part = undefined;
222 + this._ignoreData = false;
223 + this._justMatched = true;
224 + this._dashes = 0;
225 + }
226 +};
227 +
228 +Dicer.prototype._unpause = function() {
229 + if (!this._pause)
230 + return;
231 +
232 + this._pause = false;
233 + if (this._cb) {
234 + var cb = this._cb;
235 + this._cb = undefined;
236 + cb();
237 + }
238 +};
239 +
240 +module.exports = Dicer;
1 +var EventEmitter = require('events').EventEmitter,
2 + inherits = require('util').inherits;
3 +
4 +var StreamSearch = require('streamsearch');
5 +
6 +var B_DCRLF = new Buffer('\r\n\r\n'),
7 + RE_CRLF = /\r\n/g,
8 + RE_HDR = /^([^:]+):[ \t]?([\x00-\xFF]+)?$/,
9 + MAX_HEADER_PAIRS = 2000, // from node's http.js
10 + MAX_HEADER_SIZE = 80 * 1024; // from node's http_parser
11 +
12 +function HeaderParser(cfg) {
13 + EventEmitter.call(this);
14 +
15 + var self = this;
16 + this.nread = 0;
17 + this.maxed = false;
18 + this.npairs = 0;
19 + this.maxHeaderPairs = (cfg && typeof cfg.maxHeaderPairs === 'number'
20 + ? cfg.maxHeaderPairs
21 + : MAX_HEADER_PAIRS);
22 + this.buffer = '';
23 + this.header = {};
24 + this.finished = false;
25 + this.ss = new StreamSearch(B_DCRLF);
26 + this.ss.on('info', function(isMatch, data, start, end) {
27 + if (data && !self.maxed) {
28 + if (self.nread + (end - start) > MAX_HEADER_SIZE) {
29 + end = (MAX_HEADER_SIZE - self.nread);
30 + self.nread = MAX_HEADER_SIZE;
31 + } else
32 + self.nread += (end - start);
33 +
34 + if (self.nread === MAX_HEADER_SIZE)
35 + self.maxed = true;
36 +
37 + self.buffer += data.toString('binary', start, end);
38 + }
39 + if (isMatch)
40 + self._finish();
41 + });
42 +}
43 +inherits(HeaderParser, EventEmitter);
44 +
45 +HeaderParser.prototype.push = function(data) {
46 + var r = this.ss.push(data);
47 + if (this.finished)
48 + return r;
49 +};
50 +
51 +HeaderParser.prototype.reset = function() {
52 + this.finished = false;
53 + this.buffer = '';
54 + this.header = {};
55 + this.ss.reset();
56 +};
57 +
58 +HeaderParser.prototype._finish = function() {
59 + if (this.buffer)
60 + this._parseHeader();
61 + this.ss.matches = this.ss.maxMatches;
62 + var header = this.header;
63 + this.header = {};
64 + this.buffer = '';
65 + this.finished = true;
66 + this.nread = this.npairs = 0;
67 + this.maxed = false;
68 + this.emit('header', header);
69 +};
70 +
71 +HeaderParser.prototype._parseHeader = function() {
72 + if (this.npairs === this.maxHeaderPairs)
73 + return;
74 +
75 + var lines = this.buffer.split(RE_CRLF), len = lines.length, m, h,
76 + modded = false;
77 +
78 + for (var i = 0; i < len; ++i) {
79 + if (lines[i].length === 0)
80 + continue;
81 + if (lines[i][0] === '\t' || lines[i][0] === ' ') {
82 + // folded header content
83 + // RFC2822 says to just remove the CRLF and not the whitespace following
84 + // it, so we follow the RFC and include the leading whitespace ...
85 + this.header[h][this.header[h].length - 1] += lines[i];
86 + } else {
87 + m = RE_HDR.exec(lines[i]);
88 + if (m) {
89 + h = m[1].toLowerCase();
90 + if (m[2]) {
91 + if (this.header[h] === undefined)
92 + this.header[h] = [m[2]];
93 + else
94 + this.header[h].push(m[2]);
95 + } else
96 + this.header[h] = [''];
97 + if (++this.npairs === this.maxHeaderPairs)
98 + break;
99 + } else {
100 + this.buffer = lines[i];
101 + modded = true;
102 + break;
103 + }
104 + }
105 + }
106 + if (!modded)
107 + this.buffer = '';
108 +};
109 +
110 +module.exports = HeaderParser;
1 +var inherits = require('util').inherits,
2 + ReadableStream = require('stream').Readable || require('readable-stream');
3 +
4 +function PartStream(opts) {
5 + ReadableStream.call(this, opts);
6 +}
7 +inherits(PartStream, ReadableStream);
8 +
9 +PartStream.prototype._read = function(n) {};
10 +
11 +module.exports = PartStream;
1 +{
2 + "_from": "dicer@0.2.5",
3 + "_id": "dicer@0.2.5",
4 + "_inBundle": false,
5 + "_integrity": "sha1-WZbAhrszIYyBLAkL3cCc0S+stw8=",
6 + "_location": "/dicer",
7 + "_phantomChildren": {},
8 + "_requested": {
9 + "type": "version",
10 + "registry": true,
11 + "raw": "dicer@0.2.5",
12 + "name": "dicer",
13 + "escapedName": "dicer",
14 + "rawSpec": "0.2.5",
15 + "saveSpec": null,
16 + "fetchSpec": "0.2.5"
17 + },
18 + "_requiredBy": [
19 + "/busboy"
20 + ],
21 + "_resolved": "https://registry.npmjs.org/dicer/-/dicer-0.2.5.tgz",
22 + "_shasum": "5996c086bb33218c812c090bddc09cd12facb70f",
23 + "_spec": "dicer@0.2.5",
24 + "_where": "C:\\Users\\1000c\\이것저것\\옾소\\Voicoding\\node_modules\\busboy",
25 + "author": {
26 + "name": "Brian White",
27 + "email": "mscdex@mscdex.net"
28 + },
29 + "bugs": {
30 + "url": "https://github.com/mscdex/dicer/issues"
31 + },
32 + "bundleDependencies": false,
33 + "dependencies": {
34 + "readable-stream": "1.1.x",
35 + "streamsearch": "0.1.2"
36 + },
37 + "deprecated": false,
38 + "description": "A very fast streaming multipart parser for node.js",
39 + "engines": {
40 + "node": ">=0.8.0"
41 + },
42 + "homepage": "https://github.com/mscdex/dicer#readme",
43 + "keywords": [
44 + "parser",
45 + "parse",
46 + "parsing",
47 + "multipart",
48 + "form-data",
49 + "streaming"
50 + ],
51 + "licenses": [
52 + {
53 + "type": "MIT",
54 + "url": "http://github.com/mscdex/dicer/raw/master/LICENSE"
55 + }
56 + ],
57 + "main": "./lib/Dicer",
58 + "name": "dicer",
59 + "repository": {
60 + "type": "git",
61 + "url": "git+ssh://git@github.com/mscdex/dicer.git"
62 + },
63 + "scripts": {
64 + "test": "node test/test.js"
65 + },
66 + "version": "0.2.5"
67 +}
1 +------WebKitFormBoundaryWLHCs9qmcJJoyjKR
2 +Content-Disposition: form-data; name="_method"
3 +
4 +put
5 +------WebKitFormBoundaryWLHCs9qmcJJoyjKR
6 +Content-Disposition: form-data; name="profile[blog]"
7 +
8 +
9 +------WebKitFormBoundaryWLHCs9qmcJJoyjKR
10 +Content-Disposition: form-data; name="profile[public_email]"
11 +
12 +
13 +------WebKitFormBoundaryWLHCs9qmcJJoyjKR
14 +Content-Disposition: form-data; name="profile[interests]"
15 +
16 +
17 +------WebKitFormBoundaryWLHCs9qmcJJoyjKR
18 +Content-Disposition: form-data; name="profile[bio]"
19 +
20 +hello
21 +
22 +"quote"
23 +------WebKitFormBoundaryWLHCs9qmcJJoyjKR
24 +Content-Disposition: form-data; name="commit"
25 +
26 +Save
27 +------WebKitFormBoundaryWLHCs9qmcJJoyjKR
28 +Content-Disposition: form-data; name="media"; filename=""
29 +Content-Type: application/octet-stream
30 +
31 +
1 +put
...\ No newline at end of file ...\ No newline at end of file
1 +{"content-disposition": ["form-data; name=\"_method\""]}
...\ No newline at end of file ...\ No newline at end of file
1 +{"content-disposition": ["form-data; name=\"profile[blog]\""]}
...\ No newline at end of file ...\ No newline at end of file
1 +{"content-disposition": ["form-data; name=\"profile[public_email]\""]}
...\ No newline at end of file ...\ No newline at end of file
1 +{"content-disposition": ["form-data; name=\"profile[interests]\""]}
...\ No newline at end of file ...\ No newline at end of file
1 +hello
2 +
3 +"quote"
...\ No newline at end of file ...\ No newline at end of file
1 +{"content-disposition": ["form-data; name=\"profile[bio]\""]}
...\ No newline at end of file ...\ No newline at end of file
1 +Save
...\ No newline at end of file ...\ No newline at end of file
1 +{"content-disposition": ["form-data; name=\"commit\""]}
...\ No newline at end of file ...\ No newline at end of file
1 +{"content-disposition": ["form-data; name=\"media\"; filename=\"\""],
2 + "content-type": ["application/octet-stream"]}
...\ No newline at end of file ...\ No newline at end of file
1 +------WebKitFormBoundaryWLHCs9qmcJJoyjKR
2 +Content-Disposition: form-data; name="_method"
3 +
4 +put
5 +------WebKitFormBoundaryWLHCs9qmcJJoyjKR
6 +Content-Disposition: form-data; name="profile[blog]"
7 +
8 +
9 +------WebKitFormBoundaryWLHCs9qmcJJoyjKR
10 +Content-Disposition: form-data; name="profile[public_email]"
11 +
12 +
13 +------WebKitFormBoundaryWLHCs9qmcJJoyjKR
14 +Content-Disposition: form-data; name="profile[interests]"
15 +
16 +
17 +------WebKitFormBoundaryWLHCs9qmcJJoyjKR
18 +Content-Disposition: form-data; name="profile[bio]"
19 +
20 +hello
21 +
22 +"quote"
23 +------WebKitFormBoundaryWLHCs9qmcJJoyjKR
24 +Content-Disposition: form-data; name="media"; filename=""
25 +Content-Type: application/octet-stream
26 +
27 +
28 +------WebKitFormBoundaryWLHCs9qmcJJoyjKR
29 +Content-Disposition: form-data; name="commit"
30 +
31 +Save
32 +------WebKitFormBoundaryWLHCs9qmcJJoyjKR--
...\ No newline at end of file ...\ No newline at end of file
1 +
2 +------WebKitFormBoundaryWLHCs9qmcJJoyjKR
3 +Content-Disposition: form-data; name="_method"
4 +
5 +put
6 +------WebKitFormBoundaryWLHCs9qmcJJoyjKR
7 +Content-Disposition: form-data; name="profile[blog]"
8 +
9 +
10 +------WebKitFormBoundaryWLHCs9qmcJJoyjKR
11 +Content-Disposition: form-data; name="profile[public_email]"
12 +
13 +
14 +------WebKitFormBoundaryWLHCs9qmcJJoyjKR
15 +Content-Disposition: form-data; name="profile[interests]"
16 +
17 +
18 +------WebKitFormBoundaryWLHCs9qmcJJoyjKR
19 +Content-Disposition: form-data; name="profile[bio]"
20 +
21 +hello
22 +
23 +"quote"
24 +------WebKitFormBoundaryWLHCs9qmcJJoyjKR
25 +Content-Disposition: form-data; name="media"; filename=""
26 +Content-Type: application/octet-stream
27 +
28 +
29 +------WebKitFormBoundaryWLHCs9qmcJJoyjKR
30 +Content-Disposition: form-data; name="commit"
31 +
32 +Save
33 +------WebKitFormBoundaryWLHCs9qmcJJoyjKR--
...\ No newline at end of file ...\ No newline at end of file
1 +Preamble terminated early due to unexpected end of multipart data
...\ No newline at end of file ...\ No newline at end of file
1 +------WebKitFormBoundaryWLHCs9qmcJJoyjKR
2 +Content-Disposition: form-data; name="_method"
3 +
4 +put
5 +------WebKitFormBoundaryWLHCs9qmcJJoyjKR
6 +Content-Disposition: form-data; name="profile[blog]"
7 +
8 +
9 +------WebKitFormBoundaryWLHCs9qmcJJoyjKR
10 +Content-Disposition: form-data; name="profile[public_email]"
11 +
12 +
13 +------WebKitFormBoundaryWLHCs9qmcJJoyjKR
14 +Content-Disposition: form-data; name="profile[interests]"
15 +
16 +
17 +------WebKitFormBoundaryWLHCs9qmcJJoyjKR
18 +Content-Disposition: form-data; name="profile[bio]"
19 +
20 +hello
21 +
22 +"quote"
23 +------WebKitFormBoundaryWLHCs9qmcJJoyjKR
24 +Content-Disposition: form-data; name="media"; filename=""
25 +Content-Type: application/octet-stream
26 +
27 +
28 +------WebKitFormBoundaryWLHCs9qmcJJoyjKR
29 +Content-Disposition: form-data; name="commit"
30 +
31 +Save
32 +------WebKitFormBoundaryWLHCs9qmcJJoyjKR--
...\ No newline at end of file ...\ No newline at end of file
1 +put
...\ No newline at end of file ...\ No newline at end of file
1 +{"content-disposition": ["form-data; name=\"_method\""]}
...\ No newline at end of file ...\ No newline at end of file
1 +{"content-disposition": ["form-data; name=\"profile[blog]\""]}
...\ No newline at end of file ...\ No newline at end of file
1 +{"content-disposition": ["form-data; name=\"profile[public_email]\""]}
...\ No newline at end of file ...\ No newline at end of file
1 +{"content-disposition": ["form-data; name=\"profile[interests]\""]}
...\ No newline at end of file ...\ No newline at end of file
1 +hello
2 +
3 +"quote"
...\ No newline at end of file ...\ No newline at end of file
1 +{"content-disposition": ["form-data; name=\"profile[bio]\""]}
...\ No newline at end of file ...\ No newline at end of file
1 +{"content-disposition": ["form-data; name=\"media\"; filename=\"\""],
2 + "content-type": ["application/octet-stream"]}
...\ No newline at end of file ...\ No newline at end of file
1 +Save
...\ No newline at end of file ...\ No newline at end of file
1 +{"content-disposition": ["form-data; name=\"commit\""]}
...\ No newline at end of file ...\ No newline at end of file
1 +User-Agent: foo bar baz
2 +Content-Type: multipart/form-data; boundary=AaB03x
3 +
4 +--AaB03x
5 +Content-Disposition: form-data; name="foo"
6 +
7 +bar
8 +--AaB03x
9 +Content-Disposition: form-data; name="files"
10 +Content-Type: multipart/mixed, boundary=BbC04y
11 +
12 +--BbC04y
13 +Content-Disposition: attachment; filename="file.txt"
14 +Content-Type: text/plain
15 +
16 +contents
17 +--BbC04y
18 +Content-Disposition: attachment; filename="flowers.jpg"
19 +Content-Type: image/jpeg
20 +Content-Transfer-Encoding: binary
21 +
22 +contents
23 +--BbC04y--
24 +--AaB03x--
...\ No newline at end of file ...\ No newline at end of file
1 +bar
...\ No newline at end of file ...\ No newline at end of file
1 +{"content-disposition": ["form-data; name=\"foo\""]}
1 +--BbC04y
2 +Content-Disposition: attachment; filename="file.txt"
3 +Content-Type: text/plain
4 +
5 +contents
6 +--BbC04y
7 +Content-Disposition: attachment; filename="flowers.jpg"
8 +Content-Type: image/jpeg
9 +Content-Transfer-Encoding: binary
10 +
11 +contents
12 +--BbC04y--
...\ No newline at end of file ...\ No newline at end of file
1 +{"content-disposition": ["form-data; name=\"files\""],
2 + "content-type": ["multipart/mixed, boundary=BbC04y"]}
...\ No newline at end of file ...\ No newline at end of file
1 +{"user-agent": ["foo bar baz"],
2 + "content-type": ["multipart/form-data; boundary=AaB03x"]}
...\ No newline at end of file ...\ No newline at end of file
1 +--AaB03x
2 +Content-Disposition: form-data; name="foo"
3 +
4 +bar
5 +--AaB03x
6 +Content-Disposition: form-data; name="files"
7 +Content-Type: multipart/mixed, boundary=BbC04y
8 +
9 +--BbC04y
10 +Content-Disposition: attachment; filename="file.txt"
11 +Content-Type: text/plain
12 +
13 +contents
14 +--BbC04y
15 +Content-Disposition: attachment; filename="flowers.jpg"
16 +Content-Type: image/jpeg
17 +Content-Transfer-Encoding: binary
18 +
19 +contents
20 +--BbC04y--
21 +--AaB03x--
...\ No newline at end of file ...\ No newline at end of file
1 +bar
...\ No newline at end of file ...\ No newline at end of file
1 +{"content-disposition": ["form-data; name=\"foo\""]}
1 +--BbC04y
2 +Content-Disposition: attachment; filename="file.txt"
3 +Content-Type: text/plain
4 +
5 +contents
6 +--BbC04y
7 +Content-Disposition: attachment; filename="flowers.jpg"
8 +Content-Type: image/jpeg
9 +Content-Transfer-Encoding: binary
10 +
11 +contents
12 +--BbC04y--
...\ No newline at end of file ...\ No newline at end of file
1 +{"content-disposition": ["form-data; name=\"files\""],
2 + "content-type": ["multipart/mixed, boundary=BbC04y"]}
...\ No newline at end of file ...\ No newline at end of file
1 +var Dicer = require('..');
2 +var assert = require('assert');
3 +
4 +var CRLF = '\r\n';
5 +var boundary = 'boundary';
6 +
7 +var writeSep = '--' + boundary;
8 +
9 +var writePart = [
10 + writeSep,
11 + 'Content-Type: text/plain',
12 + 'Content-Length: 0'
13 + ].join(CRLF)
14 + + CRLF + CRLF
15 + + 'some data' + CRLF;
16 +
17 +var writeEnd = '--' + CRLF;
18 +
19 +var firedEnd = false;
20 +var firedFinish = false;
21 +
22 +var dicer = new Dicer({boundary: boundary});
23 +dicer.on('part', partListener);
24 +dicer.on('finish', finishListener);
25 +dicer.write(writePart+writeSep);
26 +
27 +function partListener(partReadStream) {
28 + partReadStream.on('data', function(){});
29 + partReadStream.on('end', partEndListener);
30 +}
31 +function partEndListener() {
32 + firedEnd = true;
33 + setImmediate(afterEnd);
34 +}
35 +function afterEnd() {
36 + dicer.end(writeEnd);
37 + setImmediate(afterWrite);
38 +}
39 +function finishListener() {
40 + assert(firedEnd, 'Failed to end before finishing');
41 + firedFinish = true;
42 + test2();
43 +}
44 +function afterWrite() {
45 + assert(firedFinish, 'Failed to finish');
46 +}
47 +
48 +var isPausePush = true;
49 +
50 +var firedPauseCallback = false;
51 +var firedPauseFinish = false;
52 +
53 +var dicer2 = null;
54 +
55 +function test2() {
56 + dicer2 = new Dicer({boundary: boundary});
57 + dicer2.on('part', pausePartListener);
58 + dicer2.on('finish', pauseFinish);
59 + dicer2.write(writePart+writeSep, 'utf8', pausePartCallback);
60 + setImmediate(pauseAfterWrite);
61 +}
62 +function pausePartListener(partReadStream) {
63 + partReadStream.on('data', function(){});
64 + partReadStream.on('end', function(){});
65 + var realPush = partReadStream.push;
66 + partReadStream.push = function fakePush() {
67 + realPush.apply(partReadStream, arguments);
68 + if (!isPausePush)
69 + return true;
70 + isPausePush = false;
71 + return false;
72 + };
73 +}
74 +function pauseAfterWrite() {
75 + dicer2.end(writeEnd);
76 + setImmediate(pauseAfterEnd);
77 +}
78 +function pauseAfterEnd() {
79 + assert(firedPauseCallback, 'Failed to call callback after pause');
80 + assert(firedPauseFinish, 'Failed to finish after pause');
81 +}
82 +function pauseFinish() {
83 + firedPauseFinish = true;
84 +}
85 +function pausePartCallback() {
86 + firedPauseCallback = true;
87 +}
1 +var assert = require('assert'),
2 + path = require('path');
3 +
4 +var HeaderParser = require('../lib/HeaderParser');
5 +
6 +var DCRLF = '\r\n\r\n',
7 + MAXED_BUFFER = new Buffer(128 * 1024);
8 +MAXED_BUFFER.fill(0x41); // 'A'
9 +
10 +var group = path.basename(__filename, '.js') + '/';
11 +
12 +[
13 + { source: DCRLF,
14 + expected: {},
15 + what: 'No header'
16 + },
17 + { source: ['Content-Type:\t text/plain',
18 + 'Content-Length:0'
19 + ].join('\r\n') + DCRLF,
20 + expected: {'content-type': [' text/plain'], 'content-length': ['0']},
21 + what: 'Value spacing'
22 + },
23 + { source: ['Content-Type:\r\n text/plain',
24 + 'Foo:\r\n bar\r\n baz',
25 + ].join('\r\n') + DCRLF,
26 + expected: {'content-type': [' text/plain'], 'foo': [' bar baz']},
27 + what: 'Folded values'
28 + },
29 + { source: ['Content-Type:',
30 + 'Foo: ',
31 + ].join('\r\n') + DCRLF,
32 + expected: {'content-type': [''], 'foo': ['']},
33 + what: 'Empty values'
34 + },
35 + { source: MAXED_BUFFER.toString('ascii') + DCRLF,
36 + expected: {},
37 + what: 'Max header size (single chunk)'
38 + },
39 + { source: ['ABCDEFGHIJ', MAXED_BUFFER.toString('ascii'), DCRLF],
40 + expected: {},
41 + what: 'Max header size (multiple chunks #1)'
42 + },
43 + { source: [MAXED_BUFFER.toString('ascii'), MAXED_BUFFER.toString('ascii'), DCRLF],
44 + expected: {},
45 + what: 'Max header size (multiple chunk #2)'
46 + },
47 +].forEach(function(v) {
48 + var parser = new HeaderParser(),
49 + fired = false;
50 +
51 + parser.on('header', function(header) {
52 + assert(!fired, makeMsg(v.what, 'Header event fired more than once'));
53 + fired = true;
54 + assert.deepEqual(header,
55 + v.expected,
56 + makeMsg(v.what, 'Parsed result mismatch'));
57 + });
58 + if (!Array.isArray(v.source))
59 + v.source = [v.source];
60 + v.source.forEach(function(s) {
61 + parser.push(s);
62 + });
63 + assert(fired, makeMsg(v.what, 'Did not receive header from parser'));
64 +});
65 +
66 +function makeMsg(what, msg) {
67 + return '[' + group + what + ']: ' + msg;
68 +}
...\ No newline at end of file ...\ No newline at end of file
1 +var Dicer = require('..');
2 +var assert = require('assert'),
3 + fs = require('fs'),
4 + path = require('path'),
5 + inspect = require('util').inspect;
6 +
7 +var FIXTURES_ROOT = __dirname + '/fixtures/';
8 +
9 +var t = 0,
10 + group = path.basename(__filename, '.js') + '/';
11 +
12 +var tests = [
13 + { source: 'many',
14 + opts: { boundary: '----WebKitFormBoundaryWLHCs9qmcJJoyjKR' },
15 + chsize: 16,
16 + nparts: 7,
17 + what: 'Extra trailer data pushed after finished'
18 + },
19 +];
20 +
21 +function next() {
22 + if (t === tests.length)
23 + return;
24 + var v = tests[t],
25 + fixtureBase = FIXTURES_ROOT + v.source,
26 + fd,
27 + n = 0,
28 + buffer = new Buffer(v.chsize),
29 + state = { parts: [] };
30 +
31 + fd = fs.openSync(fixtureBase + '/original', 'r');
32 +
33 + var dicer = new Dicer(v.opts),
34 + error,
35 + partErrors = 0,
36 + finishes = 0;
37 +
38 + dicer.on('part', function(p) {
39 + var part = {
40 + body: undefined,
41 + bodylen: 0,
42 + error: undefined,
43 + header: undefined
44 + };
45 +
46 + p.on('header', function(h) {
47 + part.header = h;
48 + }).on('data', function(data) {
49 + // make a copy because we are using readSync which re-uses a buffer ...
50 + var copy = new Buffer(data.length);
51 + data.copy(copy);
52 + data = copy;
53 + if (!part.body)
54 + part.body = [ data ];
55 + else
56 + part.body.push(data);
57 + part.bodylen += data.length;
58 + }).on('error', function(err) {
59 + part.error = err;
60 + ++partErrors;
61 + }).on('end', function() {
62 + if (part.body)
63 + part.body = Buffer.concat(part.body, part.bodylen);
64 + state.parts.push(part);
65 + });
66 + }).on('error', function(err) {
67 + error = err;
68 + }).on('finish', function() {
69 + assert(finishes++ === 0, makeMsg(v.what, 'finish emitted multiple times'));
70 +
71 + if (v.dicerError)
72 + assert(error !== undefined, makeMsg(v.what, 'Expected error'));
73 + else
74 + assert(error === undefined, makeMsg(v.what, 'Unexpected error'));
75 +
76 + if (v.events && v.events.indexOf('part') > -1) {
77 + assert.equal(state.parts.length,
78 + v.nparts,
79 + makeMsg(v.what,
80 + 'Part count mismatch:\nActual: '
81 + + state.parts.length
82 + + '\nExpected: '
83 + + v.nparts));
84 +
85 + if (!v.npartErrors)
86 + v.npartErrors = 0;
87 + assert.equal(partErrors,
88 + v.npartErrors,
89 + makeMsg(v.what,
90 + 'Part errors mismatch:\nActual: '
91 + + partErrors
92 + + '\nExpected: '
93 + + v.npartErrors));
94 +
95 + for (var i = 0, header, body; i < v.nparts; ++i) {
96 + if (fs.existsSync(fixtureBase + '/part' + (i+1))) {
97 + body = fs.readFileSync(fixtureBase + '/part' + (i+1));
98 + if (body.length === 0)
99 + body = undefined;
100 + } else
101 + body = undefined;
102 + assert.deepEqual(state.parts[i].body,
103 + body,
104 + makeMsg(v.what,
105 + 'Part #' + (i+1) + ' body mismatch'));
106 + if (fs.existsSync(fixtureBase + '/part' + (i+1) + '.header')) {
107 + header = fs.readFileSync(fixtureBase
108 + + '/part' + (i+1) + '.header', 'binary');
109 + header = JSON.parse(header);
110 + } else
111 + header = undefined;
112 + assert.deepEqual(state.parts[i].header,
113 + header,
114 + makeMsg(v.what,
115 + 'Part #' + (i+1)
116 + + ' parsed header mismatch:\nActual: '
117 + + inspect(state.parts[i].header)
118 + + '\nExpected: '
119 + + inspect(header)));
120 + }
121 + }
122 + ++t;
123 + next();
124 + });
125 +
126 + while (true) {
127 + n = fs.readSync(fd, buffer, 0, buffer.length, null);
128 + if (n === 0) {
129 + setTimeout(function() {
130 + dicer.write('\r\n\r\n\r\n');
131 + dicer.end();
132 + }, 50);
133 + break;
134 + }
135 + dicer.write(n === buffer.length ? buffer : buffer.slice(0, n));
136 + }
137 + fs.closeSync(fd);
138 +}
139 +next();
140 +
141 +function makeMsg(what, msg) {
142 + return '[' + group + what + ']: ' + msg;
143 +}
144 +
145 +process.on('exit', function() {
146 + assert(t === tests.length,
147 + makeMsg('_exit', 'Only ran ' + t + '/' + tests.length + ' tests'));
148 +});
...\ No newline at end of file ...\ No newline at end of file
1 +var Dicer = require('..');
2 +var assert = require('assert'),
3 + fs = require('fs'),
4 + path = require('path'),
5 + inspect = require('util').inspect;
6 +
7 +var FIXTURES_ROOT = __dirname + '/fixtures/';
8 +
9 +var t = 0,
10 + group = path.basename(__filename, '.js') + '/';
11 +
12 +var tests = [
13 + { source: 'many',
14 + opts: { boundary: '----WebKitFormBoundaryWLHCs9qmcJJoyjKR' },
15 + chsize: 16,
16 + nparts: 0,
17 + what: 'No preamble or part listeners'
18 + },
19 +];
20 +
21 +function next() {
22 + if (t === tests.length)
23 + return;
24 + var v = tests[t],
25 + fixtureBase = FIXTURES_ROOT + v.source,
26 + fd,
27 + n = 0,
28 + buffer = new Buffer(v.chsize),
29 + state = { done: false, parts: [], preamble: undefined };
30 +
31 + fd = fs.openSync(fixtureBase + '/original', 'r');
32 +
33 + var dicer = new Dicer(v.opts),
34 + error,
35 + partErrors = 0,
36 + finishes = 0;
37 +
38 + if (v.events && v.events.indexOf('preamble') > -1) {
39 + dicer.on('preamble', function(p) {
40 + var preamble = {
41 + body: undefined,
42 + bodylen: 0,
43 + error: undefined,
44 + header: undefined
45 + };
46 +
47 + p.on('header', function(h) {
48 + preamble.header = h;
49 + }).on('data', function(data) {
50 + // make a copy because we are using readSync which re-uses a buffer ...
51 + var copy = new Buffer(data.length);
52 + data.copy(copy);
53 + data = copy;
54 + if (!preamble.body)
55 + preamble.body = [ data ];
56 + else
57 + preamble.body.push(data);
58 + preamble.bodylen += data.length;
59 + }).on('error', function(err) {
60 + preamble.error = err;
61 + }).on('end', function() {
62 + if (preamble.body)
63 + preamble.body = Buffer.concat(preamble.body, preamble.bodylen);
64 + if (preamble.body || preamble.header)
65 + state.preamble = preamble;
66 + });
67 + });
68 + }
69 + if (v.events && v.events.indexOf('part') > -1) {
70 + dicer.on('part', function(p) {
71 + var part = {
72 + body: undefined,
73 + bodylen: 0,
74 + error: undefined,
75 + header: undefined
76 + };
77 +
78 + p.on('header', function(h) {
79 + part.header = h;
80 + }).on('data', function(data) {
81 + // make a copy because we are using readSync which re-uses a buffer ...
82 + var copy = new Buffer(data.length);
83 + data.copy(copy);
84 + data = copy;
85 + if (!part.body)
86 + part.body = [ data ];
87 + else
88 + part.body.push(data);
89 + part.bodylen += data.length;
90 + }).on('error', function(err) {
91 + part.error = err;
92 + ++partErrors;
93 + }).on('end', function() {
94 + if (part.body)
95 + part.body = Buffer.concat(part.body, part.bodylen);
96 + state.parts.push(part);
97 + });
98 + });
99 + }
100 + dicer.on('error', function(err) {
101 + error = err;
102 + }).on('finish', function() {
103 + assert(finishes++ === 0, makeMsg(v.what, 'finish emitted multiple times'));
104 +
105 + if (v.dicerError)
106 + assert(error !== undefined, makeMsg(v.what, 'Expected error'));
107 + else
108 + assert(error === undefined, makeMsg(v.what, 'Unexpected error'));
109 +
110 + if (v.events && v.events.indexOf('preamble') > -1) {
111 + var preamble;
112 + if (fs.existsSync(fixtureBase + '/preamble')) {
113 + var prebody = fs.readFileSync(fixtureBase + '/preamble');
114 + if (prebody.length) {
115 + preamble = {
116 + body: prebody,
117 + bodylen: prebody.length,
118 + error: undefined,
119 + header: undefined
120 + };
121 + }
122 + }
123 + if (fs.existsSync(fixtureBase + '/preamble.header')) {
124 + var prehead = JSON.parse(fs.readFileSync(fixtureBase
125 + + '/preamble.header', 'binary'));
126 + if (!preamble) {
127 + preamble = {
128 + body: undefined,
129 + bodylen: 0,
130 + error: undefined,
131 + header: prehead
132 + };
133 + } else
134 + preamble.header = prehead;
135 + }
136 + if (fs.existsSync(fixtureBase + '/preamble.error')) {
137 + var err = new Error(fs.readFileSync(fixtureBase
138 + + '/preamble.error', 'binary'));
139 + if (!preamble) {
140 + preamble = {
141 + body: undefined,
142 + bodylen: 0,
143 + error: err,
144 + header: undefined
145 + };
146 + } else
147 + preamble.error = err;
148 + }
149 +
150 + assert.deepEqual(state.preamble,
151 + preamble,
152 + makeMsg(v.what,
153 + 'Preamble mismatch:\nActual:'
154 + + inspect(state.preamble)
155 + + '\nExpected: '
156 + + inspect(preamble)));
157 + }
158 +
159 + if (v.events && v.events.indexOf('part') > -1) {
160 + assert.equal(state.parts.length,
161 + v.nparts,
162 + makeMsg(v.what,
163 + 'Part count mismatch:\nActual: '
164 + + state.parts.length
165 + + '\nExpected: '
166 + + v.nparts));
167 +
168 + if (!v.npartErrors)
169 + v.npartErrors = 0;
170 + assert.equal(partErrors,
171 + v.npartErrors,
172 + makeMsg(v.what,
173 + 'Part errors mismatch:\nActual: '
174 + + partErrors
175 + + '\nExpected: '
176 + + v.npartErrors));
177 +
178 + for (var i = 0, header, body; i < v.nparts; ++i) {
179 + if (fs.existsSync(fixtureBase + '/part' + (i+1))) {
180 + body = fs.readFileSync(fixtureBase + '/part' + (i+1));
181 + if (body.length === 0)
182 + body = undefined;
183 + } else
184 + body = undefined;
185 + assert.deepEqual(state.parts[i].body,
186 + body,
187 + makeMsg(v.what,
188 + 'Part #' + (i+1) + ' body mismatch'));
189 + if (fs.existsSync(fixtureBase + '/part' + (i+1) + '.header')) {
190 + header = fs.readFileSync(fixtureBase
191 + + '/part' + (i+1) + '.header', 'binary');
192 + header = JSON.parse(header);
193 + } else
194 + header = undefined;
195 + assert.deepEqual(state.parts[i].header,
196 + header,
197 + makeMsg(v.what,
198 + 'Part #' + (i+1)
199 + + ' parsed header mismatch:\nActual: '
200 + + inspect(state.parts[i].header)
201 + + '\nExpected: '
202 + + inspect(header)));
203 + }
204 + }
205 + ++t;
206 + next();
207 + });
208 +
209 + while (true) {
210 + n = fs.readSync(fd, buffer, 0, buffer.length, null);
211 + if (n === 0) {
212 + dicer.end();
213 + break;
214 + }
215 + dicer.write(n === buffer.length ? buffer : buffer.slice(0, n));
216 + }
217 + fs.closeSync(fd);
218 +}
219 +next();
220 +
221 +function makeMsg(what, msg) {
222 + return '[' + group + what + ']: ' + msg;
223 +}
224 +
225 +process.on('exit', function() {
226 + assert(t === tests.length,
227 + makeMsg('_exit', 'Only ran ' + t + '/' + tests.length + ' tests'));
228 +});
...\ No newline at end of file ...\ No newline at end of file
1 +var Dicer = require('..');
2 +var assert = require('assert'),
3 + fs = require('fs'),
4 + path = require('path'),
5 + inspect = require('util').inspect;
6 +
7 +var FIXTURES_ROOT = __dirname + '/fixtures/';
8 +
9 +var t = 0,
10 + group = path.basename(__filename, '.js') + '/';
11 +
12 +var tests = [
13 + { source: 'nested',
14 + opts: { boundary: 'AaB03x' },
15 + chsize: 32,
16 + nparts: 2,
17 + what: 'One nested multipart'
18 + },
19 + { source: 'many',
20 + opts: { boundary: '----WebKitFormBoundaryWLHCs9qmcJJoyjKR' },
21 + chsize: 16,
22 + nparts: 7,
23 + what: 'Many parts'
24 + },
25 + { source: 'many-wrongboundary',
26 + opts: { boundary: 'LOLOLOL' },
27 + chsize: 8,
28 + nparts: 0,
29 + dicerError: true,
30 + what: 'Many parts, wrong boundary'
31 + },
32 + { source: 'many-noend',
33 + opts: { boundary: '----WebKitFormBoundaryWLHCs9qmcJJoyjKR' },
34 + chsize: 16,
35 + nparts: 7,
36 + npartErrors: 1,
37 + dicerError: true,
38 + what: 'Many parts, end boundary missing, 1 file open'
39 + },
40 + { source: 'nested-full',
41 + opts: { boundary: 'AaB03x', headerFirst: true },
42 + chsize: 32,
43 + nparts: 2,
44 + what: 'One nested multipart with preceding header'
45 + },
46 + { source: 'nested-full',
47 + opts: { headerFirst: true },
48 + chsize: 32,
49 + nparts: 2,
50 + setBoundary: 'AaB03x',
51 + what: 'One nested multipart with preceding header, using setBoundary'
52 + },
53 +];
54 +
55 +function next() {
56 + if (t === tests.length)
57 + return;
58 + var v = tests[t],
59 + fixtureBase = FIXTURES_ROOT + v.source,
60 + n = 0,
61 + buffer = new Buffer(v.chsize),
62 + state = { parts: [], preamble: undefined };
63 +
64 + var dicer = new Dicer(v.opts),
65 + error,
66 + partErrors = 0,
67 + finishes = 0;
68 +
69 + dicer.on('preamble', function(p) {
70 + var preamble = {
71 + body: undefined,
72 + bodylen: 0,
73 + error: undefined,
74 + header: undefined
75 + };
76 +
77 + p.on('header', function(h) {
78 + preamble.header = h;
79 + if (v.setBoundary)
80 + dicer.setBoundary(v.setBoundary);
81 + }).on('data', function(data) {
82 + // make a copy because we are using readSync which re-uses a buffer ...
83 + var copy = new Buffer(data.length);
84 + data.copy(copy);
85 + data = copy;
86 + if (!preamble.body)
87 + preamble.body = [ data ];
88 + else
89 + preamble.body.push(data);
90 + preamble.bodylen += data.length;
91 + }).on('error', function(err) {
92 + preamble.error = err;
93 + }).on('end', function() {
94 + if (preamble.body)
95 + preamble.body = Buffer.concat(preamble.body, preamble.bodylen);
96 + if (preamble.body || preamble.header)
97 + state.preamble = preamble;
98 + });
99 + });
100 + dicer.on('part', function(p) {
101 + var part = {
102 + body: undefined,
103 + bodylen: 0,
104 + error: undefined,
105 + header: undefined
106 + };
107 +
108 + p.on('header', function(h) {
109 + part.header = h;
110 + }).on('data', function(data) {
111 + if (!part.body)
112 + part.body = [ data ];
113 + else
114 + part.body.push(data);
115 + part.bodylen += data.length;
116 + }).on('error', function(err) {
117 + part.error = err;
118 + ++partErrors;
119 + }).on('end', function() {
120 + if (part.body)
121 + part.body = Buffer.concat(part.body, part.bodylen);
122 + state.parts.push(part);
123 + });
124 + }).on('error', function(err) {
125 + error = err;
126 + }).on('finish', function() {
127 + assert(finishes++ === 0, makeMsg(v.what, 'finish emitted multiple times'));
128 +
129 + if (v.dicerError)
130 + assert(error !== undefined, makeMsg(v.what, 'Expected error'));
131 + else
132 + assert(error === undefined, makeMsg(v.what, 'Unexpected error: ' + error));
133 +
134 + var preamble;
135 + if (fs.existsSync(fixtureBase + '/preamble')) {
136 + var prebody = fs.readFileSync(fixtureBase + '/preamble');
137 + if (prebody.length) {
138 + preamble = {
139 + body: prebody,
140 + bodylen: prebody.length,
141 + error: undefined,
142 + header: undefined
143 + };
144 + }
145 + }
146 + if (fs.existsSync(fixtureBase + '/preamble.header')) {
147 + var prehead = JSON.parse(fs.readFileSync(fixtureBase
148 + + '/preamble.header', 'binary'));
149 + if (!preamble) {
150 + preamble = {
151 + body: undefined,
152 + bodylen: 0,
153 + error: undefined,
154 + header: prehead
155 + };
156 + } else
157 + preamble.header = prehead;
158 + }
159 + if (fs.existsSync(fixtureBase + '/preamble.error')) {
160 + var err = new Error(fs.readFileSync(fixtureBase
161 + + '/preamble.error', 'binary'));
162 + if (!preamble) {
163 + preamble = {
164 + body: undefined,
165 + bodylen: 0,
166 + error: err,
167 + header: undefined
168 + };
169 + } else
170 + preamble.error = err;
171 + }
172 +
173 + assert.deepEqual(state.preamble,
174 + preamble,
175 + makeMsg(v.what,
176 + 'Preamble mismatch:\nActual:'
177 + + inspect(state.preamble)
178 + + '\nExpected: '
179 + + inspect(preamble)));
180 +
181 + assert.equal(state.parts.length,
182 + v.nparts,
183 + makeMsg(v.what,
184 + 'Part count mismatch:\nActual: '
185 + + state.parts.length
186 + + '\nExpected: '
187 + + v.nparts));
188 +
189 + if (!v.npartErrors)
190 + v.npartErrors = 0;
191 + assert.equal(partErrors,
192 + v.npartErrors,
193 + makeMsg(v.what,
194 + 'Part errors mismatch:\nActual: '
195 + + partErrors
196 + + '\nExpected: '
197 + + v.npartErrors));
198 +
199 + for (var i = 0, header, body; i < v.nparts; ++i) {
200 + if (fs.existsSync(fixtureBase + '/part' + (i+1))) {
201 + body = fs.readFileSync(fixtureBase + '/part' + (i+1));
202 + if (body.length === 0)
203 + body = undefined;
204 + } else
205 + body = undefined;
206 + assert.deepEqual(state.parts[i].body,
207 + body,
208 + makeMsg(v.what,
209 + 'Part #' + (i+1) + ' body mismatch'));
210 + if (fs.existsSync(fixtureBase + '/part' + (i+1) + '.header')) {
211 + header = fs.readFileSync(fixtureBase
212 + + '/part' + (i+1) + '.header', 'binary');
213 + header = JSON.parse(header);
214 + } else
215 + header = undefined;
216 + assert.deepEqual(state.parts[i].header,
217 + header,
218 + makeMsg(v.what,
219 + 'Part #' + (i+1)
220 + + ' parsed header mismatch:\nActual: '
221 + + inspect(state.parts[i].header)
222 + + '\nExpected: '
223 + + inspect(header)));
224 + }
225 + ++t;
226 + next();
227 + });
228 +
229 + fs.createReadStream(fixtureBase + '/original').pipe(dicer);
230 +}
231 +next();
232 +
233 +function makeMsg(what, msg) {
234 + return '[' + group + what + ']: ' + msg;
235 +}
236 +
237 +process.on('exit', function() {
238 + assert(t === tests.length,
239 + makeMsg('_exit', 'Only ran ' + t + '/' + tests.length + ' tests'));
240 +});
...\ No newline at end of file ...\ No newline at end of file
1 +require('fs').readdirSync(__dirname).forEach(function(f) {
2 + if (f.substr(0, 5) === 'test-')
3 + require('./' + f);
4 +});
...\ No newline at end of file ...\ No newline at end of file
1 +# Developer's Certificate of Origin 1.1
2 +
3 +By making a contribution to this project, I certify that:
4 +
5 +* (a) The contribution was created in whole or in part by me and I
6 + have the right to submit it under the open source license
7 + indicated in the file; or
8 +
9 +* (b) The contribution is based upon previous work that, to the best
10 + of my knowledge, is covered under an appropriate open source
11 + license and I have the right under that license to submit that
12 + work with modifications, whether created in whole or in part
13 + by me, under the same open source license (unless I am
14 + permitted to submit under a different license), as indicated
15 + in the file; or
16 +
17 +* (c) The contribution was provided directly to me by some other
18 + person who certified (a), (b) or (c) and I have not modified
19 + it.
20 +
21 +* (d) I understand and agree that this project and the contribution
22 + are public and that a record of the contribution (including all
23 + personal information I submit with it, including my sign-off) is
24 + maintained indefinitely and may be redistributed consistent with
25 + this project or the open source license(s) involved.
26 +
27 +## Moderation Policy
28 +
29 +The [Node.js Moderation Policy] applies to this WG.
30 +
31 +## Code of Conduct
32 +
33 +The [Node.js Code of Conduct][] applies to this WG.
34 +
35 +[Node.js Code of Conduct]:
36 +https://github.com/nodejs/node/blob/master/CODE_OF_CONDUCT.md
37 +[Node.js Moderation Policy]:
38 +https://github.com/nodejs/TSC/blob/master/Moderation-Policy.md
1 +### Streams Working Group
2 +
3 +The Node.js Streams is jointly governed by a Working Group
4 +(WG)
5 +that is responsible for high-level guidance of the project.
6 +
7 +The WG has final authority over this project including:
8 +
9 +* Technical direction
10 +* Project governance and process (including this policy)
11 +* Contribution policy
12 +* GitHub repository hosting
13 +* Conduct guidelines
14 +* Maintaining the list of additional Collaborators
15 +
16 +For the current list of WG members, see the project
17 +[README.md](./README.md#current-project-team-members).
18 +
19 +### Collaborators
20 +
21 +The readable-stream GitHub repository is
22 +maintained by the WG and additional Collaborators who are added by the
23 +WG on an ongoing basis.
24 +
25 +Individuals making significant and valuable contributions are made
26 +Collaborators and given commit-access to the project. These
27 +individuals are identified by the WG and their addition as
28 +Collaborators is discussed during the WG meeting.
29 +
30 +_Note:_ If you make a significant contribution and are not considered
31 +for commit-access log an issue or contact a WG member directly and it
32 +will be brought up in the next WG meeting.
33 +
34 +Modifications of the contents of the readable-stream repository are
35 +made on
36 +a collaborative basis. Anybody with a GitHub account may propose a
37 +modification via pull request and it will be considered by the project
38 +Collaborators. All pull requests must be reviewed and accepted by a
39 +Collaborator with sufficient expertise who is able to take full
40 +responsibility for the change. In the case of pull requests proposed
41 +by an existing Collaborator, an additional Collaborator is required
42 +for sign-off. Consensus should be sought if additional Collaborators
43 +participate and there is disagreement around a particular
44 +modification. See _Consensus Seeking Process_ below for further detail
45 +on the consensus model used for governance.
46 +
47 +Collaborators may opt to elevate significant or controversial
48 +modifications, or modifications that have not found consensus to the
49 +WG for discussion by assigning the ***WG-agenda*** tag to a pull
50 +request or issue. The WG should serve as the final arbiter where
51 +required.
52 +
53 +For the current list of Collaborators, see the project
54 +[README.md](./README.md#members).
55 +
56 +### WG Membership
57 +
58 +WG seats are not time-limited. There is no fixed size of the WG.
59 +However, the expected target is between 6 and 12, to ensure adequate
60 +coverage of important areas of expertise, balanced with the ability to
61 +make decisions efficiently.
62 +
63 +There is no specific set of requirements or qualifications for WG
64 +membership beyond these rules.
65 +
66 +The WG may add additional members to the WG by unanimous consensus.
67 +
68 +A WG member may be removed from the WG by voluntary resignation, or by
69 +unanimous consensus of all other WG members.
70 +
71 +Changes to WG membership should be posted in the agenda, and may be
72 +suggested as any other agenda item (see "WG Meetings" below).
73 +
74 +If an addition or removal is proposed during a meeting, and the full
75 +WG is not in attendance to participate, then the addition or removal
76 +is added to the agenda for the subsequent meeting. This is to ensure
77 +that all members are given the opportunity to participate in all
78 +membership decisions. If a WG member is unable to attend a meeting
79 +where a planned membership decision is being made, then their consent
80 +is assumed.
81 +
82 +No more than 1/3 of the WG members may be affiliated with the same
83 +employer. If removal or resignation of a WG member, or a change of
84 +employment by a WG member, creates a situation where more than 1/3 of
85 +the WG membership shares an employer, then the situation must be
86 +immediately remedied by the resignation or removal of one or more WG
87 +members affiliated with the over-represented employer(s).
88 +
89 +### WG Meetings
90 +
91 +The WG meets occasionally on a Google Hangout On Air. A designated moderator
92 +approved by the WG runs the meeting. Each meeting should be
93 +published to YouTube.
94 +
95 +Items are added to the WG agenda that are considered contentious or
96 +are modifications of governance, contribution policy, WG membership,
97 +or release process.
98 +
99 +The intention of the agenda is not to approve or review all patches;
100 +that should happen continuously on GitHub and be handled by the larger
101 +group of Collaborators.
102 +
103 +Any community member or contributor can ask that something be added to
104 +the next meeting's agenda by logging a GitHub Issue. Any Collaborator,
105 +WG member or the moderator can add the item to the agenda by adding
106 +the ***WG-agenda*** tag to the issue.
107 +
108 +Prior to each WG meeting the moderator will share the Agenda with
109 +members of the WG. WG members can add any items they like to the
110 +agenda at the beginning of each meeting. The moderator and the WG
111 +cannot veto or remove items.
112 +
113 +The WG may invite persons or representatives from certain projects to
114 +participate in a non-voting capacity.
115 +
116 +The moderator is responsible for summarizing the discussion of each
117 +agenda item and sends it as a pull request after the meeting.
118 +
119 +### Consensus Seeking Process
120 +
121 +The WG follows a
122 +[Consensus
123 +Seeking](http://en.wikipedia.org/wiki/Consensus-seeking_decision-making)
124 +decision-making model.
125 +
126 +When an agenda item has appeared to reach a consensus the moderator
127 +will ask "Does anyone object?" as a final call for dissent from the
128 +consensus.
129 +
130 +If an agenda item cannot reach a consensus a WG member can call for
131 +either a closing vote or a vote to table the issue to the next
132 +meeting. The call for a vote must be seconded by a majority of the WG
133 +or else the discussion will continue. Simple majority wins.
134 +
135 +Note that changes to WG membership require a majority consensus. See
136 +"WG Membership" above.
1 +Node.js is licensed for use as follows:
2 +
3 +"""
4 +Copyright Node.js contributors. All rights reserved.
5 +
6 +Permission is hereby granted, free of charge, to any person obtaining a copy
7 +of this software and associated documentation files (the "Software"), to
8 +deal in the Software without restriction, including without limitation the
9 +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
10 +sell copies of the Software, and to permit persons to whom the Software is
11 +furnished to do so, subject to the following conditions:
12 +
13 +The above copyright notice and this permission notice shall be included in
14 +all copies or substantial portions of the Software.
15 +
16 +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21 +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
22 +IN THE SOFTWARE.
23 +"""
24 +
25 +This license applies to parts of Node.js originating from the
26 +https://github.com/joyent/node repository:
27 +
28 +"""
29 +Copyright Joyent, Inc. and other Node contributors. All rights reserved.
30 +Permission is hereby granted, free of charge, to any person obtaining a copy
31 +of this software and associated documentation files (the "Software"), to
32 +deal in the Software without restriction, including without limitation the
33 +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
34 +sell copies of the Software, and to permit persons to whom the Software is
35 +furnished to do so, subject to the following conditions:
36 +
37 +The above copyright notice and this permission notice shall be included in
38 +all copies or substantial portions of the Software.
39 +
40 +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
41 +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
42 +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
43 +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
44 +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
45 +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
46 +IN THE SOFTWARE.
47 +"""
1 +# readable-stream
2 +
3 +***Node.js core streams for userland*** [![Build Status](https://travis-ci.com/nodejs/readable-stream.svg?branch=master)](https://travis-ci.com/nodejs/readable-stream)
4 +
5 +
6 +[![NPM](https://nodei.co/npm/readable-stream.png?downloads=true&downloadRank=true)](https://nodei.co/npm/readable-stream/)
7 +[![NPM](https://nodei.co/npm-dl/readable-stream.png?&months=6&height=3)](https://nodei.co/npm/readable-stream/)
8 +
9 +
10 +[![Sauce Test Status](https://saucelabs.com/browser-matrix/readabe-stream.svg)](https://saucelabs.com/u/readabe-stream)
11 +
12 +```bash
13 +npm install --save readable-stream
14 +```
15 +
16 +This package is a mirror of the streams implementations in Node.js.
17 +
18 +Full documentation may be found on the [Node.js website](https://nodejs.org/dist/v10.19.0/docs/api/stream.html).
19 +
20 +If you want to guarantee a stable streams base, regardless of what version of
21 +Node you, or the users of your libraries are using, use **readable-stream** *only* and avoid the *"stream"* module in Node-core, for background see [this blogpost](http://r.va.gg/2014/06/why-i-dont-use-nodes-core-stream-module.html).
22 +
23 +As of version 2.0.0 **readable-stream** uses semantic versioning.
24 +
25 +## Version 3.x.x
26 +
27 +v3.x.x of `readable-stream` is a cut from Node 10. This version supports Node 6, 8, and 10, as well as evergreen browsers, IE 11 and latest Safari. The breaking changes introduced by v3 are composed by the combined breaking changes in [Node v9](https://nodejs.org/en/blog/release/v9.0.0/) and [Node v10](https://nodejs.org/en/blog/release/v10.0.0/), as follows:
28 +
29 +1. Error codes: https://github.com/nodejs/node/pull/13310,
30 + https://github.com/nodejs/node/pull/13291,
31 + https://github.com/nodejs/node/pull/16589,
32 + https://github.com/nodejs/node/pull/15042,
33 + https://github.com/nodejs/node/pull/15665,
34 + https://github.com/nodejs/readable-stream/pull/344
35 +2. 'readable' have precedence over flowing
36 + https://github.com/nodejs/node/pull/18994
37 +3. make virtual methods errors consistent
38 + https://github.com/nodejs/node/pull/18813
39 +4. updated streams error handling
40 + https://github.com/nodejs/node/pull/18438
41 +5. writable.end should return this.
42 + https://github.com/nodejs/node/pull/18780
43 +6. readable continues to read when push('')
44 + https://github.com/nodejs/node/pull/18211
45 +7. add custom inspect to BufferList
46 + https://github.com/nodejs/node/pull/17907
47 +8. always defer 'readable' with nextTick
48 + https://github.com/nodejs/node/pull/17979
49 +
50 +## Version 2.x.x
51 +v2.x.x of `readable-stream` is a cut of the stream module from Node 8 (there have been no semver-major changes from Node 4 to 8). This version supports all Node.js versions from 0.8, as well as evergreen browsers and IE 10 & 11.
52 +
53 +### Big Thanks
54 +
55 +Cross-browser Testing Platform and Open Source <3 Provided by [Sauce Labs][sauce]
56 +
57 +# Usage
58 +
59 +You can swap your `require('stream')` with `require('readable-stream')`
60 +without any changes, if you are just using one of the main classes and
61 +functions.
62 +
63 +```js
64 +const {
65 + Readable,
66 + Writable,
67 + Transform,
68 + Duplex,
69 + pipeline,
70 + finished
71 +} = require('readable-stream')
72 +````
73 +
74 +Note that `require('stream')` will return `Stream`, while
75 +`require('readable-stream')` will return `Readable`. We discourage using
76 +whatever is exported directly, but rather use one of the properties as
77 +shown in the example above.
78 +
79 +# Streams Working Group
80 +
81 +`readable-stream` is maintained by the Streams Working Group, which
82 +oversees the development and maintenance of the Streams API within
83 +Node.js. The responsibilities of the Streams Working Group include:
84 +
85 +* Addressing stream issues on the Node.js issue tracker.
86 +* Authoring and editing stream documentation within the Node.js project.
87 +* Reviewing changes to stream subclasses within the Node.js project.
88 +* Redirecting changes to streams from the Node.js project to this
89 + project.
90 +* Assisting in the implementation of stream providers within Node.js.
91 +* Recommending versions of `readable-stream` to be included in Node.js.
92 +* Messaging about the future of streams to give the community advance
93 + notice of changes.
94 +
95 +<a name="members"></a>
96 +## Team Members
97 +
98 +* **Calvin Metcalf** ([@calvinmetcalf](https://github.com/calvinmetcalf)) &lt;calvin.metcalf@gmail.com&gt;
99 + - Release GPG key: F3EF5F62A87FC27A22E643F714CE4FF5015AA242
100 +* **Mathias Buus** ([@mafintosh](https://github.com/mafintosh)) &lt;mathiasbuus@gmail.com&gt;
101 +* **Matteo Collina** ([@mcollina](https://github.com/mcollina)) &lt;matteo.collina@gmail.com&gt;
102 + - Release GPG key: 3ABC01543F22DD2239285CDD818674489FBC127E
103 +* **Irina Shestak** ([@lrlna](https://github.com/lrlna)) &lt;shestak.irina@gmail.com&gt;
104 +* **Yoshua Wyuts** ([@yoshuawuyts](https://github.com/yoshuawuyts)) &lt;yoshuawuyts@gmail.com&gt;
105 +
106 +[sauce]: https://saucelabs.com
1 +// Copyright Joyent, Inc. and other Node contributors.
2 +//
3 +// Permission is hereby granted, free of charge, to any person obtaining a
4 +// copy of this software and associated documentation files (the
5 +// "Software"), to deal in the Software without restriction, including
6 +// without limitation the rights to use, copy, modify, merge, publish,
7 +// distribute, sublicense, and/or sell copies of the Software, and to permit
8 +// persons to whom the Software is furnished to do so, subject to the
9 +// following conditions:
10 +//
11 +// The above copyright notice and this permission notice shall be included
12 +// in all copies or substantial portions of the Software.
13 +//
14 +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15 +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17 +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18 +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19 +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20 +// USE OR OTHER DEALINGS IN THE SOFTWARE.
21 +// a duplex stream is just a stream that is both readable and writable.
22 +// Since JS doesn't have multiple prototypal inheritance, this class
23 +// prototypally inherits from Readable, and then parasitically from
24 +// Writable.
25 +'use strict';
26 +/*<replacement>*/
27 +
28 +var objectKeys = Object.keys || function (obj) {
29 + var keys = [];
30 +
31 + for (var key in obj) {
32 + keys.push(key);
33 + }
34 +
35 + return keys;
36 +};
37 +/*</replacement>*/
38 +
39 +
40 +module.exports = Duplex;
41 +
42 +var Readable = require('./_stream_readable');
43 +
44 +var Writable = require('./_stream_writable');
45 +
46 +require('inherits')(Duplex, Readable);
47 +
48 +{
49 + // Allow the keys array to be GC'ed.
50 + var keys = objectKeys(Writable.prototype);
51 +
52 + for (var v = 0; v < keys.length; v++) {
53 + var method = keys[v];
54 + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
55 + }
56 +}
57 +
58 +function Duplex(options) {
59 + if (!(this instanceof Duplex)) return new Duplex(options);
60 + Readable.call(this, options);
61 + Writable.call(this, options);
62 + this.allowHalfOpen = true;
63 +
64 + if (options) {
65 + if (options.readable === false) this.readable = false;
66 + if (options.writable === false) this.writable = false;
67 +
68 + if (options.allowHalfOpen === false) {
69 + this.allowHalfOpen = false;
70 + this.once('end', onend);
71 + }
72 + }
73 +}
74 +
75 +Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
76 + // making it explicit this property is not enumerable
77 + // because otherwise some prototype manipulation in
78 + // userland will fail
79 + enumerable: false,
80 + get: function get() {
81 + return this._writableState.highWaterMark;
82 + }
83 +});
84 +Object.defineProperty(Duplex.prototype, 'writableBuffer', {
85 + // making it explicit this property is not enumerable
86 + // because otherwise some prototype manipulation in
87 + // userland will fail
88 + enumerable: false,
89 + get: function get() {
90 + return this._writableState && this._writableState.getBuffer();
91 + }
92 +});
93 +Object.defineProperty(Duplex.prototype, 'writableLength', {
94 + // making it explicit this property is not enumerable
95 + // because otherwise some prototype manipulation in
96 + // userland will fail
97 + enumerable: false,
98 + get: function get() {
99 + return this._writableState.length;
100 + }
101 +}); // the no-half-open enforcer
102 +
103 +function onend() {
104 + // If the writable side ended, then we're ok.
105 + if (this._writableState.ended) return; // no more data can be written.
106 + // But allow more writes to happen in this tick.
107 +
108 + process.nextTick(onEndNT, this);
109 +}
110 +
111 +function onEndNT(self) {
112 + self.end();
113 +}
114 +
115 +Object.defineProperty(Duplex.prototype, 'destroyed', {
116 + // making it explicit this property is not enumerable
117 + // because otherwise some prototype manipulation in
118 + // userland will fail
119 + enumerable: false,
120 + get: function get() {
121 + if (this._readableState === undefined || this._writableState === undefined) {
122 + return false;
123 + }
124 +
125 + return this._readableState.destroyed && this._writableState.destroyed;
126 + },
127 + set: function set(value) {
128 + // we ignore the value if the stream
129 + // has not been initialized yet
130 + if (this._readableState === undefined || this._writableState === undefined) {
131 + return;
132 + } // backward compatibility, the user is explicitly
133 + // managing destroyed
134 +
135 +
136 + this._readableState.destroyed = value;
137 + this._writableState.destroyed = value;
138 + }
139 +});
...\ No newline at end of file ...\ No newline at end of file
1 +// Copyright Joyent, Inc. and other Node contributors.
2 +//
3 +// Permission is hereby granted, free of charge, to any person obtaining a
4 +// copy of this software and associated documentation files (the
5 +// "Software"), to deal in the Software without restriction, including
6 +// without limitation the rights to use, copy, modify, merge, publish,
7 +// distribute, sublicense, and/or sell copies of the Software, and to permit
8 +// persons to whom the Software is furnished to do so, subject to the
9 +// following conditions:
10 +//
11 +// The above copyright notice and this permission notice shall be included
12 +// in all copies or substantial portions of the Software.
13 +//
14 +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15 +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17 +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18 +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19 +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20 +// USE OR OTHER DEALINGS IN THE SOFTWARE.
21 +// a passthrough stream.
22 +// basically just the most minimal sort of Transform stream.
23 +// Every written chunk gets output as-is.
24 +'use strict';
25 +
26 +module.exports = PassThrough;
27 +
28 +var Transform = require('./_stream_transform');
29 +
30 +require('inherits')(PassThrough, Transform);
31 +
32 +function PassThrough(options) {
33 + if (!(this instanceof PassThrough)) return new PassThrough(options);
34 + Transform.call(this, options);
35 +}
36 +
37 +PassThrough.prototype._transform = function (chunk, encoding, cb) {
38 + cb(null, chunk);
39 +};
...\ No newline at end of file ...\ No newline at end of file
1 +// Copyright Joyent, Inc. and other Node contributors.
2 +//
3 +// Permission is hereby granted, free of charge, to any person obtaining a
4 +// copy of this software and associated documentation files (the
5 +// "Software"), to deal in the Software without restriction, including
6 +// without limitation the rights to use, copy, modify, merge, publish,
7 +// distribute, sublicense, and/or sell copies of the Software, and to permit
8 +// persons to whom the Software is furnished to do so, subject to the
9 +// following conditions:
10 +//
11 +// The above copyright notice and this permission notice shall be included
12 +// in all copies or substantial portions of the Software.
13 +//
14 +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15 +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17 +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18 +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19 +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20 +// USE OR OTHER DEALINGS IN THE SOFTWARE.
21 +'use strict';
22 +
23 +module.exports = Readable;
24 +/*<replacement>*/
25 +
26 +var Duplex;
27 +/*</replacement>*/
28 +
29 +Readable.ReadableState = ReadableState;
30 +/*<replacement>*/
31 +
32 +var EE = require('events').EventEmitter;
33 +
34 +var EElistenerCount = function EElistenerCount(emitter, type) {
35 + return emitter.listeners(type).length;
36 +};
37 +/*</replacement>*/
38 +
39 +/*<replacement>*/
40 +
41 +
42 +var Stream = require('./internal/streams/stream');
43 +/*</replacement>*/
44 +
45 +
46 +var Buffer = require('buffer').Buffer;
47 +
48 +var OurUint8Array = global.Uint8Array || function () {};
49 +
50 +function _uint8ArrayToBuffer(chunk) {
51 + return Buffer.from(chunk);
52 +}
53 +
54 +function _isUint8Array(obj) {
55 + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
56 +}
57 +/*<replacement>*/
58 +
59 +
60 +var debugUtil = require('util');
61 +
62 +var debug;
63 +
64 +if (debugUtil && debugUtil.debuglog) {
65 + debug = debugUtil.debuglog('stream');
66 +} else {
67 + debug = function debug() {};
68 +}
69 +/*</replacement>*/
70 +
71 +
72 +var BufferList = require('./internal/streams/buffer_list');
73 +
74 +var destroyImpl = require('./internal/streams/destroy');
75 +
76 +var _require = require('./internal/streams/state'),
77 + getHighWaterMark = _require.getHighWaterMark;
78 +
79 +var _require$codes = require('../errors').codes,
80 + ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,
81 + ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF,
82 + ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
83 + ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance.
84 +
85 +
86 +var StringDecoder;
87 +var createReadableStreamAsyncIterator;
88 +var from;
89 +
90 +require('inherits')(Readable, Stream);
91 +
92 +var errorOrDestroy = destroyImpl.errorOrDestroy;
93 +var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
94 +
95 +function prependListener(emitter, event, fn) {
96 + // Sadly this is not cacheable as some libraries bundle their own
97 + // event emitter implementation with them.
98 + if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any
99 + // userland ones. NEVER DO THIS. This is here only because this code needs
100 + // to continue to work with older versions of Node.js that do not include
101 + // the prependListener() method. The goal is to eventually remove this hack.
102 +
103 + if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];
104 +}
105 +
106 +function ReadableState(options, stream, isDuplex) {
107 + Duplex = Duplex || require('./_stream_duplex');
108 + options = options || {}; // Duplex streams are both readable and writable, but share
109 + // the same options object.
110 + // However, some cases require setting options to different
111 + // values for the readable and the writable sides of the duplex stream.
112 + // These options can be provided separately as readableXXX and writableXXX.
113 +
114 + if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag. Used to make read(n) ignore n and to
115 + // make all the buffer merging and length checks go away
116 +
117 + this.objectMode = !!options.objectMode;
118 + if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer
119 + // Note: 0 is a valid value, means "don't call _read preemptively ever"
120 +
121 + this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the
122 + // linked list can remove elements from the beginning faster than
123 + // array.shift()
124 +
125 + this.buffer = new BufferList();
126 + this.length = 0;
127 + this.pipes = null;
128 + this.pipesCount = 0;
129 + this.flowing = null;
130 + this.ended = false;
131 + this.endEmitted = false;
132 + this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted
133 + // immediately, or on a later tick. We set this to true at first, because
134 + // any actions that shouldn't happen until "later" should generally also
135 + // not happen before the first read call.
136 +
137 + this.sync = true; // whenever we return null, then we set a flag to say
138 + // that we're awaiting a 'readable' event emission.
139 +
140 + this.needReadable = false;
141 + this.emittedReadable = false;
142 + this.readableListening = false;
143 + this.resumeScheduled = false;
144 + this.paused = true; // Should close be emitted on destroy. Defaults to true.
145 +
146 + this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'end' (and potentially 'finish')
147 +
148 + this.autoDestroy = !!options.autoDestroy; // has it been destroyed
149 +
150 + this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string
151 + // encoding is 'binary' so we have to make this configurable.
152 + // Everything else in the universe uses 'utf8', though.
153 +
154 + this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s
155 +
156 + this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled
157 +
158 + this.readingMore = false;
159 + this.decoder = null;
160 + this.encoding = null;
161 +
162 + if (options.encoding) {
163 + if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
164 + this.decoder = new StringDecoder(options.encoding);
165 + this.encoding = options.encoding;
166 + }
167 +}
168 +
169 +function Readable(options) {
170 + Duplex = Duplex || require('./_stream_duplex');
171 + if (!(this instanceof Readable)) return new Readable(options); // Checking for a Stream.Duplex instance is faster here instead of inside
172 + // the ReadableState constructor, at least with V8 6.5
173 +
174 + var isDuplex = this instanceof Duplex;
175 + this._readableState = new ReadableState(options, this, isDuplex); // legacy
176 +
177 + this.readable = true;
178 +
179 + if (options) {
180 + if (typeof options.read === 'function') this._read = options.read;
181 + if (typeof options.destroy === 'function') this._destroy = options.destroy;
182 + }
183 +
184 + Stream.call(this);
185 +}
186 +
187 +Object.defineProperty(Readable.prototype, 'destroyed', {
188 + // making it explicit this property is not enumerable
189 + // because otherwise some prototype manipulation in
190 + // userland will fail
191 + enumerable: false,
192 + get: function get() {
193 + if (this._readableState === undefined) {
194 + return false;
195 + }
196 +
197 + return this._readableState.destroyed;
198 + },
199 + set: function set(value) {
200 + // we ignore the value if the stream
201 + // has not been initialized yet
202 + if (!this._readableState) {
203 + return;
204 + } // backward compatibility, the user is explicitly
205 + // managing destroyed
206 +
207 +
208 + this._readableState.destroyed = value;
209 + }
210 +});
211 +Readable.prototype.destroy = destroyImpl.destroy;
212 +Readable.prototype._undestroy = destroyImpl.undestroy;
213 +
214 +Readable.prototype._destroy = function (err, cb) {
215 + cb(err);
216 +}; // Manually shove something into the read() buffer.
217 +// This returns true if the highWaterMark has not been hit yet,
218 +// similar to how Writable.write() returns true if you should
219 +// write() some more.
220 +
221 +
222 +Readable.prototype.push = function (chunk, encoding) {
223 + var state = this._readableState;
224 + var skipChunkCheck;
225 +
226 + if (!state.objectMode) {
227 + if (typeof chunk === 'string') {
228 + encoding = encoding || state.defaultEncoding;
229 +
230 + if (encoding !== state.encoding) {
231 + chunk = Buffer.from(chunk, encoding);
232 + encoding = '';
233 + }
234 +
235 + skipChunkCheck = true;
236 + }
237 + } else {
238 + skipChunkCheck = true;
239 + }
240 +
241 + return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
242 +}; // Unshift should *always* be something directly out of read()
243 +
244 +
245 +Readable.prototype.unshift = function (chunk) {
246 + return readableAddChunk(this, chunk, null, true, false);
247 +};
248 +
249 +function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
250 + debug('readableAddChunk', chunk);
251 + var state = stream._readableState;
252 +
253 + if (chunk === null) {
254 + state.reading = false;
255 + onEofChunk(stream, state);
256 + } else {
257 + var er;
258 + if (!skipChunkCheck) er = chunkInvalid(state, chunk);
259 +
260 + if (er) {
261 + errorOrDestroy(stream, er);
262 + } else if (state.objectMode || chunk && chunk.length > 0) {
263 + if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
264 + chunk = _uint8ArrayToBuffer(chunk);
265 + }
266 +
267 + if (addToFront) {
268 + if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true);
269 + } else if (state.ended) {
270 + errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF());
271 + } else if (state.destroyed) {
272 + return false;
273 + } else {
274 + state.reading = false;
275 +
276 + if (state.decoder && !encoding) {
277 + chunk = state.decoder.write(chunk);
278 + if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
279 + } else {
280 + addChunk(stream, state, chunk, false);
281 + }
282 + }
283 + } else if (!addToFront) {
284 + state.reading = false;
285 + maybeReadMore(stream, state);
286 + }
287 + } // We can push more data if we are below the highWaterMark.
288 + // Also, if we have no data yet, we can stand some more bytes.
289 + // This is to work around cases where hwm=0, such as the repl.
290 +
291 +
292 + return !state.ended && (state.length < state.highWaterMark || state.length === 0);
293 +}
294 +
295 +function addChunk(stream, state, chunk, addToFront) {
296 + if (state.flowing && state.length === 0 && !state.sync) {
297 + state.awaitDrain = 0;
298 + stream.emit('data', chunk);
299 + } else {
300 + // update the buffer info.
301 + state.length += state.objectMode ? 1 : chunk.length;
302 + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
303 + if (state.needReadable) emitReadable(stream);
304 + }
305 +
306 + maybeReadMore(stream, state);
307 +}
308 +
309 +function chunkInvalid(state, chunk) {
310 + var er;
311 +
312 + if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
313 + er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk);
314 + }
315 +
316 + return er;
317 +}
318 +
319 +Readable.prototype.isPaused = function () {
320 + return this._readableState.flowing === false;
321 +}; // backwards compatibility.
322 +
323 +
324 +Readable.prototype.setEncoding = function (enc) {
325 + if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
326 + var decoder = new StringDecoder(enc);
327 + this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8
328 +
329 + this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers:
330 +
331 + var p = this._readableState.buffer.head;
332 + var content = '';
333 +
334 + while (p !== null) {
335 + content += decoder.write(p.data);
336 + p = p.next;
337 + }
338 +
339 + this._readableState.buffer.clear();
340 +
341 + if (content !== '') this._readableState.buffer.push(content);
342 + this._readableState.length = content.length;
343 + return this;
344 +}; // Don't raise the hwm > 1GB
345 +
346 +
347 +var MAX_HWM = 0x40000000;
348 +
349 +function computeNewHighWaterMark(n) {
350 + if (n >= MAX_HWM) {
351 + // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE.
352 + n = MAX_HWM;
353 + } else {
354 + // Get the next highest power of 2 to prevent increasing hwm excessively in
355 + // tiny amounts
356 + n--;
357 + n |= n >>> 1;
358 + n |= n >>> 2;
359 + n |= n >>> 4;
360 + n |= n >>> 8;
361 + n |= n >>> 16;
362 + n++;
363 + }
364 +
365 + return n;
366 +} // This function is designed to be inlinable, so please take care when making
367 +// changes to the function body.
368 +
369 +
370 +function howMuchToRead(n, state) {
371 + if (n <= 0 || state.length === 0 && state.ended) return 0;
372 + if (state.objectMode) return 1;
373 +
374 + if (n !== n) {
375 + // Only flow one buffer at a time
376 + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
377 + } // If we're asking for more than the current hwm, then raise the hwm.
378 +
379 +
380 + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
381 + if (n <= state.length) return n; // Don't have enough
382 +
383 + if (!state.ended) {
384 + state.needReadable = true;
385 + return 0;
386 + }
387 +
388 + return state.length;
389 +} // you can override either this method, or the async _read(n) below.
390 +
391 +
392 +Readable.prototype.read = function (n) {
393 + debug('read', n);
394 + n = parseInt(n, 10);
395 + var state = this._readableState;
396 + var nOrig = n;
397 + if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we
398 + // already have a bunch of data in the buffer, then just trigger
399 + // the 'readable' event and move on.
400 +
401 + if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) {
402 + debug('read: emitReadable', state.length, state.ended);
403 + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
404 + return null;
405 + }
406 +
407 + n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up.
408 +
409 + if (n === 0 && state.ended) {
410 + if (state.length === 0) endReadable(this);
411 + return null;
412 + } // All the actual chunk generation logic needs to be
413 + // *below* the call to _read. The reason is that in certain
414 + // synthetic stream cases, such as passthrough streams, _read
415 + // may be a completely synchronous operation which may change
416 + // the state of the read buffer, providing enough data when
417 + // before there was *not* enough.
418 + //
419 + // So, the steps are:
420 + // 1. Figure out what the state of things will be after we do
421 + // a read from the buffer.
422 + //
423 + // 2. If that resulting state will trigger a _read, then call _read.
424 + // Note that this may be asynchronous, or synchronous. Yes, it is
425 + // deeply ugly to write APIs this way, but that still doesn't mean
426 + // that the Readable class should behave improperly, as streams are
427 + // designed to be sync/async agnostic.
428 + // Take note if the _read call is sync or async (ie, if the read call
429 + // has returned yet), so that we know whether or not it's safe to emit
430 + // 'readable' etc.
431 + //
432 + // 3. Actually pull the requested chunks out of the buffer and return.
433 + // if we need a readable event, then we need to do some reading.
434 +
435 +
436 + var doRead = state.needReadable;
437 + debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some
438 +
439 + if (state.length === 0 || state.length - n < state.highWaterMark) {
440 + doRead = true;
441 + debug('length less than watermark', doRead);
442 + } // however, if we've ended, then there's no point, and if we're already
443 + // reading, then it's unnecessary.
444 +
445 +
446 + if (state.ended || state.reading) {
447 + doRead = false;
448 + debug('reading or ended', doRead);
449 + } else if (doRead) {
450 + debug('do read');
451 + state.reading = true;
452 + state.sync = true; // if the length is currently zero, then we *need* a readable event.
453 +
454 + if (state.length === 0) state.needReadable = true; // call internal read method
455 +
456 + this._read(state.highWaterMark);
457 +
458 + state.sync = false; // If _read pushed data synchronously, then `reading` will be false,
459 + // and we need to re-evaluate how much data we can return to the user.
460 +
461 + if (!state.reading) n = howMuchToRead(nOrig, state);
462 + }
463 +
464 + var ret;
465 + if (n > 0) ret = fromList(n, state);else ret = null;
466 +
467 + if (ret === null) {
468 + state.needReadable = state.length <= state.highWaterMark;
469 + n = 0;
470 + } else {
471 + state.length -= n;
472 + state.awaitDrain = 0;
473 + }
474 +
475 + if (state.length === 0) {
476 + // If we have nothing in the buffer, then we want to know
477 + // as soon as we *do* get something into the buffer.
478 + if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick.
479 +
480 + if (nOrig !== n && state.ended) endReadable(this);
481 + }
482 +
483 + if (ret !== null) this.emit('data', ret);
484 + return ret;
485 +};
486 +
487 +function onEofChunk(stream, state) {
488 + debug('onEofChunk');
489 + if (state.ended) return;
490 +
491 + if (state.decoder) {
492 + var chunk = state.decoder.end();
493 +
494 + if (chunk && chunk.length) {
495 + state.buffer.push(chunk);
496 + state.length += state.objectMode ? 1 : chunk.length;
497 + }
498 + }
499 +
500 + state.ended = true;
501 +
502 + if (state.sync) {
503 + // if we are sync, wait until next tick to emit the data.
504 + // Otherwise we risk emitting data in the flow()
505 + // the readable code triggers during a read() call
506 + emitReadable(stream);
507 + } else {
508 + // emit 'readable' now to make sure it gets picked up.
509 + state.needReadable = false;
510 +
511 + if (!state.emittedReadable) {
512 + state.emittedReadable = true;
513 + emitReadable_(stream);
514 + }
515 + }
516 +} // Don't emit readable right away in sync mode, because this can trigger
517 +// another read() call => stack overflow. This way, it might trigger
518 +// a nextTick recursion warning, but that's not so bad.
519 +
520 +
521 +function emitReadable(stream) {
522 + var state = stream._readableState;
523 + debug('emitReadable', state.needReadable, state.emittedReadable);
524 + state.needReadable = false;
525 +
526 + if (!state.emittedReadable) {
527 + debug('emitReadable', state.flowing);
528 + state.emittedReadable = true;
529 + process.nextTick(emitReadable_, stream);
530 + }
531 +}
532 +
533 +function emitReadable_(stream) {
534 + var state = stream._readableState;
535 + debug('emitReadable_', state.destroyed, state.length, state.ended);
536 +
537 + if (!state.destroyed && (state.length || state.ended)) {
538 + stream.emit('readable');
539 + state.emittedReadable = false;
540 + } // The stream needs another readable event if
541 + // 1. It is not flowing, as the flow mechanism will take
542 + // care of it.
543 + // 2. It is not ended.
544 + // 3. It is below the highWaterMark, so we can schedule
545 + // another readable later.
546 +
547 +
548 + state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark;
549 + flow(stream);
550 +} // at this point, the user has presumably seen the 'readable' event,
551 +// and called read() to consume some data. that may have triggered
552 +// in turn another _read(n) call, in which case reading = true if
553 +// it's in progress.
554 +// However, if we're not ended, or reading, and the length < hwm,
555 +// then go ahead and try to read some more preemptively.
556 +
557 +
558 +function maybeReadMore(stream, state) {
559 + if (!state.readingMore) {
560 + state.readingMore = true;
561 + process.nextTick(maybeReadMore_, stream, state);
562 + }
563 +}
564 +
565 +function maybeReadMore_(stream, state) {
566 + // Attempt to read more data if we should.
567 + //
568 + // The conditions for reading more data are (one of):
569 + // - Not enough data buffered (state.length < state.highWaterMark). The loop
570 + // is responsible for filling the buffer with enough data if such data
571 + // is available. If highWaterMark is 0 and we are not in the flowing mode
572 + // we should _not_ attempt to buffer any extra data. We'll get more data
573 + // when the stream consumer calls read() instead.
574 + // - No data in the buffer, and the stream is in flowing mode. In this mode
575 + // the loop below is responsible for ensuring read() is called. Failing to
576 + // call read here would abort the flow and there's no other mechanism for
577 + // continuing the flow if the stream consumer has just subscribed to the
578 + // 'data' event.
579 + //
580 + // In addition to the above conditions to keep reading data, the following
581 + // conditions prevent the data from being read:
582 + // - The stream has ended (state.ended).
583 + // - There is already a pending 'read' operation (state.reading). This is a
584 + // case where the the stream has called the implementation defined _read()
585 + // method, but they are processing the call asynchronously and have _not_
586 + // called push() with new data. In this case we skip performing more
587 + // read()s. The execution ends in this method again after the _read() ends
588 + // up calling push() with more data.
589 + while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) {
590 + var len = state.length;
591 + debug('maybeReadMore read 0');
592 + stream.read(0);
593 + if (len === state.length) // didn't get any data, stop spinning.
594 + break;
595 + }
596 +
597 + state.readingMore = false;
598 +} // abstract method. to be overridden in specific implementation classes.
599 +// call cb(er, data) where data is <= n in length.
600 +// for virtual (non-string, non-buffer) streams, "length" is somewhat
601 +// arbitrary, and perhaps not very meaningful.
602 +
603 +
604 +Readable.prototype._read = function (n) {
605 + errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()'));
606 +};
607 +
608 +Readable.prototype.pipe = function (dest, pipeOpts) {
609 + var src = this;
610 + var state = this._readableState;
611 +
612 + switch (state.pipesCount) {
613 + case 0:
614 + state.pipes = dest;
615 + break;
616 +
617 + case 1:
618 + state.pipes = [state.pipes, dest];
619 + break;
620 +
621 + default:
622 + state.pipes.push(dest);
623 + break;
624 + }
625 +
626 + state.pipesCount += 1;
627 + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
628 + var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
629 + var endFn = doEnd ? onend : unpipe;
630 + if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn);
631 + dest.on('unpipe', onunpipe);
632 +
633 + function onunpipe(readable, unpipeInfo) {
634 + debug('onunpipe');
635 +
636 + if (readable === src) {
637 + if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
638 + unpipeInfo.hasUnpiped = true;
639 + cleanup();
640 + }
641 + }
642 + }
643 +
644 + function onend() {
645 + debug('onend');
646 + dest.end();
647 + } // when the dest drains, it reduces the awaitDrain counter
648 + // on the source. This would be more elegant with a .once()
649 + // handler in flow(), but adding and removing repeatedly is
650 + // too slow.
651 +
652 +
653 + var ondrain = pipeOnDrain(src);
654 + dest.on('drain', ondrain);
655 + var cleanedUp = false;
656 +
657 + function cleanup() {
658 + debug('cleanup'); // cleanup event handlers once the pipe is broken
659 +
660 + dest.removeListener('close', onclose);
661 + dest.removeListener('finish', onfinish);
662 + dest.removeListener('drain', ondrain);
663 + dest.removeListener('error', onerror);
664 + dest.removeListener('unpipe', onunpipe);
665 + src.removeListener('end', onend);
666 + src.removeListener('end', unpipe);
667 + src.removeListener('data', ondata);
668 + cleanedUp = true; // if the reader is waiting for a drain event from this
669 + // specific writer, then it would cause it to never start
670 + // flowing again.
671 + // So, if this is awaiting a drain, then we just call it now.
672 + // If we don't know, then assume that we are waiting for one.
673 +
674 + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
675 + }
676 +
677 + src.on('data', ondata);
678 +
679 + function ondata(chunk) {
680 + debug('ondata');
681 + var ret = dest.write(chunk);
682 + debug('dest.write', ret);
683 +
684 + if (ret === false) {
685 + // If the user unpiped during `dest.write()`, it is possible
686 + // to get stuck in a permanently paused state if that write
687 + // also returned false.
688 + // => Check whether `dest` is still a piping destination.
689 + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
690 + debug('false write response, pause', state.awaitDrain);
691 + state.awaitDrain++;
692 + }
693 +
694 + src.pause();
695 + }
696 + } // if the dest has an error, then stop piping into it.
697 + // however, don't suppress the throwing behavior for this.
698 +
699 +
700 + function onerror(er) {
701 + debug('onerror', er);
702 + unpipe();
703 + dest.removeListener('error', onerror);
704 + if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er);
705 + } // Make sure our error handler is attached before userland ones.
706 +
707 +
708 + prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once.
709 +
710 + function onclose() {
711 + dest.removeListener('finish', onfinish);
712 + unpipe();
713 + }
714 +
715 + dest.once('close', onclose);
716 +
717 + function onfinish() {
718 + debug('onfinish');
719 + dest.removeListener('close', onclose);
720 + unpipe();
721 + }
722 +
723 + dest.once('finish', onfinish);
724 +
725 + function unpipe() {
726 + debug('unpipe');
727 + src.unpipe(dest);
728 + } // tell the dest that it's being piped to
729 +
730 +
731 + dest.emit('pipe', src); // start the flow if it hasn't been started already.
732 +
733 + if (!state.flowing) {
734 + debug('pipe resume');
735 + src.resume();
736 + }
737 +
738 + return dest;
739 +};
740 +
741 +function pipeOnDrain(src) {
742 + return function pipeOnDrainFunctionResult() {
743 + var state = src._readableState;
744 + debug('pipeOnDrain', state.awaitDrain);
745 + if (state.awaitDrain) state.awaitDrain--;
746 +
747 + if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
748 + state.flowing = true;
749 + flow(src);
750 + }
751 + };
752 +}
753 +
754 +Readable.prototype.unpipe = function (dest) {
755 + var state = this._readableState;
756 + var unpipeInfo = {
757 + hasUnpiped: false
758 + }; // if we're not piping anywhere, then do nothing.
759 +
760 + if (state.pipesCount === 0) return this; // just one destination. most common case.
761 +
762 + if (state.pipesCount === 1) {
763 + // passed in one, but it's not the right one.
764 + if (dest && dest !== state.pipes) return this;
765 + if (!dest) dest = state.pipes; // got a match.
766 +
767 + state.pipes = null;
768 + state.pipesCount = 0;
769 + state.flowing = false;
770 + if (dest) dest.emit('unpipe', this, unpipeInfo);
771 + return this;
772 + } // slow case. multiple pipe destinations.
773 +
774 +
775 + if (!dest) {
776 + // remove all.
777 + var dests = state.pipes;
778 + var len = state.pipesCount;
779 + state.pipes = null;
780 + state.pipesCount = 0;
781 + state.flowing = false;
782 +
783 + for (var i = 0; i < len; i++) {
784 + dests[i].emit('unpipe', this, {
785 + hasUnpiped: false
786 + });
787 + }
788 +
789 + return this;
790 + } // try to find the right one.
791 +
792 +
793 + var index = indexOf(state.pipes, dest);
794 + if (index === -1) return this;
795 + state.pipes.splice(index, 1);
796 + state.pipesCount -= 1;
797 + if (state.pipesCount === 1) state.pipes = state.pipes[0];
798 + dest.emit('unpipe', this, unpipeInfo);
799 + return this;
800 +}; // set up data events if they are asked for
801 +// Ensure readable listeners eventually get something
802 +
803 +
804 +Readable.prototype.on = function (ev, fn) {
805 + var res = Stream.prototype.on.call(this, ev, fn);
806 + var state = this._readableState;
807 +
808 + if (ev === 'data') {
809 + // update readableListening so that resume() may be a no-op
810 + // a few lines down. This is needed to support once('readable').
811 + state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused
812 +
813 + if (state.flowing !== false) this.resume();
814 + } else if (ev === 'readable') {
815 + if (!state.endEmitted && !state.readableListening) {
816 + state.readableListening = state.needReadable = true;
817 + state.flowing = false;
818 + state.emittedReadable = false;
819 + debug('on readable', state.length, state.reading);
820 +
821 + if (state.length) {
822 + emitReadable(this);
823 + } else if (!state.reading) {
824 + process.nextTick(nReadingNextTick, this);
825 + }
826 + }
827 + }
828 +
829 + return res;
830 +};
831 +
832 +Readable.prototype.addListener = Readable.prototype.on;
833 +
834 +Readable.prototype.removeListener = function (ev, fn) {
835 + var res = Stream.prototype.removeListener.call(this, ev, fn);
836 +
837 + if (ev === 'readable') {
838 + // We need to check if there is someone still listening to
839 + // readable and reset the state. However this needs to happen
840 + // after readable has been emitted but before I/O (nextTick) to
841 + // support once('readable', fn) cycles. This means that calling
842 + // resume within the same tick will have no
843 + // effect.
844 + process.nextTick(updateReadableListening, this);
845 + }
846 +
847 + return res;
848 +};
849 +
850 +Readable.prototype.removeAllListeners = function (ev) {
851 + var res = Stream.prototype.removeAllListeners.apply(this, arguments);
852 +
853 + if (ev === 'readable' || ev === undefined) {
854 + // We need to check if there is someone still listening to
855 + // readable and reset the state. However this needs to happen
856 + // after readable has been emitted but before I/O (nextTick) to
857 + // support once('readable', fn) cycles. This means that calling
858 + // resume within the same tick will have no
859 + // effect.
860 + process.nextTick(updateReadableListening, this);
861 + }
862 +
863 + return res;
864 +};
865 +
866 +function updateReadableListening(self) {
867 + var state = self._readableState;
868 + state.readableListening = self.listenerCount('readable') > 0;
869 +
870 + if (state.resumeScheduled && !state.paused) {
871 + // flowing needs to be set to true now, otherwise
872 + // the upcoming resume will not flow.
873 + state.flowing = true; // crude way to check if we should resume
874 + } else if (self.listenerCount('data') > 0) {
875 + self.resume();
876 + }
877 +}
878 +
879 +function nReadingNextTick(self) {
880 + debug('readable nexttick read 0');
881 + self.read(0);
882 +} // pause() and resume() are remnants of the legacy readable stream API
883 +// If the user uses them, then switch into old mode.
884 +
885 +
886 +Readable.prototype.resume = function () {
887 + var state = this._readableState;
888 +
889 + if (!state.flowing) {
890 + debug('resume'); // we flow only if there is no one listening
891 + // for readable, but we still have to call
892 + // resume()
893 +
894 + state.flowing = !state.readableListening;
895 + resume(this, state);
896 + }
897 +
898 + state.paused = false;
899 + return this;
900 +};
901 +
902 +function resume(stream, state) {
903 + if (!state.resumeScheduled) {
904 + state.resumeScheduled = true;
905 + process.nextTick(resume_, stream, state);
906 + }
907 +}
908 +
909 +function resume_(stream, state) {
910 + debug('resume', state.reading);
911 +
912 + if (!state.reading) {
913 + stream.read(0);
914 + }
915 +
916 + state.resumeScheduled = false;
917 + stream.emit('resume');
918 + flow(stream);
919 + if (state.flowing && !state.reading) stream.read(0);
920 +}
921 +
922 +Readable.prototype.pause = function () {
923 + debug('call pause flowing=%j', this._readableState.flowing);
924 +
925 + if (this._readableState.flowing !== false) {
926 + debug('pause');
927 + this._readableState.flowing = false;
928 + this.emit('pause');
929 + }
930 +
931 + this._readableState.paused = true;
932 + return this;
933 +};
934 +
935 +function flow(stream) {
936 + var state = stream._readableState;
937 + debug('flow', state.flowing);
938 +
939 + while (state.flowing && stream.read() !== null) {
940 + ;
941 + }
942 +} // wrap an old-style stream as the async data source.
943 +// This is *not* part of the readable stream interface.
944 +// It is an ugly unfortunate mess of history.
945 +
946 +
947 +Readable.prototype.wrap = function (stream) {
948 + var _this = this;
949 +
950 + var state = this._readableState;
951 + var paused = false;
952 + stream.on('end', function () {
953 + debug('wrapped end');
954 +
955 + if (state.decoder && !state.ended) {
956 + var chunk = state.decoder.end();
957 + if (chunk && chunk.length) _this.push(chunk);
958 + }
959 +
960 + _this.push(null);
961 + });
962 + stream.on('data', function (chunk) {
963 + debug('wrapped data');
964 + if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode
965 +
966 + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
967 +
968 + var ret = _this.push(chunk);
969 +
970 + if (!ret) {
971 + paused = true;
972 + stream.pause();
973 + }
974 + }); // proxy all the other methods.
975 + // important when wrapping filters and duplexes.
976 +
977 + for (var i in stream) {
978 + if (this[i] === undefined && typeof stream[i] === 'function') {
979 + this[i] = function methodWrap(method) {
980 + return function methodWrapReturnFunction() {
981 + return stream[method].apply(stream, arguments);
982 + };
983 + }(i);
984 + }
985 + } // proxy certain important events.
986 +
987 +
988 + for (var n = 0; n < kProxyEvents.length; n++) {
989 + stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));
990 + } // when we try to consume some more bytes, simply unpause the
991 + // underlying stream.
992 +
993 +
994 + this._read = function (n) {
995 + debug('wrapped _read', n);
996 +
997 + if (paused) {
998 + paused = false;
999 + stream.resume();
1000 + }
1001 + };
1002 +
1003 + return this;
1004 +};
1005 +
1006 +if (typeof Symbol === 'function') {
1007 + Readable.prototype[Symbol.asyncIterator] = function () {
1008 + if (createReadableStreamAsyncIterator === undefined) {
1009 + createReadableStreamAsyncIterator = require('./internal/streams/async_iterator');
1010 + }
1011 +
1012 + return createReadableStreamAsyncIterator(this);
1013 + };
1014 +}
1015 +
1016 +Object.defineProperty(Readable.prototype, 'readableHighWaterMark', {
1017 + // making it explicit this property is not enumerable
1018 + // because otherwise some prototype manipulation in
1019 + // userland will fail
1020 + enumerable: false,
1021 + get: function get() {
1022 + return this._readableState.highWaterMark;
1023 + }
1024 +});
1025 +Object.defineProperty(Readable.prototype, 'readableBuffer', {
1026 + // making it explicit this property is not enumerable
1027 + // because otherwise some prototype manipulation in
1028 + // userland will fail
1029 + enumerable: false,
1030 + get: function get() {
1031 + return this._readableState && this._readableState.buffer;
1032 + }
1033 +});
1034 +Object.defineProperty(Readable.prototype, 'readableFlowing', {
1035 + // making it explicit this property is not enumerable
1036 + // because otherwise some prototype manipulation in
1037 + // userland will fail
1038 + enumerable: false,
1039 + get: function get() {
1040 + return this._readableState.flowing;
1041 + },
1042 + set: function set(state) {
1043 + if (this._readableState) {
1044 + this._readableState.flowing = state;
1045 + }
1046 + }
1047 +}); // exposed for testing purposes only.
1048 +
1049 +Readable._fromList = fromList;
1050 +Object.defineProperty(Readable.prototype, 'readableLength', {
1051 + // making it explicit this property is not enumerable
1052 + // because otherwise some prototype manipulation in
1053 + // userland will fail
1054 + enumerable: false,
1055 + get: function get() {
1056 + return this._readableState.length;
1057 + }
1058 +}); // Pluck off n bytes from an array of buffers.
1059 +// Length is the combined lengths of all the buffers in the list.
1060 +// This function is designed to be inlinable, so please take care when making
1061 +// changes to the function body.
1062 +
1063 +function fromList(n, state) {
1064 + // nothing buffered
1065 + if (state.length === 0) return null;
1066 + var ret;
1067 + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
1068 + // read it all, truncate the list
1069 + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length);
1070 + state.buffer.clear();
1071 + } else {
1072 + // read part of list
1073 + ret = state.buffer.consume(n, state.decoder);
1074 + }
1075 + return ret;
1076 +}
1077 +
1078 +function endReadable(stream) {
1079 + var state = stream._readableState;
1080 + debug('endReadable', state.endEmitted);
1081 +
1082 + if (!state.endEmitted) {
1083 + state.ended = true;
1084 + process.nextTick(endReadableNT, state, stream);
1085 + }
1086 +}
1087 +
1088 +function endReadableNT(state, stream) {
1089 + debug('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift.
1090 +
1091 + if (!state.endEmitted && state.length === 0) {
1092 + state.endEmitted = true;
1093 + stream.readable = false;
1094 + stream.emit('end');
1095 +
1096 + if (state.autoDestroy) {
1097 + // In case of duplex streams we need a way to detect
1098 + // if the writable side is ready for autoDestroy as well
1099 + var wState = stream._writableState;
1100 +
1101 + if (!wState || wState.autoDestroy && wState.finished) {
1102 + stream.destroy();
1103 + }
1104 + }
1105 + }
1106 +}
1107 +
1108 +if (typeof Symbol === 'function') {
1109 + Readable.from = function (iterable, opts) {
1110 + if (from === undefined) {
1111 + from = require('./internal/streams/from');
1112 + }
1113 +
1114 + return from(Readable, iterable, opts);
1115 + };
1116 +}
1117 +
1118 +function indexOf(xs, x) {
1119 + for (var i = 0, l = xs.length; i < l; i++) {
1120 + if (xs[i] === x) return i;
1121 + }
1122 +
1123 + return -1;
1124 +}
...\ No newline at end of file ...\ No newline at end of file
1 +// Copyright Joyent, Inc. and other Node contributors.
2 +//
3 +// Permission is hereby granted, free of charge, to any person obtaining a
4 +// copy of this software and associated documentation files (the
5 +// "Software"), to deal in the Software without restriction, including
6 +// without limitation the rights to use, copy, modify, merge, publish,
7 +// distribute, sublicense, and/or sell copies of the Software, and to permit
8 +// persons to whom the Software is furnished to do so, subject to the
9 +// following conditions:
10 +//
11 +// The above copyright notice and this permission notice shall be included
12 +// in all copies or substantial portions of the Software.
13 +//
14 +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15 +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17 +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18 +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19 +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20 +// USE OR OTHER DEALINGS IN THE SOFTWARE.
21 +// a transform stream is a readable/writable stream where you do
22 +// something with the data. Sometimes it's called a "filter",
23 +// but that's not a great name for it, since that implies a thing where
24 +// some bits pass through, and others are simply ignored. (That would
25 +// be a valid example of a transform, of course.)
26 +//
27 +// While the output is causally related to the input, it's not a
28 +// necessarily symmetric or synchronous transformation. For example,
29 +// a zlib stream might take multiple plain-text writes(), and then
30 +// emit a single compressed chunk some time in the future.
31 +//
32 +// Here's how this works:
33 +//
34 +// The Transform stream has all the aspects of the readable and writable
35 +// stream classes. When you write(chunk), that calls _write(chunk,cb)
36 +// internally, and returns false if there's a lot of pending writes
37 +// buffered up. When you call read(), that calls _read(n) until
38 +// there's enough pending readable data buffered up.
39 +//
40 +// In a transform stream, the written data is placed in a buffer. When
41 +// _read(n) is called, it transforms the queued up data, calling the
42 +// buffered _write cb's as it consumes chunks. If consuming a single
43 +// written chunk would result in multiple output chunks, then the first
44 +// outputted bit calls the readcb, and subsequent chunks just go into
45 +// the read buffer, and will cause it to emit 'readable' if necessary.
46 +//
47 +// This way, back-pressure is actually determined by the reading side,
48 +// since _read has to be called to start processing a new chunk. However,
49 +// a pathological inflate type of transform can cause excessive buffering
50 +// here. For example, imagine a stream where every byte of input is
51 +// interpreted as an integer from 0-255, and then results in that many
52 +// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
53 +// 1kb of data being output. In this case, you could write a very small
54 +// amount of input, and end up with a very large amount of output. In
55 +// such a pathological inflating mechanism, there'd be no way to tell
56 +// the system to stop doing the transform. A single 4MB write could
57 +// cause the system to run out of memory.
58 +//
59 +// However, even in such a pathological case, only a single written chunk
60 +// would be consumed, and then the rest would wait (un-transformed) until
61 +// the results of the previous transformed chunk were consumed.
62 +'use strict';
63 +
64 +module.exports = Transform;
65 +
66 +var _require$codes = require('../errors').codes,
67 + ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
68 + ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,
69 + ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING,
70 + ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0;
71 +
72 +var Duplex = require('./_stream_duplex');
73 +
74 +require('inherits')(Transform, Duplex);
75 +
76 +function afterTransform(er, data) {
77 + var ts = this._transformState;
78 + ts.transforming = false;
79 + var cb = ts.writecb;
80 +
81 + if (cb === null) {
82 + return this.emit('error', new ERR_MULTIPLE_CALLBACK());
83 + }
84 +
85 + ts.writechunk = null;
86 + ts.writecb = null;
87 + if (data != null) // single equals check for both `null` and `undefined`
88 + this.push(data);
89 + cb(er);
90 + var rs = this._readableState;
91 + rs.reading = false;
92 +
93 + if (rs.needReadable || rs.length < rs.highWaterMark) {
94 + this._read(rs.highWaterMark);
95 + }
96 +}
97 +
98 +function Transform(options) {
99 + if (!(this instanceof Transform)) return new Transform(options);
100 + Duplex.call(this, options);
101 + this._transformState = {
102 + afterTransform: afterTransform.bind(this),
103 + needTransform: false,
104 + transforming: false,
105 + writecb: null,
106 + writechunk: null,
107 + writeencoding: null
108 + }; // start out asking for a readable event once data is transformed.
109 +
110 + this._readableState.needReadable = true; // we have implemented the _read method, and done the other things
111 + // that Readable wants before the first _read call, so unset the
112 + // sync guard flag.
113 +
114 + this._readableState.sync = false;
115 +
116 + if (options) {
117 + if (typeof options.transform === 'function') this._transform = options.transform;
118 + if (typeof options.flush === 'function') this._flush = options.flush;
119 + } // When the writable side finishes, then flush out anything remaining.
120 +
121 +
122 + this.on('prefinish', prefinish);
123 +}
124 +
125 +function prefinish() {
126 + var _this = this;
127 +
128 + if (typeof this._flush === 'function' && !this._readableState.destroyed) {
129 + this._flush(function (er, data) {
130 + done(_this, er, data);
131 + });
132 + } else {
133 + done(this, null, null);
134 + }
135 +}
136 +
137 +Transform.prototype.push = function (chunk, encoding) {
138 + this._transformState.needTransform = false;
139 + return Duplex.prototype.push.call(this, chunk, encoding);
140 +}; // This is the part where you do stuff!
141 +// override this function in implementation classes.
142 +// 'chunk' is an input chunk.
143 +//
144 +// Call `push(newChunk)` to pass along transformed output
145 +// to the readable side. You may call 'push' zero or more times.
146 +//
147 +// Call `cb(err)` when you are done with this chunk. If you pass
148 +// an error, then that'll put the hurt on the whole operation. If you
149 +// never call cb(), then you'll never get another chunk.
150 +
151 +
152 +Transform.prototype._transform = function (chunk, encoding, cb) {
153 + cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()'));
154 +};
155 +
156 +Transform.prototype._write = function (chunk, encoding, cb) {
157 + var ts = this._transformState;
158 + ts.writecb = cb;
159 + ts.writechunk = chunk;
160 + ts.writeencoding = encoding;
161 +
162 + if (!ts.transforming) {
163 + var rs = this._readableState;
164 + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
165 + }
166 +}; // Doesn't matter what the args are here.
167 +// _transform does all the work.
168 +// That we got here means that the readable side wants more data.
169 +
170 +
171 +Transform.prototype._read = function (n) {
172 + var ts = this._transformState;
173 +
174 + if (ts.writechunk !== null && !ts.transforming) {
175 + ts.transforming = true;
176 +
177 + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
178 + } else {
179 + // mark that we need a transform, so that any data that comes in
180 + // will get processed, now that we've asked for it.
181 + ts.needTransform = true;
182 + }
183 +};
184 +
185 +Transform.prototype._destroy = function (err, cb) {
186 + Duplex.prototype._destroy.call(this, err, function (err2) {
187 + cb(err2);
188 + });
189 +};
190 +
191 +function done(stream, er, data) {
192 + if (er) return stream.emit('error', er);
193 + if (data != null) // single equals check for both `null` and `undefined`
194 + stream.push(data); // TODO(BridgeAR): Write a test for these two error cases
195 + // if there's nothing in the write buffer, then that means
196 + // that nothing more will ever be provided
197 +
198 + if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0();
199 + if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING();
200 + return stream.push(null);
201 +}
...\ No newline at end of file ...\ No newline at end of file
1 +// Copyright Joyent, Inc. and other Node contributors.
2 +//
3 +// Permission is hereby granted, free of charge, to any person obtaining a
4 +// copy of this software and associated documentation files (the
5 +// "Software"), to deal in the Software without restriction, including
6 +// without limitation the rights to use, copy, modify, merge, publish,
7 +// distribute, sublicense, and/or sell copies of the Software, and to permit
8 +// persons to whom the Software is furnished to do so, subject to the
9 +// following conditions:
10 +//
11 +// The above copyright notice and this permission notice shall be included
12 +// in all copies or substantial portions of the Software.
13 +//
14 +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15 +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17 +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18 +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19 +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20 +// USE OR OTHER DEALINGS IN THE SOFTWARE.
21 +// A bit simpler than readable streams.
22 +// Implement an async ._write(chunk, encoding, cb), and it'll handle all
23 +// the drain event emission and buffering.
24 +'use strict';
25 +
26 +module.exports = Writable;
27 +/* <replacement> */
28 +
29 +function WriteReq(chunk, encoding, cb) {
30 + this.chunk = chunk;
31 + this.encoding = encoding;
32 + this.callback = cb;
33 + this.next = null;
34 +} // It seems a linked list but it is not
35 +// there will be only 2 of these for each stream
36 +
37 +
38 +function CorkedRequest(state) {
39 + var _this = this;
40 +
41 + this.next = null;
42 + this.entry = null;
43 +
44 + this.finish = function () {
45 + onCorkedFinish(_this, state);
46 + };
47 +}
48 +/* </replacement> */
49 +
50 +/*<replacement>*/
51 +
52 +
53 +var Duplex;
54 +/*</replacement>*/
55 +
56 +Writable.WritableState = WritableState;
57 +/*<replacement>*/
58 +
59 +var internalUtil = {
60 + deprecate: require('util-deprecate')
61 +};
62 +/*</replacement>*/
63 +
64 +/*<replacement>*/
65 +
66 +var Stream = require('./internal/streams/stream');
67 +/*</replacement>*/
68 +
69 +
70 +var Buffer = require('buffer').Buffer;
71 +
72 +var OurUint8Array = global.Uint8Array || function () {};
73 +
74 +function _uint8ArrayToBuffer(chunk) {
75 + return Buffer.from(chunk);
76 +}
77 +
78 +function _isUint8Array(obj) {
79 + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
80 +}
81 +
82 +var destroyImpl = require('./internal/streams/destroy');
83 +
84 +var _require = require('./internal/streams/state'),
85 + getHighWaterMark = _require.getHighWaterMark;
86 +
87 +var _require$codes = require('../errors').codes,
88 + ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,
89 + ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
90 + ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,
91 + ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE,
92 + ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED,
93 + ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES,
94 + ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END,
95 + ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING;
96 +
97 +var errorOrDestroy = destroyImpl.errorOrDestroy;
98 +
99 +require('inherits')(Writable, Stream);
100 +
101 +function nop() {}
102 +
103 +function WritableState(options, stream, isDuplex) {
104 + Duplex = Duplex || require('./_stream_duplex');
105 + options = options || {}; // Duplex streams are both readable and writable, but share
106 + // the same options object.
107 + // However, some cases require setting options to different
108 + // values for the readable and the writable sides of the duplex stream,
109 + // e.g. options.readableObjectMode vs. options.writableObjectMode, etc.
110 +
111 + if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag to indicate whether or not this stream
112 + // contains buffers or objects.
113 +
114 + this.objectMode = !!options.objectMode;
115 + if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false
116 + // Note: 0 is a valid value, means that we always return false if
117 + // the entire buffer is not flushed immediately on write()
118 +
119 + this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called
120 +
121 + this.finalCalled = false; // drain event flag.
122 +
123 + this.needDrain = false; // at the start of calling end()
124 +
125 + this.ending = false; // when end() has been called, and returned
126 +
127 + this.ended = false; // when 'finish' is emitted
128 +
129 + this.finished = false; // has it been destroyed
130 +
131 + this.destroyed = false; // should we decode strings into buffers before passing to _write?
132 + // this is here so that some node-core streams can optimize string
133 + // handling at a lower level.
134 +
135 + var noDecode = options.decodeStrings === false;
136 + this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string
137 + // encoding is 'binary' so we have to make this configurable.
138 + // Everything else in the universe uses 'utf8', though.
139 +
140 + this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement
141 + // of how much we're waiting to get pushed to some underlying
142 + // socket or file.
143 +
144 + this.length = 0; // a flag to see when we're in the middle of a write.
145 +
146 + this.writing = false; // when true all writes will be buffered until .uncork() call
147 +
148 + this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately,
149 + // or on a later tick. We set this to true at first, because any
150 + // actions that shouldn't happen until "later" should generally also
151 + // not happen before the first write call.
152 +
153 + this.sync = true; // a flag to know if we're processing previously buffered items, which
154 + // may call the _write() callback in the same tick, so that we don't
155 + // end up in an overlapped onwrite situation.
156 +
157 + this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb)
158 +
159 + this.onwrite = function (er) {
160 + onwrite(stream, er);
161 + }; // the callback that the user supplies to write(chunk,encoding,cb)
162 +
163 +
164 + this.writecb = null; // the amount that is being written when _write is called.
165 +
166 + this.writelen = 0;
167 + this.bufferedRequest = null;
168 + this.lastBufferedRequest = null; // number of pending user-supplied write callbacks
169 + // this must be 0 before 'finish' can be emitted
170 +
171 + this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs
172 + // This is relevant for synchronous Transform streams
173 +
174 + this.prefinished = false; // True if the error was already emitted and should not be thrown again
175 +
176 + this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true.
177 +
178 + this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'finish' (and potentially 'end')
179 +
180 + this.autoDestroy = !!options.autoDestroy; // count buffered requests
181 +
182 + this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always
183 + // one allocated and free to use, and we maintain at most two
184 +
185 + this.corkedRequestsFree = new CorkedRequest(this);
186 +}
187 +
188 +WritableState.prototype.getBuffer = function getBuffer() {
189 + var current = this.bufferedRequest;
190 + var out = [];
191 +
192 + while (current) {
193 + out.push(current);
194 + current = current.next;
195 + }
196 +
197 + return out;
198 +};
199 +
200 +(function () {
201 + try {
202 + Object.defineProperty(WritableState.prototype, 'buffer', {
203 + get: internalUtil.deprecate(function writableStateBufferGetter() {
204 + return this.getBuffer();
205 + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
206 + });
207 + } catch (_) {}
208 +})(); // Test _writableState for inheritance to account for Duplex streams,
209 +// whose prototype chain only points to Readable.
210 +
211 +
212 +var realHasInstance;
213 +
214 +if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
215 + realHasInstance = Function.prototype[Symbol.hasInstance];
216 + Object.defineProperty(Writable, Symbol.hasInstance, {
217 + value: function value(object) {
218 + if (realHasInstance.call(this, object)) return true;
219 + if (this !== Writable) return false;
220 + return object && object._writableState instanceof WritableState;
221 + }
222 + });
223 +} else {
224 + realHasInstance = function realHasInstance(object) {
225 + return object instanceof this;
226 + };
227 +}
228 +
229 +function Writable(options) {
230 + Duplex = Duplex || require('./_stream_duplex'); // Writable ctor is applied to Duplexes, too.
231 + // `realHasInstance` is necessary because using plain `instanceof`
232 + // would return false, as no `_writableState` property is attached.
233 + // Trying to use the custom `instanceof` for Writable here will also break the
234 + // Node.js LazyTransform implementation, which has a non-trivial getter for
235 + // `_writableState` that would lead to infinite recursion.
236 + // Checking for a Stream.Duplex instance is faster here instead of inside
237 + // the WritableState constructor, at least with V8 6.5
238 +
239 + var isDuplex = this instanceof Duplex;
240 + if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options);
241 + this._writableState = new WritableState(options, this, isDuplex); // legacy.
242 +
243 + this.writable = true;
244 +
245 + if (options) {
246 + if (typeof options.write === 'function') this._write = options.write;
247 + if (typeof options.writev === 'function') this._writev = options.writev;
248 + if (typeof options.destroy === 'function') this._destroy = options.destroy;
249 + if (typeof options.final === 'function') this._final = options.final;
250 + }
251 +
252 + Stream.call(this);
253 +} // Otherwise people can pipe Writable streams, which is just wrong.
254 +
255 +
256 +Writable.prototype.pipe = function () {
257 + errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE());
258 +};
259 +
260 +function writeAfterEnd(stream, cb) {
261 + var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb
262 +
263 + errorOrDestroy(stream, er);
264 + process.nextTick(cb, er);
265 +} // Checks that a user-supplied chunk is valid, especially for the particular
266 +// mode the stream is in. Currently this means that `null` is never accepted
267 +// and undefined/non-string values are only allowed in object mode.
268 +
269 +
270 +function validChunk(stream, state, chunk, cb) {
271 + var er;
272 +
273 + if (chunk === null) {
274 + er = new ERR_STREAM_NULL_VALUES();
275 + } else if (typeof chunk !== 'string' && !state.objectMode) {
276 + er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk);
277 + }
278 +
279 + if (er) {
280 + errorOrDestroy(stream, er);
281 + process.nextTick(cb, er);
282 + return false;
283 + }
284 +
285 + return true;
286 +}
287 +
288 +Writable.prototype.write = function (chunk, encoding, cb) {
289 + var state = this._writableState;
290 + var ret = false;
291 +
292 + var isBuf = !state.objectMode && _isUint8Array(chunk);
293 +
294 + if (isBuf && !Buffer.isBuffer(chunk)) {
295 + chunk = _uint8ArrayToBuffer(chunk);
296 + }
297 +
298 + if (typeof encoding === 'function') {
299 + cb = encoding;
300 + encoding = null;
301 + }
302 +
303 + if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
304 + if (typeof cb !== 'function') cb = nop;
305 + if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
306 + state.pendingcb++;
307 + ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
308 + }
309 + return ret;
310 +};
311 +
312 +Writable.prototype.cork = function () {
313 + this._writableState.corked++;
314 +};
315 +
316 +Writable.prototype.uncork = function () {
317 + var state = this._writableState;
318 +
319 + if (state.corked) {
320 + state.corked--;
321 + if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
322 + }
323 +};
324 +
325 +Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
326 + // node::ParseEncoding() requires lower case.
327 + if (typeof encoding === 'string') encoding = encoding.toLowerCase();
328 + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding);
329 + this._writableState.defaultEncoding = encoding;
330 + return this;
331 +};
332 +
333 +Object.defineProperty(Writable.prototype, 'writableBuffer', {
334 + // making it explicit this property is not enumerable
335 + // because otherwise some prototype manipulation in
336 + // userland will fail
337 + enumerable: false,
338 + get: function get() {
339 + return this._writableState && this._writableState.getBuffer();
340 + }
341 +});
342 +
343 +function decodeChunk(state, chunk, encoding) {
344 + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
345 + chunk = Buffer.from(chunk, encoding);
346 + }
347 +
348 + return chunk;
349 +}
350 +
351 +Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
352 + // making it explicit this property is not enumerable
353 + // because otherwise some prototype manipulation in
354 + // userland will fail
355 + enumerable: false,
356 + get: function get() {
357 + return this._writableState.highWaterMark;
358 + }
359 +}); // if we're already writing something, then just put this
360 +// in the queue, and wait our turn. Otherwise, call _write
361 +// If we return false, then we need a drain event, so set that flag.
362 +
363 +function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
364 + if (!isBuf) {
365 + var newChunk = decodeChunk(state, chunk, encoding);
366 +
367 + if (chunk !== newChunk) {
368 + isBuf = true;
369 + encoding = 'buffer';
370 + chunk = newChunk;
371 + }
372 + }
373 +
374 + var len = state.objectMode ? 1 : chunk.length;
375 + state.length += len;
376 + var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false.
377 +
378 + if (!ret) state.needDrain = true;
379 +
380 + if (state.writing || state.corked) {
381 + var last = state.lastBufferedRequest;
382 + state.lastBufferedRequest = {
383 + chunk: chunk,
384 + encoding: encoding,
385 + isBuf: isBuf,
386 + callback: cb,
387 + next: null
388 + };
389 +
390 + if (last) {
391 + last.next = state.lastBufferedRequest;
392 + } else {
393 + state.bufferedRequest = state.lastBufferedRequest;
394 + }
395 +
396 + state.bufferedRequestCount += 1;
397 + } else {
398 + doWrite(stream, state, false, len, chunk, encoding, cb);
399 + }
400 +
401 + return ret;
402 +}
403 +
404 +function doWrite(stream, state, writev, len, chunk, encoding, cb) {
405 + state.writelen = len;
406 + state.writecb = cb;
407 + state.writing = true;
408 + state.sync = true;
409 + if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
410 + state.sync = false;
411 +}
412 +
413 +function onwriteError(stream, state, sync, er, cb) {
414 + --state.pendingcb;
415 +
416 + if (sync) {
417 + // defer the callback if we are being called synchronously
418 + // to avoid piling up things on the stack
419 + process.nextTick(cb, er); // this can emit finish, and it will always happen
420 + // after error
421 +
422 + process.nextTick(finishMaybe, stream, state);
423 + stream._writableState.errorEmitted = true;
424 + errorOrDestroy(stream, er);
425 + } else {
426 + // the caller expect this to happen before if
427 + // it is async
428 + cb(er);
429 + stream._writableState.errorEmitted = true;
430 + errorOrDestroy(stream, er); // this can emit finish, but finish must
431 + // always follow error
432 +
433 + finishMaybe(stream, state);
434 + }
435 +}
436 +
437 +function onwriteStateUpdate(state) {
438 + state.writing = false;
439 + state.writecb = null;
440 + state.length -= state.writelen;
441 + state.writelen = 0;
442 +}
443 +
444 +function onwrite(stream, er) {
445 + var state = stream._writableState;
446 + var sync = state.sync;
447 + var cb = state.writecb;
448 + if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK();
449 + onwriteStateUpdate(state);
450 + if (er) onwriteError(stream, state, sync, er, cb);else {
451 + // Check if we're actually ready to finish, but don't emit yet
452 + var finished = needFinish(state) || stream.destroyed;
453 +
454 + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
455 + clearBuffer(stream, state);
456 + }
457 +
458 + if (sync) {
459 + process.nextTick(afterWrite, stream, state, finished, cb);
460 + } else {
461 + afterWrite(stream, state, finished, cb);
462 + }
463 + }
464 +}
465 +
466 +function afterWrite(stream, state, finished, cb) {
467 + if (!finished) onwriteDrain(stream, state);
468 + state.pendingcb--;
469 + cb();
470 + finishMaybe(stream, state);
471 +} // Must force callback to be called on nextTick, so that we don't
472 +// emit 'drain' before the write() consumer gets the 'false' return
473 +// value, and has a chance to attach a 'drain' listener.
474 +
475 +
476 +function onwriteDrain(stream, state) {
477 + if (state.length === 0 && state.needDrain) {
478 + state.needDrain = false;
479 + stream.emit('drain');
480 + }
481 +} // if there's something in the buffer waiting, then process it
482 +
483 +
484 +function clearBuffer(stream, state) {
485 + state.bufferProcessing = true;
486 + var entry = state.bufferedRequest;
487 +
488 + if (stream._writev && entry && entry.next) {
489 + // Fast case, write everything using _writev()
490 + var l = state.bufferedRequestCount;
491 + var buffer = new Array(l);
492 + var holder = state.corkedRequestsFree;
493 + holder.entry = entry;
494 + var count = 0;
495 + var allBuffers = true;
496 +
497 + while (entry) {
498 + buffer[count] = entry;
499 + if (!entry.isBuf) allBuffers = false;
500 + entry = entry.next;
501 + count += 1;
502 + }
503 +
504 + buffer.allBuffers = allBuffers;
505 + doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time
506 + // as the hot path ends with doWrite
507 +
508 + state.pendingcb++;
509 + state.lastBufferedRequest = null;
510 +
511 + if (holder.next) {
512 + state.corkedRequestsFree = holder.next;
513 + holder.next = null;
514 + } else {
515 + state.corkedRequestsFree = new CorkedRequest(state);
516 + }
517 +
518 + state.bufferedRequestCount = 0;
519 + } else {
520 + // Slow case, write chunks one-by-one
521 + while (entry) {
522 + var chunk = entry.chunk;
523 + var encoding = entry.encoding;
524 + var cb = entry.callback;
525 + var len = state.objectMode ? 1 : chunk.length;
526 + doWrite(stream, state, false, len, chunk, encoding, cb);
527 + entry = entry.next;
528 + state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then
529 + // it means that we need to wait until it does.
530 + // also, that means that the chunk and cb are currently
531 + // being processed, so move the buffer counter past them.
532 +
533 + if (state.writing) {
534 + break;
535 + }
536 + }
537 +
538 + if (entry === null) state.lastBufferedRequest = null;
539 + }
540 +
541 + state.bufferedRequest = entry;
542 + state.bufferProcessing = false;
543 +}
544 +
545 +Writable.prototype._write = function (chunk, encoding, cb) {
546 + cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()'));
547 +};
548 +
549 +Writable.prototype._writev = null;
550 +
551 +Writable.prototype.end = function (chunk, encoding, cb) {
552 + var state = this._writableState;
553 +
554 + if (typeof chunk === 'function') {
555 + cb = chunk;
556 + chunk = null;
557 + encoding = null;
558 + } else if (typeof encoding === 'function') {
559 + cb = encoding;
560 + encoding = null;
561 + }
562 +
563 + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks
564 +
565 + if (state.corked) {
566 + state.corked = 1;
567 + this.uncork();
568 + } // ignore unnecessary end() calls.
569 +
570 +
571 + if (!state.ending) endWritable(this, state, cb);
572 + return this;
573 +};
574 +
575 +Object.defineProperty(Writable.prototype, 'writableLength', {
576 + // making it explicit this property is not enumerable
577 + // because otherwise some prototype manipulation in
578 + // userland will fail
579 + enumerable: false,
580 + get: function get() {
581 + return this._writableState.length;
582 + }
583 +});
584 +
585 +function needFinish(state) {
586 + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
587 +}
588 +
589 +function callFinal(stream, state) {
590 + stream._final(function (err) {
591 + state.pendingcb--;
592 +
593 + if (err) {
594 + errorOrDestroy(stream, err);
595 + }
596 +
597 + state.prefinished = true;
598 + stream.emit('prefinish');
599 + finishMaybe(stream, state);
600 + });
601 +}
602 +
603 +function prefinish(stream, state) {
604 + if (!state.prefinished && !state.finalCalled) {
605 + if (typeof stream._final === 'function' && !state.destroyed) {
606 + state.pendingcb++;
607 + state.finalCalled = true;
608 + process.nextTick(callFinal, stream, state);
609 + } else {
610 + state.prefinished = true;
611 + stream.emit('prefinish');
612 + }
613 + }
614 +}
615 +
616 +function finishMaybe(stream, state) {
617 + var need = needFinish(state);
618 +
619 + if (need) {
620 + prefinish(stream, state);
621 +
622 + if (state.pendingcb === 0) {
623 + state.finished = true;
624 + stream.emit('finish');
625 +
626 + if (state.autoDestroy) {
627 + // In case of duplex streams we need a way to detect
628 + // if the readable side is ready for autoDestroy as well
629 + var rState = stream._readableState;
630 +
631 + if (!rState || rState.autoDestroy && rState.endEmitted) {
632 + stream.destroy();
633 + }
634 + }
635 + }
636 + }
637 +
638 + return need;
639 +}
640 +
641 +function endWritable(stream, state, cb) {
642 + state.ending = true;
643 + finishMaybe(stream, state);
644 +
645 + if (cb) {
646 + if (state.finished) process.nextTick(cb);else stream.once('finish', cb);
647 + }
648 +
649 + state.ended = true;
650 + stream.writable = false;
651 +}
652 +
653 +function onCorkedFinish(corkReq, state, err) {
654 + var entry = corkReq.entry;
655 + corkReq.entry = null;
656 +
657 + while (entry) {
658 + var cb = entry.callback;
659 + state.pendingcb--;
660 + cb(err);
661 + entry = entry.next;
662 + } // reuse the free corkReq.
663 +
664 +
665 + state.corkedRequestsFree.next = corkReq;
666 +}
667 +
668 +Object.defineProperty(Writable.prototype, 'destroyed', {
669 + // making it explicit this property is not enumerable
670 + // because otherwise some prototype manipulation in
671 + // userland will fail
672 + enumerable: false,
673 + get: function get() {
674 + if (this._writableState === undefined) {
675 + return false;
676 + }
677 +
678 + return this._writableState.destroyed;
679 + },
680 + set: function set(value) {
681 + // we ignore the value if the stream
682 + // has not been initialized yet
683 + if (!this._writableState) {
684 + return;
685 + } // backward compatibility, the user is explicitly
686 + // managing destroyed
687 +
688 +
689 + this._writableState.destroyed = value;
690 + }
691 +});
692 +Writable.prototype.destroy = destroyImpl.destroy;
693 +Writable.prototype._undestroy = destroyImpl.undestroy;
694 +
695 +Writable.prototype._destroy = function (err, cb) {
696 + cb(err);
697 +};
...\ No newline at end of file ...\ No newline at end of file
1 +{
2 + "_from": "readable-stream@^3.1.1",
3 + "_id": "readable-stream@3.6.0",
4 + "_inBundle": false,
5 + "_integrity": "sha512-BViHy7LKeTz4oNnkcLJ+lVSL6vpiFeX6/d3oSH8zCW7UxP2onchk+vTGB143xuFjHS3deTgkKoXXymXqymiIdA==",
6 + "_location": "/duplexify/readable-stream",
7 + "_phantomChildren": {},
8 + "_requested": {
9 + "type": "range",
10 + "registry": true,
11 + "raw": "readable-stream@^3.1.1",
12 + "name": "readable-stream",
13 + "escapedName": "readable-stream",
14 + "rawSpec": "^3.1.1",
15 + "saveSpec": null,
16 + "fetchSpec": "^3.1.1"
17 + },
18 + "_requiredBy": [
19 + "/duplexify"
20 + ],
21 + "_resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.0.tgz",
22 + "_shasum": "337bbda3adc0706bd3e024426a286d4b4b2c9198",
23 + "_spec": "readable-stream@^3.1.1",
24 + "_where": "C:\\Users\\1000c\\이것저것\\옾소\\Voicoding\\node_modules\\duplexify",
25 + "browser": {
26 + "util": false,
27 + "worker_threads": false,
28 + "./errors": "./errors-browser.js",
29 + "./readable.js": "./readable-browser.js",
30 + "./lib/internal/streams/from.js": "./lib/internal/streams/from-browser.js",
31 + "./lib/internal/streams/stream.js": "./lib/internal/streams/stream-browser.js"
32 + },
33 + "bugs": {
34 + "url": "https://github.com/nodejs/readable-stream/issues"
35 + },
36 + "bundleDependencies": false,
37 + "dependencies": {
38 + "inherits": "^2.0.3",
39 + "string_decoder": "^1.1.1",
40 + "util-deprecate": "^1.0.1"
41 + },
42 + "deprecated": false,
43 + "description": "Streams3, a user-land copy of the stream library from Node.js",
44 + "devDependencies": {
45 + "@babel/cli": "^7.2.0",
46 + "@babel/core": "^7.2.0",
47 + "@babel/polyfill": "^7.0.0",
48 + "@babel/preset-env": "^7.2.0",
49 + "airtap": "0.0.9",
50 + "assert": "^1.4.0",
51 + "bl": "^2.0.0",
52 + "deep-strict-equal": "^0.2.0",
53 + "events.once": "^2.0.2",
54 + "glob": "^7.1.2",
55 + "gunzip-maybe": "^1.4.1",
56 + "hyperquest": "^2.1.3",
57 + "lolex": "^2.6.0",
58 + "nyc": "^11.0.0",
59 + "pump": "^3.0.0",
60 + "rimraf": "^2.6.2",
61 + "tap": "^12.0.0",
62 + "tape": "^4.9.0",
63 + "tar-fs": "^1.16.2",
64 + "util-promisify": "^2.1.0"
65 + },
66 + "engines": {
67 + "node": ">= 6"
68 + },
69 + "homepage": "https://github.com/nodejs/readable-stream#readme",
70 + "keywords": [
71 + "readable",
72 + "stream",
73 + "pipe"
74 + ],
75 + "license": "MIT",
76 + "main": "readable.js",
77 + "name": "readable-stream",
78 + "nyc": {
79 + "include": [
80 + "lib/**.js"
81 + ]
82 + },
83 + "repository": {
84 + "type": "git",
85 + "url": "git://github.com/nodejs/readable-stream.git"
86 + },
87 + "scripts": {
88 + "ci": "TAP=1 tap --no-esm test/parallel/*.js test/ours/*.js | tee test.tap",
89 + "cover": "nyc npm test",
90 + "report": "nyc report --reporter=lcov",
91 + "test": "tap -J --no-esm test/parallel/*.js test/ours/*.js",
92 + "test-browser-local": "airtap --open --local -- test/browser.js",
93 + "test-browsers": "airtap --sauce-connect --loopback airtap.local -- test/browser.js",
94 + "update-browser-errors": "babel -o errors-browser.js errors.js"
95 + },
96 + "version": "3.6.0"
97 +}
1 +var Stream = require('stream');
2 +if (process.env.READABLE_STREAM === 'disable' && Stream) {
3 + module.exports = Stream.Readable;
4 + Object.assign(module.exports, Stream);
5 + module.exports.Stream = Stream;
6 +} else {
7 + exports = module.exports = require('./lib/_stream_readable.js');
8 + exports.Stream = Stream || exports;
9 + exports.Readable = exports;
10 + exports.Writable = require('./lib/_stream_writable.js');
11 + exports.Duplex = require('./lib/_stream_duplex.js');
12 + exports.Transform = require('./lib/_stream_transform.js');
13 + exports.PassThrough = require('./lib/_stream_passthrough.js');
14 + exports.finished = require('./lib/internal/streams/end-of-stream.js');
15 + exports.pipeline = require('./lib/internal/streams/pipeline.js');
16 +}
1 +The MIT License (MIT)
2 +
3 +Copyright (c) Feross Aboukhadijeh
4 +
5 +Permission is hereby granted, free of charge, to any person obtaining a copy
6 +of this software and associated documentation files (the "Software"), to deal
7 +in the Software without restriction, including without limitation the rights
8 +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 +copies of the Software, and to permit persons to whom the Software is
10 +furnished to do so, subject to the following conditions:
11 +
12 +The above copyright notice and this permission notice shall be included in
13 +all copies or substantial portions of the Software.
14 +
15 +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21 +THE SOFTWARE.
1 +# safe-buffer [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url]
2 +
3 +[travis-image]: https://img.shields.io/travis/feross/safe-buffer/master.svg
4 +[travis-url]: https://travis-ci.org/feross/safe-buffer
5 +[npm-image]: https://img.shields.io/npm/v/safe-buffer.svg
6 +[npm-url]: https://npmjs.org/package/safe-buffer
7 +[downloads-image]: https://img.shields.io/npm/dm/safe-buffer.svg
8 +[downloads-url]: https://npmjs.org/package/safe-buffer
9 +[standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg
10 +[standard-url]: https://standardjs.com
11 +
12 +#### Safer Node.js Buffer API
13 +
14 +**Use the new Node.js Buffer APIs (`Buffer.from`, `Buffer.alloc`,
15 +`Buffer.allocUnsafe`, `Buffer.allocUnsafeSlow`) in all versions of Node.js.**
16 +
17 +**Uses the built-in implementation when available.**
18 +
19 +## install
20 +
21 +```
22 +npm install safe-buffer
23 +```
24 +
25 +## usage
26 +
27 +The goal of this package is to provide a safe replacement for the node.js `Buffer`.
28 +
29 +It's a drop-in replacement for `Buffer`. You can use it by adding one `require` line to
30 +the top of your node.js modules:
31 +
32 +```js
33 +var Buffer = require('safe-buffer').Buffer
34 +
35 +// Existing buffer code will continue to work without issues:
36 +
37 +new Buffer('hey', 'utf8')
38 +new Buffer([1, 2, 3], 'utf8')
39 +new Buffer(obj)
40 +new Buffer(16) // create an uninitialized buffer (potentially unsafe)
41 +
42 +// But you can use these new explicit APIs to make clear what you want:
43 +
44 +Buffer.from('hey', 'utf8') // convert from many types to a Buffer
45 +Buffer.alloc(16) // create a zero-filled buffer (safe)
46 +Buffer.allocUnsafe(16) // create an uninitialized buffer (potentially unsafe)
47 +```
48 +
49 +## api
50 +
51 +### Class Method: Buffer.from(array)
52 +<!-- YAML
53 +added: v3.0.0
54 +-->
55 +
56 +* `array` {Array}
57 +
58 +Allocates a new `Buffer` using an `array` of octets.
59 +
60 +```js
61 +const buf = Buffer.from([0x62,0x75,0x66,0x66,0x65,0x72]);
62 + // creates a new Buffer containing ASCII bytes
63 + // ['b','u','f','f','e','r']
64 +```
65 +
66 +A `TypeError` will be thrown if `array` is not an `Array`.
67 +
68 +### Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]])
69 +<!-- YAML
70 +added: v5.10.0
71 +-->
72 +
73 +* `arrayBuffer` {ArrayBuffer} The `.buffer` property of a `TypedArray` or
74 + a `new ArrayBuffer()`
75 +* `byteOffset` {Number} Default: `0`
76 +* `length` {Number} Default: `arrayBuffer.length - byteOffset`
77 +
78 +When passed a reference to the `.buffer` property of a `TypedArray` instance,
79 +the newly created `Buffer` will share the same allocated memory as the
80 +TypedArray.
81 +
82 +```js
83 +const arr = new Uint16Array(2);
84 +arr[0] = 5000;
85 +arr[1] = 4000;
86 +
87 +const buf = Buffer.from(arr.buffer); // shares the memory with arr;
88 +
89 +console.log(buf);
90 + // Prints: <Buffer 88 13 a0 0f>
91 +
92 +// changing the TypedArray changes the Buffer also
93 +arr[1] = 6000;
94 +
95 +console.log(buf);
96 + // Prints: <Buffer 88 13 70 17>
97 +```
98 +
99 +The optional `byteOffset` and `length` arguments specify a memory range within
100 +the `arrayBuffer` that will be shared by the `Buffer`.
101 +
102 +```js
103 +const ab = new ArrayBuffer(10);
104 +const buf = Buffer.from(ab, 0, 2);
105 +console.log(buf.length);
106 + // Prints: 2
107 +```
108 +
109 +A `TypeError` will be thrown if `arrayBuffer` is not an `ArrayBuffer`.
110 +
111 +### Class Method: Buffer.from(buffer)
112 +<!-- YAML
113 +added: v3.0.0
114 +-->
115 +
116 +* `buffer` {Buffer}
117 +
118 +Copies the passed `buffer` data onto a new `Buffer` instance.
119 +
120 +```js
121 +const buf1 = Buffer.from('buffer');
122 +const buf2 = Buffer.from(buf1);
123 +
124 +buf1[0] = 0x61;
125 +console.log(buf1.toString());
126 + // 'auffer'
127 +console.log(buf2.toString());
128 + // 'buffer' (copy is not changed)
129 +```
130 +
131 +A `TypeError` will be thrown if `buffer` is not a `Buffer`.
132 +
133 +### Class Method: Buffer.from(str[, encoding])
134 +<!-- YAML
135 +added: v5.10.0
136 +-->
137 +
138 +* `str` {String} String to encode.
139 +* `encoding` {String} Encoding to use, Default: `'utf8'`
140 +
141 +Creates a new `Buffer` containing the given JavaScript string `str`. If
142 +provided, the `encoding` parameter identifies the character encoding.
143 +If not provided, `encoding` defaults to `'utf8'`.
144 +
145 +```js
146 +const buf1 = Buffer.from('this is a tést');
147 +console.log(buf1.toString());
148 + // prints: this is a tést
149 +console.log(buf1.toString('ascii'));
150 + // prints: this is a tC)st
151 +
152 +const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex');
153 +console.log(buf2.toString());
154 + // prints: this is a tést
155 +```
156 +
157 +A `TypeError` will be thrown if `str` is not a string.
158 +
159 +### Class Method: Buffer.alloc(size[, fill[, encoding]])
160 +<!-- YAML
161 +added: v5.10.0
162 +-->
163 +
164 +* `size` {Number}
165 +* `fill` {Value} Default: `undefined`
166 +* `encoding` {String} Default: `utf8`
167 +
168 +Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the
169 +`Buffer` will be *zero-filled*.
170 +
171 +```js
172 +const buf = Buffer.alloc(5);
173 +console.log(buf);
174 + // <Buffer 00 00 00 00 00>
175 +```
176 +
177 +The `size` must be less than or equal to the value of
178 +`require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is
179 +`(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will
180 +be created if a `size` less than or equal to 0 is specified.
181 +
182 +If `fill` is specified, the allocated `Buffer` will be initialized by calling
183 +`buf.fill(fill)`. See [`buf.fill()`][] for more information.
184 +
185 +```js
186 +const buf = Buffer.alloc(5, 'a');
187 +console.log(buf);
188 + // <Buffer 61 61 61 61 61>
189 +```
190 +
191 +If both `fill` and `encoding` are specified, the allocated `Buffer` will be
192 +initialized by calling `buf.fill(fill, encoding)`. For example:
193 +
194 +```js
195 +const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64');
196 +console.log(buf);
197 + // <Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64>
198 +```
199 +
200 +Calling `Buffer.alloc(size)` can be significantly slower than the alternative
201 +`Buffer.allocUnsafe(size)` but ensures that the newly created `Buffer` instance
202 +contents will *never contain sensitive data*.
203 +
204 +A `TypeError` will be thrown if `size` is not a number.
205 +
206 +### Class Method: Buffer.allocUnsafe(size)
207 +<!-- YAML
208 +added: v5.10.0
209 +-->
210 +
211 +* `size` {Number}
212 +
213 +Allocates a new *non-zero-filled* `Buffer` of `size` bytes. The `size` must
214 +be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit
215 +architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is
216 +thrown. A zero-length Buffer will be created if a `size` less than or equal to
217 +0 is specified.
218 +
219 +The underlying memory for `Buffer` instances created in this way is *not
220 +initialized*. The contents of the newly created `Buffer` are unknown and
221 +*may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such
222 +`Buffer` instances to zeroes.
223 +
224 +```js
225 +const buf = Buffer.allocUnsafe(5);
226 +console.log(buf);
227 + // <Buffer 78 e0 82 02 01>
228 + // (octets will be different, every time)
229 +buf.fill(0);
230 +console.log(buf);
231 + // <Buffer 00 00 00 00 00>
232 +```
233 +
234 +A `TypeError` will be thrown if `size` is not a number.
235 +
236 +Note that the `Buffer` module pre-allocates an internal `Buffer` instance of
237 +size `Buffer.poolSize` that is used as a pool for the fast allocation of new
238 +`Buffer` instances created using `Buffer.allocUnsafe(size)` (and the deprecated
239 +`new Buffer(size)` constructor) only when `size` is less than or equal to
240 +`Buffer.poolSize >> 1` (floor of `Buffer.poolSize` divided by two). The default
241 +value of `Buffer.poolSize` is `8192` but can be modified.
242 +
243 +Use of this pre-allocated internal memory pool is a key difference between
244 +calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`.
245 +Specifically, `Buffer.alloc(size, fill)` will *never* use the internal Buffer
246 +pool, while `Buffer.allocUnsafe(size).fill(fill)` *will* use the internal
247 +Buffer pool if `size` is less than or equal to half `Buffer.poolSize`. The
248 +difference is subtle but can be important when an application requires the
249 +additional performance that `Buffer.allocUnsafe(size)` provides.
250 +
251 +### Class Method: Buffer.allocUnsafeSlow(size)
252 +<!-- YAML
253 +added: v5.10.0
254 +-->
255 +
256 +* `size` {Number}
257 +
258 +Allocates a new *non-zero-filled* and non-pooled `Buffer` of `size` bytes. The
259 +`size` must be less than or equal to the value of
260 +`require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is
261 +`(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will
262 +be created if a `size` less than or equal to 0 is specified.
263 +
264 +The underlying memory for `Buffer` instances created in this way is *not
265 +initialized*. The contents of the newly created `Buffer` are unknown and
266 +*may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such
267 +`Buffer` instances to zeroes.
268 +
269 +When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances,
270 +allocations under 4KB are, by default, sliced from a single pre-allocated
271 +`Buffer`. This allows applications to avoid the garbage collection overhead of
272 +creating many individually allocated Buffers. This approach improves both
273 +performance and memory usage by eliminating the need to track and cleanup as
274 +many `Persistent` objects.
275 +
276 +However, in the case where a developer may need to retain a small chunk of
277 +memory from a pool for an indeterminate amount of time, it may be appropriate
278 +to create an un-pooled Buffer instance using `Buffer.allocUnsafeSlow()` then
279 +copy out the relevant bits.
280 +
281 +```js
282 +// need to keep around a few small chunks of memory
283 +const store = [];
284 +
285 +socket.on('readable', () => {
286 + const data = socket.read();
287 + // allocate for retained data
288 + const sb = Buffer.allocUnsafeSlow(10);
289 + // copy the data into the new allocation
290 + data.copy(sb, 0, 0, 10);
291 + store.push(sb);
292 +});
293 +```
294 +
295 +Use of `Buffer.allocUnsafeSlow()` should be used only as a last resort *after*
296 +a developer has observed undue memory retention in their applications.
297 +
298 +A `TypeError` will be thrown if `size` is not a number.
299 +
300 +### All the Rest
301 +
302 +The rest of the `Buffer` API is exactly the same as in node.js.
303 +[See the docs](https://nodejs.org/api/buffer.html).
304 +
305 +
306 +## Related links
307 +
308 +- [Node.js issue: Buffer(number) is unsafe](https://github.com/nodejs/node/issues/4660)
309 +- [Node.js Enhancement Proposal: Buffer.from/Buffer.alloc/Buffer.zalloc/Buffer() soft-deprecate](https://github.com/nodejs/node-eps/pull/4)
310 +
311 +## Why is `Buffer` unsafe?
312 +
313 +Today, the node.js `Buffer` constructor is overloaded to handle many different argument
314 +types like `String`, `Array`, `Object`, `TypedArrayView` (`Uint8Array`, etc.),
315 +`ArrayBuffer`, and also `Number`.
316 +
317 +The API is optimized for convenience: you can throw any type at it, and it will try to do
318 +what you want.
319 +
320 +Because the Buffer constructor is so powerful, you often see code like this:
321 +
322 +```js
323 +// Convert UTF-8 strings to hex
324 +function toHex (str) {
325 + return new Buffer(str).toString('hex')
326 +}
327 +```
328 +
329 +***But what happens if `toHex` is called with a `Number` argument?***
330 +
331 +### Remote Memory Disclosure
332 +
333 +If an attacker can make your program call the `Buffer` constructor with a `Number`
334 +argument, then they can make it allocate uninitialized memory from the node.js process.
335 +This could potentially disclose TLS private keys, user data, or database passwords.
336 +
337 +When the `Buffer` constructor is passed a `Number` argument, it returns an
338 +**UNINITIALIZED** block of memory of the specified `size`. When you create a `Buffer` like
339 +this, you **MUST** overwrite the contents before returning it to the user.
340 +
341 +From the [node.js docs](https://nodejs.org/api/buffer.html#buffer_new_buffer_size):
342 +
343 +> `new Buffer(size)`
344 +>
345 +> - `size` Number
346 +>
347 +> The underlying memory for `Buffer` instances created in this way is not initialized.
348 +> **The contents of a newly created `Buffer` are unknown and could contain sensitive
349 +> data.** Use `buf.fill(0)` to initialize a Buffer to zeroes.
350 +
351 +(Emphasis our own.)
352 +
353 +Whenever the programmer intended to create an uninitialized `Buffer` you often see code
354 +like this:
355 +
356 +```js
357 +var buf = new Buffer(16)
358 +
359 +// Immediately overwrite the uninitialized buffer with data from another buffer
360 +for (var i = 0; i < buf.length; i++) {
361 + buf[i] = otherBuf[i]
362 +}
363 +```
364 +
365 +
366 +### Would this ever be a problem in real code?
367 +
368 +Yes. It's surprisingly common to forget to check the type of your variables in a
369 +dynamically-typed language like JavaScript.
370 +
371 +Usually the consequences of assuming the wrong type is that your program crashes with an
372 +uncaught exception. But the failure mode for forgetting to check the type of arguments to
373 +the `Buffer` constructor is more catastrophic.
374 +
375 +Here's an example of a vulnerable service that takes a JSON payload and converts it to
376 +hex:
377 +
378 +```js
379 +// Take a JSON payload {str: "some string"} and convert it to hex
380 +var server = http.createServer(function (req, res) {
381 + var data = ''
382 + req.setEncoding('utf8')
383 + req.on('data', function (chunk) {
384 + data += chunk
385 + })
386 + req.on('end', function () {
387 + var body = JSON.parse(data)
388 + res.end(new Buffer(body.str).toString('hex'))
389 + })
390 +})
391 +
392 +server.listen(8080)
393 +```
394 +
395 +In this example, an http client just has to send:
396 +
397 +```json
398 +{
399 + "str": 1000
400 +}
401 +```
402 +
403 +and it will get back 1,000 bytes of uninitialized memory from the server.
404 +
405 +This is a very serious bug. It's similar in severity to the
406 +[the Heartbleed bug](http://heartbleed.com/) that allowed disclosure of OpenSSL process
407 +memory by remote attackers.
408 +
409 +
410 +### Which real-world packages were vulnerable?
411 +
412 +#### [`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht)
413 +
414 +[Mathias Buus](https://github.com/mafintosh) and I
415 +([Feross Aboukhadijeh](http://feross.org/)) found this issue in one of our own packages,
416 +[`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht). The bug would allow
417 +anyone on the internet to send a series of messages to a user of `bittorrent-dht` and get
418 +them to reveal 20 bytes at a time of uninitialized memory from the node.js process.
419 +
420 +Here's
421 +[the commit](https://github.com/feross/bittorrent-dht/commit/6c7da04025d5633699800a99ec3fbadf70ad35b8)
422 +that fixed it. We released a new fixed version, created a
423 +[Node Security Project disclosure](https://nodesecurity.io/advisories/68), and deprecated all
424 +vulnerable versions on npm so users will get a warning to upgrade to a newer version.
425 +
426 +#### [`ws`](https://www.npmjs.com/package/ws)
427 +
428 +That got us wondering if there were other vulnerable packages. Sure enough, within a short
429 +period of time, we found the same issue in [`ws`](https://www.npmjs.com/package/ws), the
430 +most popular WebSocket implementation in node.js.
431 +
432 +If certain APIs were called with `Number` parameters instead of `String` or `Buffer` as
433 +expected, then uninitialized server memory would be disclosed to the remote peer.
434 +
435 +These were the vulnerable methods:
436 +
437 +```js
438 +socket.send(number)
439 +socket.ping(number)
440 +socket.pong(number)
441 +```
442 +
443 +Here's a vulnerable socket server with some echo functionality:
444 +
445 +```js
446 +server.on('connection', function (socket) {
447 + socket.on('message', function (message) {
448 + message = JSON.parse(message)
449 + if (message.type === 'echo') {
450 + socket.send(message.data) // send back the user's message
451 + }
452 + })
453 +})
454 +```
455 +
456 +`socket.send(number)` called on the server, will disclose server memory.
457 +
458 +Here's [the release](https://github.com/websockets/ws/releases/tag/1.0.1) where the issue
459 +was fixed, with a more detailed explanation. Props to
460 +[Arnout Kazemier](https://github.com/3rd-Eden) for the quick fix. Here's the
461 +[Node Security Project disclosure](https://nodesecurity.io/advisories/67).
462 +
463 +
464 +### What's the solution?
465 +
466 +It's important that node.js offers a fast way to get memory otherwise performance-critical
467 +applications would needlessly get a lot slower.
468 +
469 +But we need a better way to *signal our intent* as programmers. **When we want
470 +uninitialized memory, we should request it explicitly.**
471 +
472 +Sensitive functionality should not be packed into a developer-friendly API that loosely
473 +accepts many different types. This type of API encourages the lazy practice of passing
474 +variables in without checking the type very carefully.
475 +
476 +#### A new API: `Buffer.allocUnsafe(number)`
477 +
478 +The functionality of creating buffers with uninitialized memory should be part of another
479 +API. We propose `Buffer.allocUnsafe(number)`. This way, it's not part of an API that
480 +frequently gets user input of all sorts of different types passed into it.
481 +
482 +```js
483 +var buf = Buffer.allocUnsafe(16) // careful, uninitialized memory!
484 +
485 +// Immediately overwrite the uninitialized buffer with data from another buffer
486 +for (var i = 0; i < buf.length; i++) {
487 + buf[i] = otherBuf[i]
488 +}
489 +```
490 +
491 +
492 +### How do we fix node.js core?
493 +
494 +We sent [a PR to node.js core](https://github.com/nodejs/node/pull/4514) (merged as
495 +`semver-major`) which defends against one case:
496 +
497 +```js
498 +var str = 16
499 +new Buffer(str, 'utf8')
500 +```
501 +
502 +In this situation, it's implied that the programmer intended the first argument to be a
503 +string, since they passed an encoding as a second argument. Today, node.js will allocate
504 +uninitialized memory in the case of `new Buffer(number, encoding)`, which is probably not
505 +what the programmer intended.
506 +
507 +But this is only a partial solution, since if the programmer does `new Buffer(variable)`
508 +(without an `encoding` parameter) there's no way to know what they intended. If `variable`
509 +is sometimes a number, then uninitialized memory will sometimes be returned.
510 +
511 +### What's the real long-term fix?
512 +
513 +We could deprecate and remove `new Buffer(number)` and use `Buffer.allocUnsafe(number)` when
514 +we need uninitialized memory. But that would break 1000s of packages.
515 +
516 +~~We believe the best solution is to:~~
517 +
518 +~~1. Change `new Buffer(number)` to return safe, zeroed-out memory~~
519 +
520 +~~2. Create a new API for creating uninitialized Buffers. We propose: `Buffer.allocUnsafe(number)`~~
521 +
522 +#### Update
523 +
524 +We now support adding three new APIs:
525 +
526 +- `Buffer.from(value)` - convert from any type to a buffer
527 +- `Buffer.alloc(size)` - create a zero-filled buffer
528 +- `Buffer.allocUnsafe(size)` - create an uninitialized buffer with given size
529 +
530 +This solves the core problem that affected `ws` and `bittorrent-dht` which is
531 +`Buffer(variable)` getting tricked into taking a number argument.
532 +
533 +This way, existing code continues working and the impact on the npm ecosystem will be
534 +minimal. Over time, npm maintainers can migrate performance-critical code to use
535 +`Buffer.allocUnsafe(number)` instead of `new Buffer(number)`.
536 +
537 +
538 +### Conclusion
539 +
540 +We think there's a serious design issue with the `Buffer` API as it exists today. It
541 +promotes insecure software by putting high-risk functionality into a convenient API
542 +with friendly "developer ergonomics".
543 +
544 +This wasn't merely a theoretical exercise because we found the issue in some of the
545 +most popular npm packages.
546 +
547 +Fortunately, there's an easy fix that can be applied today. Use `safe-buffer` in place of
548 +`buffer`.
549 +
550 +```js
551 +var Buffer = require('safe-buffer').Buffer
552 +```
553 +
554 +Eventually, we hope that node.js core can switch to this new, safer behavior. We believe
555 +the impact on the ecosystem would be minimal since it's not a breaking change.
556 +Well-maintained, popular packages would be updated to use `Buffer.alloc` quickly, while
557 +older, insecure packages would magically become safe from this attack vector.
558 +
559 +
560 +## links
561 +
562 +- [Node.js PR: buffer: throw if both length and enc are passed](https://github.com/nodejs/node/pull/4514)
563 +- [Node Security Project disclosure for `ws`](https://nodesecurity.io/advisories/67)
564 +- [Node Security Project disclosure for`bittorrent-dht`](https://nodesecurity.io/advisories/68)
565 +
566 +
567 +## credit
568 +
569 +The original issues in `bittorrent-dht`
570 +([disclosure](https://nodesecurity.io/advisories/68)) and
571 +`ws` ([disclosure](https://nodesecurity.io/advisories/67)) were discovered by
572 +[Mathias Buus](https://github.com/mafintosh) and
573 +[Feross Aboukhadijeh](http://feross.org/).
574 +
575 +Thanks to [Adam Baldwin](https://github.com/evilpacket) for helping disclose these issues
576 +and for his work running the [Node Security Project](https://nodesecurity.io/).
577 +
578 +Thanks to [John Hiesey](https://github.com/jhiesey) for proofreading this README and
579 +auditing the code.
580 +
581 +
582 +## license
583 +
584 +MIT. Copyright (C) [Feross Aboukhadijeh](http://feross.org)
1 +declare module "safe-buffer" {
2 + export class Buffer {
3 + length: number
4 + write(string: string, offset?: number, length?: number, encoding?: string): number;
5 + toString(encoding?: string, start?: number, end?: number): string;
6 + toJSON(): { type: 'Buffer', data: any[] };
7 + equals(otherBuffer: Buffer): boolean;
8 + compare(otherBuffer: Buffer, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): number;
9 + copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number;
10 + slice(start?: number, end?: number): Buffer;
11 + writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number;
12 + writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number;
13 + writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number;
14 + writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number;
15 + readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number;
16 + readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number;
17 + readIntLE(offset: number, byteLength: number, noAssert?: boolean): number;
18 + readIntBE(offset: number, byteLength: number, noAssert?: boolean): number;
19 + readUInt8(offset: number, noAssert?: boolean): number;
20 + readUInt16LE(offset: number, noAssert?: boolean): number;
21 + readUInt16BE(offset: number, noAssert?: boolean): number;
22 + readUInt32LE(offset: number, noAssert?: boolean): number;
23 + readUInt32BE(offset: number, noAssert?: boolean): number;
24 + readInt8(offset: number, noAssert?: boolean): number;
25 + readInt16LE(offset: number, noAssert?: boolean): number;
26 + readInt16BE(offset: number, noAssert?: boolean): number;
27 + readInt32LE(offset: number, noAssert?: boolean): number;
28 + readInt32BE(offset: number, noAssert?: boolean): number;
29 + readFloatLE(offset: number, noAssert?: boolean): number;
30 + readFloatBE(offset: number, noAssert?: boolean): number;
31 + readDoubleLE(offset: number, noAssert?: boolean): number;
32 + readDoubleBE(offset: number, noAssert?: boolean): number;
33 + swap16(): Buffer;
34 + swap32(): Buffer;
35 + swap64(): Buffer;
36 + writeUInt8(value: number, offset: number, noAssert?: boolean): number;
37 + writeUInt16LE(value: number, offset: number, noAssert?: boolean): number;
38 + writeUInt16BE(value: number, offset: number, noAssert?: boolean): number;
39 + writeUInt32LE(value: number, offset: number, noAssert?: boolean): number;
40 + writeUInt32BE(value: number, offset: number, noAssert?: boolean): number;
41 + writeInt8(value: number, offset: number, noAssert?: boolean): number;
42 + writeInt16LE(value: number, offset: number, noAssert?: boolean): number;
43 + writeInt16BE(value: number, offset: number, noAssert?: boolean): number;
44 + writeInt32LE(value: number, offset: number, noAssert?: boolean): number;
45 + writeInt32BE(value: number, offset: number, noAssert?: boolean): number;
46 + writeFloatLE(value: number, offset: number, noAssert?: boolean): number;
47 + writeFloatBE(value: number, offset: number, noAssert?: boolean): number;
48 + writeDoubleLE(value: number, offset: number, noAssert?: boolean): number;
49 + writeDoubleBE(value: number, offset: number, noAssert?: boolean): number;
50 + fill(value: any, offset?: number, end?: number): this;
51 + indexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number;
52 + lastIndexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number;
53 + includes(value: string | number | Buffer, byteOffset?: number, encoding?: string): boolean;
54 +
55 + /**
56 + * Allocates a new buffer containing the given {str}.
57 + *
58 + * @param str String to store in buffer.
59 + * @param encoding encoding to use, optional. Default is 'utf8'
60 + */
61 + constructor (str: string, encoding?: string);
62 + /**
63 + * Allocates a new buffer of {size} octets.
64 + *
65 + * @param size count of octets to allocate.
66 + */
67 + constructor (size: number);
68 + /**
69 + * Allocates a new buffer containing the given {array} of octets.
70 + *
71 + * @param array The octets to store.
72 + */
73 + constructor (array: Uint8Array);
74 + /**
75 + * Produces a Buffer backed by the same allocated memory as
76 + * the given {ArrayBuffer}.
77 + *
78 + *
79 + * @param arrayBuffer The ArrayBuffer with which to share memory.
80 + */
81 + constructor (arrayBuffer: ArrayBuffer);
82 + /**
83 + * Allocates a new buffer containing the given {array} of octets.
84 + *
85 + * @param array The octets to store.
86 + */
87 + constructor (array: any[]);
88 + /**
89 + * Copies the passed {buffer} data onto a new {Buffer} instance.
90 + *
91 + * @param buffer The buffer to copy.
92 + */
93 + constructor (buffer: Buffer);
94 + prototype: Buffer;
95 + /**
96 + * Allocates a new Buffer using an {array} of octets.
97 + *
98 + * @param array
99 + */
100 + static from(array: any[]): Buffer;
101 + /**
102 + * When passed a reference to the .buffer property of a TypedArray instance,
103 + * the newly created Buffer will share the same allocated memory as the TypedArray.
104 + * The optional {byteOffset} and {length} arguments specify a memory range
105 + * within the {arrayBuffer} that will be shared by the Buffer.
106 + *
107 + * @param arrayBuffer The .buffer property of a TypedArray or a new ArrayBuffer()
108 + * @param byteOffset
109 + * @param length
110 + */
111 + static from(arrayBuffer: ArrayBuffer, byteOffset?: number, length?: number): Buffer;
112 + /**
113 + * Copies the passed {buffer} data onto a new Buffer instance.
114 + *
115 + * @param buffer
116 + */
117 + static from(buffer: Buffer): Buffer;
118 + /**
119 + * Creates a new Buffer containing the given JavaScript string {str}.
120 + * If provided, the {encoding} parameter identifies the character encoding.
121 + * If not provided, {encoding} defaults to 'utf8'.
122 + *
123 + * @param str
124 + */
125 + static from(str: string, encoding?: string): Buffer;
126 + /**
127 + * Returns true if {obj} is a Buffer
128 + *
129 + * @param obj object to test.
130 + */
131 + static isBuffer(obj: any): obj is Buffer;
132 + /**
133 + * Returns true if {encoding} is a valid encoding argument.
134 + * Valid string encodings in Node 0.12: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex'
135 + *
136 + * @param encoding string to test.
137 + */
138 + static isEncoding(encoding: string): boolean;
139 + /**
140 + * Gives the actual byte length of a string. encoding defaults to 'utf8'.
141 + * This is not the same as String.prototype.length since that returns the number of characters in a string.
142 + *
143 + * @param string string to test.
144 + * @param encoding encoding used to evaluate (defaults to 'utf8')
145 + */
146 + static byteLength(string: string, encoding?: string): number;
147 + /**
148 + * Returns a buffer which is the result of concatenating all the buffers in the list together.
149 + *
150 + * If the list has no items, or if the totalLength is 0, then it returns a zero-length buffer.
151 + * If the list has exactly one item, then the first item of the list is returned.
152 + * If the list has more than one item, then a new Buffer is created.
153 + *
154 + * @param list An array of Buffer objects to concatenate
155 + * @param totalLength Total length of the buffers when concatenated.
156 + * If totalLength is not provided, it is read from the buffers in the list. However, this adds an additional loop to the function, so it is faster to provide the length explicitly.
157 + */
158 + static concat(list: Buffer[], totalLength?: number): Buffer;
159 + /**
160 + * The same as buf1.compare(buf2).
161 + */
162 + static compare(buf1: Buffer, buf2: Buffer): number;
163 + /**
164 + * Allocates a new buffer of {size} octets.
165 + *
166 + * @param size count of octets to allocate.
167 + * @param fill if specified, buffer will be initialized by calling buf.fill(fill).
168 + * If parameter is omitted, buffer will be filled with zeros.
169 + * @param encoding encoding used for call to buf.fill while initalizing
170 + */
171 + static alloc(size: number, fill?: string | Buffer | number, encoding?: string): Buffer;
172 + /**
173 + * Allocates a new buffer of {size} octets, leaving memory not initialized, so the contents
174 + * of the newly created Buffer are unknown and may contain sensitive data.
175 + *
176 + * @param size count of octets to allocate
177 + */
178 + static allocUnsafe(size: number): Buffer;
179 + /**
180 + * Allocates a new non-pooled buffer of {size} octets, leaving memory not initialized, so the contents
181 + * of the newly created Buffer are unknown and may contain sensitive data.
182 + *
183 + * @param size count of octets to allocate
184 + */
185 + static allocUnsafeSlow(size: number): Buffer;
186 + }
187 +}
...\ No newline at end of file ...\ No newline at end of file
1 +/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
2 +/* eslint-disable node/no-deprecated-api */
3 +var buffer = require('buffer')
4 +var Buffer = buffer.Buffer
5 +
6 +// alternative to using Object.keys for old browsers
7 +function copyProps (src, dst) {
8 + for (var key in src) {
9 + dst[key] = src[key]
10 + }
11 +}
12 +if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
13 + module.exports = buffer
14 +} else {
15 + // Copy properties from require('buffer')
16 + copyProps(buffer, exports)
17 + exports.Buffer = SafeBuffer
18 +}
19 +
20 +function SafeBuffer (arg, encodingOrOffset, length) {
21 + return Buffer(arg, encodingOrOffset, length)
22 +}
23 +
24 +SafeBuffer.prototype = Object.create(Buffer.prototype)
25 +
26 +// Copy static methods from Buffer
27 +copyProps(Buffer, SafeBuffer)
28 +
29 +SafeBuffer.from = function (arg, encodingOrOffset, length) {
30 + if (typeof arg === 'number') {
31 + throw new TypeError('Argument must not be a number')
32 + }
33 + return Buffer(arg, encodingOrOffset, length)
34 +}
35 +
36 +SafeBuffer.alloc = function (size, fill, encoding) {
37 + if (typeof size !== 'number') {
38 + throw new TypeError('Argument must be a number')
39 + }
40 + var buf = Buffer(size)
41 + if (fill !== undefined) {
42 + if (typeof encoding === 'string') {
43 + buf.fill(fill, encoding)
44 + } else {
45 + buf.fill(fill)
46 + }
47 + } else {
48 + buf.fill(0)
49 + }
50 + return buf
51 +}
52 +
53 +SafeBuffer.allocUnsafe = function (size) {
54 + if (typeof size !== 'number') {
55 + throw new TypeError('Argument must be a number')
56 + }
57 + return Buffer(size)
58 +}
59 +
60 +SafeBuffer.allocUnsafeSlow = function (size) {
61 + if (typeof size !== 'number') {
62 + throw new TypeError('Argument must be a number')
63 + }
64 + return buffer.SlowBuffer(size)
65 +}
1 +{
2 + "_from": "safe-buffer@~5.2.0",
3 + "_id": "safe-buffer@5.2.1",
4 + "_inBundle": false,
5 + "_integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==",
6 + "_location": "/duplexify/safe-buffer",
7 + "_phantomChildren": {},
8 + "_requested": {
9 + "type": "range",
10 + "registry": true,
11 + "raw": "safe-buffer@~5.2.0",
12 + "name": "safe-buffer",
13 + "escapedName": "safe-buffer",
14 + "rawSpec": "~5.2.0",
15 + "saveSpec": null,
16 + "fetchSpec": "~5.2.0"
17 + },
18 + "_requiredBy": [
19 + "/duplexify/string_decoder"
20 + ],
21 + "_resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
22 + "_shasum": "1eaf9fa9bdb1fdd4ec75f58f9cdb4e6b7827eec6",
23 + "_spec": "safe-buffer@~5.2.0",
24 + "_where": "C:\\Users\\1000c\\이것저것\\옾소\\Voicoding\\node_modules\\duplexify\\node_modules\\string_decoder",
25 + "author": {
26 + "name": "Feross Aboukhadijeh",
27 + "email": "feross@feross.org",
28 + "url": "https://feross.org"
29 + },
30 + "bugs": {
31 + "url": "https://github.com/feross/safe-buffer/issues"
32 + },
33 + "bundleDependencies": false,
34 + "deprecated": false,
35 + "description": "Safer Node.js Buffer API",
36 + "devDependencies": {
37 + "standard": "*",
38 + "tape": "^5.0.0"
39 + },
40 + "funding": [
41 + {
42 + "type": "github",
43 + "url": "https://github.com/sponsors/feross"
44 + },
45 + {
46 + "type": "patreon",
47 + "url": "https://www.patreon.com/feross"
48 + },
49 + {
50 + "type": "consulting",
51 + "url": "https://feross.org/support"
52 + }
53 + ],
54 + "homepage": "https://github.com/feross/safe-buffer",
55 + "keywords": [
56 + "buffer",
57 + "buffer allocate",
58 + "node security",
59 + "safe",
60 + "safe-buffer",
61 + "security",
62 + "uninitialized"
63 + ],
64 + "license": "MIT",
65 + "main": "index.js",
66 + "name": "safe-buffer",
67 + "repository": {
68 + "type": "git",
69 + "url": "git://github.com/feross/safe-buffer.git"
70 + },
71 + "scripts": {
72 + "test": "standard && tape test/*.js"
73 + },
74 + "types": "index.d.ts",
75 + "version": "5.2.1"
76 +}
1 +Node.js is licensed for use as follows:
2 +
3 +"""
4 +Copyright Node.js contributors. All rights reserved.
5 +
6 +Permission is hereby granted, free of charge, to any person obtaining a copy
7 +of this software and associated documentation files (the "Software"), to
8 +deal in the Software without restriction, including without limitation the
9 +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
10 +sell copies of the Software, and to permit persons to whom the Software is
11 +furnished to do so, subject to the following conditions:
12 +
13 +The above copyright notice and this permission notice shall be included in
14 +all copies or substantial portions of the Software.
15 +
16 +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21 +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
22 +IN THE SOFTWARE.
23 +"""
24 +
25 +This license applies to parts of Node.js originating from the
26 +https://github.com/joyent/node repository:
27 +
28 +"""
29 +Copyright Joyent, Inc. and other Node contributors. All rights reserved.
30 +Permission is hereby granted, free of charge, to any person obtaining a copy
31 +of this software and associated documentation files (the "Software"), to
32 +deal in the Software without restriction, including without limitation the
33 +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
34 +sell copies of the Software, and to permit persons to whom the Software is
35 +furnished to do so, subject to the following conditions:
36 +
37 +The above copyright notice and this permission notice shall be included in
38 +all copies or substantial portions of the Software.
39 +
40 +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
41 +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
42 +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
43 +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
44 +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
45 +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
46 +IN THE SOFTWARE.
47 +"""
48 +
1 +# string_decoder
2 +
3 +***Node-core v8.9.4 string_decoder for userland***
4 +
5 +
6 +[![NPM](https://nodei.co/npm/string_decoder.png?downloads=true&downloadRank=true)](https://nodei.co/npm/string_decoder/)
7 +[![NPM](https://nodei.co/npm-dl/string_decoder.png?&months=6&height=3)](https://nodei.co/npm/string_decoder/)
8 +
9 +
10 +```bash
11 +npm install --save string_decoder
12 +```
13 +
14 +***Node-core string_decoder for userland***
15 +
16 +This package is a mirror of the string_decoder implementation in Node-core.
17 +
18 +Full documentation may be found on the [Node.js website](https://nodejs.org/dist/v8.9.4/docs/api/).
19 +
20 +As of version 1.0.0 **string_decoder** uses semantic versioning.
21 +
22 +## Previous versions
23 +
24 +Previous version numbers match the versions found in Node core, e.g. 0.10.24 matches Node 0.10.24, likewise 0.11.10 matches Node 0.11.10.
25 +
26 +## Update
27 +
28 +The *build/* directory contains a build script that will scrape the source from the [nodejs/node](https://github.com/nodejs/node) repo given a specific Node version.
29 +
30 +## Streams Working Group
31 +
32 +`string_decoder` is maintained by the Streams Working Group, which
33 +oversees the development and maintenance of the Streams API within
34 +Node.js. The responsibilities of the Streams Working Group include:
35 +
36 +* Addressing stream issues on the Node.js issue tracker.
37 +* Authoring and editing stream documentation within the Node.js project.
38 +* Reviewing changes to stream subclasses within the Node.js project.
39 +* Redirecting changes to streams from the Node.js project to this
40 + project.
41 +* Assisting in the implementation of stream providers within Node.js.
42 +* Recommending versions of `readable-stream` to be included in Node.js.
43 +* Messaging about the future of streams to give the community advance
44 + notice of changes.
45 +
46 +See [readable-stream](https://github.com/nodejs/readable-stream) for
47 +more details.
1 +// Copyright Joyent, Inc. and other Node contributors.
2 +//
3 +// Permission is hereby granted, free of charge, to any person obtaining a
4 +// copy of this software and associated documentation files (the
5 +// "Software"), to deal in the Software without restriction, including
6 +// without limitation the rights to use, copy, modify, merge, publish,
7 +// distribute, sublicense, and/or sell copies of the Software, and to permit
8 +// persons to whom the Software is furnished to do so, subject to the
9 +// following conditions:
10 +//
11 +// The above copyright notice and this permission notice shall be included
12 +// in all copies or substantial portions of the Software.
13 +//
14 +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15 +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17 +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18 +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19 +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20 +// USE OR OTHER DEALINGS IN THE SOFTWARE.
21 +
22 +'use strict';
23 +
24 +/*<replacement>*/
25 +
26 +var Buffer = require('safe-buffer').Buffer;
27 +/*</replacement>*/
28 +
29 +var isEncoding = Buffer.isEncoding || function (encoding) {
30 + encoding = '' + encoding;
31 + switch (encoding && encoding.toLowerCase()) {
32 + 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':
33 + return true;
34 + default:
35 + return false;
36 + }
37 +};
38 +
39 +function _normalizeEncoding(enc) {
40 + if (!enc) return 'utf8';
41 + var retried;
42 + while (true) {
43 + switch (enc) {
44 + case 'utf8':
45 + case 'utf-8':
46 + return 'utf8';
47 + case 'ucs2':
48 + case 'ucs-2':
49 + case 'utf16le':
50 + case 'utf-16le':
51 + return 'utf16le';
52 + case 'latin1':
53 + case 'binary':
54 + return 'latin1';
55 + case 'base64':
56 + case 'ascii':
57 + case 'hex':
58 + return enc;
59 + default:
60 + if (retried) return; // undefined
61 + enc = ('' + enc).toLowerCase();
62 + retried = true;
63 + }
64 + }
65 +};
66 +
67 +// Do not cache `Buffer.isEncoding` when checking encoding names as some
68 +// modules monkey-patch it to support additional encodings
69 +function normalizeEncoding(enc) {
70 + var nenc = _normalizeEncoding(enc);
71 + if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);
72 + return nenc || enc;
73 +}
74 +
75 +// StringDecoder provides an interface for efficiently splitting a series of
76 +// buffers into a series of JS strings without breaking apart multi-byte
77 +// characters.
78 +exports.StringDecoder = StringDecoder;
79 +function StringDecoder(encoding) {
80 + this.encoding = normalizeEncoding(encoding);
81 + var nb;
82 + switch (this.encoding) {
83 + case 'utf16le':
84 + this.text = utf16Text;
85 + this.end = utf16End;
86 + nb = 4;
87 + break;
88 + case 'utf8':
89 + this.fillLast = utf8FillLast;
90 + nb = 4;
91 + break;
92 + case 'base64':
93 + this.text = base64Text;
94 + this.end = base64End;
95 + nb = 3;
96 + break;
97 + default:
98 + this.write = simpleWrite;
99 + this.end = simpleEnd;
100 + return;
101 + }
102 + this.lastNeed = 0;
103 + this.lastTotal = 0;
104 + this.lastChar = Buffer.allocUnsafe(nb);
105 +}
106 +
107 +StringDecoder.prototype.write = function (buf) {
108 + if (buf.length === 0) return '';
109 + var r;
110 + var i;
111 + if (this.lastNeed) {
112 + r = this.fillLast(buf);
113 + if (r === undefined) return '';
114 + i = this.lastNeed;
115 + this.lastNeed = 0;
116 + } else {
117 + i = 0;
118 + }
119 + if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);
120 + return r || '';
121 +};
122 +
123 +StringDecoder.prototype.end = utf8End;
124 +
125 +// Returns only complete characters in a Buffer
126 +StringDecoder.prototype.text = utf8Text;
127 +
128 +// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer
129 +StringDecoder.prototype.fillLast = function (buf) {
130 + if (this.lastNeed <= buf.length) {
131 + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
132 + return this.lastChar.toString(this.encoding, 0, this.lastTotal);
133 + }
134 + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
135 + this.lastNeed -= buf.length;
136 +};
137 +
138 +// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a
139 +// continuation byte. If an invalid byte is detected, -2 is returned.
140 +function utf8CheckByte(byte) {
141 + if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4;
142 + return byte >> 6 === 0x02 ? -1 : -2;
143 +}
144 +
145 +// Checks at most 3 bytes at the end of a Buffer in order to detect an
146 +// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)
147 +// needed to complete the UTF-8 character (if applicable) are returned.
148 +function utf8CheckIncomplete(self, buf, i) {
149 + var j = buf.length - 1;
150 + if (j < i) return 0;
151 + var nb = utf8CheckByte(buf[j]);
152 + if (nb >= 0) {
153 + if (nb > 0) self.lastNeed = nb - 1;
154 + return nb;
155 + }
156 + if (--j < i || nb === -2) return 0;
157 + nb = utf8CheckByte(buf[j]);
158 + if (nb >= 0) {
159 + if (nb > 0) self.lastNeed = nb - 2;
160 + return nb;
161 + }
162 + if (--j < i || nb === -2) return 0;
163 + nb = utf8CheckByte(buf[j]);
164 + if (nb >= 0) {
165 + if (nb > 0) {
166 + if (nb === 2) nb = 0;else self.lastNeed = nb - 3;
167 + }
168 + return nb;
169 + }
170 + return 0;
171 +}
172 +
173 +// Validates as many continuation bytes for a multi-byte UTF-8 character as
174 +// needed or are available. If we see a non-continuation byte where we expect
175 +// one, we "replace" the validated continuation bytes we've seen so far with
176 +// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding
177 +// behavior. The continuation byte check is included three times in the case
178 +// where all of the continuation bytes for a character exist in the same buffer.
179 +// It is also done this way as a slight performance increase instead of using a
180 +// loop.
181 +function utf8CheckExtraBytes(self, buf, p) {
182 + if ((buf[0] & 0xC0) !== 0x80) {
183 + self.lastNeed = 0;
184 + return '\ufffd';
185 + }
186 + if (self.lastNeed > 1 && buf.length > 1) {
187 + if ((buf[1] & 0xC0) !== 0x80) {
188 + self.lastNeed = 1;
189 + return '\ufffd';
190 + }
191 + if (self.lastNeed > 2 && buf.length > 2) {
192 + if ((buf[2] & 0xC0) !== 0x80) {
193 + self.lastNeed = 2;
194 + return '\ufffd';
195 + }
196 + }
197 + }
198 +}
199 +
200 +// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.
201 +function utf8FillLast(buf) {
202 + var p = this.lastTotal - this.lastNeed;
203 + var r = utf8CheckExtraBytes(this, buf, p);
204 + if (r !== undefined) return r;
205 + if (this.lastNeed <= buf.length) {
206 + buf.copy(this.lastChar, p, 0, this.lastNeed);
207 + return this.lastChar.toString(this.encoding, 0, this.lastTotal);
208 + }
209 + buf.copy(this.lastChar, p, 0, buf.length);
210 + this.lastNeed -= buf.length;
211 +}
212 +
213 +// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a
214 +// partial character, the character's bytes are buffered until the required
215 +// number of bytes are available.
216 +function utf8Text(buf, i) {
217 + var total = utf8CheckIncomplete(this, buf, i);
218 + if (!this.lastNeed) return buf.toString('utf8', i);
219 + this.lastTotal = total;
220 + var end = buf.length - (total - this.lastNeed);
221 + buf.copy(this.lastChar, 0, end);
222 + return buf.toString('utf8', i, end);
223 +}
224 +
225 +// For UTF-8, a replacement character is added when ending on a partial
226 +// character.
227 +function utf8End(buf) {
228 + var r = buf && buf.length ? this.write(buf) : '';
229 + if (this.lastNeed) return r + '\ufffd';
230 + return r;
231 +}
232 +
233 +// UTF-16LE typically needs two bytes per character, but even if we have an even
234 +// number of bytes available, we need to check if we end on a leading/high
235 +// surrogate. In that case, we need to wait for the next two bytes in order to
236 +// decode the last character properly.
237 +function utf16Text(buf, i) {
238 + if ((buf.length - i) % 2 === 0) {
239 + var r = buf.toString('utf16le', i);
240 + if (r) {
241 + var c = r.charCodeAt(r.length - 1);
242 + if (c >= 0xD800 && c <= 0xDBFF) {
243 + this.lastNeed = 2;
244 + this.lastTotal = 4;
245 + this.lastChar[0] = buf[buf.length - 2];
246 + this.lastChar[1] = buf[buf.length - 1];
247 + return r.slice(0, -1);
248 + }
249 + }
250 + return r;
251 + }
252 + this.lastNeed = 1;
253 + this.lastTotal = 2;
254 + this.lastChar[0] = buf[buf.length - 1];
255 + return buf.toString('utf16le', i, buf.length - 1);
256 +}
257 +
258 +// For UTF-16LE we do not explicitly append special replacement characters if we
259 +// end on a partial character, we simply let v8 handle that.
260 +function utf16End(buf) {
261 + var r = buf && buf.length ? this.write(buf) : '';
262 + if (this.lastNeed) {
263 + var end = this.lastTotal - this.lastNeed;
264 + return r + this.lastChar.toString('utf16le', 0, end);
265 + }
266 + return r;
267 +}
268 +
269 +function base64Text(buf, i) {
270 + var n = (buf.length - i) % 3;
271 + if (n === 0) return buf.toString('base64', i);
272 + this.lastNeed = 3 - n;
273 + this.lastTotal = 3;
274 + if (n === 1) {
275 + this.lastChar[0] = buf[buf.length - 1];
276 + } else {
277 + this.lastChar[0] = buf[buf.length - 2];
278 + this.lastChar[1] = buf[buf.length - 1];
279 + }
280 + return buf.toString('base64', i, buf.length - n);
281 +}
282 +
283 +function base64End(buf) {
284 + var r = buf && buf.length ? this.write(buf) : '';
285 + if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);
286 + return r;
287 +}
288 +
289 +// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)
290 +function simpleWrite(buf) {
291 + return buf.toString(this.encoding);
292 +}
293 +
294 +function simpleEnd(buf) {
295 + return buf && buf.length ? this.write(buf) : '';
296 +}
...\ No newline at end of file ...\ No newline at end of file
1 +{
2 + "_from": "string_decoder@^1.1.1",
3 + "_id": "string_decoder@1.3.0",
4 + "_inBundle": false,
5 + "_integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==",
6 + "_location": "/duplexify/string_decoder",
7 + "_phantomChildren": {},
8 + "_requested": {
9 + "type": "range",
10 + "registry": true,
11 + "raw": "string_decoder@^1.1.1",
12 + "name": "string_decoder",
13 + "escapedName": "string_decoder",
14 + "rawSpec": "^1.1.1",
15 + "saveSpec": null,
16 + "fetchSpec": "^1.1.1"
17 + },
18 + "_requiredBy": [
19 + "/duplexify/readable-stream"
20 + ],
21 + "_resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz",
22 + "_shasum": "42f114594a46cf1a8e30b0a84f56c78c3edac21e",
23 + "_spec": "string_decoder@^1.1.1",
24 + "_where": "C:\\Users\\1000c\\이것저것\\옾소\\Voicoding\\node_modules\\duplexify\\node_modules\\readable-stream",
25 + "bugs": {
26 + "url": "https://github.com/nodejs/string_decoder/issues"
27 + },
28 + "bundleDependencies": false,
29 + "dependencies": {
30 + "safe-buffer": "~5.2.0"
31 + },
32 + "deprecated": false,
33 + "description": "The string_decoder module from Node core",
34 + "devDependencies": {
35 + "babel-polyfill": "^6.23.0",
36 + "core-util-is": "^1.0.2",
37 + "inherits": "^2.0.3",
38 + "tap": "~0.4.8"
39 + },
40 + "files": [
41 + "lib"
42 + ],
43 + "homepage": "https://github.com/nodejs/string_decoder",
44 + "keywords": [
45 + "string",
46 + "decoder",
47 + "browser",
48 + "browserify"
49 + ],
50 + "license": "MIT",
51 + "main": "lib/string_decoder.js",
52 + "name": "string_decoder",
53 + "repository": {
54 + "type": "git",
55 + "url": "git://github.com/nodejs/string_decoder.git"
56 + },
57 + "scripts": {
58 + "ci": "tap test/parallel/*.js test/ours/*.js --tap | tee test.tap && node test/verify-dependencies.js",
59 + "test": "tap test/parallel/*.js && node test/verify-dependencies"
60 + },
61 + "version": "1.3.0"
62 +}
...@@ -4,7 +4,10 @@ ...@@ -4,7 +4,10 @@
4 "_inBundle": false, 4 "_inBundle": false,
5 "_integrity": "sha512-DY3xVEmVHTv1wSzKNbwoU6nVjzI369Y6sPoqfYr0/xlx3IdX2n94xIszTcjPO8W8ZIv0Wb0PXNcjuZyT4wiICA==", 5 "_integrity": "sha512-DY3xVEmVHTv1wSzKNbwoU6nVjzI369Y6sPoqfYr0/xlx3IdX2n94xIszTcjPO8W8ZIv0Wb0PXNcjuZyT4wiICA==",
6 "_location": "/duplexify", 6 "_location": "/duplexify",
7 - "_phantomChildren": {}, 7 + "_phantomChildren": {
8 + "inherits": "2.0.4",
9 + "util-deprecate": "1.0.2"
10 + },
8 "_requested": { 11 "_requested": {
9 "type": "range", 12 "type": "range",
10 "registry": true, 13 "registry": true,
......
1 +# Security holding package
2 +
3 +This package name is not currently in use, but was formerly occupied
4 +by another package. To avoid malicious use, npm is hanging on to the
5 +package name, but loosely, and we'll probably give it to you if you
6 +want it.
7 +
8 +You may adopt this package by contacting support@npmjs.com and
9 +requesting the name.
1 +{
2 + "_from": "fs",
3 + "_id": "fs@0.0.1-security",
4 + "_inBundle": false,
5 + "_integrity": "sha1-invTcYa23d84E/I4WLV+yq9eQdQ=",
6 + "_location": "/fs",
7 + "_phantomChildren": {},
8 + "_requested": {
9 + "type": "tag",
10 + "registry": true,
11 + "raw": "fs",
12 + "name": "fs",
13 + "escapedName": "fs",
14 + "rawSpec": "",
15 + "saveSpec": null,
16 + "fetchSpec": "latest"
17 + },
18 + "_requiredBy": [
19 + "#USER",
20 + "/"
21 + ],
22 + "_resolved": "https://registry.npmjs.org/fs/-/fs-0.0.1-security.tgz",
23 + "_shasum": "8a7bd37186b6dddf3813f23858b57ecaaf5e41d4",
24 + "_spec": "fs",
25 + "_where": "C:\\Users\\1000c\\이것저것\\옾소\\Voicoding",
26 + "author": "",
27 + "bugs": {
28 + "url": "https://github.com/npm/security-holder/issues"
29 + },
30 + "bundleDependencies": false,
31 + "deprecated": false,
32 + "description": "This package name is not currently in use, but was formerly occupied by another package. To avoid malicious use, npm is hanging on to the package name, but loosely, and we'll probably give it to you if you want it.",
33 + "homepage": "https://github.com/npm/security-holder#readme",
34 + "keywords": [],
35 + "license": "ISC",
36 + "main": "index.js",
37 + "name": "fs",
38 + "repository": {
39 + "type": "git",
40 + "url": "git+https://github.com/npm/security-holder.git"
41 + },
42 + "scripts": {
43 + "test": "echo \"Error: no test specified\" && exit 1"
44 + },
45 + "version": "0.0.1-security"
46 +}
1 # Changelog 1 # Changelog
2 2
3 +## [4.3.0](https://www.github.com/googleapis/gaxios/compare/v4.2.1...v4.3.0) (2021-05-26)
4 +
5 +
6 +### Features
7 +
8 +* allow cert and key to be provided for mTLS ([#399](https://www.github.com/googleapis/gaxios/issues/399)) ([d74ab91](https://www.github.com/googleapis/gaxios/commit/d74ab9125d581e46d655614729872e79317c740d))
9 +
3 ### [4.2.1](https://www.github.com/googleapis/gaxios/compare/v4.2.0...v4.2.1) (2021-04-20) 10 ### [4.2.1](https://www.github.com/googleapis/gaxios/compare/v4.2.0...v4.2.1) (2021-04-20)
4 11
5 12
......
...@@ -67,6 +67,8 @@ export interface GaxiosOptions { ...@@ -67,6 +67,8 @@ export interface GaxiosOptions {
67 * in node.js otherwise. 67 * in node.js otherwise.
68 */ 68 */
69 fetchImplementation?: FetchImplementation; 69 fetchImplementation?: FetchImplementation;
70 + cert?: string;
71 + key?: string;
70 } 72 }
71 /** 73 /**
72 * Configuration for the Gaxios `request` method. 74 * Configuration for the Gaxios `request` method.
......
1 +/// <reference types="node" />
2 +import { Agent } from 'http';
3 +import { URL } from 'url';
1 import { GaxiosOptions, GaxiosPromise } from './common'; 4 import { GaxiosOptions, GaxiosPromise } from './common';
2 export declare class Gaxios { 5 export declare class Gaxios {
3 - private agentCache; 6 + protected agentCache: Map<string, Agent | ((parsedUrl: URL) => Agent)>;
4 /** 7 /**
5 * Default HTTP options that will be used for every HTTP request. 8 * Default HTTP options that will be used for every HTTP request.
6 */ 9 */
...@@ -20,7 +23,7 @@ export declare class Gaxios { ...@@ -20,7 +23,7 @@ export declare class Gaxios {
20 * Internal, retryable version of the `request` method. 23 * Internal, retryable version of the `request` method.
21 * @param opts Set of HTTP options that will be used for this HTTP request. 24 * @param opts Set of HTTP options that will be used for this HTTP request.
22 */ 25 */
23 - private _request; 26 + protected _request<T = any>(opts?: GaxiosOptions): GaxiosPromise<T>;
24 private getResponseData; 27 private getResponseData;
25 /** 28 /**
26 * Validates the options, and merges them with defaults. 29 * Validates the options, and merges them with defaults.
......
...@@ -17,9 +17,11 @@ var __importDefault = (this && this.__importDefault) || function (mod) { ...@@ -17,9 +17,11 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
17 Object.defineProperty(exports, "__esModule", { value: true }); 17 Object.defineProperty(exports, "__esModule", { value: true });
18 exports.Gaxios = void 0; 18 exports.Gaxios = void 0;
19 const extend_1 = __importDefault(require("extend")); 19 const extend_1 = __importDefault(require("extend"));
20 +const https_1 = require("https");
20 const node_fetch_1 = __importDefault(require("node-fetch")); 21 const node_fetch_1 = __importDefault(require("node-fetch"));
21 const querystring_1 = __importDefault(require("querystring")); 22 const querystring_1 = __importDefault(require("querystring"));
22 const is_stream_1 = __importDefault(require("is-stream")); 23 const is_stream_1 = __importDefault(require("is-stream"));
24 +const url_1 = require("url");
23 const common_1 = require("./common"); 25 const common_1 = require("./common");
24 const retry_1 = require("./retry"); 26 const retry_1 = require("./retry");
25 /* eslint-disable @typescript-eslint/no-explicit-any */ 27 /* eslint-disable @typescript-eslint/no-explicit-any */
...@@ -64,7 +66,7 @@ function skipProxy(url) { ...@@ -64,7 +66,7 @@ function skipProxy(url) {
64 return false; 66 return false;
65 } 67 }
66 const noProxyUrls = noProxyEnv.split(','); 68 const noProxyUrls = noProxyEnv.split(',');
67 - const parsedURL = new URL(url); 69 + const parsedURL = new url_1.URL(url);
68 return !!noProxyUrls.find(url => { 70 return !!noProxyUrls.find(url => {
69 if (url.startsWith('*.') || url.startsWith('.')) { 71 if (url.startsWith('*.') || url.startsWith('.')) {
70 url = url.replace('*', ''); 72 url = url.replace('*', '');
...@@ -133,7 +135,8 @@ class Gaxios { ...@@ -133,7 +135,8 @@ class Gaxios {
133 err.config = opts; 135 err.config = opts;
134 const { shouldRetry, config } = await retry_1.getRetryConfig(e); 136 const { shouldRetry, config } = await retry_1.getRetryConfig(e);
135 if (shouldRetry && config) { 137 if (shouldRetry && config) {
136 - err.config.retryConfig.currentRetryAttempt = config.retryConfig.currentRetryAttempt; 138 + err.config.retryConfig.currentRetryAttempt =
139 + config.retryConfig.currentRetryAttempt;
137 return this._request(err.config); 140 return this._request(err.config);
138 } 141 }
139 throw err; 142 throw err;
...@@ -232,10 +235,36 @@ class Gaxios { ...@@ -232,10 +235,36 @@ class Gaxios {
232 opts.agent = this.agentCache.get(proxy); 235 opts.agent = this.agentCache.get(proxy);
233 } 236 }
234 else { 237 else {
235 - opts.agent = new HttpsProxyAgent(proxy); 238 + // Proxy is being used in conjunction with mTLS.
239 + if (opts.cert && opts.key) {
240 + const parsedURL = new url_1.URL(proxy);
241 + opts.agent = new HttpsProxyAgent({
242 + port: parsedURL.port,
243 + host: parsedURL.host,
244 + protocol: parsedURL.protocol,
245 + cert: opts.cert,
246 + key: opts.key,
247 + });
248 + }
249 + else {
250 + opts.agent = new HttpsProxyAgent(proxy);
251 + }
236 this.agentCache.set(proxy, opts.agent); 252 this.agentCache.set(proxy, opts.agent);
237 } 253 }
238 } 254 }
255 + else if (opts.cert && opts.key) {
256 + // Configure client for mTLS:
257 + if (this.agentCache.has(opts.key)) {
258 + opts.agent = this.agentCache.get(opts.key);
259 + }
260 + else {
261 + opts.agent = new https_1.Agent({
262 + cert: opts.cert,
263 + key: opts.key,
264 + });
265 + this.agentCache.set(opts.key, opts.agent);
266 + }
267 + }
239 return opts; 268 return opts;
240 } 269 }
241 /** 270 /**
......
1 -{"version":3,"file":"gaxios.js","sourceRoot":"","sources":["../../src/gaxios.ts"],"names":[],"mappings":";AAAA,4BAA4B;AAC5B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,gDAAgD;AAChD,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;;;;;;AAEjC,oDAA4B;AAE5B,4DAAmC;AACnC,8DAA6B;AAC7B,0DAAiC;AAGjC,qCAOkB;AAClB,mCAAuC;AAEvC,uDAAuD;AAEvD,MAAM,KAAK,GAAG,QAAQ,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,oBAAS,CAAC;AAEpD,SAAS,SAAS;IAChB,OAAO,OAAO,MAAM,KAAK,WAAW,IAAI,CAAC,CAAC,MAAM,CAAC;AACnD,CAAC;AAED,SAAS,QAAQ;IACf,OAAO,SAAS,EAAE,IAAI,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC;AACvC,CAAC;AAED,SAAS,SAAS;IAChB,OAAO,OAAO,MAAM,KAAK,WAAW,CAAC;AACvC,CAAC;AAED,SAAS,SAAS,CAAC,OAAsB,EAAE,MAAc;IACvD,OAAO,CAAC,CAAC,SAAS,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;AACtC,CAAC;AAED,SAAS,SAAS,CAAC,OAAsB,EAAE,MAAc;IACvD,MAAM,GAAG,MAAM,CAAC,WAAW,EAAE,CAAC;IAC9B,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,CAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,OAAO,KAAI,EAAE,CAAC,EAAE;QACrD,IAAI,MAAM,KAAK,GAAG,CAAC,WAAW,EAAE,EAAE;YAChC,OAAO,OAAO,CAAC,OAAQ,CAAC,GAAG,CAAC,CAAC;SAC9B;KACF;IACD,OAAO,SAAS,CAAC;AACnB,CAAC;AAED,IAAI,eAAoB,CAAC;AAEzB,SAAS,SAAS;IAChB,MAAM,KAAK,GACT,OAAO,CAAC,GAAG,CAAC,WAAW;QACvB,OAAO,CAAC,GAAG,CAAC,WAAW;QACvB,OAAO,CAAC,GAAG,CAAC,UAAU;QACtB,OAAO,CAAC,GAAG,CAAC,UAAU,CAAC;IACzB,IAAI,KAAK,EAAE;QACT,eAAe,GAAG,OAAO,CAAC,mBAAmB,CAAC,CAAC;KAChD;IACD,OAAO,KAAK,CAAC;AACf,CAAC;AACD,SAAS,EAAE,CAAC;AAEZ,SAAS,SAAS,CAAC,GAAW;;IAC5B,MAAM,UAAU,SAAG,OAAO,CAAC,GAAG,CAAC,QAAQ,mCAAI,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC;IAChE,IAAI,CAAC,UAAU,EAAE;QACf,OAAO,KAAK,CAAC;KACd;IACD,MAAM,WAAW,GAAG,UAAU,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IAC1C,MAAM,SAAS,GAAG,IAAI,GAAG,CAAC,GAAG,CAAC,CAAC;IAC/B,OAAO,CAAC,CAAC,WAAW,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE;QAC9B,IAAI,GAAG,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,GAAG,CAAC,UAAU,CAAC,GAAG,CAAC,EAAE;YAC/C,GAAG,GAAG,GAAG,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC;YAC3B,OAAO,SAAS,CAAC,QAAQ,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC;SACzC;aAAM;YACL,OAAO,GAAG,KAAK,SAAS,CAAC,MAAM,IAAI,GAAG,KAAK,SAAS,CAAC,QAAQ,CAAC;SAC/D;IACH,CAAC,CAAC,CAAC;AACL,CAAC;AAED,wEAAwE;AACxE,wDAAwD;AACxD,SAAS,QAAQ,CAAC,GAAW;IAC3B,wFAAwF;IACxF,IAAI,SAAS,CAAC,GAAG,CAAC,EAAE;QAClB,OAAO,SAAS,CAAC;QACjB,kHAAkH;KACnH;SAAM;QACL,OAAO,SAAS,EAAE,CAAC;KACpB;AACH,CAAC;AAED,MAAa,MAAM;IAWjB;;;OAGG;IACH,YAAY,QAAwB;QAd5B,eAAU,GAAG,IAAI,GAAG,EAGzB,CAAC;QAYF,IAAI,CAAC,QAAQ,GAAG,QAAQ,IAAI,EAAE,CAAC;IACjC,CAAC;IAED;;;OAGG;IACH,KAAK,CAAC,OAAO,CAAU,OAAsB,EAAE;QAC7C,IAAI,GAAG,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC;QAC/B,OAAO,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;IAC7B,CAAC;IAEO,KAAK,CAAC,eAAe,CAC3B,IAAmB;QAEnB,MAAM,SAAS,GAAG,IAAI,CAAC,mBAAmB,IAAI,KAAK,CAAC;QACpD,MAAM,GAAG,GAAG,CAAC,MAAM,SAAS,CAAC,IAAI,CAAC,GAAI,EAAE,IAAI,CAAC,CAAkB,CAAC;QAChE,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,eAAe,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC;QACnD,OAAO,IAAI,CAAC,iBAAiB,CAAI,IAAI,EAAE,GAAG,EAAE,IAAI,CAAC,CAAC;IACpD,CAAC;IAED;;;OAGG;IACK,KAAK,CAAC,QAAQ,CAAU,OAAsB,EAAE;QACtD,IAAI;YACF,IAAI,kBAAqC,CAAC;YAC1C,IAAI,IAAI,CAAC,OAAO,EAAE;gBAChB,kBAAkB,GAAG,MAAM,IAAI,CAAC,OAAO,CACrC,IAAI,EACJ,IAAI,CAAC,eAAe,CAAC,IAAI,CAAC,IAAI,CAAC,CAChC,CAAC;aACH;iBAAM;gBACL,kBAAkB,GAAG,MAAM,IAAI,CAAC,eAAe,CAAC,IAAI,CAAC,CAAC;aACvD;YACD,IAAI,CAAC,IAAI,CAAC,cAAe,CAAC,kBAAkB,CAAC,MAAM,CAAC,EAAE;gBACpD,MAAM,IAAI,oBAAW,CACnB,mCAAmC,kBAAkB,CAAC,MAAM,EAAE,EAC9D,IAAI,EACJ,kBAAkB,CACnB,CAAC;aACH;YACD,OAAO,kBAAkB,CAAC;SAC3B;QAAC,OAAO,CAAC,EAAE;YACV,MAAM,GAAG,GAAG,CAAgB,CAAC;YAC7B,GAAG,CAAC,MAAM,GAAG,IAAI,CAAC;YAClB,MAAM,EAAC,WAAW,EAAE,MAAM,EAAC,GAAG,MAAM,sBAAc,CAAC,CAAC,CAAC,CAAC;YACtD,IAAI,WAAW,IAAI,MAAM,EAAE;gBACzB,GAAG,CAAC,MAAM,CAAC,WAAY,CAAC,mBAAmB,GAAG,MAAM,CAAC,WAAY,CAAC,mBAAmB,CAAC;gBACtF,OAAO,IAAI,CAAC,QAAQ,CAAI,GAAG,CAAC,MAAM,CAAC,CAAC;aACrC;YACD,MAAM,GAAG,CAAC;SACX;IACH,CAAC;IAEO,KAAK,CAAC,eAAe,CAC3B,IAAmB,EACnB,GAAkB;QAElB,QAAQ,IAAI,CAAC,YAAY,EAAE;YACzB,KAAK,QAAQ;gBACX,OAAO,GAAG,CAAC,IAAI,CAAC;YAClB,KAAK,MAAM,CAAC,CAAC;gBACX,IAAI,IAAI,GAAG,MAAM,GAAG,CAAC,IAAI,EAAE,CAAC;gBAC5B,IAAI;oBACF,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;iBACzB;gBAAC,WAAM;oBACN,WAAW;iBACZ;gBACD,OAAO,IAAU,CAAC;aACnB;YACD,KAAK,aAAa;gBAChB,OAAO,GAAG,CAAC,WAAW,EAAE,CAAC;YAC3B,KAAK,MAAM;gBACT,OAAO,GAAG,CAAC,IAAI,EAAE,CAAC;YACpB;gBACE,OAAO,GAAG,CAAC,IAAI,EAAE,CAAC;SACrB;IACH,CAAC;IAED;;;OAGG;IACK,YAAY,CAAC,OAAsB;QACzC,MAAM,IAAI,GAAG,gBAAM,CAAC,IAAI,EAAE,EAAE,EAAE,IAAI,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC;QACtD,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE;YACb,MAAM,IAAI,KAAK,CAAC,kBAAkB,CAAC,CAAC;SACrC;QAED,6CAA6C;QAC7C,MAAM,OAAO,GAAG,IAAI,CAAC,OAAO,IAAI,IAAI,CAAC,OAAO,CAAC;QAC7C,IAAI,OAAO,EAAE;YACX,IAAI,CAAC,GAAG,GAAG,OAAO,GAAG,IAAI,CAAC,GAAG,CAAC;SAC/B;QAED,IAAI,CAAC,gBAAgB,GAAG,IAAI,CAAC,gBAAgB,IAAI,IAAI,CAAC,gBAAgB,CAAC;QACvE,IAAI,IAAI,CAAC,MAAM,IAAI,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,MAAM,GAAG,CAAC,EAAE;YACtD,IAAI,qBAAqB,GAAG,IAAI,CAAC,gBAAgB,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;YAC/D,IAAI,qBAAqB,CAAC,UAAU,CAAC,GAAG,CAAC,EAAE;gBACzC,qBAAqB,GAAG,qBAAqB,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;aACxD;YACD,MAAM,MAAM,GAAG,IAAI,CAAC,GAAG,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC;YAClD,IAAI,CAAC,GAAG,GAAG,IAAI,CAAC,GAAG,GAAG,MAAM,GAAG,qBAAqB,CAAC;SACtD;QAED,IAAI,OAAO,OAAO,CAAC,gBAAgB,KAAK,QAAQ,EAAE;YAChD,IAAI,CAAC,IAAI,GAAG,OAAO,CAAC,gBAAgB,CAAC;SACtC;QAED,IAAI,OAAO,OAAO,CAAC,YAAY,KAAK,QAAQ,EAAE;YAC5C,IAAI,CAAC,MAAM,GAAG,OAAO,CAAC,YAAY,CAAC;SACpC;QAED,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,IAAI,EAAE,CAAC;QAClC,IAAI,IAAI,CAAC,IAAI,EAAE;YACb,IAAI,mBAAQ,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE;gBAChC,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC;aACvB;iBAAM,IAAI,SAAS,EAAE,IAAI,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE;gBACpD,+CAA+C;gBAC/C,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC;gBACtB,IAAI,CAAC,SAAS,CAAC,IAAI,EAAE,cAAc,CAAC,EAAE;oBACpC,IAAI,CAAC,OAAO,CAAC,cAAc,CAAC,GAAG,kBAAkB,CAAC;iBACnD;aACF;iBAAM,IAAI,OAAO,IAAI,CAAC,IAAI,KAAK,QAAQ,EAAE;gBACxC,gEAAgE;gBAChE,kEAAkE;gBAClE,IACE,SAAS,CAAC,IAAI,EAAE,cAAc,CAAC;oBAC/B,mCAAmC,EACnC;oBACA,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,gBAAgB,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;iBAC9C;qBAAM;oBACL,IAAI,CAAC,SAAS,CAAC,IAAI,EAAE,cAAc,CAAC,EAAE;wBACpC,IAAI,CAAC,OAAO,CAAC,cAAc,CAAC,GAAG,kBAAkB,CAAC;qBACnD;oBACD,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;iBACvC;aACF;iBAAM;gBACL,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC;aACvB;SACF;QAED,IAAI,CAAC,cAAc,GAAG,IAAI,CAAC,cAAc,IAAI,IAAI,CAAC,cAAc,CAAC;QACjE,IAAI,CAAC,YAAY,GAAG,IAAI,CAAC,YAAY,IAAI,MAAM,CAAC;QAChD,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,IAAI,IAAI,CAAC,YAAY,KAAK,MAAM,EAAE;YAC3D,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,GAAG,kBAAkB,CAAC;SAC7C;QACD,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,IAAI,KAAK,CAAC;QAEnC,MAAM,KAAK,GAAG,QAAQ,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;QACjC,IAAI,KAAK,EAAE;YACT,IAAI,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,KAAK,CAAC,EAAE;gBAC9B,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;aACzC;iBAAM;gBACL,IAAI,CAAC,KAAK,GAAG,IAAI,eAAe,CAAC,KAAK,CAAC,CAAC;gBACxC,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,KAAK,EAAE,IAAI,CAAC,KAAM,CAAC,CAAC;aACzC;SACF;QAED,OAAO,IAAI,CAAC;IACd,CAAC;IAED;;;OAGG;IACK,cAAc,CAAC,MAAc;QACnC,OAAO,MAAM,IAAI,GAAG,IAAI,MAAM,GAAG,GAAG,CAAC;IACvC,CAAC;IAED;;;OAGG;IACK,gBAAgB,CAAC,MAA0C;QACjE,OAAO,qBAAE,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC;IAC9B,CAAC;IAEO,iBAAiB,CACvB,IAAmB,EACnB,GAAkB,EAClB,IAAQ;QAER,oDAAoD;QACpD,MAAM,OAAO,GAAG,EAAa,CAAC;QAC9B,GAAG,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,KAAK,EAAE,GAAG,EAAE,EAAE;YACjC,OAAO,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;QACvB,CAAC,CAAC,CAAC;QAEH,OAAO;YACL,MAAM,EAAE,IAAI;YACZ,IAAI,EAAE,IAAS;YACf,OAAO;YACP,MAAM,EAAE,GAAG,CAAC,MAAM;YAClB,UAAU,EAAE,GAAG,CAAC,UAAU;YAE1B,qBAAqB;YACrB,OAAO,EAAE;gBACP,WAAW,EAAE,GAAG,CAAC,GAAG;aACrB;SACF,CAAC;IACJ,CAAC;CACF;AA5ND,wBA4NC"}
...\ No newline at end of file ...\ No newline at end of file
1 +{"version":3,"file":"gaxios.js","sourceRoot":"","sources":["../../src/gaxios.ts"],"names":[],"mappings":";AAAA,4BAA4B;AAC5B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,gDAAgD;AAChD,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;;;;;;AAEjC,oDAA4B;AAE5B,iCAA0C;AAC1C,4DAAmC;AACnC,8DAA6B;AAC7B,0DAAiC;AACjC,6BAAwB;AAExB,qCAOkB;AAClB,mCAAuC;AAEvC,uDAAuD;AAEvD,MAAM,KAAK,GAAG,QAAQ,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,oBAAS,CAAC;AAEpD,SAAS,SAAS;IAChB,OAAO,OAAO,MAAM,KAAK,WAAW,IAAI,CAAC,CAAC,MAAM,CAAC;AACnD,CAAC;AAED,SAAS,QAAQ;IACf,OAAO,SAAS,EAAE,IAAI,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC;AACvC,CAAC;AAED,SAAS,SAAS;IAChB,OAAO,OAAO,MAAM,KAAK,WAAW,CAAC;AACvC,CAAC;AAED,SAAS,SAAS,CAAC,OAAsB,EAAE,MAAc;IACvD,OAAO,CAAC,CAAC,SAAS,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;AACtC,CAAC;AAED,SAAS,SAAS,CAAC,OAAsB,EAAE,MAAc;IACvD,MAAM,GAAG,MAAM,CAAC,WAAW,EAAE,CAAC;IAC9B,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,CAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,OAAO,KAAI,EAAE,CAAC,EAAE;QACrD,IAAI,MAAM,KAAK,GAAG,CAAC,WAAW,EAAE,EAAE;YAChC,OAAO,OAAO,CAAC,OAAQ,CAAC,GAAG,CAAC,CAAC;SAC9B;KACF;IACD,OAAO,SAAS,CAAC;AACnB,CAAC;AAED,IAAI,eAAoB,CAAC;AAEzB,SAAS,SAAS;IAChB,MAAM,KAAK,GACT,OAAO,CAAC,GAAG,CAAC,WAAW;QACvB,OAAO,CAAC,GAAG,CAAC,WAAW;QACvB,OAAO,CAAC,GAAG,CAAC,UAAU;QACtB,OAAO,CAAC,GAAG,CAAC,UAAU,CAAC;IACzB,IAAI,KAAK,EAAE;QACT,eAAe,GAAG,OAAO,CAAC,mBAAmB,CAAC,CAAC;KAChD;IACD,OAAO,KAAK,CAAC;AACf,CAAC;AACD,SAAS,EAAE,CAAC;AAEZ,SAAS,SAAS,CAAC,GAAW;;IAC5B,MAAM,UAAU,SAAG,OAAO,CAAC,GAAG,CAAC,QAAQ,mCAAI,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC;IAChE,IAAI,CAAC,UAAU,EAAE;QACf,OAAO,KAAK,CAAC;KACd;IACD,MAAM,WAAW,GAAG,UAAU,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IAC1C,MAAM,SAAS,GAAG,IAAI,SAAG,CAAC,GAAG,CAAC,CAAC;IAC/B,OAAO,CAAC,CAAC,WAAW,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE;QAC9B,IAAI,GAAG,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,GAAG,CAAC,UAAU,CAAC,GAAG,CAAC,EAAE;YAC/C,GAAG,GAAG,GAAG,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC;YAC3B,OAAO,SAAS,CAAC,QAAQ,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC;SACzC;aAAM;YACL,OAAO,GAAG,KAAK,SAAS,CAAC,MAAM,IAAI,GAAG,KAAK,SAAS,CAAC,QAAQ,CAAC;SAC/D;IACH,CAAC,CAAC,CAAC;AACL,CAAC;AAED,wEAAwE;AACxE,wDAAwD;AACxD,SAAS,QAAQ,CAAC,GAAW;IAC3B,wFAAwF;IACxF,IAAI,SAAS,CAAC,GAAG,CAAC,EAAE;QAClB,OAAO,SAAS,CAAC;QACjB,kHAAkH;KACnH;SAAM;QACL,OAAO,SAAS,EAAE,CAAC;KACpB;AACH,CAAC;AAED,MAAa,MAAM;IAQjB;;;OAGG;IACH,YAAY,QAAwB;QAX1B,eAAU,GAAG,IAAI,GAAG,EAA+C,CAAC;QAY5E,IAAI,CAAC,QAAQ,GAAG,QAAQ,IAAI,EAAE,CAAC;IACjC,CAAC;IAED;;;OAGG;IACH,KAAK,CAAC,OAAO,CAAU,OAAsB,EAAE;QAC7C,IAAI,GAAG,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC;QAC/B,OAAO,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;IAC7B,CAAC;IAEO,KAAK,CAAC,eAAe,CAC3B,IAAmB;QAEnB,MAAM,SAAS,GAAG,IAAI,CAAC,mBAAmB,IAAI,KAAK,CAAC;QACpD,MAAM,GAAG,GAAG,CAAC,MAAM,SAAS,CAAC,IAAI,CAAC,GAAI,EAAE,IAAI,CAAC,CAAkB,CAAC;QAChE,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,eAAe,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC;QACnD,OAAO,IAAI,CAAC,iBAAiB,CAAI,IAAI,EAAE,GAAG,EAAE,IAAI,CAAC,CAAC;IACpD,CAAC;IAED;;;OAGG;IACO,KAAK,CAAC,QAAQ,CACtB,OAAsB,EAAE;QAExB,IAAI;YACF,IAAI,kBAAqC,CAAC;YAC1C,IAAI,IAAI,CAAC,OAAO,EAAE;gBAChB,kBAAkB,GAAG,MAAM,IAAI,CAAC,OAAO,CACrC,IAAI,EACJ,IAAI,CAAC,eAAe,CAAC,IAAI,CAAC,IAAI,CAAC,CAChC,CAAC;aACH;iBAAM;gBACL,kBAAkB,GAAG,MAAM,IAAI,CAAC,eAAe,CAAC,IAAI,CAAC,CAAC;aACvD;YACD,IAAI,CAAC,IAAI,CAAC,cAAe,CAAC,kBAAkB,CAAC,MAAM,CAAC,EAAE;gBACpD,MAAM,IAAI,oBAAW,CACnB,mCAAmC,kBAAkB,CAAC,MAAM,EAAE,EAC9D,IAAI,EACJ,kBAAkB,CACnB,CAAC;aACH;YACD,OAAO,kBAAkB,CAAC;SAC3B;QAAC,OAAO,CAAC,EAAE;YACV,MAAM,GAAG,GAAG,CAAgB,CAAC;YAC7B,GAAG,CAAC,MAAM,GAAG,IAAI,CAAC;YAClB,MAAM,EAAC,WAAW,EAAE,MAAM,EAAC,GAAG,MAAM,sBAAc,CAAC,CAAC,CAAC,CAAC;YACtD,IAAI,WAAW,IAAI,MAAM,EAAE;gBACzB,GAAG,CAAC,MAAM,CAAC,WAAY,CAAC,mBAAmB;oBACzC,MAAM,CAAC,WAAY,CAAC,mBAAmB,CAAC;gBAC1C,OAAO,IAAI,CAAC,QAAQ,CAAI,GAAG,CAAC,MAAM,CAAC,CAAC;aACrC;YACD,MAAM,GAAG,CAAC;SACX;IACH,CAAC;IAEO,KAAK,CAAC,eAAe,CAC3B,IAAmB,EACnB,GAAkB;QAElB,QAAQ,IAAI,CAAC,YAAY,EAAE;YACzB,KAAK,QAAQ;gBACX,OAAO,GAAG,CAAC,IAAI,CAAC;YAClB,KAAK,MAAM,CAAC,CAAC;gBACX,IAAI,IAAI,GAAG,MAAM,GAAG,CAAC,IAAI,EAAE,CAAC;gBAC5B,IAAI;oBACF,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;iBACzB;gBAAC,WAAM;oBACN,WAAW;iBACZ;gBACD,OAAO,IAAU,CAAC;aACnB;YACD,KAAK,aAAa;gBAChB,OAAO,GAAG,CAAC,WAAW,EAAE,CAAC;YAC3B,KAAK,MAAM;gBACT,OAAO,GAAG,CAAC,IAAI,EAAE,CAAC;YACpB;gBACE,OAAO,GAAG,CAAC,IAAI,EAAE,CAAC;SACrB;IACH,CAAC;IAED;;;OAGG;IACK,YAAY,CAAC,OAAsB;QACzC,MAAM,IAAI,GAAG,gBAAM,CAAC,IAAI,EAAE,EAAE,EAAE,IAAI,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC;QACtD,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE;YACb,MAAM,IAAI,KAAK,CAAC,kBAAkB,CAAC,CAAC;SACrC;QAED,6CAA6C;QAC7C,MAAM,OAAO,GAAG,IAAI,CAAC,OAAO,IAAI,IAAI,CAAC,OAAO,CAAC;QAC7C,IAAI,OAAO,EAAE;YACX,IAAI,CAAC,GAAG,GAAG,OAAO,GAAG,IAAI,CAAC,GAAG,CAAC;SAC/B;QAED,IAAI,CAAC,gBAAgB,GAAG,IAAI,CAAC,gBAAgB,IAAI,IAAI,CAAC,gBAAgB,CAAC;QACvE,IAAI,IAAI,CAAC,MAAM,IAAI,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,MAAM,GAAG,CAAC,EAAE;YACtD,IAAI,qBAAqB,GAAG,IAAI,CAAC,gBAAgB,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;YAC/D,IAAI,qBAAqB,CAAC,UAAU,CAAC,GAAG,CAAC,EAAE;gBACzC,qBAAqB,GAAG,qBAAqB,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;aACxD;YACD,MAAM,MAAM,GAAG,IAAI,CAAC,GAAG,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC;YAClD,IAAI,CAAC,GAAG,GAAG,IAAI,CAAC,GAAG,GAAG,MAAM,GAAG,qBAAqB,CAAC;SACtD;QAED,IAAI,OAAO,OAAO,CAAC,gBAAgB,KAAK,QAAQ,EAAE;YAChD,IAAI,CAAC,IAAI,GAAG,OAAO,CAAC,gBAAgB,CAAC;SACtC;QAED,IAAI,OAAO,OAAO,CAAC,YAAY,KAAK,QAAQ,EAAE;YAC5C,IAAI,CAAC,MAAM,GAAG,OAAO,CAAC,YAAY,CAAC;SACpC;QAED,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,IAAI,EAAE,CAAC;QAClC,IAAI,IAAI,CAAC,IAAI,EAAE;YACb,IAAI,mBAAQ,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE;gBAChC,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC;aACvB;iBAAM,IAAI,SAAS,EAAE,IAAI,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE;gBACpD,+CAA+C;gBAC/C,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC;gBACtB,IAAI,CAAC,SAAS,CAAC,IAAI,EAAE,cAAc,CAAC,EAAE;oBACpC,IAAI,CAAC,OAAO,CAAC,cAAc,CAAC,GAAG,kBAAkB,CAAC;iBACnD;aACF;iBAAM,IAAI,OAAO,IAAI,CAAC,IAAI,KAAK,QAAQ,EAAE;gBACxC,gEAAgE;gBAChE,kEAAkE;gBAClE,IACE,SAAS,CAAC,IAAI,EAAE,cAAc,CAAC;oBAC/B,mCAAmC,EACnC;oBACA,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,gBAAgB,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;iBAC9C;qBAAM;oBACL,IAAI,CAAC,SAAS,CAAC,IAAI,EAAE,cAAc,CAAC,EAAE;wBACpC,IAAI,CAAC,OAAO,CAAC,cAAc,CAAC,GAAG,kBAAkB,CAAC;qBACnD;oBACD,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;iBACvC;aACF;iBAAM;gBACL,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC;aACvB;SACF;QAED,IAAI,CAAC,cAAc,GAAG,IAAI,CAAC,cAAc,IAAI,IAAI,CAAC,cAAc,CAAC;QACjE,IAAI,CAAC,YAAY,GAAG,IAAI,CAAC,YAAY,IAAI,MAAM,CAAC;QAChD,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,IAAI,IAAI,CAAC,YAAY,KAAK,MAAM,EAAE;YAC3D,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,GAAG,kBAAkB,CAAC;SAC7C;QACD,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,IAAI,KAAK,CAAC;QAEnC,MAAM,KAAK,GAAG,QAAQ,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;QACjC,IAAI,KAAK,EAAE;YACT,IAAI,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,KAAK,CAAC,EAAE;gBAC9B,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;aACzC;iBAAM;gBACL,gDAAgD;gBAChD,IAAI,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC,GAAG,EAAE;oBACzB,MAAM,SAAS,GAAG,IAAI,SAAG,CAAC,KAAK,CAAC,CAAC;oBACjC,IAAI,CAAC,KAAK,GAAG,IAAI,eAAe,CAAC;wBAC/B,IAAI,EAAE,SAAS,CAAC,IAAI;wBACpB,IAAI,EAAE,SAAS,CAAC,IAAI;wBACpB,QAAQ,EAAE,SAAS,CAAC,QAAQ;wBAC5B,IAAI,EAAE,IAAI,CAAC,IAAI;wBACf,GAAG,EAAE,IAAI,CAAC,GAAG;qBACd,CAAC,CAAC;iBACJ;qBAAM;oBACL,IAAI,CAAC,KAAK,GAAG,IAAI,eAAe,CAAC,KAAK,CAAC,CAAC;iBACzC;gBACD,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,KAAK,EAAE,IAAI,CAAC,KAAM,CAAC,CAAC;aACzC;SACF;aAAM,IAAI,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC,GAAG,EAAE;YAChC,6BAA6B;YAC7B,IAAI,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE;gBACjC,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;aAC5C;iBAAM;gBACL,IAAI,CAAC,KAAK,GAAG,IAAI,aAAU,CAAC;oBAC1B,IAAI,EAAE,IAAI,CAAC,IAAI;oBACf,GAAG,EAAE,IAAI,CAAC,GAAG;iBACd,CAAC,CAAC;gBACH,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,EAAE,IAAI,CAAC,KAAM,CAAC,CAAC;aAC5C;SACF;QAED,OAAO,IAAI,CAAC;IACd,CAAC;IAED;;;OAGG;IACK,cAAc,CAAC,MAAc;QACnC,OAAO,MAAM,IAAI,GAAG,IAAI,MAAM,GAAG,GAAG,CAAC;IACvC,CAAC;IAED;;;OAGG;IACK,gBAAgB,CAAC,MAA0C;QACjE,OAAO,qBAAE,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC;IAC9B,CAAC;IAEO,iBAAiB,CACvB,IAAmB,EACnB,GAAkB,EAClB,IAAQ;QAER,oDAAoD;QACpD,MAAM,OAAO,GAAG,EAAa,CAAC;QAC9B,GAAG,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,KAAK,EAAE,GAAG,EAAE,EAAE;YACjC,OAAO,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;QACvB,CAAC,CAAC,CAAC;QAEH,OAAO;YACL,MAAM,EAAE,IAAI;YACZ,IAAI,EAAE,IAAS;YACf,OAAO;YACP,MAAM,EAAE,GAAG,CAAC,MAAM;YAClB,UAAU,EAAE,GAAG,CAAC,UAAU;YAE1B,qBAAqB;YACrB,OAAO,EAAE;gBACP,WAAW,EAAE,GAAG,CAAC,GAAG;aACrB;SACF,CAAC;IACJ,CAAC;CACF;AAnPD,wBAmPC"}
...\ No newline at end of file ...\ No newline at end of file
......
1 { 1 {
2 "_from": "gaxios@^4.0.0", 2 "_from": "gaxios@^4.0.0",
3 - "_id": "gaxios@4.2.1", 3 + "_id": "gaxios@4.3.0",
4 "_inBundle": false, 4 "_inBundle": false,
5 - "_integrity": "sha512-s+rTywpw6CmfB8r9TXYkpix7YFeuRjnR/AqhaJrQqsNhsAqej+IAiCc3hadzQH3gHyWth30tvYjxH8EVjQt/8Q==", 5 + "_integrity": "sha512-pHplNbslpwCLMyII/lHPWFQbJWOX0B3R1hwBEOvzYi1GmdKZruuEHK4N9V6f7tf1EaPYyF80mui1+344p6SmLg==",
6 "_location": "/gaxios", 6 "_location": "/gaxios",
7 "_phantomChildren": {}, 7 "_phantomChildren": {},
8 "_requested": { 8 "_requested": {
...@@ -20,8 +20,8 @@ ...@@ -20,8 +20,8 @@
20 "/google-auth-library", 20 "/google-auth-library",
21 "/gtoken" 21 "/gtoken"
22 ], 22 ],
23 - "_resolved": "https://registry.npmjs.org/gaxios/-/gaxios-4.2.1.tgz", 23 + "_resolved": "https://registry.npmjs.org/gaxios/-/gaxios-4.3.0.tgz",
24 - "_shasum": "7463d3a06f56ddbffa745a242d2b4933b88b2ada", 24 + "_shasum": "ad4814d89061f85b97ef52aed888c5dbec32f774",
25 "_spec": "gaxios@^4.0.0", 25 "_spec": "gaxios@^4.0.0",
26 "_where": "C:\\Users\\1000c\\이것저것\\옾소\\Voicoding\\node_modules\\google-auth-library", 26 "_where": "C:\\Users\\1000c\\이것저것\\옾소\\Voicoding\\node_modules\\google-auth-library",
27 "author": { 27 "author": {
...@@ -52,11 +52,13 @@ ...@@ -52,11 +52,13 @@
52 "@types/multiparty": "0.0.32", 52 "@types/multiparty": "0.0.32",
53 "@types/mv": "^2.1.0", 53 "@types/mv": "^2.1.0",
54 "@types/ncp": "^2.0.1", 54 "@types/ncp": "^2.0.1",
55 - "@types/node": "^11.9.5", 55 + "@types/node": "^14.0.0",
56 "@types/node-fetch": "^2.5.7", 56 "@types/node-fetch": "^2.5.7",
57 "@types/sinon": "^10.0.0", 57 "@types/sinon": "^10.0.0",
58 "@types/tmp": "0.2.0", 58 "@types/tmp": "0.2.0",
59 "@types/uuid": "^8.0.0", 59 "@types/uuid": "^8.0.0",
60 + "assert": "^2.0.0",
61 + "browserify": "^17.0.0",
60 "c8": "^7.0.0", 62 "c8": "^7.0.0",
61 "cors": "^2.8.5", 63 "cors": "^2.8.5",
62 "execa": "^5.0.0", 64 "execa": "^5.0.0",
...@@ -79,12 +81,13 @@ ...@@ -79,12 +81,13 @@
79 "nock": "^13.0.0", 81 "nock": "^13.0.0",
80 "null-loader": "^4.0.0", 82 "null-loader": "^4.0.0",
81 "puppeteer": "^8.0.0", 83 "puppeteer": "^8.0.0",
82 - "sinon": "^10.0.0", 84 + "sinon": "^11.0.0",
85 + "stream-browserify": "^3.0.0",
83 "tmp": "0.2.1", 86 "tmp": "0.2.1",
84 "ts-loader": "^8.0.0", 87 "ts-loader": "^8.0.0",
85 "typescript": "^3.8.3", 88 "typescript": "^3.8.3",
86 "uuid": "^8.0.0", 89 "uuid": "^8.0.0",
87 - "webpack": "^5.30.0", 90 + "webpack": "^5.35.0",
88 "webpack-cli": "^4.0.0" 91 "webpack-cli": "^4.0.0"
89 }, 92 },
90 "engines": { 93 "engines": {
...@@ -127,5 +130,5 @@ ...@@ -127,5 +130,5 @@
127 "webpack": "webpack" 130 "webpack": "webpack"
128 }, 131 },
129 "types": "build/src/index.d.ts", 132 "types": "build/src/index.d.ts",
130 - "version": "4.2.1" 133 + "version": "4.3.0"
131 } 134 }
......
...@@ -4,6 +4,14 @@ ...@@ -4,6 +4,14 @@
4 4
5 [1]: https://www.npmjs.com/package/google-auth-library-nodejs?activeTab=versions 5 [1]: https://www.npmjs.com/package/google-auth-library-nodejs?activeTab=versions
6 6
7 +## [7.1.0](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v7.0.4...v7.1.0) (2021-05-21)
8 +
9 +
10 +### Features
11 +
12 +* add `gcf-owl-bot[bot]` to `ignoreAuthors` ([#1174](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1174)) ([f377adc](https://www.github.com/googleapis/google-auth-library-nodejs/commit/f377adc01ca16687bb905aa14f6c62a23e90aaa9))
13 +* add detection for Cloud Run ([#1177](https://www.github.com/googleapis/google-auth-library-nodejs/issues/1177)) ([4512363](https://www.github.com/googleapis/google-auth-library-nodejs/commit/4512363cf712dff5f178af0e7022c258775dfec7))
14 +
7 ### [7.0.4](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v7.0.3...v7.0.4) (2021-04-06) 15 ### [7.0.4](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v7.0.3...v7.0.4) (2021-04-06)
8 16
9 17
......
...@@ -3,6 +3,7 @@ export declare enum GCPEnv { ...@@ -3,6 +3,7 @@ export declare enum GCPEnv {
3 KUBERNETES_ENGINE = "KUBERNETES_ENGINE", 3 KUBERNETES_ENGINE = "KUBERNETES_ENGINE",
4 CLOUD_FUNCTIONS = "CLOUD_FUNCTIONS", 4 CLOUD_FUNCTIONS = "CLOUD_FUNCTIONS",
5 COMPUTE_ENGINE = "COMPUTE_ENGINE", 5 COMPUTE_ENGINE = "COMPUTE_ENGINE",
6 + CLOUD_RUN = "CLOUD_RUN",
6 NONE = "NONE" 7 NONE = "NONE"
7 } 8 }
8 export declare function clear(): void; 9 export declare function clear(): void;
......
...@@ -21,6 +21,7 @@ var GCPEnv; ...@@ -21,6 +21,7 @@ var GCPEnv;
21 GCPEnv["KUBERNETES_ENGINE"] = "KUBERNETES_ENGINE"; 21 GCPEnv["KUBERNETES_ENGINE"] = "KUBERNETES_ENGINE";
22 GCPEnv["CLOUD_FUNCTIONS"] = "CLOUD_FUNCTIONS"; 22 GCPEnv["CLOUD_FUNCTIONS"] = "CLOUD_FUNCTIONS";
23 GCPEnv["COMPUTE_ENGINE"] = "COMPUTE_ENGINE"; 23 GCPEnv["COMPUTE_ENGINE"] = "COMPUTE_ENGINE";
24 + GCPEnv["CLOUD_RUN"] = "CLOUD_RUN";
24 GCPEnv["NONE"] = "NONE"; 25 GCPEnv["NONE"] = "NONE";
25 })(GCPEnv = exports.GCPEnv || (exports.GCPEnv = {})); 26 })(GCPEnv = exports.GCPEnv || (exports.GCPEnv = {}));
26 let envPromise; 27 let envPromise;
...@@ -48,6 +49,9 @@ async function getEnvMemoized() { ...@@ -48,6 +49,9 @@ async function getEnvMemoized() {
48 if (await isKubernetesEngine()) { 49 if (await isKubernetesEngine()) {
49 env = GCPEnv.KUBERNETES_ENGINE; 50 env = GCPEnv.KUBERNETES_ENGINE;
50 } 51 }
52 + else if (isCloudRun()) {
53 + env = GCPEnv.CLOUD_RUN;
54 + }
51 else { 55 else {
52 env = GCPEnv.COMPUTE_ENGINE; 56 env = GCPEnv.COMPUTE_ENGINE;
53 } 57 }
...@@ -63,6 +67,14 @@ function isAppEngine() { ...@@ -63,6 +67,14 @@ function isAppEngine() {
63 function isCloudFunction() { 67 function isCloudFunction() {
64 return !!(process.env.FUNCTION_NAME || process.env.FUNCTION_TARGET); 68 return !!(process.env.FUNCTION_NAME || process.env.FUNCTION_TARGET);
65 } 69 }
70 +/**
71 + * This check only verifies that the environment is running knative.
72 + * This must be run *after* checking for Kubernetes, otherwise it will
73 + * return a false positive.
74 + */
75 +function isCloudRun() {
76 + return !!process.env.K_CONFIGURATION;
77 +}
66 async function isKubernetesEngine() { 78 async function isKubernetesEngine() {
67 try { 79 try {
68 await gcpMetadata.instance('attributes/cluster-name'); 80 await gcpMetadata.instance('attributes/cluster-name');
......
...@@ -132,7 +132,8 @@ class GoogleAuth { ...@@ -132,7 +132,8 @@ class GoogleAuth {
132 // Check for the existence of a local environment variable pointing to the 132 // Check for the existence of a local environment variable pointing to the
133 // location of the credential file. This is typically used in local 133 // location of the credential file. This is typically used in local
134 // developer scenarios. 134 // developer scenarios.
135 - credential = await this._tryGetApplicationCredentialsFromEnvironmentVariable(options); 135 + credential =
136 + await this._tryGetApplicationCredentialsFromEnvironmentVariable(options);
136 if (credential) { 137 if (credential) {
137 if (credential instanceof jwtclient_1.JWT) { 138 if (credential instanceof jwtclient_1.JWT) {
138 credential.defaultScopes = this.defaultScopes; 139 credential.defaultScopes = this.defaultScopes;
...@@ -414,8 +415,7 @@ class GoogleAuth { ...@@ -414,8 +415,7 @@ class GoogleAuth {
414 child_process_1.exec('gcloud config config-helper --format json', (err, stdout) => { 415 child_process_1.exec('gcloud config config-helper --format json', (err, stdout) => {
415 if (!err && stdout) { 416 if (!err && stdout) {
416 try { 417 try {
417 - const projectId = JSON.parse(stdout).configuration.properties.core 418 + const projectId = JSON.parse(stdout).configuration.properties.core.project;
418 - .project;
419 resolve(projectId); 419 resolve(projectId);
420 return; 420 return;
421 } 421 }
......
1 { 1 {
2 "_from": "google-auth-library@^7.0.2", 2 "_from": "google-auth-library@^7.0.2",
3 - "_id": "google-auth-library@7.0.4", 3 + "_id": "google-auth-library@7.1.0",
4 "_inBundle": false, 4 "_inBundle": false,
5 - "_integrity": "sha512-o8irYyeijEiecTXeoEe8UKNEzV1X+uhR4b2oNdapDMZixypp0J+eHimGOyx5Joa3UAeokGngdtDLXtq9vDqG2Q==", 5 + "_integrity": "sha512-X+gbkGjnLN3HUZP2W3KBREuA603BXd80ITvL0PeS0QpyDNYz/u0pIZ7aRuGnrSuUc0grk/qxEgtVTFt1ogbP+A==",
6 "_location": "/google-auth-library", 6 "_location": "/google-auth-library",
7 "_phantomChildren": {}, 7 "_phantomChildren": {},
8 "_requested": { 8 "_requested": {
...@@ -19,8 +19,8 @@ ...@@ -19,8 +19,8 @@
19 "/@google-cloud/common", 19 "/@google-cloud/common",
20 "/google-gax" 20 "/google-gax"
21 ], 21 ],
22 - "_resolved": "https://registry.npmjs.org/google-auth-library/-/google-auth-library-7.0.4.tgz", 22 + "_resolved": "https://registry.npmjs.org/google-auth-library/-/google-auth-library-7.1.0.tgz",
23 - "_shasum": "610cb010de71435dca47dfbe8dc7fbff23055d2c", 23 + "_shasum": "d83b6bed1d170e30649e15e9b5b17cb375e88919",
24 "_spec": "google-auth-library@^7.0.2", 24 "_spec": "google-auth-library@^7.0.2",
25 "_where": "C:\\Users\\1000c\\이것저것\\옾소\\Voicoding\\node_modules\\@google-cloud\\common", 25 "_where": "C:\\Users\\1000c\\이것저것\\옾소\\Voicoding\\node_modules\\@google-cloud\\common",
26 "author": { 26 "author": {
...@@ -55,7 +55,7 @@ ...@@ -55,7 +55,7 @@
55 "@types/mv": "^2.1.0", 55 "@types/mv": "^2.1.0",
56 "@types/ncp": "^2.0.1", 56 "@types/ncp": "^2.0.1",
57 "@types/node": "^10.5.1", 57 "@types/node": "^10.5.1",
58 - "@types/sinon": "^9.0.0", 58 + "@types/sinon": "^10.0.0",
59 "@types/tmp": "^0.2.0", 59 "@types/tmp": "^0.2.0",
60 "assert-rejects": "^1.0.0", 60 "assert-rejects": "^1.0.0",
61 "c8": "^7.0.0", 61 "c8": "^7.0.0",
...@@ -132,5 +132,5 @@ ...@@ -132,5 +132,5 @@
132 "webpack": "webpack" 132 "webpack": "webpack"
133 }, 133 },
134 "types": "./build/src/index.d.ts", 134 "types": "./build/src/index.d.ts",
135 - "version": "7.0.4" 135 + "version": "7.1.0"
136 } 136 }
......
...@@ -4,6 +4,22 @@ ...@@ -4,6 +4,22 @@
4 4
5 [1]: https://www.npmjs.com/package/gax-nodejs?activeTab=versions 5 [1]: https://www.npmjs.com/package/gax-nodejs?activeTab=versions
6 6
7 +### [2.14.1](https://www.github.com/googleapis/gax-nodejs/compare/v2.14.0...v2.14.1) (2021-05-27)
8 +
9 +
10 +### Bug Fixes
11 +
12 +* rest transport enum value display incorectly ([#1015](https://www.github.com/googleapis/gax-nodejs/issues/1015)) ([055387b](https://www.github.com/googleapis/gax-nodejs/commit/055387b1f497f6a4132f228d82d95d9a6f6c53f7))
13 +
14 +## [2.14.0](https://www.github.com/googleapis/gax-nodejs/compare/v2.13.0...v2.14.0) (2021-05-24)
15 +
16 +
17 +### Features
18 +
19 +* add `gcf-owl-bot[bot]` to `ignoreAuthors` ([#1007](https://www.github.com/googleapis/gax-nodejs/issues/1007)) ([4fac451](https://www.github.com/googleapis/gax-nodejs/commit/4fac45186cea40c0945598636faee5d9d7ba1103))
20 +* add type parameter to warn function ([#1009](https://www.github.com/googleapis/gax-nodejs/issues/1009)) ([fef2e7c](https://www.github.com/googleapis/gax-nodejs/commit/fef2e7c7d81d2187b05542862386c2391e7edd74))
21 +* update rest version for metrics ([#1005](https://www.github.com/googleapis/gax-nodejs/issues/1005)) ([233d6a7](https://www.github.com/googleapis/gax-nodejs/commit/233d6a7dbed5655652a0b5100773cc7837e59a5f))
22 +
7 ## [2.13.0](https://www.github.com/googleapis/gax-nodejs/compare/v2.12.0...v2.13.0) (2021-05-12) 23 ## [2.13.0](https://www.github.com/googleapis/gax-nodejs/compare/v2.12.0...v2.13.0) (2021-05-12)
8 24
9 25
......
...@@ -92,7 +92,7 @@ class GrpcClient { ...@@ -92,7 +92,7 @@ class GrpcClient {
92 new google_auth_library_1.GoogleAuth(options); 92 new google_auth_library_1.GoogleAuth(options);
93 } 93 }
94 this.fallback = options.fallback !== 'rest' ? 'proto' : 'rest'; 94 this.fallback = options.fallback !== 'rest' ? 'proto' : 'rest';
95 - this.grpcVersion = 'fallback'; // won't be used anywhere but we need it to exist in the class 95 + this.grpcVersion = require('../../package.json').version;
96 } 96 }
97 /** 97 /**
98 * In rare cases users might need to deallocate all memory consumed by loaded protos. 98 * In rare cases users might need to deallocate all memory consumed by loaded protos.
...@@ -224,7 +224,18 @@ class GrpcClient { ...@@ -224,7 +224,18 @@ class GrpcClient {
224 const newServiceStub = service.create(serviceClientImpl, false, false); 224 const newServiceStub = service.create(serviceClientImpl, false, false);
225 for (const methodName of methods) { 225 for (const methodName of methods) {
226 newServiceStub[methodName] = (req, options, metadata, callback) => { 226 newServiceStub[methodName] = (req, options, metadata, callback) => {
227 - const [method, requestData, serviceCallback] = serviceStub[methodName].apply(serviceStub, [req, callback]); 227 + const [method, requestData, serviceCallback] = serviceStub[methodName].apply(serviceStub, [
228 + req,
229 + (err, response) => {
230 + if (!err) {
231 + // converts a protobuf message instance to a plain JavaScript object with enum conversion options specified
232 + response = method.resolvedResponseType.toObject(response, {
233 + enums: String,
234 + });
235 + }
236 + callback(err, response);
237 + },
238 + ]);
228 // eslint-disable-next-line @typescript-eslint/no-explicit-any 239 // eslint-disable-next-line @typescript-eslint/no-explicit-any
229 let cancelController, cancelSignal; 240 let cancelController, cancelSignal;
230 if (isbrowser_1.isBrowser() || typeof AbortController !== 'undefined') { 241 if (isbrowser_1.isBrowser() || typeof AbortController !== 'undefined') {
......
1 -{"version":3,"file":"fallback.js","sourceRoot":"","sources":["../../src/fallback.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;;AAEH,uEAAuE;AACvE,6EAA6E;AAC7E,0BAA0B;AAC1B,2CAAsC;AACtC,IAAI,uBAAuB,GAAG,KAAK,CAAC;AAEpC,IACE,qBAAS,EAAE;IACX,sEAAsE;IACtE,CAAC,OAAO,WAAW,KAAK,WAAW,IAAI,OAAO,WAAW,KAAK,WAAW,CAAC,EAC1E;IACA,uBAAuB,GAAG,IAAI,CAAC;CAChC;AACD,IACE,OAAO,OAAO,KAAK,WAAW,WAC9B,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,QAAQ,0CAAE,IAAI,CAAA,WACvB,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,QAAQ,0CAAE,IAAI,CAAC,KAAK,CAAC,OAAO,EAAC,EACtC;IACA,8CAA8C;IAC9C,uEAAuE;IACvE,8DAA8D;IAC9D,MAAM,IAAI,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;IAC7B,MAAM,CAAC,MAAM,CAAC,MAAM,EAAE;QACpB,WAAW,EAAE,IAAI,CAAC,WAAW;QAC7B,WAAW,EAAE,IAAI,CAAC,WAAW;KAC9B,CAAC,CAAC;CACJ;AACD,IAAI,uBAAuB,EAAE;IAC3B,OAAO,CAAC,oBAAoB,CAAC,CAAC;CAC/B;AAED,uCAAuC;AAmf/B,4BAAQ;AAlfhB,6BAA6B;AAC7B,2CAAmC;AAEnC,iDAAiD;AAuBzC,sCAAa;AAtBrB,uDAAwE;AACxE,qCAAgC;AAEhC,6DAQ6B;AAC7B,0CAA0C;AAC1C,yDAA2D;AAI3D,mDAAgE;AAChE,mDAA2E;AAC3E,+CAAwC;AAExC,+CAA4C;AAApC,4GAAA,YAAY,OAAA;AAEpB,6BAAoE;AAA5D,mGAAA,YAAY,OAAA;AAAE,wGAAA,iBAAiB,OAAA;AAAE,mGAAA,YAAY,OAAA;AACxC,QAAA,OAAO,GAAG,OAAO,CAAC,oBAAoB,CAAC,CAAC,OAAO,GAAG,WAAW,CAAC;AAE3E,2CAKsB;AAJpB,8GAAA,gBAAgB,OAAA;AAChB,mHAAA,qBAAqB,OAAA;AACrB,4GAAA,cAAc,OAAA;AACd,8GAAA,gBAAgB,OAAA;AAGlB,wDAAsD;AAA9C,uGAAA,UAAU,OAAA;AAMlB,MAAM,qBAAqB,GAAG,mBAAmB,CAAC;AAMlD,MAAa,UAAU;IAoBrB;;;;;;;OAOG;IAEH,YACE,UAEI,EAAE;QAEN,IAAI,qBAAS,EAAE,EAAE;YACf,IAAI,CAAC,OAAO,CAAC,IAAI,EAAE;gBACjB,MAAM,IAAI,KAAK,CACb,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC;oBACrB,mHAAmH,CACtH,CAAC;aACH;YACD,IAAI,CAAC,IAAI,GAAG,OAAO,CAAC,IAAoB,CAAC;SAC1C;aAAM;YACL,IAAI,CAAC,IAAI;gBACN,OAAO,CAAC,IAAmB;oBAC5B,IAAI,gCAAU,CAAC,OAA4B,CAAC,CAAC;SAChD;QACD,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC,QAAQ,KAAK,MAAM,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC;QAC/D,IAAI,CAAC,WAAW,GAAG,UAAU,CAAC,CAAC,8DAA8D;IAC/F,CAAC;IArCD;;;OAGG;IACH,MAAM,CAAC,eAAe;QACpB,UAAU,CAAC,UAAU,CAAC,KAAK,EAAE,CAAC;IAChC,CAAC;IAiCD;;;;;OAKG;IACH,SAAS,CAAC,UAAc;QACtB,MAAM,UAAU,GAAG,QAAQ,CAAC,IAAI,CAAC,QAAQ,CAAC,UAAU,CAAC,CAAC;QACtD,OAAO,UAAU,CAAC;IACpB,CAAC;IAED,aAAa,CAAC,IAAyB,EAAE,WAAW,GAAG,KAAK;QAC1D,MAAM,IAAI,GAAG,UAAU,CAAC,IAAI,CAAC,CAAC;QAC9B,MAAM,MAAM,GAAG,UAAU,CAAC,UAAU,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QAC/C,IAAI,MAAM,IAAI,CAAC,WAAW,EAAE;YAC1B,OAAO,MAAM,CAAC;SACf;QACD,MAAM,IAAI,GAAG,QAAQ,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;QAC1C,UAAU,CAAC,UAAU,CAAC,GAAG,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;QACtC,OAAO,IAAI,CAAC;IACd,CAAC;IAEO,iBAAiB,CAAC,OAAyB;QACjD,MAAM,OAAO,GAAG,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;QAE7C,MAAM,qBAAqB,GAAG,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE;YACjD,OAAO,MAAM,CAAC,CAAC,CAAC,CAAC,WAAW,EAAE,GAAG,MAAM,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC;QACvD,CAAC,CAAC,CAAC;QAEH,OAAO,qBAAqB,CAAC;IAC/B,CAAC;IAED;;;;;;;;;;;OAWG;IACH,iBAAiB,CACf,WAAmB,EACnB,YAA8B,EAC9B,eAAiC,EACjC,OAA4B;QAE5B,SAAS,aAAa,CAAC,OAAW,EAAE,WAAgC;YAClE,MAAM,QAAQ,GAAwB,EAAE,CAAC;YACzC,IAAI,CAAC,OAAO,EAAE;gBACZ,OAAO,GAAG,EAAE,CAAC;aACd;YACD,iDAAiD;YACjD,2CAA2C;YAC3C,KAAK,MAAM,GAAG,IAAI,OAAO,EAAE;gBACzB,QAAQ,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;oBACzC,CAAC,CAAE,OAAO,CAAC,GAAG,CAAc;oBAC5B,CAAC,CAAE,CAAC,OAAO,CAAC,GAAG,CAAC,CAAc,CAAC;aAClC;YAED,qEAAqE;YACrE,MAAM,cAAc,GAAa,EAAE,CAAC;YACpC,IACE,QAAQ,CAAC,qBAAqB,CAAC;gBAE7B,QAAQ,CAAC,qBAAqB,CAC/B,CAAC,CAAC,CAAC,EACJ;gBACA,cAAc,CAAC,IAAI,CACjB,GAAI,QAAQ,CAAC,qBAAqB,CAAc,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAC/D,CAAC;aACH;YACD,cAAc,CAAC,IAAI,CAAC,YAAY,eAAO,EAAE,CAAC,CAAC;YAC3C,QAAQ,CAAC,qBAAqB,CAAC,GAAG,CAAC,cAAc,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;YAE7D,IAAI,CAAC,WAAW,EAAE;gBAChB,OAAO,QAAQ,CAAC;aACjB;YACD,KAAK,MAAM,GAAG,IAAI,WAAW,EAAE;gBAC7B,IAAI,GAAG,CAAC,WAAW,EAAE,KAAK,qBAAqB,EAAE;oBAC/C,MAAM,KAAK,GAAG,WAAW,CAAC,GAAG,CAAC,CAAC;oBAC/B,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE;wBACxB,IAAI,QAAQ,CAAC,GAAG,CAAC,KAAK,SAAS,EAAE;4BAC/B,QAAQ,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;yBACvB;6BAAM;4BACL,IAAI,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,EAAE;gCAE9B,QAAQ,CAAC,GAAG,CAGb,CAAC,IAAI,CAAC,GAAG,KAAK,CAAC,CAAC;6BAClB;iCAAM;gCACL,MAAM,IAAI,KAAK,CACb,qBAAqB,KAAK,wBAAwB,CACnD,CAAC;6BACH;yBACF;qBACF;yBAAM;wBACL,QAAQ,CAAC,GAAG,CAAC,GAAG,CAAC,KAAK,CAAa,CAAC;qBACrC;iBACF;aACF;YACD,OAAO,QAAQ,CAAC;QAClB,CAAC;QACD,OAAO,GAAG,CAAC,iBAAiB,CAC1B,WAAW,EACX,YAAY,EACZ,eAAe,EACf,eAAM,EACN,EAAC,eAAe,EAAE,aAAa,EAAC,CACjC,CAAC;IACJ,CAAC;IAED;;;;;;;;;;OAUG;IACH,KAAK,CAAC,UAAU,CAAC,OAAyB,EAAE,IAAuB;QACjE,qDAAqD;QACrD,SAAS,iBAAiB,CACxB,MAKK,EACL,WAAuB,EACvB,QAAkC;YAElC,OAAO,CAAC,MAAM,EAAE,WAAW,EAAE,QAAQ,CAAC,CAAC;QACzC,CAAC;QAED,yCAAyC;QACzC,MAAM,aAAa,GAAG,IAAI,oCAAoB,EAAE,CAAC;QAEjD,IAAI,CAAC,IAAI,CAAC,UAAU,EAAE;YACpB,IAAI,IAAI,CAAC,IAAI,IAAI,WAAW,IAAI,IAAI,CAAC,IAAI,EAAE;gBACzC,IAAI,CAAC,UAAU,GAAG,MAAM,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,CAAC;aAC/C;iBAAM,IAAI,IAAI,CAAC,IAAI,IAAI,mBAAmB,IAAI,IAAI,CAAC,IAAI,EAAE;gBACxD,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC,IAAI,CAAC;aAC7B;SACF;QACD,IAAI,CAAC,IAAI,CAAC,UAAU,EAAE;YACpB,MAAM,IAAI,KAAK,CAAC,gCAAgC,CAAC,CAAC;SACnD;QACD,MAAM,UAAU,GAAG,MAAM,IAAI,CAAC,UAAU,CAAC,iBAAiB,EAAE,CAAC;QAC7D,MAAM,WAAW,GAAG,OAAO,CAAC,MAAM,CAChC,iBAAiB,EACjB,KAAK,EACL,KAAK,CAC4B,CAAC;QACpC,MAAM,OAAO,GAAG,IAAI,CAAC,iBAAiB,CAAC,OAAO,CAAC,CAAC;QAEhD,MAAM,cAAc,GAAG,OAAO,CAAC,MAAM,CACnC,iBAAiB,EACjB,KAAK,EACL,KAAK,CAC4B,CAAC;QACpC,KAAK,MAAM,UAAU,IAAI,OAAO,EAAE;YAChC,cAAc,CAAC,UAAU,CAAC,GAAG,CAC3B,GAAO,EACP,OAAiC,EACjC,QAAY,EACZ,QAAkB,EAClB,EAAE;gBACF,MAAM,CAAC,MAAM,EAAE,WAAW,EAAE,eAAe,CAAC,GAAG,WAAW,CACxD,UAAU,CACX,CAAC,KAAK,CAAC,WAAW,EAAE,CAAC,GAAG,EAAE,QAAQ,CAAC,CAAC,CAAC;gBACtC,8DAA8D;gBAC9D,IAAI,gBAAiC,EAAE,YAAiB,CAAC;gBACzD,IAAI,qBAAS,EAAE,IAAI,OAAO,eAAe,KAAK,WAAW,EAAE;oBACzD,oCAAoC;oBACpC,gBAAgB,GAAG,IAAI,eAAe,EAAE,CAAC;iBAC1C;qBAAM;oBACL,gBAAgB,GAAG,IAAI,kCAAmB,EAAE,CAAC;iBAC9C;gBACD,IAAI,gBAAgB,EAAE;oBACpB,YAAY,GAAG,gBAAgB,CAAC,MAAM,CAAC;iBACxC;gBACD,IAAI,eAAe,GAAG,KAAK,CAAC;gBAE5B,MAAM,OAAO,GAAG,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,UAAU,CAAC,CAAC;gBAC9C,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE;oBACtC,OAAO,CAAC,GAAG,CAAC,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;iBAChC;gBAED,MAAM,oBAAoB,GAAG,IAAI,CAAC,QAAQ,IAAI,OAAO,CAAC;gBACtD,IAAI,WAAW,GAAG,IAAI,CAAC,WAAW,CAAC;gBACnC,IACE,CAAC,WAAW;oBACZ,OAAO,CAAC,OAAO;oBACf,OAAO,CAAC,OAAO,CAAC,2BAA2B,CAAC,EAC5C;oBACA,WAAW,GAAG,OAAO,CAAC,OAAO,CAAC,2BAA2B,CAAC,CAAC;iBAC5D;gBACD,IAAI,CAAC,WAAW,EAAE;oBAChB,eAAe,CAAC,IAAI,KAAK,CAAC,2BAA2B,CAAC,CAAC,CAAC;oBACxD,OAAO;iBACR;gBAED,IAAI,WAAW,CAAC;gBAChB,MAAM,KAAK,GAAG,WAAY,CAAC,KAAK,CAAC,cAAc,CAAC,CAAC;gBACjD,IAAI,KAAK,EAAE;oBACT,WAAW,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;oBACvB,WAAW,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;iBACxB;gBACD,IAAI,IAAI,CAAC,IAAI,EAAE;oBACb,WAAW,GAAG,IAAI,CAAC,IAAI,CAAC;iBACzB;qBAAM,IAAI,CAAC,WAAW,EAAE;oBACvB,WAAW,GAAG,GAAG,CAAC;iBACnB;gBAED,MAAM,eAAe,GAAa,EAAE,CAAC;gBACrC,IAAI,aAAa,GAAG,MAAM,CAAC,MAAM,CAAC;gBAClC,OAAO,aAAa,CAAC,IAAI,KAAK,EAAE,EAAE;oBAChC,eAAe,CAAC,OAAO,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC;oBAC5C,aAAa,GAAG,aAAa,CAAC,MAAM,CAAC;iBACtC;gBACD,MAAM,gBAAgB,GAAG,eAAe,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;gBACnD,MAAM,OAAO,GAAG,MAAM,CAAC,IAAI,CAAC;gBAE5B,IAAI,GAAW,CAAC;gBAChB,IAAI,IAAY,CAAC;gBACjB,IAAI,UAAkB,CAAC;gBAEvB,+EAA+E;gBAC/E,8BAA8B;gBAC9B,IAAI,IAAI,CAAC,QAAQ,KAAK,MAAM,EAAE;oBAC5B,iDAAiD;oBACjD,OAAO,CAAC,cAAc,CAAC,GAAG,kBAAkB,CAAC;oBAC7C,MAAM,cAAc,GAAG,MAAM,CAAC,mBAAmB,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC;oBACtE,MAAM,WAAW,GAAG,MAAM,CAAC,mBAAmB,CAAC,QAAQ;oBACrD,uCAAuC;oBACvC,cAAc,CACf,CAAC;oBACF,MAAM,UAAU,GAAG,uBAAS,CAC1B,WAAW,EACX,MAAM,CAAC,aAAa,EACpB,MAAM,CAAC,mBAAmB,CAAC,MAAM,CAClC,CAAC;oBACF,IAAI,CAAC,UAAU,EAAE;wBACf,MAAM,IAAI,KAAK,CACb,iCAAiC,IAAI,CAAC,SAAS,CAC7C,WAAW,CACZ,aAAa,MAAM,CAAC,IAAI,EAAE,CAC5B,CAAC;qBACH;oBACD,UAAU,GAAG,UAAU,CAAC,UAAU,CAAC;oBACnC,IAAI,GAAG,IAAI,CAAC,SAAS,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;oBACvC,GAAG,GAAG,GAAG,oBAAoB,MAAM,WAAW,IAAI,WAAW,IAAI,UAAU,CAAC,GAAG,CAAC,OAAO,CACrF,KAAK,EACL,EAAE,CACH,IAAI,UAAU,CAAC,WAAW,EAAE,CAAC;iBAC/B;qBAAM;oBACL,mCAAmC;oBACnC,OAAO,CAAC,cAAc,CAAC,GAAG,wBAAwB,CAAC;oBACnD,UAAU,GAAG,MAAM,CAAC;oBACpB,IAAI,GAAG,WAAW,CAAC;oBACnB,GAAG,GAAG,GAAG,oBAAoB,MAAM,WAAW,IAAI,WAAW,SAAS,gBAAgB,IAAI,OAAO,EAAE,CAAC;iBACrG;gBAED,MAAM,KAAK,GAAG,qBAAS,EAAE;oBACvB,CAAC,CAAC,oCAAoC;wBACpC,MAAM,CAAC,KAAK;oBACd,CAAC,CAAE,oBAAsC,CAAC;gBAC5C,MAAM,YAAY,GAAG;oBACnB,OAAO;oBACP,IAAI,EAAE,IAA0B;oBAChC,MAAM,EAAE,UAAU;oBAClB,MAAM,EAAE,YAAY;iBACrB,CAAC;gBACF,IACE,UAAU,KAAK,KAAK;oBACpB,UAAU,KAAK,QAAQ;oBACvB,UAAU,KAAK,MAAM,EACrB;oBACA,OAAO,YAAY,CAAC,MAAM,CAAC,CAAC;iBAC7B;gBACD,KAAK,CAAC,GAAG,EAAE,YAAY,CAAC;qBACrB,IAAI,CAAC,CAAC,QAAsC,EAAE,EAAE;oBAC/C,OAAO,OAAO,CAAC,GAAG,CAAC;wBACjB,OAAO,CAAC,OAAO,CAAC,QAAQ,CAAC,EAAE,CAAC;wBAC5B,QAAQ,CAAC,WAAW,EAAE;qBACvB,CAAC,CAAC;gBACL,CAAC,CAAC;qBACD,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,MAAM,CAAkC,EAAE,EAAE;oBACtD,4DAA4D;oBAC5D,0BAA0B;oBAC1B,IAAI,IAAI,CAAC,QAAQ,KAAK,MAAM,EAAE;wBAC5B,4BAA4B;wBAC5B,sEAAsE;wBACtE,MAAM,aAAa,GAAG,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;wBACvD,MAAM,QAAQ,GAAG,IAAI,CAAC,KAAK,CAAC,aAAa,CAAC,CAAC;wBAC3C,IAAI,CAAC,EAAE,EAAE;4BACP,MAAM,KAAK,GAAG,MAAM,CAAC,MAAM,CACzB,IAAI,KAAK,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC,SAAS,CAAC,CAAC,EACvC,QAAQ,CAAC,KAAK,CACf,CAAC;4BACF,MAAM,KAAK,CAAC;yBACb;wBACD,MAAM,OAAO,GAAG,MAAM,CAAC,oBAAoB,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC;wBACjE,MAAM,OAAO,GAAG,MAAM,CAAC,oBAAoB;6BACxC,MAAM,CAAC,OAAO,CAAC;6BACf,MAAM,EAAE,CAAC;wBACZ,eAAe,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;qBAChC;yBAAM;wBACL,mCAAmC;wBACnC,IAAI,CAAC,EAAE,EAAE;4BACP,MAAM,KAAK,GAAG,aAAa,CAAC,qBAAqB,CAAC,MAAM,CAAC,CAAC;4BAC1D,MAAM,KAAK,CAAC;yBACb;wBACD,eAAe,CAAC,IAAI,EAAE,IAAI,UAAU,CAAC,MAAM,CAAC,CAAC,CAAC;qBAC/C;gBACH,CAAC,CAAC;qBACD,KAAK,CAAC,CAAC,GAAU,EAAE,EAAE;oBACpB,IAAI,CAAC,eAAe,IAAI,GAAG,CAAC,IAAI,KAAK,YAAY,EAAE;wBACjD,eAAe,CAAC,GAAG,CAAC,CAAC;qBACtB;gBACH,CAAC,CAAC,CAAC;gBAEL,OAAO;oBACL,MAAM,EAAE,GAAG,EAAE;wBACX,IAAI,CAAC,gBAAgB,EAAE;4BACrB,OAAO,CAAC,IAAI,CACV,8EAA8E,CAC/E,CAAC;4BACF,OAAO;yBACR;wBACD,eAAe,GAAG,IAAI,CAAC;wBACvB,gBAAgB,CAAC,KAAK,EAAE,CAAC;oBAC3B,CAAC;iBACF,CAAC;YACJ,CAAC,CAAC;SACH;QACD,OAAO,cAAc,CAAC;IACxB,CAAC;;AA5YH,gCA6YC;AAnYgB,qBAAU,GAAG,IAAI,GAAG,EAAyB,CAAC;AAqY/D;;;;;GAKG;AACH,SAAgB,GAAG,CAAC,OAA0B;IAC5C,OAAO,GAAG,MAAM,CAAC,MAAM,CAAC,EAAC,MAAM,EAAE,EAAE,EAAC,EAAE,OAAO,CAAC,CAAC;IAC/C,MAAM,OAAO,GAAG,IAAI,UAAU,CAAC,OAAO,CAAC,CAAC;IACxC,OAAO,IAAI,0CAAuB,CAAC,OAAO,CAAC,CAAC;AAC9C,CAAC;AAJD,kBAIC;AAED;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,SAAgB,aAAa,CAC3B,IAAkC,EAClC,QAA0B,EAC1B,UAAuB;IAEvB,IAAI,UAAU,IAAI,WAAW,IAAI,UAAU,EAAE;QAC3C,OAAO,GAAG,EAAE;YACV,MAAM,IAAI,KAAK,CACb,oHAAoH,CACrH,CAAC;QACJ,CAAC,CAAC;KACH;IACD,OAAO,6BAAc,CAAC,IAAI,EAAE,QAAQ,EAAE,UAAU,CAAC,CAAC;AACpD,CAAC;AAbD,sCAaC;AAGD,wDAAsD;AAEtD,4EAA4E;AAC5E,8EAA8E;AAC9E,8DAA8D;AAC9D,uEAAuE;AACvE,qCAAqC;AACrC,2EAA2E;AAC3E,qBAAqB;AACrB,MAAM,QAAQ,GAAG,MAAM,CAAC,OAAO,CAAC;AACxB,4BAAQ"}
...\ No newline at end of file ...\ No newline at end of file
1 +{"version":3,"file":"fallback.js","sourceRoot":"","sources":["../../src/fallback.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;;AAEH,uEAAuE;AACvE,6EAA6E;AAC7E,0BAA0B;AAC1B,2CAAsC;AACtC,IAAI,uBAAuB,GAAG,KAAK,CAAC;AAEpC,IACE,qBAAS,EAAE;IACX,sEAAsE;IACtE,CAAC,OAAO,WAAW,KAAK,WAAW,IAAI,OAAO,WAAW,KAAK,WAAW,CAAC,EAC1E;IACA,uBAAuB,GAAG,IAAI,CAAC;CAChC;AACD,IACE,OAAO,OAAO,KAAK,WAAW,WAC9B,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,QAAQ,0CAAE,IAAI,CAAA,WACvB,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,QAAQ,0CAAE,IAAI,CAAC,KAAK,CAAC,OAAO,EAAC,EACtC;IACA,8CAA8C;IAC9C,uEAAuE;IACvE,8DAA8D;IAC9D,MAAM,IAAI,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;IAC7B,MAAM,CAAC,MAAM,CAAC,MAAM,EAAE;QACpB,WAAW,EAAE,IAAI,CAAC,WAAW;QAC7B,WAAW,EAAE,IAAI,CAAC,WAAW;KAC9B,CAAC,CAAC;CACJ;AACD,IAAI,uBAAuB,EAAE;IAC3B,OAAO,CAAC,oBAAoB,CAAC,CAAC;CAC/B;AAED,uCAAuC;AA8f/B,4BAAQ;AA7fhB,6BAA6B;AAC7B,2CAAmC;AAEnC,iDAAiD;AAuBzC,sCAAa;AAtBrB,uDAAwE;AACxE,qCAAgC;AAEhC,6DAQ6B;AAC7B,0CAA0C;AAC1C,yDAA2D;AAI3D,mDAAgE;AAChE,mDAA2E;AAC3E,+CAAwC;AAExC,+CAA4C;AAApC,4GAAA,YAAY,OAAA;AAEpB,6BAAoE;AAA5D,mGAAA,YAAY,OAAA;AAAE,wGAAA,iBAAiB,OAAA;AAAE,mGAAA,YAAY,OAAA;AACxC,QAAA,OAAO,GAAG,OAAO,CAAC,oBAAoB,CAAC,CAAC,OAAO,GAAG,WAAW,CAAC;AAE3E,2CAKsB;AAJpB,8GAAA,gBAAgB,OAAA;AAChB,mHAAA,qBAAqB,OAAA;AACrB,4GAAA,cAAc,OAAA;AACd,8GAAA,gBAAgB,OAAA;AAGlB,wDAAsD;AAA9C,uGAAA,UAAU,OAAA;AAMlB,MAAM,qBAAqB,GAAG,mBAAmB,CAAC;AAMlD,MAAa,UAAU;IAoBrB;;;;;;;OAOG;IAEH,YACE,UAEI,EAAE;QAEN,IAAI,qBAAS,EAAE,EAAE;YACf,IAAI,CAAC,OAAO,CAAC,IAAI,EAAE;gBACjB,MAAM,IAAI,KAAK,CACb,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC;oBACrB,mHAAmH,CACtH,CAAC;aACH;YACD,IAAI,CAAC,IAAI,GAAG,OAAO,CAAC,IAAoB,CAAC;SAC1C;aAAM;YACL,IAAI,CAAC,IAAI;gBACN,OAAO,CAAC,IAAmB;oBAC5B,IAAI,gCAAU,CAAC,OAA4B,CAAC,CAAC;SAChD;QACD,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC,QAAQ,KAAK,MAAM,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC;QAC/D,IAAI,CAAC,WAAW,GAAG,OAAO,CAAC,oBAAoB,CAAC,CAAC,OAAO,CAAC;IAC3D,CAAC;IArCD;;;OAGG;IACH,MAAM,CAAC,eAAe;QACpB,UAAU,CAAC,UAAU,CAAC,KAAK,EAAE,CAAC;IAChC,CAAC;IAiCD;;;;;OAKG;IACH,SAAS,CAAC,UAAc;QACtB,MAAM,UAAU,GAAG,QAAQ,CAAC,IAAI,CAAC,QAAQ,CAAC,UAAU,CAAC,CAAC;QACtD,OAAO,UAAU,CAAC;IACpB,CAAC;IAED,aAAa,CAAC,IAAyB,EAAE,WAAW,GAAG,KAAK;QAC1D,MAAM,IAAI,GAAG,UAAU,CAAC,IAAI,CAAC,CAAC;QAC9B,MAAM,MAAM,GAAG,UAAU,CAAC,UAAU,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QAC/C,IAAI,MAAM,IAAI,CAAC,WAAW,EAAE;YAC1B,OAAO,MAAM,CAAC;SACf;QACD,MAAM,IAAI,GAAG,QAAQ,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;QAC1C,UAAU,CAAC,UAAU,CAAC,GAAG,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;QACtC,OAAO,IAAI,CAAC;IACd,CAAC;IAEO,iBAAiB,CAAC,OAAyB;QACjD,MAAM,OAAO,GAAG,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;QAE7C,MAAM,qBAAqB,GAAG,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE;YACjD,OAAO,MAAM,CAAC,CAAC,CAAC,CAAC,WAAW,EAAE,GAAG,MAAM,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC;QACvD,CAAC,CAAC,CAAC;QAEH,OAAO,qBAAqB,CAAC;IAC/B,CAAC;IAED;;;;;;;;;;;OAWG;IACH,iBAAiB,CACf,WAAmB,EACnB,YAA8B,EAC9B,eAAiC,EACjC,OAA4B;QAE5B,SAAS,aAAa,CAAC,OAAW,EAAE,WAAgC;YAClE,MAAM,QAAQ,GAAwB,EAAE,CAAC;YACzC,IAAI,CAAC,OAAO,EAAE;gBACZ,OAAO,GAAG,EAAE,CAAC;aACd;YACD,iDAAiD;YACjD,2CAA2C;YAC3C,KAAK,MAAM,GAAG,IAAI,OAAO,EAAE;gBACzB,QAAQ,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;oBACzC,CAAC,CAAE,OAAO,CAAC,GAAG,CAAc;oBAC5B,CAAC,CAAE,CAAC,OAAO,CAAC,GAAG,CAAC,CAAc,CAAC;aAClC;YAED,qEAAqE;YACrE,MAAM,cAAc,GAAa,EAAE,CAAC;YACpC,IACE,QAAQ,CAAC,qBAAqB,CAAC;gBAE7B,QAAQ,CAAC,qBAAqB,CAC/B,CAAC,CAAC,CAAC,EACJ;gBACA,cAAc,CAAC,IAAI,CACjB,GAAI,QAAQ,CAAC,qBAAqB,CAAc,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAC/D,CAAC;aACH;YACD,cAAc,CAAC,IAAI,CAAC,YAAY,eAAO,EAAE,CAAC,CAAC;YAC3C,QAAQ,CAAC,qBAAqB,CAAC,GAAG,CAAC,cAAc,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;YAE7D,IAAI,CAAC,WAAW,EAAE;gBAChB,OAAO,QAAQ,CAAC;aACjB;YACD,KAAK,MAAM,GAAG,IAAI,WAAW,EAAE;gBAC7B,IAAI,GAAG,CAAC,WAAW,EAAE,KAAK,qBAAqB,EAAE;oBAC/C,MAAM,KAAK,GAAG,WAAW,CAAC,GAAG,CAAC,CAAC;oBAC/B,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE;wBACxB,IAAI,QAAQ,CAAC,GAAG,CAAC,KAAK,SAAS,EAAE;4BAC/B,QAAQ,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;yBACvB;6BAAM;4BACL,IAAI,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,EAAE;gCAE9B,QAAQ,CAAC,GAAG,CAGb,CAAC,IAAI,CAAC,GAAG,KAAK,CAAC,CAAC;6BAClB;iCAAM;gCACL,MAAM,IAAI,KAAK,CACb,qBAAqB,KAAK,wBAAwB,CACnD,CAAC;6BACH;yBACF;qBACF;yBAAM;wBACL,QAAQ,CAAC,GAAG,CAAC,GAAG,CAAC,KAAK,CAAa,CAAC;qBACrC;iBACF;aACF;YACD,OAAO,QAAQ,CAAC;QAClB,CAAC;QACD,OAAO,GAAG,CAAC,iBAAiB,CAC1B,WAAW,EACX,YAAY,EACZ,eAAe,EACf,eAAM,EACN,EAAC,eAAe,EAAE,aAAa,EAAC,CACjC,CAAC;IACJ,CAAC;IAED;;;;;;;;;;OAUG;IACH,KAAK,CAAC,UAAU,CAAC,OAAyB,EAAE,IAAuB;QACjE,qDAAqD;QACrD,SAAS,iBAAiB,CACxB,MAKK,EACL,WAAuB,EACvB,QAAkC;YAElC,OAAO,CAAC,MAAM,EAAE,WAAW,EAAE,QAAQ,CAAC,CAAC;QACzC,CAAC;QAED,yCAAyC;QACzC,MAAM,aAAa,GAAG,IAAI,oCAAoB,EAAE,CAAC;QAEjD,IAAI,CAAC,IAAI,CAAC,UAAU,EAAE;YACpB,IAAI,IAAI,CAAC,IAAI,IAAI,WAAW,IAAI,IAAI,CAAC,IAAI,EAAE;gBACzC,IAAI,CAAC,UAAU,GAAG,MAAM,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,CAAC;aAC/C;iBAAM,IAAI,IAAI,CAAC,IAAI,IAAI,mBAAmB,IAAI,IAAI,CAAC,IAAI,EAAE;gBACxD,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC,IAAI,CAAC;aAC7B;SACF;QACD,IAAI,CAAC,IAAI,CAAC,UAAU,EAAE;YACpB,MAAM,IAAI,KAAK,CAAC,gCAAgC,CAAC,CAAC;SACnD;QACD,MAAM,UAAU,GAAG,MAAM,IAAI,CAAC,UAAU,CAAC,iBAAiB,EAAE,CAAC;QAC7D,MAAM,WAAW,GAAG,OAAO,CAAC,MAAM,CAChC,iBAAiB,EACjB,KAAK,EACL,KAAK,CAC4B,CAAC;QACpC,MAAM,OAAO,GAAG,IAAI,CAAC,iBAAiB,CAAC,OAAO,CAAC,CAAC;QAEhD,MAAM,cAAc,GAAG,OAAO,CAAC,MAAM,CACnC,iBAAiB,EACjB,KAAK,EACL,KAAK,CAC4B,CAAC;QACpC,KAAK,MAAM,UAAU,IAAI,OAAO,EAAE;YAChC,cAAc,CAAC,UAAU,CAAC,GAAG,CAC3B,GAAO,EACP,OAAiC,EACjC,QAAY,EACZ,QAAkB,EAClB,EAAE;gBACF,MAAM,CAAC,MAAM,EAAE,WAAW,EAAE,eAAe,CAAC,GAAG,WAAW,CACxD,UAAU,CACX,CAAC,KAAK,CAAC,WAAW,EAAE;oBACnB,GAAG;oBACH,CAAC,GAAiB,EAAE,QAAY,EAAE,EAAE;wBAClC,IAAI,CAAC,GAAG,EAAE;4BACR,2GAA2G;4BAC3G,QAAQ,GAAG,MAAM,CAAC,oBAAoB,CAAC,QAAQ,CAAC,QAAQ,EAAE;gCACxD,KAAK,EAAE,MAAM;6BACd,CAAC,CAAC;yBACJ;wBACD,QAAQ,CAAC,GAAG,EAAE,QAAQ,CAAC,CAAC;oBAC1B,CAAC;iBACF,CAAC,CAAC;gBACH,8DAA8D;gBAC9D,IAAI,gBAAiC,EAAE,YAAiB,CAAC;gBACzD,IAAI,qBAAS,EAAE,IAAI,OAAO,eAAe,KAAK,WAAW,EAAE;oBACzD,oCAAoC;oBACpC,gBAAgB,GAAG,IAAI,eAAe,EAAE,CAAC;iBAC1C;qBAAM;oBACL,gBAAgB,GAAG,IAAI,kCAAmB,EAAE,CAAC;iBAC9C;gBACD,IAAI,gBAAgB,EAAE;oBACpB,YAAY,GAAG,gBAAgB,CAAC,MAAM,CAAC;iBACxC;gBACD,IAAI,eAAe,GAAG,KAAK,CAAC;gBAE5B,MAAM,OAAO,GAAG,MAAM,CAAC,MAAM,CAAC,EAAE,EAAE,UAAU,CAAC,CAAC;gBAC9C,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE;oBACtC,OAAO,CAAC,GAAG,CAAC,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;iBAChC;gBAED,MAAM,oBAAoB,GAAG,IAAI,CAAC,QAAQ,IAAI,OAAO,CAAC;gBACtD,IAAI,WAAW,GAAG,IAAI,CAAC,WAAW,CAAC;gBACnC,IACE,CAAC,WAAW;oBACZ,OAAO,CAAC,OAAO;oBACf,OAAO,CAAC,OAAO,CAAC,2BAA2B,CAAC,EAC5C;oBACA,WAAW,GAAG,OAAO,CAAC,OAAO,CAAC,2BAA2B,CAAC,CAAC;iBAC5D;gBACD,IAAI,CAAC,WAAW,EAAE;oBAChB,eAAe,CAAC,IAAI,KAAK,CAAC,2BAA2B,CAAC,CAAC,CAAC;oBACxD,OAAO;iBACR;gBAED,IAAI,WAAW,CAAC;gBAChB,MAAM,KAAK,GAAG,WAAY,CAAC,KAAK,CAAC,cAAc,CAAC,CAAC;gBACjD,IAAI,KAAK,EAAE;oBACT,WAAW,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;oBACvB,WAAW,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;iBACxB;gBACD,IAAI,IAAI,CAAC,IAAI,EAAE;oBACb,WAAW,GAAG,IAAI,CAAC,IAAI,CAAC;iBACzB;qBAAM,IAAI,CAAC,WAAW,EAAE;oBACvB,WAAW,GAAG,GAAG,CAAC;iBACnB;gBAED,MAAM,eAAe,GAAa,EAAE,CAAC;gBACrC,IAAI,aAAa,GAAG,MAAM,CAAC,MAAM,CAAC;gBAClC,OAAO,aAAa,CAAC,IAAI,KAAK,EAAE,EAAE;oBAChC,eAAe,CAAC,OAAO,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC;oBAC5C,aAAa,GAAG,aAAa,CAAC,MAAM,CAAC;iBACtC;gBACD,MAAM,gBAAgB,GAAG,eAAe,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;gBACnD,MAAM,OAAO,GAAG,MAAM,CAAC,IAAI,CAAC;gBAE5B,IAAI,GAAW,CAAC;gBAChB,IAAI,IAAY,CAAC;gBACjB,IAAI,UAAkB,CAAC;gBAEvB,+EAA+E;gBAC/E,8BAA8B;gBAC9B,IAAI,IAAI,CAAC,QAAQ,KAAK,MAAM,EAAE;oBAC5B,iDAAiD;oBACjD,OAAO,CAAC,cAAc,CAAC,GAAG,kBAAkB,CAAC;oBAC7C,MAAM,cAAc,GAAG,MAAM,CAAC,mBAAmB,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC;oBACtE,MAAM,WAAW,GAAG,MAAM,CAAC,mBAAmB,CAAC,QAAQ;oBACrD,uCAAuC;oBACvC,cAAc,CACf,CAAC;oBACF,MAAM,UAAU,GAAG,uBAAS,CAC1B,WAAW,EACX,MAAM,CAAC,aAAa,EACpB,MAAM,CAAC,mBAAmB,CAAC,MAAM,CAClC,CAAC;oBACF,IAAI,CAAC,UAAU,EAAE;wBACf,MAAM,IAAI,KAAK,CACb,iCAAiC,IAAI,CAAC,SAAS,CAC7C,WAAW,CACZ,aAAa,MAAM,CAAC,IAAI,EAAE,CAC5B,CAAC;qBACH;oBACD,UAAU,GAAG,UAAU,CAAC,UAAU,CAAC;oBACnC,IAAI,GAAG,IAAI,CAAC,SAAS,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;oBACvC,GAAG,GAAG,GAAG,oBAAoB,MAAM,WAAW,IAAI,WAAW,IAAI,UAAU,CAAC,GAAG,CAAC,OAAO,CACrF,KAAK,EACL,EAAE,CACH,IAAI,UAAU,CAAC,WAAW,EAAE,CAAC;iBAC/B;qBAAM;oBACL,mCAAmC;oBACnC,OAAO,CAAC,cAAc,CAAC,GAAG,wBAAwB,CAAC;oBACnD,UAAU,GAAG,MAAM,CAAC;oBACpB,IAAI,GAAG,WAAW,CAAC;oBACnB,GAAG,GAAG,GAAG,oBAAoB,MAAM,WAAW,IAAI,WAAW,SAAS,gBAAgB,IAAI,OAAO,EAAE,CAAC;iBACrG;gBAED,MAAM,KAAK,GAAG,qBAAS,EAAE;oBACvB,CAAC,CAAC,oCAAoC;wBACpC,MAAM,CAAC,KAAK;oBACd,CAAC,CAAE,oBAAsC,CAAC;gBAC5C,MAAM,YAAY,GAAG;oBACnB,OAAO;oBACP,IAAI,EAAE,IAA0B;oBAChC,MAAM,EAAE,UAAU;oBAClB,MAAM,EAAE,YAAY;iBACrB,CAAC;gBACF,IACE,UAAU,KAAK,KAAK;oBACpB,UAAU,KAAK,QAAQ;oBACvB,UAAU,KAAK,MAAM,EACrB;oBACA,OAAO,YAAY,CAAC,MAAM,CAAC,CAAC;iBAC7B;gBACD,KAAK,CAAC,GAAG,EAAE,YAAY,CAAC;qBACrB,IAAI,CAAC,CAAC,QAAsC,EAAE,EAAE;oBAC/C,OAAO,OAAO,CAAC,GAAG,CAAC;wBACjB,OAAO,CAAC,OAAO,CAAC,QAAQ,CAAC,EAAE,CAAC;wBAC5B,QAAQ,CAAC,WAAW,EAAE;qBACvB,CAAC,CAAC;gBACL,CAAC,CAAC;qBACD,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,MAAM,CAAkC,EAAE,EAAE;oBACtD,4DAA4D;oBAC5D,0BAA0B;oBAC1B,IAAI,IAAI,CAAC,QAAQ,KAAK,MAAM,EAAE;wBAC5B,4BAA4B;wBAC5B,sEAAsE;wBACtE,MAAM,aAAa,GAAG,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;wBACvD,MAAM,QAAQ,GAAG,IAAI,CAAC,KAAK,CAAC,aAAa,CAAC,CAAC;wBAC3C,IAAI,CAAC,EAAE,EAAE;4BACP,MAAM,KAAK,GAAG,MAAM,CAAC,MAAM,CACzB,IAAI,KAAK,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC,SAAS,CAAC,CAAC,EACvC,QAAQ,CAAC,KAAK,CACf,CAAC;4BACF,MAAM,KAAK,CAAC;yBACb;wBACD,MAAM,OAAO,GAAG,MAAM,CAAC,oBAAoB,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC;wBACjE,MAAM,OAAO,GAAG,MAAM,CAAC,oBAAoB;6BACxC,MAAM,CAAC,OAAO,CAAC;6BACf,MAAM,EAAE,CAAC;wBACZ,eAAe,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;qBAChC;yBAAM;wBACL,mCAAmC;wBACnC,IAAI,CAAC,EAAE,EAAE;4BACP,MAAM,KAAK,GAAG,aAAa,CAAC,qBAAqB,CAAC,MAAM,CAAC,CAAC;4BAC1D,MAAM,KAAK,CAAC;yBACb;wBACD,eAAe,CAAC,IAAI,EAAE,IAAI,UAAU,CAAC,MAAM,CAAC,CAAC,CAAC;qBAC/C;gBACH,CAAC,CAAC;qBACD,KAAK,CAAC,CAAC,GAAU,EAAE,EAAE;oBACpB,IAAI,CAAC,eAAe,IAAI,GAAG,CAAC,IAAI,KAAK,YAAY,EAAE;wBACjD,eAAe,CAAC,GAAG,CAAC,CAAC;qBACtB;gBACH,CAAC,CAAC,CAAC;gBAEL,OAAO;oBACL,MAAM,EAAE,GAAG,EAAE;wBACX,IAAI,CAAC,gBAAgB,EAAE;4BACrB,OAAO,CAAC,IAAI,CACV,8EAA8E,CAC/E,CAAC;4BACF,OAAO;yBACR;wBACD,eAAe,GAAG,IAAI,CAAC;wBACvB,gBAAgB,CAAC,KAAK,EAAE,CAAC;oBAC3B,CAAC;iBACF,CAAC;YACJ,CAAC,CAAC;SACH;QACD,OAAO,cAAc,CAAC;IACxB,CAAC;;AAvZH,gCAwZC;AA9YgB,qBAAU,GAAG,IAAI,GAAG,EAAyB,CAAC;AAgZ/D;;;;;GAKG;AACH,SAAgB,GAAG,CAAC,OAA0B;IAC5C,OAAO,GAAG,MAAM,CAAC,MAAM,CAAC,EAAC,MAAM,EAAE,EAAE,EAAC,EAAE,OAAO,CAAC,CAAC;IAC/C,MAAM,OAAO,GAAG,IAAI,UAAU,CAAC,OAAO,CAAC,CAAC;IACxC,OAAO,IAAI,0CAAuB,CAAC,OAAO,CAAC,CAAC;AAC9C,CAAC;AAJD,kBAIC;AAED;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,SAAgB,aAAa,CAC3B,IAAkC,EAClC,QAA0B,EAC1B,UAAuB;IAEvB,IAAI,UAAU,IAAI,WAAW,IAAI,UAAU,EAAE;QAC3C,OAAO,GAAG,EAAE;YACV,MAAM,IAAI,KAAK,CACb,oHAAoH,CACrH,CAAC;QACJ,CAAC,CAAC;KACH;IACD,OAAO,6BAAc,CAAC,IAAI,EAAE,QAAQ,EAAE,UAAU,CAAC,CAAC;AACpD,CAAC;AAbD,sCAaC;AAGD,wDAAsD;AAEtD,4EAA4E;AAC5E,8EAA8E;AAC9E,8DAA8D;AAC9D,uEAAuE;AACvE,qCAAqC;AACrC,2EAA2E;AAC3E,qBAAqB;AACrB,MAAM,QAAQ,GAAG,MAAM,CAAC,OAAO,CAAC;AACxB,4BAAQ"}
...\ No newline at end of file ...\ No newline at end of file
......
...@@ -50,3 +50,4 @@ export { fallback }; ...@@ -50,3 +50,4 @@ export { fallback };
50 export { APICallback, GRPCCallResult, ServerStreamingCall, ClientStreamingCall, BiDiStreamingCall, UnaryCall, GRPCCall, GaxCall, CancellableStream, } from './apitypes'; 50 export { APICallback, GRPCCallResult, ServerStreamingCall, ClientStreamingCall, BiDiStreamingCall, UnaryCall, GRPCCall, GaxCall, CancellableStream, } from './apitypes';
51 export { ClientOptions, Descriptors, Callback, LROperation, PaginationCallback, PaginationResponse, } from './clientInterface'; 51 export { ClientOptions, Descriptors, Callback, LROperation, PaginationCallback, PaginationResponse, } from './clientInterface';
52 export { ServiceError, ChannelCredentials } from '@grpc/grpc-js'; 52 export { ServiceError, ChannelCredentials } from '@grpc/grpc-js';
53 +export { warn } from './warnings';
......
...@@ -82,4 +82,6 @@ const fallback = require("./fallback"); ...@@ -82,4 +82,6 @@ const fallback = require("./fallback");
82 exports.fallback = fallback; 82 exports.fallback = fallback;
83 var grpc_js_1 = require("@grpc/grpc-js"); 83 var grpc_js_1 = require("@grpc/grpc-js");
84 Object.defineProperty(exports, "ChannelCredentials", { enumerable: true, get: function () { return grpc_js_1.ChannelCredentials; } }); 84 Object.defineProperty(exports, "ChannelCredentials", { enumerable: true, get: function () { return grpc_js_1.ChannelCredentials; } });
85 +var warnings_1 = require("./warnings");
86 +Object.defineProperty(exports, "warn", { enumerable: true, get: function () { return warnings_1.warn; } });
85 //# sourceMappingURL=index.js.map 87 //# sourceMappingURL=index.js.map
...\ No newline at end of file ...\ No newline at end of file
......
1 -{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEH,sCAAsC;AAQ9B,oBAAI;AAPZ,iCAAqD;AACrD,mDAAmD;AAsDpB,8BAAS;AArDxC,yDAAyD;AAqD5C,4CAAgB;AApD7B,uDAAuD;AACvD,iDAAiD;AAwCzC,sCAAa;AAtCrB,2DAAkE;AAA1D,iHAAA,UAAU,OAAA;AAElB,+BAAuD;AAA3B,mGAAA,WAAW,OAAA;AACvC,iDAA8C;AAAtC,8GAAA,aAAa,OAAA;AACrB,2CAKsB;AAJpB,8GAAA,gBAAgB,OAAA;AAChB,mHAAA,qBAAqB,OAAA;AACrB,4GAAA,cAAc,OAAA;AACd,8GAAA,gBAAgB,OAAA;AAElB,6BAYe;AAVb,mGAAA,YAAY,OAAA;AAEZ,wGAAA,iBAAiB,OAAA;AACjB,mGAAA,YAAY,OAAA;AAEZ,yGAAA,kBAAkB,OAAA;AAClB,0GAAA,mBAAmB,OAAA;AACnB,4GAAA,qBAAqB,OAAA;AACrB,mHAAA,4BAA4B,OAAA;AAC5B,sHAAA,+BAA+B,OAAA;AAEjC,6CAA0C;AAAlC,0GAAA,WAAW,OAAA;AACnB,+BASgB;AARd,kGAAA,UAAU,OAAA;AAEV,4GAAA,oBAAoB,OAAA;AACpB,kGAAA,UAAU,OAAA;AAMZ,8DAAoE;AAA5D,wGAAA,SAAS,OAAA;AAAE,wGAAA,SAAS,OAAA;AAC5B,+CAA4C;AAApC,4GAAA,YAAY,OAAA;AACpB,mCAAgC;AAAxB,gGAAA,MAAM,OAAA;AACd,wDAAsD;AAA9C,uGAAA,UAAU,OAAA;AAGlB,SAAS,GAAG,CAAC,OAA0B;IACrC,OAAO,GAAG,MAAM,CAAC,MAAM,CAAC,EAAC,MAAM,EAAE,GAAG,CAAC,UAAU,EAAC,EAAE,OAAO,CAAC,CAAC;IAC3D,MAAM,OAAO,GAAG,IAAI,iBAAU,CAAC,OAAO,CAAC,CAAC;IACxC,OAAO,IAAI,gBAAgB,CAAC,uBAAuB,CAAC,OAAO,CAAC,CAAC;AAC/D,CAAC;AAKO,kBAAG;AAHX,GAAG,CAAC,eAAe,GAAG,gBAAgB,CAAC,eAAe,CAAC;AACvD,GAAG,CAAC,UAAU,GAAG,gBAAgB,CAAC,UAAU,CAAC;AAG7C,uDAAoD;AAA5C,oHAAA,gBAAgB,OAAA;AACxB,2CAAuC;AAA/B,uGAAA,SAAS,OAAA;AACJ,QAAA,wBAAwB,GAAG,iBAAU,CAAC,wBAAwB,CAAC;AAC/D,QAAA,OAAO,GAAG,OAAO,CAAC,oBAAoB,CAAC,CAAC,OAAO,CAAC;AAE7D,uCAAuC;AAC/B,4BAAQ;AAChB,wDAAsD;AAEtD,uCAAuC;AAC/B,4BAAQ;AAuBhB,yCAA+D;AAAzC,6GAAA,kBAAkB,OAAA"}
...\ No newline at end of file ...\ No newline at end of file
1 +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEH,sCAAsC;AAQ9B,oBAAI;AAPZ,iCAAqD;AACrD,mDAAmD;AAsDpB,8BAAS;AArDxC,yDAAyD;AAqD5C,4CAAgB;AApD7B,uDAAuD;AACvD,iDAAiD;AAwCzC,sCAAa;AAtCrB,2DAAkE;AAA1D,iHAAA,UAAU,OAAA;AAElB,+BAAuD;AAA3B,mGAAA,WAAW,OAAA;AACvC,iDAA8C;AAAtC,8GAAA,aAAa,OAAA;AACrB,2CAKsB;AAJpB,8GAAA,gBAAgB,OAAA;AAChB,mHAAA,qBAAqB,OAAA;AACrB,4GAAA,cAAc,OAAA;AACd,8GAAA,gBAAgB,OAAA;AAElB,6BAYe;AAVb,mGAAA,YAAY,OAAA;AAEZ,wGAAA,iBAAiB,OAAA;AACjB,mGAAA,YAAY,OAAA;AAEZ,yGAAA,kBAAkB,OAAA;AAClB,0GAAA,mBAAmB,OAAA;AACnB,4GAAA,qBAAqB,OAAA;AACrB,mHAAA,4BAA4B,OAAA;AAC5B,sHAAA,+BAA+B,OAAA;AAEjC,6CAA0C;AAAlC,0GAAA,WAAW,OAAA;AACnB,+BASgB;AARd,kGAAA,UAAU,OAAA;AAEV,4GAAA,oBAAoB,OAAA;AACpB,kGAAA,UAAU,OAAA;AAMZ,8DAAoE;AAA5D,wGAAA,SAAS,OAAA;AAAE,wGAAA,SAAS,OAAA;AAC5B,+CAA4C;AAApC,4GAAA,YAAY,OAAA;AACpB,mCAAgC;AAAxB,gGAAA,MAAM,OAAA;AACd,wDAAsD;AAA9C,uGAAA,UAAU,OAAA;AAGlB,SAAS,GAAG,CAAC,OAA0B;IACrC,OAAO,GAAG,MAAM,CAAC,MAAM,CAAC,EAAC,MAAM,EAAE,GAAG,CAAC,UAAU,EAAC,EAAE,OAAO,CAAC,CAAC;IAC3D,MAAM,OAAO,GAAG,IAAI,iBAAU,CAAC,OAAO,CAAC,CAAC;IACxC,OAAO,IAAI,gBAAgB,CAAC,uBAAuB,CAAC,OAAO,CAAC,CAAC;AAC/D,CAAC;AAKO,kBAAG;AAHX,GAAG,CAAC,eAAe,GAAG,gBAAgB,CAAC,eAAe,CAAC;AACvD,GAAG,CAAC,UAAU,GAAG,gBAAgB,CAAC,UAAU,CAAC;AAG7C,uDAAoD;AAA5C,oHAAA,gBAAgB,OAAA;AACxB,2CAAuC;AAA/B,uGAAA,SAAS,OAAA;AACJ,QAAA,wBAAwB,GAAG,iBAAU,CAAC,wBAAwB,CAAC;AAC/D,QAAA,OAAO,GAAG,OAAO,CAAC,oBAAoB,CAAC,CAAC,OAAO,CAAC;AAE7D,uCAAuC;AAC/B,4BAAQ;AAChB,wDAAsD;AAEtD,uCAAuC;AAC/B,4BAAQ;AAuBhB,yCAA+D;AAAzC,6GAAA,kBAAkB,OAAA;AACxC,uCAAgC;AAAxB,gGAAA,IAAI,OAAA"}
...\ No newline at end of file ...\ No newline at end of file
......
...@@ -13,4 +13,4 @@ ...@@ -13,4 +13,4 @@
13 * See the License for the specific language governing permissions and 13 * See the License for the specific language governing permissions and
14 * limitations under the License. 14 * limitations under the License.
15 */ 15 */
16 -export declare function warn(code: string, message: string): void; 16 +export declare function warn(code: string, message: string, warnType?: string): void;
......
...@@ -18,7 +18,8 @@ Object.defineProperty(exports, "__esModule", { value: true }); ...@@ -18,7 +18,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
18 exports.warn = void 0; 18 exports.warn = void 0;
19 const isbrowser_1 = require("./isbrowser"); 19 const isbrowser_1 = require("./isbrowser");
20 const emittedWarnings = new Set(); 20 const emittedWarnings = new Set();
21 -function warn(code, message) { 21 +// warnType is the type of warning (e.g. 'DeprecationWarning', 'ExperimentalWarning', etc.)
22 +function warn(code, message, warnType) {
22 // Only show a given warning once 23 // Only show a given warning once
23 if (emittedWarnings.has(code)) { 24 if (emittedWarnings.has(code)) {
24 return; 25 return;
...@@ -27,6 +28,11 @@ function warn(code, message) { ...@@ -27,6 +28,11 @@ function warn(code, message) {
27 if (isbrowser_1.isBrowser()) { 28 if (isbrowser_1.isBrowser()) {
28 console.warn(message); 29 console.warn(message);
29 } 30 }
31 + else if (typeof warnType !== 'undefined') {
32 + process.emitWarning(message, {
33 + type: warnType,
34 + });
35 + }
30 else { 36 else {
31 process.emitWarning(message); 37 process.emitWarning(message);
32 } 38 }
......
1 -{"version":3,"file":"warnings.js","sourceRoot":"","sources":["../../src/warnings.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEH,2CAAsC;AAEtC,MAAM,eAAe,GAAG,IAAI,GAAG,EAAU,CAAC;AAE1C,SAAgB,IAAI,CAAC,IAAY,EAAE,OAAe;IAChD,iCAAiC;IACjC,IAAI,eAAe,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE;QAC7B,OAAO;KACR;IACD,eAAe,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;IAE1B,IAAI,qBAAS,EAAE,EAAE;QACf,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;KACvB;SAAM;QACL,OAAO,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;KAC9B;AACH,CAAC;AAZD,oBAYC"}
...\ No newline at end of file ...\ No newline at end of file
1 +{"version":3,"file":"warnings.js","sourceRoot":"","sources":["../../src/warnings.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEH,2CAAsC;AAEtC,MAAM,eAAe,GAAG,IAAI,GAAG,EAAU,CAAC;AAE1C,2FAA2F;AAC3F,SAAgB,IAAI,CAAC,IAAY,EAAE,OAAe,EAAE,QAAiB;IACnE,iCAAiC;IACjC,IAAI,eAAe,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE;QAC7B,OAAO;KACR;IACD,eAAe,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;IAE1B,IAAI,qBAAS,EAAE,EAAE;QACf,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;KACvB;SAAM,IAAI,OAAO,QAAQ,KAAK,WAAW,EAAE;QAC1C,OAAO,CAAC,WAAW,CAAC,OAAO,EAAE;YAC3B,IAAI,EAAE,QAAQ;SACf,CAAC,CAAC;KACJ;SAAM;QACL,OAAO,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;KAC9B;AACH,CAAC;AAhBD,oBAgBC"}
...\ No newline at end of file ...\ No newline at end of file
......
1 { 1 {
2 "_from": "google-gax@^2.12.0", 2 "_from": "google-gax@^2.12.0",
3 - "_id": "google-gax@2.13.0", 3 + "_id": "google-gax@2.14.1",
4 "_inBundle": false, 4 "_inBundle": false,
5 - "_integrity": "sha512-aKNJy2+Vv2I7flyNYbwpq0aYBHp6Qv32HZn+wr6ZhZ8xlSCLS9K9k7izfh2nd1rCJQcsqB6KMxHV0Vwny6Rc1g==", 5 + "_integrity": "sha512-I5RDEN7MEptrCxeHX3ht7nKFGfyjgYX4hQKI9eVMBohMzVbFSwWUndo0CcKXu8es7NhB4gt2XYLm1AHkXhtHpA==",
6 "_location": "/google-gax", 6 "_location": "/google-gax",
7 "_phantomChildren": {}, 7 "_phantomChildren": {},
8 "_requested": { 8 "_requested": {
...@@ -18,8 +18,8 @@ ...@@ -18,8 +18,8 @@
18 "_requiredBy": [ 18 "_requiredBy": [
19 "/@google-cloud/speech" 19 "/@google-cloud/speech"
20 ], 20 ],
21 - "_resolved": "https://registry.npmjs.org/google-gax/-/google-gax-2.13.0.tgz", 21 + "_resolved": "https://registry.npmjs.org/google-gax/-/google-gax-2.14.1.tgz",
22 - "_shasum": "404bb9df62c3a0a414e2f5339eda4d751f540304", 22 + "_shasum": "74885c5d9f01db412917fc49bbf20c4884828d36",
23 "_spec": "google-gax@^2.12.0", 23 "_spec": "google-gax@^2.12.0",
24 "_where": "C:\\Users\\1000c\\이것저것\\옾소\\Voicoding\\node_modules\\@google-cloud\\speech", 24 "_where": "C:\\Users\\1000c\\이것저것\\옾소\\Voicoding\\node_modules\\@google-cloud\\speech",
25 "author": { 25 "author": {
...@@ -57,7 +57,7 @@ ...@@ -57,7 +57,7 @@
57 "@types/fs-extra": "^8.0.1", 57 "@types/fs-extra": "^8.0.1",
58 "@types/mocha": "^8.0.0", 58 "@types/mocha": "^8.0.0",
59 "@types/ncp": "^2.0.1", 59 "@types/ncp": "^2.0.1",
60 - "@types/node": "^10.3.2", 60 + "@types/node": ">=15.6.0",
61 "@types/node-fetch": "^2.5.4", 61 "@types/node-fetch": "^2.5.4",
62 "@types/object-hash": "^2.1.0", 62 "@types/object-hash": "^2.1.0",
63 "@types/proxyquire": "^1.3.28", 63 "@types/proxyquire": "^1.3.28",
...@@ -91,7 +91,7 @@ ...@@ -91,7 +91,7 @@
91 "pumpify": "^2.0.0", 91 "pumpify": "^2.0.0",
92 "puppeteer": "^8.0.0", 92 "puppeteer": "^8.0.0",
93 "rimraf": "^3.0.0", 93 "rimraf": "^3.0.0",
94 - "sinon": "^10.0.0", 94 + "sinon": "^11.0.0",
95 "stream-events": "^1.0.4", 95 "stream-events": "^1.0.4",
96 "ts-loader": "^8.0.0", 96 "ts-loader": "^8.0.0",
97 "typescript": "^3.8.3", 97 "typescript": "^3.8.3",
...@@ -144,5 +144,5 @@ ...@@ -144,5 +144,5 @@
144 "update-protos": "node ./build/tools/listProtos.js" 144 "update-protos": "node ./build/tools/listProtos.js"
145 }, 145 },
146 "types": "build/src/index.d.ts", 146 "types": "build/src/index.d.ts",
147 - "version": "2.13.0" 147 + "version": "2.14.1"
148 } 148 }
......
1 { 1 {
2 - "_from": "inherits@^2.0.3", 2 + "_from": "inherits@~2.0.1",
3 "_id": "inherits@2.0.4", 3 "_id": "inherits@2.0.4",
4 "_inBundle": false, 4 "_inBundle": false,
5 "_integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", 5 "_integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",
...@@ -8,22 +8,22 @@ ...@@ -8,22 +8,22 @@
8 "_requested": { 8 "_requested": {
9 "type": "range", 9 "type": "range",
10 "registry": true, 10 "registry": true,
11 - "raw": "inherits@^2.0.3", 11 + "raw": "inherits@~2.0.1",
12 "name": "inherits", 12 "name": "inherits",
13 "escapedName": "inherits", 13 "escapedName": "inherits",
14 - "rawSpec": "^2.0.3", 14 + "rawSpec": "~2.0.1",
15 "saveSpec": null, 15 "saveSpec": null,
16 - "fetchSpec": "^2.0.3" 16 + "fetchSpec": "~2.0.1"
17 }, 17 },
18 "_requiredBy": [ 18 "_requiredBy": [
19 - "/duplexify", 19 + "/concat-stream",
20 - "/pumpify", 20 + "/concat-stream/readable-stream",
21 "/readable-stream" 21 "/readable-stream"
22 ], 22 ],
23 "_resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", 23 "_resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
24 "_shasum": "0fa2c64f932917c3433a0ded55363aae37416b7c", 24 "_shasum": "0fa2c64f932917c3433a0ded55363aae37416b7c",
25 - "_spec": "inherits@^2.0.3", 25 + "_spec": "inherits@~2.0.1",
26 - "_where": "C:\\Users\\1000c\\이것저것\\옾소\\Voicoding\\node_modules\\duplexify", 26 + "_where": "C:\\Users\\1000c\\이것저것\\옾소\\Voicoding\\node_modules\\readable-stream",
27 "browser": "./inherits_browser.js", 27 "browser": "./inherits_browser.js",
28 "bugs": { 28 "bugs": {
29 "url": "https://github.com/isaacs/inherits/issues" 29 "url": "https://github.com/isaacs/inherits/issues"
......
1 +
2 +# isarray
3 +
4 +`Array#isArray` for older browsers.
5 +
6 +## Usage
7 +
8 +```js
9 +var isArray = require('isarray');
10 +
11 +console.log(isArray([])); // => true
12 +console.log(isArray({})); // => false
13 +```
14 +
15 +## Installation
16 +
17 +With [npm](http://npmjs.org) do
18 +
19 +```bash
20 +$ npm install isarray
21 +```
22 +
23 +Then bundle for the browser with
24 +[browserify](https://github.com/substack/browserify).
25 +
26 +With [component](http://component.io) do
27 +
28 +```bash
29 +$ component install juliangruber/isarray
30 +```
31 +
32 +## License
33 +
34 +(MIT)
35 +
36 +Copyright (c) 2013 Julian Gruber &lt;julian@juliangruber.com&gt;
37 +
38 +Permission is hereby granted, free of charge, to any person obtaining a copy of
39 +this software and associated documentation files (the "Software"), to deal in
40 +the Software without restriction, including without limitation the rights to
41 +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
42 +of the Software, and to permit persons to whom the Software is furnished to do
43 +so, subject to the following conditions:
44 +
45 +The above copyright notice and this permission notice shall be included in all
46 +copies or substantial portions of the Software.
47 +
48 +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
49 +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
50 +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
51 +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
52 +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
53 +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
54 +SOFTWARE.
1 +
2 +/**
3 + * Require the given path.
4 + *
5 + * @param {String} path
6 + * @return {Object} exports
7 + * @api public
8 + */
9 +
10 +function require(path, parent, orig) {
11 + var resolved = require.resolve(path);
12 +
13 + // lookup failed
14 + if (null == resolved) {
15 + orig = orig || path;
16 + parent = parent || 'root';
17 + var err = new Error('Failed to require "' + orig + '" from "' + parent + '"');
18 + err.path = orig;
19 + err.parent = parent;
20 + err.require = true;
21 + throw err;
22 + }
23 +
24 + var module = require.modules[resolved];
25 +
26 + // perform real require()
27 + // by invoking the module's
28 + // registered function
29 + if (!module.exports) {
30 + module.exports = {};
31 + module.client = module.component = true;
32 + module.call(this, module.exports, require.relative(resolved), module);
33 + }
34 +
35 + return module.exports;
36 +}
37 +
38 +/**
39 + * Registered modules.
40 + */
41 +
42 +require.modules = {};
43 +
44 +/**
45 + * Registered aliases.
46 + */
47 +
48 +require.aliases = {};
49 +
50 +/**
51 + * Resolve `path`.
52 + *
53 + * Lookup:
54 + *
55 + * - PATH/index.js
56 + * - PATH.js
57 + * - PATH
58 + *
59 + * @param {String} path
60 + * @return {String} path or null
61 + * @api private
62 + */
63 +
64 +require.resolve = function(path) {
65 + if (path.charAt(0) === '/') path = path.slice(1);
66 + var index = path + '/index.js';
67 +
68 + var paths = [
69 + path,
70 + path + '.js',
71 + path + '.json',
72 + path + '/index.js',
73 + path + '/index.json'
74 + ];
75 +
76 + for (var i = 0; i < paths.length; i++) {
77 + var path = paths[i];
78 + if (require.modules.hasOwnProperty(path)) return path;
79 + }
80 +
81 + if (require.aliases.hasOwnProperty(index)) {
82 + return require.aliases[index];
83 + }
84 +};
85 +
86 +/**
87 + * Normalize `path` relative to the current path.
88 + *
89 + * @param {String} curr
90 + * @param {String} path
91 + * @return {String}
92 + * @api private
93 + */
94 +
95 +require.normalize = function(curr, path) {
96 + var segs = [];
97 +
98 + if ('.' != path.charAt(0)) return path;
99 +
100 + curr = curr.split('/');
101 + path = path.split('/');
102 +
103 + for (var i = 0; i < path.length; ++i) {
104 + if ('..' == path[i]) {
105 + curr.pop();
106 + } else if ('.' != path[i] && '' != path[i]) {
107 + segs.push(path[i]);
108 + }
109 + }
110 +
111 + return curr.concat(segs).join('/');
112 +};
113 +
114 +/**
115 + * Register module at `path` with callback `definition`.
116 + *
117 + * @param {String} path
118 + * @param {Function} definition
119 + * @api private
120 + */
121 +
122 +require.register = function(path, definition) {
123 + require.modules[path] = definition;
124 +};
125 +
126 +/**
127 + * Alias a module definition.
128 + *
129 + * @param {String} from
130 + * @param {String} to
131 + * @api private
132 + */
133 +
134 +require.alias = function(from, to) {
135 + if (!require.modules.hasOwnProperty(from)) {
136 + throw new Error('Failed to alias "' + from + '", it does not exist');
137 + }
138 + require.aliases[to] = from;
139 +};
140 +
141 +/**
142 + * Return a require function relative to the `parent` path.
143 + *
144 + * @param {String} parent
145 + * @return {Function}
146 + * @api private
147 + */
148 +
149 +require.relative = function(parent) {
150 + var p = require.normalize(parent, '..');
151 +
152 + /**
153 + * lastIndexOf helper.
154 + */
155 +
156 + function lastIndexOf(arr, obj) {
157 + var i = arr.length;
158 + while (i--) {
159 + if (arr[i] === obj) return i;
160 + }
161 + return -1;
162 + }
163 +
164 + /**
165 + * The relative require() itself.
166 + */
167 +
168 + function localRequire(path) {
169 + var resolved = localRequire.resolve(path);
170 + return require(resolved, parent, path);
171 + }
172 +
173 + /**
174 + * Resolve relative to the parent.
175 + */
176 +
177 + localRequire.resolve = function(path) {
178 + var c = path.charAt(0);
179 + if ('/' == c) return path.slice(1);
180 + if ('.' == c) return require.normalize(p, path);
181 +
182 + // resolve deps by returning
183 + // the dep in the nearest "deps"
184 + // directory
185 + var segs = parent.split('/');
186 + var i = lastIndexOf(segs, 'deps') + 1;
187 + if (!i) i = 0;
188 + path = segs.slice(0, i + 1).join('/') + '/deps/' + path;
189 + return path;
190 + };
191 +
192 + /**
193 + * Check if module is defined at `path`.
194 + */
195 +
196 + localRequire.exists = function(path) {
197 + return require.modules.hasOwnProperty(localRequire.resolve(path));
198 + };
199 +
200 + return localRequire;
201 +};
202 +require.register("isarray/index.js", function(exports, require, module){
203 +module.exports = Array.isArray || function (arr) {
204 + return Object.prototype.toString.call(arr) == '[object Array]';
205 +};
206 +
207 +});
208 +require.alias("isarray/index.js", "isarray/index.js");
209 +
1 +{
2 + "name" : "isarray",
3 + "description" : "Array#isArray for older browsers",
4 + "version" : "0.0.1",
5 + "repository" : "juliangruber/isarray",
6 + "homepage": "https://github.com/juliangruber/isarray",
7 + "main" : "index.js",
8 + "scripts" : [
9 + "index.js"
10 + ],
11 + "dependencies" : {},
12 + "keywords": ["browser","isarray","array"],
13 + "author": {
14 + "name": "Julian Gruber",
15 + "email": "mail@juliangruber.com",
16 + "url": "http://juliangruber.com"
17 + },
18 + "license": "MIT"
19 +}
1 +module.exports = Array.isArray || function (arr) {
2 + return Object.prototype.toString.call(arr) == '[object Array]';
3 +};
1 +{
2 + "_from": "isarray@0.0.1",
3 + "_id": "isarray@0.0.1",
4 + "_inBundle": false,
5 + "_integrity": "sha1-ihis/Kmo9Bd+Cav8YDiTmwXR7t8=",
6 + "_location": "/isarray",
7 + "_phantomChildren": {},
8 + "_requested": {
9 + "type": "version",
10 + "registry": true,
11 + "raw": "isarray@0.0.1",
12 + "name": "isarray",
13 + "escapedName": "isarray",
14 + "rawSpec": "0.0.1",
15 + "saveSpec": null,
16 + "fetchSpec": "0.0.1"
17 + },
18 + "_requiredBy": [
19 + "/readable-stream"
20 + ],
21 + "_resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz",
22 + "_shasum": "8a18acfca9a8f4177e09abfc6038939b05d1eedf",
23 + "_spec": "isarray@0.0.1",
24 + "_where": "C:\\Users\\1000c\\이것저것\\옾소\\Voicoding\\node_modules\\readable-stream",
25 + "author": {
26 + "name": "Julian Gruber",
27 + "email": "mail@juliangruber.com",
28 + "url": "http://juliangruber.com"
29 + },
30 + "bugs": {
31 + "url": "https://github.com/juliangruber/isarray/issues"
32 + },
33 + "bundleDependencies": false,
34 + "dependencies": {},
35 + "deprecated": false,
36 + "description": "Array#isArray for older browsers",
37 + "devDependencies": {
38 + "tap": "*"
39 + },
40 + "homepage": "https://github.com/juliangruber/isarray",
41 + "keywords": [
42 + "browser",
43 + "isarray",
44 + "array"
45 + ],
46 + "license": "MIT",
47 + "main": "index.js",
48 + "name": "isarray",
49 + "repository": {
50 + "type": "git",
51 + "url": "git://github.com/juliangruber/isarray.git"
52 + },
53 + "scripts": {
54 + "test": "tap test/*.js"
55 + },
56 + "version": "0.0.1"
57 +}
1 +language: node_js
2 +node_js:
3 + - "0.8"
4 + - "0.10"
5 + - "0.12"
6 + - "iojs"
7 +before_install:
8 + - npm install -g npm@~1.4.6
1 +This software is released under the MIT license:
2 +
3 +Permission is hereby granted, free of charge, to any person obtaining a copy of
4 +this software and associated documentation files (the "Software"), to deal in
5 +the Software without restriction, including without limitation the rights to
6 +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
7 +the Software, and to permit persons to whom the Software is furnished to do so,
8 +subject to the following conditions:
9 +
10 +The above copyright notice and this permission notice shall be included in all
11 +copies or substantial portions of the Software.
12 +
13 +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
15 +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
16 +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
17 +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
18 +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
1 +var argv = require('../')(process.argv.slice(2));
2 +console.log(argv);
1 +module.exports = function (args, opts) {
2 + if (!opts) opts = {};
3 +
4 + var flags = { bools : {}, strings : {}, unknownFn: null };
5 +
6 + if (typeof opts['unknown'] === 'function') {
7 + flags.unknownFn = opts['unknown'];
8 + }
9 +
10 + if (typeof opts['boolean'] === 'boolean' && opts['boolean']) {
11 + flags.allBools = true;
12 + } else {
13 + [].concat(opts['boolean']).filter(Boolean).forEach(function (key) {
14 + flags.bools[key] = true;
15 + });
16 + }
17 +
18 + var aliases = {};
19 + Object.keys(opts.alias || {}).forEach(function (key) {
20 + aliases[key] = [].concat(opts.alias[key]);
21 + aliases[key].forEach(function (x) {
22 + aliases[x] = [key].concat(aliases[key].filter(function (y) {
23 + return x !== y;
24 + }));
25 + });
26 + });
27 +
28 + [].concat(opts.string).filter(Boolean).forEach(function (key) {
29 + flags.strings[key] = true;
30 + if (aliases[key]) {
31 + flags.strings[aliases[key]] = true;
32 + }
33 + });
34 +
35 + var defaults = opts['default'] || {};
36 +
37 + var argv = { _ : [] };
38 + Object.keys(flags.bools).forEach(function (key) {
39 + setArg(key, defaults[key] === undefined ? false : defaults[key]);
40 + });
41 +
42 + var notFlags = [];
43 +
44 + if (args.indexOf('--') !== -1) {
45 + notFlags = args.slice(args.indexOf('--')+1);
46 + args = args.slice(0, args.indexOf('--'));
47 + }
48 +
49 + function argDefined(key, arg) {
50 + return (flags.allBools && /^--[^=]+$/.test(arg)) ||
51 + flags.strings[key] || flags.bools[key] || aliases[key];
52 + }
53 +
54 + function setArg (key, val, arg) {
55 + if (arg && flags.unknownFn && !argDefined(key, arg)) {
56 + if (flags.unknownFn(arg) === false) return;
57 + }
58 +
59 + var value = !flags.strings[key] && isNumber(val)
60 + ? Number(val) : val
61 + ;
62 + setKey(argv, key.split('.'), value);
63 +
64 + (aliases[key] || []).forEach(function (x) {
65 + setKey(argv, x.split('.'), value);
66 + });
67 + }
68 +
69 + function setKey (obj, keys, value) {
70 + var o = obj;
71 + for (var i = 0; i < keys.length-1; i++) {
72 + var key = keys[i];
73 + if (key === '__proto__') return;
74 + if (o[key] === undefined) o[key] = {};
75 + if (o[key] === Object.prototype || o[key] === Number.prototype
76 + || o[key] === String.prototype) o[key] = {};
77 + if (o[key] === Array.prototype) o[key] = [];
78 + o = o[key];
79 + }
80 +
81 + var key = keys[keys.length - 1];
82 + if (key === '__proto__') return;
83 + if (o === Object.prototype || o === Number.prototype
84 + || o === String.prototype) o = {};
85 + if (o === Array.prototype) o = [];
86 + if (o[key] === undefined || flags.bools[key] || typeof o[key] === 'boolean') {
87 + o[key] = value;
88 + }
89 + else if (Array.isArray(o[key])) {
90 + o[key].push(value);
91 + }
92 + else {
93 + o[key] = [ o[key], value ];
94 + }
95 + }
96 +
97 + function aliasIsBoolean(key) {
98 + return aliases[key].some(function (x) {
99 + return flags.bools[x];
100 + });
101 + }
102 +
103 + for (var i = 0; i < args.length; i++) {
104 + var arg = args[i];
105 +
106 + if (/^--.+=/.test(arg)) {
107 + // Using [\s\S] instead of . because js doesn't support the
108 + // 'dotall' regex modifier. See:
109 + // http://stackoverflow.com/a/1068308/13216
110 + var m = arg.match(/^--([^=]+)=([\s\S]*)$/);
111 + var key = m[1];
112 + var value = m[2];
113 + if (flags.bools[key]) {
114 + value = value !== 'false';
115 + }
116 + setArg(key, value, arg);
117 + }
118 + else if (/^--no-.+/.test(arg)) {
119 + var key = arg.match(/^--no-(.+)/)[1];
120 + setArg(key, false, arg);
121 + }
122 + else if (/^--.+/.test(arg)) {
123 + var key = arg.match(/^--(.+)/)[1];
124 + var next = args[i + 1];
125 + if (next !== undefined && !/^-/.test(next)
126 + && !flags.bools[key]
127 + && !flags.allBools
128 + && (aliases[key] ? !aliasIsBoolean(key) : true)) {
129 + setArg(key, next, arg);
130 + i++;
131 + }
132 + else if (/^(true|false)$/.test(next)) {
133 + setArg(key, next === 'true', arg);
134 + i++;
135 + }
136 + else {
137 + setArg(key, flags.strings[key] ? '' : true, arg);
138 + }
139 + }
140 + else if (/^-[^-]+/.test(arg)) {
141 + var letters = arg.slice(1,-1).split('');
142 +
143 + var broken = false;
144 + for (var j = 0; j < letters.length; j++) {
145 + var next = arg.slice(j+2);
146 +
147 + if (next === '-') {
148 + setArg(letters[j], next, arg)
149 + continue;
150 + }
151 +
152 + if (/[A-Za-z]/.test(letters[j]) && /=/.test(next)) {
153 + setArg(letters[j], next.split('=')[1], arg);
154 + broken = true;
155 + break;
156 + }
157 +
158 + if (/[A-Za-z]/.test(letters[j])
159 + && /-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) {
160 + setArg(letters[j], next, arg);
161 + broken = true;
162 + break;
163 + }
164 +
165 + if (letters[j+1] && letters[j+1].match(/\W/)) {
166 + setArg(letters[j], arg.slice(j+2), arg);
167 + broken = true;
168 + break;
169 + }
170 + else {
171 + setArg(letters[j], flags.strings[letters[j]] ? '' : true, arg);
172 + }
173 + }
174 +
175 + var key = arg.slice(-1)[0];
176 + if (!broken && key !== '-') {
177 + if (args[i+1] && !/^(-|--)[^-]/.test(args[i+1])
178 + && !flags.bools[key]
179 + && (aliases[key] ? !aliasIsBoolean(key) : true)) {
180 + setArg(key, args[i+1], arg);
181 + i++;
182 + }
183 + else if (args[i+1] && /^(true|false)$/.test(args[i+1])) {
184 + setArg(key, args[i+1] === 'true', arg);
185 + i++;
186 + }
187 + else {
188 + setArg(key, flags.strings[key] ? '' : true, arg);
189 + }
190 + }
191 + }
192 + else {
193 + if (!flags.unknownFn || flags.unknownFn(arg) !== false) {
194 + argv._.push(
195 + flags.strings['_'] || !isNumber(arg) ? arg : Number(arg)
196 + );
197 + }
198 + if (opts.stopEarly) {
199 + argv._.push.apply(argv._, args.slice(i + 1));
200 + break;
201 + }
202 + }
203 + }
204 +
205 + Object.keys(defaults).forEach(function (key) {
206 + if (!hasKey(argv, key.split('.'))) {
207 + setKey(argv, key.split('.'), defaults[key]);
208 +
209 + (aliases[key] || []).forEach(function (x) {
210 + setKey(argv, x.split('.'), defaults[key]);
211 + });
212 + }
213 + });
214 +
215 + if (opts['--']) {
216 + argv['--'] = new Array();
217 + notFlags.forEach(function(key) {
218 + argv['--'].push(key);
219 + });
220 + }
221 + else {
222 + notFlags.forEach(function(key) {
223 + argv._.push(key);
224 + });
225 + }
226 +
227 + return argv;
228 +};
229 +
230 +function hasKey (obj, keys) {
231 + var o = obj;
232 + keys.slice(0,-1).forEach(function (key) {
233 + o = (o[key] || {});
234 + });
235 +
236 + var key = keys[keys.length - 1];
237 + return key in o;
238 +}
239 +
240 +function isNumber (x) {
241 + if (typeof x === 'number') return true;
242 + if (/^0x[0-9a-f]+$/i.test(x)) return true;
243 + return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x);
244 +}
245 +
1 +{
2 + "_from": "minimist@^1.2.5",
3 + "_id": "minimist@1.2.5",
4 + "_inBundle": false,
5 + "_integrity": "sha512-FM9nNUYrRBAELZQT3xeZQ7fmMOBg6nWNmJKTcgsJeaLstP/UODVpGsr5OhXhhXg6f+qtJ8uiZ+PUxkDWcgIXLw==",
6 + "_location": "/minimist",
7 + "_phantomChildren": {},
8 + "_requested": {
9 + "type": "range",
10 + "registry": true,
11 + "raw": "minimist@^1.2.5",
12 + "name": "minimist",
13 + "escapedName": "minimist",
14 + "rawSpec": "^1.2.5",
15 + "saveSpec": null,
16 + "fetchSpec": "^1.2.5"
17 + },
18 + "_requiredBy": [
19 + "/mkdirp"
20 + ],
21 + "_resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.5.tgz",
22 + "_shasum": "67d66014b66a6a8aaa0c083c5fd58df4e4e97602",
23 + "_spec": "minimist@^1.2.5",
24 + "_where": "C:\\Users\\1000c\\이것저것\\옾소\\Voicoding\\node_modules\\mkdirp",
25 + "author": {
26 + "name": "James Halliday",
27 + "email": "mail@substack.net",
28 + "url": "http://substack.net"
29 + },
30 + "bugs": {
31 + "url": "https://github.com/substack/minimist/issues"
32 + },
33 + "bundleDependencies": false,
34 + "deprecated": false,
35 + "description": "parse argument options",
36 + "devDependencies": {
37 + "covert": "^1.0.0",
38 + "tap": "~0.4.0",
39 + "tape": "^3.5.0"
40 + },
41 + "homepage": "https://github.com/substack/minimist",
42 + "keywords": [
43 + "argv",
44 + "getopt",
45 + "parser",
46 + "optimist"
47 + ],
48 + "license": "MIT",
49 + "main": "index.js",
50 + "name": "minimist",
51 + "repository": {
52 + "type": "git",
53 + "url": "git://github.com/substack/minimist.git"
54 + },
55 + "scripts": {
56 + "coverage": "covert test/*.js",
57 + "test": "tap test/*.js"
58 + },
59 + "testling": {
60 + "files": "test/*.js",
61 + "browsers": [
62 + "ie/6..latest",
63 + "ff/5",
64 + "firefox/latest",
65 + "chrome/10",
66 + "chrome/latest",
67 + "safari/5.1",
68 + "safari/latest",
69 + "opera/12"
70 + ]
71 + },
72 + "version": "1.2.5"
73 +}
1 +# minimist
2 +
3 +parse argument options
4 +
5 +This module is the guts of optimist's argument parser without all the
6 +fanciful decoration.
7 +
8 +# example
9 +
10 +``` js
11 +var argv = require('minimist')(process.argv.slice(2));
12 +console.log(argv);
13 +```
14 +
15 +```
16 +$ node example/parse.js -a beep -b boop
17 +{ _: [], a: 'beep', b: 'boop' }
18 +```
19 +
20 +```
21 +$ node example/parse.js -x 3 -y 4 -n5 -abc --beep=boop foo bar baz
22 +{ _: [ 'foo', 'bar', 'baz' ],
23 + x: 3,
24 + y: 4,
25 + n: 5,
26 + a: true,
27 + b: true,
28 + c: true,
29 + beep: 'boop' }
30 +```
31 +
32 +# security
33 +
34 +Previous versions had a prototype pollution bug that could cause privilege
35 +escalation in some circumstances when handling untrusted user input.
36 +
37 +Please use version 1.2.3 or later: https://snyk.io/vuln/SNYK-JS-MINIMIST-559764
38 +
39 +# methods
40 +
41 +``` js
42 +var parseArgs = require('minimist')
43 +```
44 +
45 +## var argv = parseArgs(args, opts={})
46 +
47 +Return an argument object `argv` populated with the array arguments from `args`.
48 +
49 +`argv._` contains all the arguments that didn't have an option associated with
50 +them.
51 +
52 +Numeric-looking arguments will be returned as numbers unless `opts.string` or
53 +`opts.boolean` is set for that argument name.
54 +
55 +Any arguments after `'--'` will not be parsed and will end up in `argv._`.
56 +
57 +options can be:
58 +
59 +* `opts.string` - a string or array of strings argument names to always treat as
60 +strings
61 +* `opts.boolean` - a boolean, string or array of strings to always treat as
62 +booleans. if `true` will treat all double hyphenated arguments without equal signs
63 +as boolean (e.g. affects `--foo`, not `-f` or `--foo=bar`)
64 +* `opts.alias` - an object mapping string names to strings or arrays of string
65 +argument names to use as aliases
66 +* `opts.default` - an object mapping string argument names to default values
67 +* `opts.stopEarly` - when true, populate `argv._` with everything after the
68 +first non-option
69 +* `opts['--']` - when true, populate `argv._` with everything before the `--`
70 +and `argv['--']` with everything after the `--`. Here's an example:
71 +
72 + ```
73 + > require('./')('one two three -- four five --six'.split(' '), { '--': true })
74 + { _: [ 'one', 'two', 'three' ],
75 + '--': [ 'four', 'five', '--six' ] }
76 + ```
77 +
78 + Note that with `opts['--']` set, parsing for arguments still stops after the
79 + `--`.
80 +
81 +* `opts.unknown` - a function which is invoked with a command line parameter not
82 +defined in the `opts` configuration object. If the function returns `false`, the
83 +unknown option is not added to `argv`.
84 +
85 +# install
86 +
87 +With [npm](https://npmjs.org) do:
88 +
89 +```
90 +npm install minimist
91 +```
92 +
93 +# license
94 +
95 +MIT
1 +var parse = require('../');
2 +var test = require('tape');
3 +
4 +test('flag boolean true (default all --args to boolean)', function (t) {
5 + var argv = parse(['moo', '--honk', 'cow'], {
6 + boolean: true
7 + });
8 +
9 + t.deepEqual(argv, {
10 + honk: true,
11 + _: ['moo', 'cow']
12 + });
13 +
14 + t.deepEqual(typeof argv.honk, 'boolean');
15 + t.end();
16 +});
17 +
18 +test('flag boolean true only affects double hyphen arguments without equals signs', function (t) {
19 + var argv = parse(['moo', '--honk', 'cow', '-p', '55', '--tacos=good'], {
20 + boolean: true
21 + });
22 +
23 + t.deepEqual(argv, {
24 + honk: true,
25 + tacos: 'good',
26 + p: 55,
27 + _: ['moo', 'cow']
28 + });
29 +
30 + t.deepEqual(typeof argv.honk, 'boolean');
31 + t.end();
32 +});
1 +var parse = require('../');
2 +var test = require('tape');
3 +
4 +test('flag boolean default false', function (t) {
5 + var argv = parse(['moo'], {
6 + boolean: ['t', 'verbose'],
7 + default: { verbose: false, t: false }
8 + });
9 +
10 + t.deepEqual(argv, {
11 + verbose: false,
12 + t: false,
13 + _: ['moo']
14 + });
15 +
16 + t.deepEqual(typeof argv.verbose, 'boolean');
17 + t.deepEqual(typeof argv.t, 'boolean');
18 + t.end();
19 +
20 +});
21 +
22 +test('boolean groups', function (t) {
23 + var argv = parse([ '-x', '-z', 'one', 'two', 'three' ], {
24 + boolean: ['x','y','z']
25 + });
26 +
27 + t.deepEqual(argv, {
28 + x : true,
29 + y : false,
30 + z : true,
31 + _ : [ 'one', 'two', 'three' ]
32 + });
33 +
34 + t.deepEqual(typeof argv.x, 'boolean');
35 + t.deepEqual(typeof argv.y, 'boolean');
36 + t.deepEqual(typeof argv.z, 'boolean');
37 + t.end();
38 +});
39 +test('boolean and alias with chainable api', function (t) {
40 + var aliased = [ '-h', 'derp' ];
41 + var regular = [ '--herp', 'derp' ];
42 + var opts = {
43 + herp: { alias: 'h', boolean: true }
44 + };
45 + var aliasedArgv = parse(aliased, {
46 + boolean: 'herp',
47 + alias: { h: 'herp' }
48 + });
49 + var propertyArgv = parse(regular, {
50 + boolean: 'herp',
51 + alias: { h: 'herp' }
52 + });
53 + var expected = {
54 + herp: true,
55 + h: true,
56 + '_': [ 'derp' ]
57 + };
58 +
59 + t.same(aliasedArgv, expected);
60 + t.same(propertyArgv, expected);
61 + t.end();
62 +});
63 +
64 +test('boolean and alias with options hash', function (t) {
65 + var aliased = [ '-h', 'derp' ];
66 + var regular = [ '--herp', 'derp' ];
67 + var opts = {
68 + alias: { 'h': 'herp' },
69 + boolean: 'herp'
70 + };
71 + var aliasedArgv = parse(aliased, opts);
72 + var propertyArgv = parse(regular, opts);
73 + var expected = {
74 + herp: true,
75 + h: true,
76 + '_': [ 'derp' ]
77 + };
78 + t.same(aliasedArgv, expected);
79 + t.same(propertyArgv, expected);
80 + t.end();
81 +});
82 +
83 +test('boolean and alias array with options hash', function (t) {
84 + var aliased = [ '-h', 'derp' ];
85 + var regular = [ '--herp', 'derp' ];
86 + var alt = [ '--harp', 'derp' ];
87 + var opts = {
88 + alias: { 'h': ['herp', 'harp'] },
89 + boolean: 'h'
90 + };
91 + var aliasedArgv = parse(aliased, opts);
92 + var propertyArgv = parse(regular, opts);
93 + var altPropertyArgv = parse(alt, opts);
94 + var expected = {
95 + harp: true,
96 + herp: true,
97 + h: true,
98 + '_': [ 'derp' ]
99 + };
100 + t.same(aliasedArgv, expected);
101 + t.same(propertyArgv, expected);
102 + t.same(altPropertyArgv, expected);
103 + t.end();
104 +});
105 +
106 +test('boolean and alias using explicit true', function (t) {
107 + var aliased = [ '-h', 'true' ];
108 + var regular = [ '--herp', 'true' ];
109 + var opts = {
110 + alias: { h: 'herp' },
111 + boolean: 'h'
112 + };
113 + var aliasedArgv = parse(aliased, opts);
114 + var propertyArgv = parse(regular, opts);
115 + var expected = {
116 + herp: true,
117 + h: true,
118 + '_': [ ]
119 + };
120 +
121 + t.same(aliasedArgv, expected);
122 + t.same(propertyArgv, expected);
123 + t.end();
124 +});
125 +
126 +// regression, see https://github.com/substack/node-optimist/issues/71
127 +test('boolean and --x=true', function(t) {
128 + var parsed = parse(['--boool', '--other=true'], {
129 + boolean: 'boool'
130 + });
131 +
132 + t.same(parsed.boool, true);
133 + t.same(parsed.other, 'true');
134 +
135 + parsed = parse(['--boool', '--other=false'], {
136 + boolean: 'boool'
137 + });
138 +
139 + t.same(parsed.boool, true);
140 + t.same(parsed.other, 'false');
141 + t.end();
142 +});
143 +
144 +test('boolean --boool=true', function (t) {
145 + var parsed = parse(['--boool=true'], {
146 + default: {
147 + boool: false
148 + },
149 + boolean: ['boool']
150 + });
151 +
152 + t.same(parsed.boool, true);
153 + t.end();
154 +});
155 +
156 +test('boolean --boool=false', function (t) {
157 + var parsed = parse(['--boool=false'], {
158 + default: {
159 + boool: true
160 + },
161 + boolean: ['boool']
162 + });
163 +
164 + t.same(parsed.boool, false);
165 + t.end();
166 +});
167 +
168 +test('boolean using something similar to true', function (t) {
169 + var opts = { boolean: 'h' };
170 + var result = parse(['-h', 'true.txt'], opts);
171 + var expected = {
172 + h: true,
173 + '_': ['true.txt']
174 + };
175 +
176 + t.same(result, expected);
177 + t.end();
178 +});
...\ No newline at end of file ...\ No newline at end of file
1 +var parse = require('../');
2 +var test = require('tape');
3 +
4 +test('-', function (t) {
5 + t.plan(5);
6 + t.deepEqual(parse([ '-n', '-' ]), { n: '-', _: [] });
7 + t.deepEqual(parse([ '-' ]), { _: [ '-' ] });
8 + t.deepEqual(parse([ '-f-' ]), { f: '-', _: [] });
9 + t.deepEqual(
10 + parse([ '-b', '-' ], { boolean: 'b' }),
11 + { b: true, _: [ '-' ] }
12 + );
13 + t.deepEqual(
14 + parse([ '-s', '-' ], { string: 's' }),
15 + { s: '-', _: [] }
16 + );
17 +});
18 +
19 +test('-a -- b', function (t) {
20 + t.plan(3);
21 + t.deepEqual(parse([ '-a', '--', 'b' ]), { a: true, _: [ 'b' ] });
22 + t.deepEqual(parse([ '--a', '--', 'b' ]), { a: true, _: [ 'b' ] });
23 + t.deepEqual(parse([ '--a', '--', 'b' ]), { a: true, _: [ 'b' ] });
24 +});
25 +
26 +test('move arguments after the -- into their own `--` array', function(t) {
27 + t.plan(1);
28 + t.deepEqual(
29 + parse([ '--name', 'John', 'before', '--', 'after' ], { '--': true }),
30 + { name: 'John', _: [ 'before' ], '--': [ 'after' ] });
31 +});
1 +var test = require('tape');
2 +var parse = require('../');
3 +
4 +test('boolean default true', function (t) {
5 + var argv = parse([], {
6 + boolean: 'sometrue',
7 + default: { sometrue: true }
8 + });
9 + t.equal(argv.sometrue, true);
10 + t.end();
11 +});
12 +
13 +test('boolean default false', function (t) {
14 + var argv = parse([], {
15 + boolean: 'somefalse',
16 + default: { somefalse: false }
17 + });
18 + t.equal(argv.somefalse, false);
19 + t.end();
20 +});
21 +
22 +test('boolean default to null', function (t) {
23 + var argv = parse([], {
24 + boolean: 'maybe',
25 + default: { maybe: null }
26 + });
27 + t.equal(argv.maybe, null);
28 + var argv = parse(['--maybe'], {
29 + boolean: 'maybe',
30 + default: { maybe: null }
31 + });
32 + t.equal(argv.maybe, true);
33 + t.end();
34 +
35 +})
1 +var parse = require('../');
2 +var test = require('tape');
3 +
4 +test('dotted alias', function (t) {
5 + var argv = parse(['--a.b', '22'], {default: {'a.b': 11}, alias: {'a.b': 'aa.bb'}});
6 + t.equal(argv.a.b, 22);
7 + t.equal(argv.aa.bb, 22);
8 + t.end();
9 +});
10 +
11 +test('dotted default', function (t) {
12 + var argv = parse('', {default: {'a.b': 11}, alias: {'a.b': 'aa.bb'}});
13 + t.equal(argv.a.b, 11);
14 + t.equal(argv.aa.bb, 11);
15 + t.end();
16 +});
17 +
18 +test('dotted default with no alias', function (t) {
19 + var argv = parse('', {default: {'a.b': 11}});
20 + t.equal(argv.a.b, 11);
21 + t.end();
22 +});
1 +var parse = require('../');
2 +var test = require('tape');
3 +
4 +test('short -k=v' , function (t) {
5 + t.plan(1);
6 +
7 + var argv = parse([ '-b=123' ]);
8 + t.deepEqual(argv, { b: 123, _: [] });
9 +});
10 +
11 +test('multi short -k=v' , function (t) {
12 + t.plan(1);
13 +
14 + var argv = parse([ '-a=whatever', '-b=robots' ]);
15 + t.deepEqual(argv, { a: 'whatever', b: 'robots', _: [] });
16 +});
1 +var test = require('tape');
2 +var parse = require('../');
3 +
4 +test('long opts', function (t) {
5 + t.deepEqual(
6 + parse([ '--bool' ]),
7 + { bool : true, _ : [] },
8 + 'long boolean'
9 + );
10 + t.deepEqual(
11 + parse([ '--pow', 'xixxle' ]),
12 + { pow : 'xixxle', _ : [] },
13 + 'long capture sp'
14 + );
15 + t.deepEqual(
16 + parse([ '--pow=xixxle' ]),
17 + { pow : 'xixxle', _ : [] },
18 + 'long capture eq'
19 + );
20 + t.deepEqual(
21 + parse([ '--host', 'localhost', '--port', '555' ]),
22 + { host : 'localhost', port : 555, _ : [] },
23 + 'long captures sp'
24 + );
25 + t.deepEqual(
26 + parse([ '--host=localhost', '--port=555' ]),
27 + { host : 'localhost', port : 555, _ : [] },
28 + 'long captures eq'
29 + );
30 + t.end();
31 +});
1 +var parse = require('../');
2 +var test = require('tape');
3 +
4 +test('nums', function (t) {
5 + var argv = parse([
6 + '-x', '1234',
7 + '-y', '5.67',
8 + '-z', '1e7',
9 + '-w', '10f',
10 + '--hex', '0xdeadbeef',
11 + '789'
12 + ]);
13 + t.deepEqual(argv, {
14 + x : 1234,
15 + y : 5.67,
16 + z : 1e7,
17 + w : '10f',
18 + hex : 0xdeadbeef,
19 + _ : [ 789 ]
20 + });
21 + t.deepEqual(typeof argv.x, 'number');
22 + t.deepEqual(typeof argv.y, 'number');
23 + t.deepEqual(typeof argv.z, 'number');
24 + t.deepEqual(typeof argv.w, 'string');
25 + t.deepEqual(typeof argv.hex, 'number');
26 + t.deepEqual(typeof argv._[0], 'number');
27 + t.end();
28 +});
29 +
30 +test('already a number', function (t) {
31 + var argv = parse([ '-x', 1234, 789 ]);
32 + t.deepEqual(argv, { x : 1234, _ : [ 789 ] });
33 + t.deepEqual(typeof argv.x, 'number');
34 + t.deepEqual(typeof argv._[0], 'number');
35 + t.end();
36 +});
1 +var parse = require('../');
2 +var test = require('tape');
3 +
4 +test('parse args', function (t) {
5 + t.deepEqual(
6 + parse([ '--no-moo' ]),
7 + { moo : false, _ : [] },
8 + 'no'
9 + );
10 + t.deepEqual(
11 + parse([ '-v', 'a', '-v', 'b', '-v', 'c' ]),
12 + { v : ['a','b','c'], _ : [] },
13 + 'multi'
14 + );
15 + t.end();
16 +});
17 +
18 +test('comprehensive', function (t) {
19 + t.deepEqual(
20 + parse([
21 + '--name=meowmers', 'bare', '-cats', 'woo',
22 + '-h', 'awesome', '--multi=quux',
23 + '--key', 'value',
24 + '-b', '--bool', '--no-meep', '--multi=baz',
25 + '--', '--not-a-flag', 'eek'
26 + ]),
27 + {
28 + c : true,
29 + a : true,
30 + t : true,
31 + s : 'woo',
32 + h : 'awesome',
33 + b : true,
34 + bool : true,
35 + key : 'value',
36 + multi : [ 'quux', 'baz' ],
37 + meep : false,
38 + name : 'meowmers',
39 + _ : [ 'bare', '--not-a-flag', 'eek' ]
40 + }
41 + );
42 + t.end();
43 +});
44 +
45 +test('flag boolean', function (t) {
46 + var argv = parse([ '-t', 'moo' ], { boolean: 't' });
47 + t.deepEqual(argv, { t : true, _ : [ 'moo' ] });
48 + t.deepEqual(typeof argv.t, 'boolean');
49 + t.end();
50 +});
51 +
52 +test('flag boolean value', function (t) {
53 + var argv = parse(['--verbose', 'false', 'moo', '-t', 'true'], {
54 + boolean: [ 't', 'verbose' ],
55 + default: { verbose: true }
56 + });
57 +
58 + t.deepEqual(argv, {
59 + verbose: false,
60 + t: true,
61 + _: ['moo']
62 + });
63 +
64 + t.deepEqual(typeof argv.verbose, 'boolean');
65 + t.deepEqual(typeof argv.t, 'boolean');
66 + t.end();
67 +});
68 +
69 +test('newlines in params' , function (t) {
70 + var args = parse([ '-s', "X\nX" ])
71 + t.deepEqual(args, { _ : [], s : "X\nX" });
72 +
73 + // reproduce in bash:
74 + // VALUE="new
75 + // line"
76 + // node program.js --s="$VALUE"
77 + args = parse([ "--s=X\nX" ])
78 + t.deepEqual(args, { _ : [], s : "X\nX" });
79 + t.end();
80 +});
81 +
82 +test('strings' , function (t) {
83 + var s = parse([ '-s', '0001234' ], { string: 's' }).s;
84 + t.equal(s, '0001234');
85 + t.equal(typeof s, 'string');
86 +
87 + var x = parse([ '-x', '56' ], { string: 'x' }).x;
88 + t.equal(x, '56');
89 + t.equal(typeof x, 'string');
90 + t.end();
91 +});
92 +
93 +test('stringArgs', function (t) {
94 + var s = parse([ ' ', ' ' ], { string: '_' })._;
95 + t.same(s.length, 2);
96 + t.same(typeof s[0], 'string');
97 + t.same(s[0], ' ');
98 + t.same(typeof s[1], 'string');
99 + t.same(s[1], ' ');
100 + t.end();
101 +});
102 +
103 +test('empty strings', function(t) {
104 + var s = parse([ '-s' ], { string: 's' }).s;
105 + t.equal(s, '');
106 + t.equal(typeof s, 'string');
107 +
108 + var str = parse([ '--str' ], { string: 'str' }).str;
109 + t.equal(str, '');
110 + t.equal(typeof str, 'string');
111 +
112 + var letters = parse([ '-art' ], {
113 + string: [ 'a', 't' ]
114 + });
115 +
116 + t.equal(letters.a, '');
117 + t.equal(letters.r, true);
118 + t.equal(letters.t, '');
119 +
120 + t.end();
121 +});
122 +
123 +
124 +test('string and alias', function(t) {
125 + var x = parse([ '--str', '000123' ], {
126 + string: 's',
127 + alias: { s: 'str' }
128 + });
129 +
130 + t.equal(x.str, '000123');
131 + t.equal(typeof x.str, 'string');
132 + t.equal(x.s, '000123');
133 + t.equal(typeof x.s, 'string');
134 +
135 + var y = parse([ '-s', '000123' ], {
136 + string: 'str',
137 + alias: { str: 's' }
138 + });
139 +
140 + t.equal(y.str, '000123');
141 + t.equal(typeof y.str, 'string');
142 + t.equal(y.s, '000123');
143 + t.equal(typeof y.s, 'string');
144 + t.end();
145 +});
146 +
147 +test('slashBreak', function (t) {
148 + t.same(
149 + parse([ '-I/foo/bar/baz' ]),
150 + { I : '/foo/bar/baz', _ : [] }
151 + );
152 + t.same(
153 + parse([ '-xyz/foo/bar/baz' ]),
154 + { x : true, y : true, z : '/foo/bar/baz', _ : [] }
155 + );
156 + t.end();
157 +});
158 +
159 +test('alias', function (t) {
160 + var argv = parse([ '-f', '11', '--zoom', '55' ], {
161 + alias: { z: 'zoom' }
162 + });
163 + t.equal(argv.zoom, 55);
164 + t.equal(argv.z, argv.zoom);
165 + t.equal(argv.f, 11);
166 + t.end();
167 +});
168 +
169 +test('multiAlias', function (t) {
170 + var argv = parse([ '-f', '11', '--zoom', '55' ], {
171 + alias: { z: [ 'zm', 'zoom' ] }
172 + });
173 + t.equal(argv.zoom, 55);
174 + t.equal(argv.z, argv.zoom);
175 + t.equal(argv.z, argv.zm);
176 + t.equal(argv.f, 11);
177 + t.end();
178 +});
179 +
180 +test('nested dotted objects', function (t) {
181 + var argv = parse([
182 + '--foo.bar', '3', '--foo.baz', '4',
183 + '--foo.quux.quibble', '5', '--foo.quux.o_O',
184 + '--beep.boop'
185 + ]);
186 +
187 + t.same(argv.foo, {
188 + bar : 3,
189 + baz : 4,
190 + quux : {
191 + quibble : 5,
192 + o_O : true
193 + }
194 + });
195 + t.same(argv.beep, { boop : true });
196 + t.end();
197 +});
1 +var parse = require('../');
2 +var test = require('tape');
3 +
4 +test('parse with modifier functions' , function (t) {
5 + t.plan(1);
6 +
7 + var argv = parse([ '-b', '123' ], { boolean: 'b' });
8 + t.deepEqual(argv, { b: true, _: [123] });
9 +});
1 +var parse = require('../');
2 +var test = require('tape');
3 +
4 +test('proto pollution', function (t) {
5 + var argv = parse(['--__proto__.x','123']);
6 + t.equal({}.x, undefined);
7 + t.equal(argv.__proto__.x, undefined);
8 + t.equal(argv.x, undefined);
9 + t.end();
10 +});
11 +
12 +test('proto pollution (array)', function (t) {
13 + var argv = parse(['--x','4','--x','5','--x.__proto__.z','789']);
14 + t.equal({}.z, undefined);
15 + t.deepEqual(argv.x, [4,5]);
16 + t.equal(argv.x.z, undefined);
17 + t.equal(argv.x.__proto__.z, undefined);
18 + t.end();
19 +});
20 +
21 +test('proto pollution (number)', function (t) {
22 + var argv = parse(['--x','5','--x.__proto__.z','100']);
23 + t.equal({}.z, undefined);
24 + t.equal((4).z, undefined);
25 + t.equal(argv.x, 5);
26 + t.equal(argv.x.z, undefined);
27 + t.end();
28 +});
29 +
30 +test('proto pollution (string)', function (t) {
31 + var argv = parse(['--x','abc','--x.__proto__.z','def']);
32 + t.equal({}.z, undefined);
33 + t.equal('...'.z, undefined);
34 + t.equal(argv.x, 'abc');
35 + t.equal(argv.x.z, undefined);
36 + t.end();
37 +});
38 +
39 +test('proto pollution (constructor)', function (t) {
40 + var argv = parse(['--constructor.prototype.y','123']);
41 + t.equal({}.y, undefined);
42 + t.equal(argv.y, undefined);
43 + t.end();
44 +});
1 +var parse = require('../');
2 +var test = require('tape');
3 +
4 +test('numeric short args', function (t) {
5 + t.plan(2);
6 + t.deepEqual(parse([ '-n123' ]), { n: 123, _: [] });
7 + t.deepEqual(
8 + parse([ '-123', '456' ]),
9 + { 1: true, 2: true, 3: 456, _: [] }
10 + );
11 +});
12 +
13 +test('short', function (t) {
14 + t.deepEqual(
15 + parse([ '-b' ]),
16 + { b : true, _ : [] },
17 + 'short boolean'
18 + );
19 + t.deepEqual(
20 + parse([ 'foo', 'bar', 'baz' ]),
21 + { _ : [ 'foo', 'bar', 'baz' ] },
22 + 'bare'
23 + );
24 + t.deepEqual(
25 + parse([ '-cats' ]),
26 + { c : true, a : true, t : true, s : true, _ : [] },
27 + 'group'
28 + );
29 + t.deepEqual(
30 + parse([ '-cats', 'meow' ]),
31 + { c : true, a : true, t : true, s : 'meow', _ : [] },
32 + 'short group next'
33 + );
34 + t.deepEqual(
35 + parse([ '-h', 'localhost' ]),
36 + { h : 'localhost', _ : [] },
37 + 'short capture'
38 + );
39 + t.deepEqual(
40 + parse([ '-h', 'localhost', '-p', '555' ]),
41 + { h : 'localhost', p : 555, _ : [] },
42 + 'short captures'
43 + );
44 + t.end();
45 +});
46 +
47 +test('mixed short bool and capture', function (t) {
48 + t.same(
49 + parse([ '-h', 'localhost', '-fp', '555', 'script.js' ]),
50 + {
51 + f : true, p : 555, h : 'localhost',
52 + _ : [ 'script.js' ]
53 + }
54 + );
55 + t.end();
56 +});
57 +
58 +test('short and long', function (t) {
59 + t.deepEqual(
60 + parse([ '-h', 'localhost', '-fp', '555', 'script.js' ]),
61 + {
62 + f : true, p : 555, h : 'localhost',
63 + _ : [ 'script.js' ]
64 + }
65 + );
66 + t.end();
67 +});
1 +var parse = require('../');
2 +var test = require('tape');
3 +
4 +test('stops parsing on the first non-option when stopEarly is set', function (t) {
5 + var argv = parse(['--aaa', 'bbb', 'ccc', '--ddd'], {
6 + stopEarly: true
7 + });
8 +
9 + t.deepEqual(argv, {
10 + aaa: 'bbb',
11 + _: ['ccc', '--ddd']
12 + });
13 +
14 + t.end();
15 +});
1 +var parse = require('../');
2 +var test = require('tape');
3 +
4 +test('boolean and alias is not unknown', function (t) {
5 + var unknown = [];
6 + function unknownFn(arg) {
7 + unknown.push(arg);
8 + return false;
9 + }
10 + var aliased = [ '-h', 'true', '--derp', 'true' ];
11 + var regular = [ '--herp', 'true', '-d', 'true' ];
12 + var opts = {
13 + alias: { h: 'herp' },
14 + boolean: 'h',
15 + unknown: unknownFn
16 + };
17 + var aliasedArgv = parse(aliased, opts);
18 + var propertyArgv = parse(regular, opts);
19 +
20 + t.same(unknown, ['--derp', '-d']);
21 + t.end();
22 +});
23 +
24 +test('flag boolean true any double hyphen argument is not unknown', function (t) {
25 + var unknown = [];
26 + function unknownFn(arg) {
27 + unknown.push(arg);
28 + return false;
29 + }
30 + var argv = parse(['--honk', '--tacos=good', 'cow', '-p', '55'], {
31 + boolean: true,
32 + unknown: unknownFn
33 + });
34 + t.same(unknown, ['--tacos=good', 'cow', '-p']);
35 + t.same(argv, {
36 + honk: true,
37 + _: []
38 + });
39 + t.end();
40 +});
41 +
42 +test('string and alias is not unknown', function (t) {
43 + var unknown = [];
44 + function unknownFn(arg) {
45 + unknown.push(arg);
46 + return false;
47 + }
48 + var aliased = [ '-h', 'hello', '--derp', 'goodbye' ];
49 + var regular = [ '--herp', 'hello', '-d', 'moon' ];
50 + var opts = {
51 + alias: { h: 'herp' },
52 + string: 'h',
53 + unknown: unknownFn
54 + };
55 + var aliasedArgv = parse(aliased, opts);
56 + var propertyArgv = parse(regular, opts);
57 +
58 + t.same(unknown, ['--derp', '-d']);
59 + t.end();
60 +});
61 +
62 +test('default and alias is not unknown', function (t) {
63 + var unknown = [];
64 + function unknownFn(arg) {
65 + unknown.push(arg);
66 + return false;
67 + }
68 + var aliased = [ '-h', 'hello' ];
69 + var regular = [ '--herp', 'hello' ];
70 + var opts = {
71 + default: { 'h': 'bar' },
72 + alias: { 'h': 'herp' },
73 + unknown: unknownFn
74 + };
75 + var aliasedArgv = parse(aliased, opts);
76 + var propertyArgv = parse(regular, opts);
77 +
78 + t.same(unknown, []);
79 + t.end();
80 + unknownFn(); // exercise fn for 100% coverage
81 +});
82 +
83 +test('value following -- is not unknown', function (t) {
84 + var unknown = [];
85 + function unknownFn(arg) {
86 + unknown.push(arg);
87 + return false;
88 + }
89 + var aliased = [ '--bad', '--', 'good', 'arg' ];
90 + var opts = {
91 + '--': true,
92 + unknown: unknownFn
93 + };
94 + var argv = parse(aliased, opts);
95 +
96 + t.same(unknown, ['--bad']);
97 + t.same(argv, {
98 + '--': ['good', 'arg'],
99 + '_': []
100 + })
101 + t.end();
102 +});
1 +var parse = require('../');
2 +var test = require('tape');
3 +
4 +test('whitespace should be whitespace' , function (t) {
5 + t.plan(1);
6 + var x = parse([ '-x', '\t' ]).x;
7 + t.equal(x, '\t');
8 +});
1 +Copyright 2010 James Halliday (mail@substack.net)
2 +
3 +This project is free software released under the MIT/X11 license:
4 +
5 +Permission is hereby granted, free of charge, to any person obtaining a copy
6 +of this software and associated documentation files (the "Software"), to deal
7 +in the Software without restriction, including without limitation the rights
8 +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 +copies of the Software, and to permit persons to whom the Software is
10 +furnished to do so, subject to the following conditions:
11 +
12 +The above copyright notice and this permission notice shall be included in
13 +all copies or substantial portions of the Software.
14 +
15 +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21 +THE SOFTWARE.
1 +#!/usr/bin/env node
2 +
3 +var mkdirp = require('../');
4 +var minimist = require('minimist');
5 +var fs = require('fs');
6 +
7 +var argv = minimist(process.argv.slice(2), {
8 + alias: { m: 'mode', h: 'help' },
9 + string: [ 'mode' ]
10 +});
11 +if (argv.help) {
12 + fs.createReadStream(__dirname + '/usage.txt').pipe(process.stdout);
13 + return;
14 +}
15 +
16 +var paths = argv._.slice();
17 +var mode = argv.mode ? parseInt(argv.mode, 8) : undefined;
18 +
19 +(function next () {
20 + if (paths.length === 0) return;
21 + var p = paths.shift();
22 +
23 + if (mode === undefined) mkdirp(p, cb)
24 + else mkdirp(p, mode, cb)
25 +
26 + function cb (err) {
27 + if (err) {
28 + console.error(err.message);
29 + process.exit(1);
30 + }
31 + else next();
32 + }
33 +})();
1 +usage: mkdirp [DIR1,DIR2..] {OPTIONS}
2 +
3 + Create each supplied directory including any necessary parent directories that
4 + don't yet exist.
5 +
6 + If the directory already exists, do nothing.
7 +
8 +OPTIONS are:
9 +
10 + -m, --mode If a directory needs to be created, set the mode as an octal
11 + permission string.
12 +
1 +var path = require('path');
2 +var fs = require('fs');
3 +var _0777 = parseInt('0777', 8);
4 +
5 +module.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP;
6 +
7 +function mkdirP (p, opts, f, made) {
8 + if (typeof opts === 'function') {
9 + f = opts;
10 + opts = {};
11 + }
12 + else if (!opts || typeof opts !== 'object') {
13 + opts = { mode: opts };
14 + }
15 +
16 + var mode = opts.mode;
17 + var xfs = opts.fs || fs;
18 +
19 + if (mode === undefined) {
20 + mode = _0777
21 + }
22 + if (!made) made = null;
23 +
24 + var cb = f || function () {};
25 + p = path.resolve(p);
26 +
27 + xfs.mkdir(p, mode, function (er) {
28 + if (!er) {
29 + made = made || p;
30 + return cb(null, made);
31 + }
32 + switch (er.code) {
33 + case 'ENOENT':
34 + if (path.dirname(p) === p) return cb(er);
35 + mkdirP(path.dirname(p), opts, function (er, made) {
36 + if (er) cb(er, made);
37 + else mkdirP(p, opts, cb, made);
38 + });
39 + break;
40 +
41 + // In the case of any other error, just see if there's a dir
42 + // there already. If so, then hooray! If not, then something
43 + // is borked.
44 + default:
45 + xfs.stat(p, function (er2, stat) {
46 + // if the stat fails, then that's super weird.
47 + // let the original error be the failure reason.
48 + if (er2 || !stat.isDirectory()) cb(er, made)
49 + else cb(null, made);
50 + });
51 + break;
52 + }
53 + });
54 +}
55 +
56 +mkdirP.sync = function sync (p, opts, made) {
57 + if (!opts || typeof opts !== 'object') {
58 + opts = { mode: opts };
59 + }
60 +
61 + var mode = opts.mode;
62 + var xfs = opts.fs || fs;
63 +
64 + if (mode === undefined) {
65 + mode = _0777
66 + }
67 + if (!made) made = null;
68 +
69 + p = path.resolve(p);
70 +
71 + try {
72 + xfs.mkdirSync(p, mode);
73 + made = made || p;
74 + }
75 + catch (err0) {
76 + switch (err0.code) {
77 + case 'ENOENT' :
78 + made = sync(path.dirname(p), opts, made);
79 + sync(p, opts, made);
80 + break;
81 +
82 + // In the case of any other error, just see if there's a dir
83 + // there already. If so, then hooray! If not, then something
84 + // is borked.
85 + default:
86 + var stat;
87 + try {
88 + stat = xfs.statSync(p);
89 + }
90 + catch (err1) {
91 + throw err0;
92 + }
93 + if (!stat.isDirectory()) throw err0;
94 + break;
95 + }
96 + }
97 +
98 + return made;
99 +};
1 +{
2 + "_from": "mkdirp@^0.5.1",
3 + "_id": "mkdirp@0.5.5",
4 + "_inBundle": false,
5 + "_integrity": "sha512-NKmAlESf6jMGym1++R0Ra7wvhV+wFW63FaSOFPwRahvea0gMUcGUhVeAg/0BC0wiv9ih5NYPB1Wn1UEI1/L+xQ==",
6 + "_location": "/mkdirp",
7 + "_phantomChildren": {},
8 + "_requested": {
9 + "type": "range",
10 + "registry": true,
11 + "raw": "mkdirp@^0.5.1",
12 + "name": "mkdirp",
13 + "escapedName": "mkdirp",
14 + "rawSpec": "^0.5.1",
15 + "saveSpec": null,
16 + "fetchSpec": "^0.5.1"
17 + },
18 + "_requiredBy": [
19 + "/multer"
20 + ],
21 + "_resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.5.tgz",
22 + "_shasum": "d91cefd62d1436ca0f41620e251288d420099def",
23 + "_spec": "mkdirp@^0.5.1",
24 + "_where": "C:\\Users\\1000c\\이것저것\\옾소\\Voicoding\\node_modules\\multer",
25 + "author": {
26 + "name": "James Halliday",
27 + "email": "mail@substack.net",
28 + "url": "http://substack.net"
29 + },
30 + "bin": {
31 + "mkdirp": "bin/cmd.js"
32 + },
33 + "bugs": {
34 + "url": "https://github.com/substack/node-mkdirp/issues"
35 + },
36 + "bundleDependencies": false,
37 + "dependencies": {
38 + "minimist": "^1.2.5"
39 + },
40 + "deprecated": false,
41 + "description": "Recursively mkdir, like `mkdir -p`",
42 + "devDependencies": {
43 + "mock-fs": "^3.7.0",
44 + "tap": "^5.4.2"
45 + },
46 + "files": [
47 + "bin",
48 + "index.js"
49 + ],
50 + "homepage": "https://github.com/substack/node-mkdirp#readme",
51 + "keywords": [
52 + "mkdir",
53 + "directory"
54 + ],
55 + "license": "MIT",
56 + "main": "index.js",
57 + "name": "mkdirp",
58 + "publishConfig": {
59 + "tag": "legacy"
60 + },
61 + "repository": {
62 + "type": "git",
63 + "url": "git+https://github.com/substack/node-mkdirp.git"
64 + },
65 + "scripts": {
66 + "test": "tap test/*.js"
67 + },
68 + "version": "0.5.5"
69 +}
1 +# mkdirp
2 +
3 +Like `mkdir -p`, but in node.js!
4 +
5 +[![build status](https://secure.travis-ci.org/substack/node-mkdirp.png)](http://travis-ci.org/substack/node-mkdirp)
6 +
7 +# example
8 +
9 +## pow.js
10 +
11 +```js
12 +var mkdirp = require('mkdirp');
13 +
14 +mkdirp('/tmp/foo/bar/baz', function (err) {
15 + if (err) console.error(err)
16 + else console.log('pow!')
17 +});
18 +```
19 +
20 +Output
21 +
22 +```
23 +pow!
24 +```
25 +
26 +And now /tmp/foo/bar/baz exists, huzzah!
27 +
28 +# methods
29 +
30 +```js
31 +var mkdirp = require('mkdirp');
32 +```
33 +
34 +## mkdirp(dir, opts, cb)
35 +
36 +Create a new directory and any necessary subdirectories at `dir` with octal
37 +permission string `opts.mode`. If `opts` is a non-object, it will be treated as
38 +the `opts.mode`.
39 +
40 +If `opts.mode` isn't specified, it defaults to `0777`.
41 +
42 +`cb(err, made)` fires with the error or the first directory `made`
43 +that had to be created, if any.
44 +
45 +You can optionally pass in an alternate `fs` implementation by passing in
46 +`opts.fs`. Your implementation should have `opts.fs.mkdir(path, mode, cb)` and
47 +`opts.fs.stat(path, cb)`.
48 +
49 +## mkdirp.sync(dir, opts)
50 +
51 +Synchronously create a new directory and any necessary subdirectories at `dir`
52 +with octal permission string `opts.mode`. If `opts` is a non-object, it will be
53 +treated as the `opts.mode`.
54 +
55 +If `opts.mode` isn't specified, it defaults to `0777`.
56 +
57 +Returns the first directory that had to be created, if any.
58 +
59 +You can optionally pass in an alternate `fs` implementation by passing in
60 +`opts.fs`. Your implementation should have `opts.fs.mkdirSync(path, mode)` and
61 +`opts.fs.statSync(path)`.
62 +
63 +# usage
64 +
65 +This package also ships with a `mkdirp` command.
66 +
67 +```
68 +usage: mkdirp [DIR1,DIR2..] {OPTIONS}
69 +
70 + Create each supplied directory including any necessary parent directories that
71 + don't yet exist.
72 +
73 + If the directory already exists, do nothing.
74 +
75 +OPTIONS are:
76 +
77 + -m, --mode If a directory needs to be created, set the mode as an octal
78 + permission string.
79 +
80 +```
81 +
82 +# install
83 +
84 +With [npm](http://npmjs.org) do:
85 +
86 +```
87 +npm install mkdirp
88 +```
89 +
90 +to get the library, or
91 +
92 +```
93 +npm install -g mkdirp
94 +```
95 +
96 +to get the command.
97 +
98 +# license
99 +
100 +MIT
1 -const express = require('express');
2 -const speech = require('@google-cloud/speech');
3 -const app = express();
4 -app.use(express.json());
5 -const project_id = "ace-sight-314313"
6 -const port = `https://speech.googleapis.com/v1p1beta1/projects/${project_id}/locations/global/phraseSets`
7 -
8 -const usage = `curl -X POST -H "Authorization: Bearer $(gcloud auth-impersonate-service-account=$SA_EMAIL print-access-token)" -H` + '"Content-Type: application/json; charset=utf-8"' +
9 - `"https://speech.googleapis.com/v1p1beta1/projects/${project_id}/locations/global/phraseSets"` +
10 - '-d "{"phraseSetId": "test-phrase-set-1"}"'
11 -
12 -app.post('', function(req, res){
13 - res.send(usage)
14 -})
...\ No newline at end of file ...\ No newline at end of file
1 +# Change log
2 +
3 +All notable changes to this project will be documented in this file.
4 +This project adheres to [Semantic Versioning](http://semver.org/).
5 +
6 +## 1.4.2 - 2019-07-16
7 +
8 +- Docs: Add Russian translation for README (#662)
9 +- Docs: Patch zh-CN README base on newest README (#670)
10 +- Docs: Fix broken link in Readme (#679)
11 +- Docs: Fix broken link in Chinese Readme (#730)
12 +- Docs: Fix typo in Russian README (#738)
13 +- Docs: Add unit for fieldSize in busboy limit params (#734)
14 +- Internal: Make unit tests comaptible with Node.js 13.x (#752)
15 +
16 +## 1.4.1 - 2018-10-11
17 +
18 +- Bugfix: Make sure that req.file.buffer always is a Buffer
19 +
20 +## 1.4.0 - 2018-09-26
21 +
22 +- Feature: Make Multer errors inherit from MulterError
23 +
24 +## 1.3.1 - 2018-06-28
25 +
26 +- Bugfix: Bump vulnerable dependency
27 +
28 +## 1.3.0 - 2017-01-25
29 +
30 +- Feature: Expose preservePath option
31 +
32 +## 1.2.1 - 2016-12-14
33 +
34 +- Bugfix: Prevent Multiple Errors from Crashing
35 +
36 +## 1.2.0 - 2016-08-04
37 +
38 +- Feature: add .none() for accepting only fields
39 +
40 +## 1.1.0 - 2015-10-23
41 +
42 +- Feature: accept any file, regardless of fieldname
43 +
44 +## 1.0.6 - 2015-10-03
45 +
46 +- Bugfix: always report limit errors
47 +
48 +## 1.0.5 - 2015-09-19
49 +
50 +- Bugfix: drain the stream before considering request done
51 +
52 +## 1.0.4 - 2015-09-19
53 +
54 +- Bugfix: propagate all errors from busboy
55 +
56 +## 1.0.3 - 2015-08-06
57 +
58 +- Bugfix: ensure file order is correct
59 +
60 +## 1.0.2 - 2015-08-06
61 +
62 +- Bugfix: don't hang when hitting size limit
63 +
64 +## 1.0.1 - 2015-07-20
65 +
66 +- Bugfix: decrement pending writes on error
67 +
68 +## 1.0.0 - 2015-07-18
69 +
70 +- Introduce storage engines
71 +- Specify expected fields
72 +- Follow the W3C JSON form spec
1 +Copyright (c) 2014 Hage Yaapa <[http://www.hacksparrow.com](http://www.hacksparrow.com)>
2 +
3 +Permission is hereby granted, free of charge, to any person obtaining a copy
4 +of this software and associated documentation files (the "Software"), to deal
5 +in the Software without restriction, including without limitation the rights
6 +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7 +copies of the Software, and to permit persons to whom the Software is
8 +furnished to do so, subject to the following conditions:
9 +
10 +The above copyright notice and this permission notice shall be included in
11 +all copies or substantial portions of the Software.
12 +
13 +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
1 +# Multer [![Build Status](https://travis-ci.org/expressjs/multer.svg?branch=master)](https://travis-ci.org/expressjs/multer) [![NPM version](https://badge.fury.io/js/multer.svg)](https://badge.fury.io/js/multer) [![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat)](https://github.com/feross/standard)
2 +
3 +Multer is a node.js middleware for handling `multipart/form-data`, which is primarily used for uploading files. It is written
4 +on top of [busboy](https://github.com/mscdex/busboy) for maximum efficiency.
5 +
6 +**NOTE**: Multer will not process any form which is not multipart (`multipart/form-data`).
7 +
8 +## Translations
9 +
10 +This README is also available in other languages:
11 +
12 +- [简体中文](https://github.com/expressjs/multer/blob/master/doc/README-zh-cn.md) (Chinese)
13 +- [한국어](https://github.com/expressjs/multer/blob/master/doc/README-ko.md) (Korean)
14 +- [Русский язык](https://github.com/expressjs/multer/blob/master/doc/README-ru.md) (Russian)
15 +
16 +## Installation
17 +
18 +```sh
19 +$ npm install --save multer
20 +```
21 +
22 +## Usage
23 +
24 +Multer adds a `body` object and a `file` or `files` object to the `request` object. The `body` object contains the values of the text fields of the form, the `file` or `files` object contains the files uploaded via the form.
25 +
26 +Basic usage example:
27 +
28 +Don't forget the `enctype="multipart/form-data"` in your form.
29 +
30 +```html
31 +<form action="/profile" method="post" enctype="multipart/form-data">
32 + <input type="file" name="avatar" />
33 +</form>
34 +```
35 +
36 +```javascript
37 +var express = require('express')
38 +var multer = require('multer')
39 +var upload = multer({ dest: 'uploads/' })
40 +
41 +var app = express()
42 +
43 +app.post('/profile', upload.single('avatar'), function (req, res, next) {
44 + // req.file is the `avatar` file
45 + // req.body will hold the text fields, if there were any
46 +})
47 +
48 +app.post('/photos/upload', upload.array('photos', 12), function (req, res, next) {
49 + // req.files is array of `photos` files
50 + // req.body will contain the text fields, if there were any
51 +})
52 +
53 +var cpUpload = upload.fields([{ name: 'avatar', maxCount: 1 }, { name: 'gallery', maxCount: 8 }])
54 +app.post('/cool-profile', cpUpload, function (req, res, next) {
55 + // req.files is an object (String -> Array) where fieldname is the key, and the value is array of files
56 + //
57 + // e.g.
58 + // req.files['avatar'][0] -> File
59 + // req.files['gallery'] -> Array
60 + //
61 + // req.body will contain the text fields, if there were any
62 +})
63 +```
64 +
65 +In case you need to handle a text-only multipart form, you should use the `.none()` method:
66 +
67 +```javascript
68 +var express = require('express')
69 +var app = express()
70 +var multer = require('multer')
71 +var upload = multer()
72 +
73 +app.post('/profile', upload.none(), function (req, res, next) {
74 + // req.body contains the text fields
75 +})
76 +```
77 +
78 +## API
79 +
80 +### File information
81 +
82 +Each file contains the following information:
83 +
84 +Key | Description | Note
85 +--- | --- | ---
86 +`fieldname` | Field name specified in the form |
87 +`originalname` | Name of the file on the user's computer |
88 +`encoding` | Encoding type of the file |
89 +`mimetype` | Mime type of the file |
90 +`size` | Size of the file in bytes |
91 +`destination` | The folder to which the file has been saved | `DiskStorage`
92 +`filename` | The name of the file within the `destination` | `DiskStorage`
93 +`path` | The full path to the uploaded file | `DiskStorage`
94 +`buffer` | A `Buffer` of the entire file | `MemoryStorage`
95 +
96 +### `multer(opts)`
97 +
98 +Multer accepts an options object, the most basic of which is the `dest`
99 +property, which tells Multer where to upload the files. In case you omit the
100 +options object, the files will be kept in memory and never written to disk.
101 +
102 +By default, Multer will rename the files so as to avoid naming conflicts. The
103 +renaming function can be customized according to your needs.
104 +
105 +The following are the options that can be passed to Multer.
106 +
107 +Key | Description
108 +--- | ---
109 +`dest` or `storage` | Where to store the files
110 +`fileFilter` | Function to control which files are accepted
111 +`limits` | Limits of the uploaded data
112 +`preservePath` | Keep the full path of files instead of just the base name
113 +
114 +In an average web app, only `dest` might be required, and configured as shown in
115 +the following example.
116 +
117 +```javascript
118 +var upload = multer({ dest: 'uploads/' })
119 +```
120 +
121 +If you want more control over your uploads, you'll want to use the `storage`
122 +option instead of `dest`. Multer ships with storage engines `DiskStorage`
123 +and `MemoryStorage`; More engines are available from third parties.
124 +
125 +#### `.single(fieldname)`
126 +
127 +Accept a single file with the name `fieldname`. The single file will be stored
128 +in `req.file`.
129 +
130 +#### `.array(fieldname[, maxCount])`
131 +
132 +Accept an array of files, all with the name `fieldname`. Optionally error out if
133 +more than `maxCount` files are uploaded. The array of files will be stored in
134 +`req.files`.
135 +
136 +#### `.fields(fields)`
137 +
138 +Accept a mix of files, specified by `fields`. An object with arrays of files
139 +will be stored in `req.files`.
140 +
141 +`fields` should be an array of objects with `name` and optionally a `maxCount`.
142 +Example:
143 +
144 +```javascript
145 +[
146 + { name: 'avatar', maxCount: 1 },
147 + { name: 'gallery', maxCount: 8 }
148 +]
149 +```
150 +
151 +#### `.none()`
152 +
153 +Accept only text fields. If any file upload is made, error with code
154 +"LIMIT\_UNEXPECTED\_FILE" will be issued.
155 +
156 +#### `.any()`
157 +
158 +Accepts all files that comes over the wire. An array of files will be stored in
159 +`req.files`.
160 +
161 +**WARNING:** Make sure that you always handle the files that a user uploads.
162 +Never add multer as a global middleware since a malicious user could upload
163 +files to a route that you didn't anticipate. Only use this function on routes
164 +where you are handling the uploaded files.
165 +
166 +### `storage`
167 +
168 +#### `DiskStorage`
169 +
170 +The disk storage engine gives you full control on storing files to disk.
171 +
172 +```javascript
173 +var storage = multer.diskStorage({
174 + destination: function (req, file, cb) {
175 + cb(null, '/tmp/my-uploads')
176 + },
177 + filename: function (req, file, cb) {
178 + cb(null, file.fieldname + '-' + Date.now())
179 + }
180 +})
181 +
182 +var upload = multer({ storage: storage })
183 +```
184 +
185 +There are two options available, `destination` and `filename`. They are both
186 +functions that determine where the file should be stored.
187 +
188 +`destination` is used to determine within which folder the uploaded files should
189 +be stored. This can also be given as a `string` (e.g. `'/tmp/uploads'`). If no
190 +`destination` is given, the operating system's default directory for temporary
191 +files is used.
192 +
193 +**Note:** You are responsible for creating the directory when providing
194 +`destination` as a function. When passing a string, multer will make sure that
195 +the directory is created for you.
196 +
197 +`filename` is used to determine what the file should be named inside the folder.
198 +If no `filename` is given, each file will be given a random name that doesn't
199 +include any file extension.
200 +
201 +**Note:** Multer will not append any file extension for you, your function
202 +should return a filename complete with an file extension.
203 +
204 +Each function gets passed both the request (`req`) and some information about
205 +the file (`file`) to aid with the decision.
206 +
207 +Note that `req.body` might not have been fully populated yet. It depends on the
208 +order that the client transmits fields and files to the server.
209 +
210 +#### `MemoryStorage`
211 +
212 +The memory storage engine stores the files in memory as `Buffer` objects. It
213 +doesn't have any options.
214 +
215 +```javascript
216 +var storage = multer.memoryStorage()
217 +var upload = multer({ storage: storage })
218 +```
219 +
220 +When using memory storage, the file info will contain a field called
221 +`buffer` that contains the entire file.
222 +
223 +**WARNING**: Uploading very large files, or relatively small files in large
224 +numbers very quickly, can cause your application to run out of memory when
225 +memory storage is used.
226 +
227 +### `limits`
228 +
229 +An object specifying the size limits of the following optional properties. Multer passes this object into busboy directly, and the details of the properties can be found on [busboy's page](https://github.com/mscdex/busboy#busboy-methods).
230 +
231 +The following integer values are available:
232 +
233 +Key | Description | Default
234 +--- | --- | ---
235 +`fieldNameSize` | Max field name size | 100 bytes
236 +`fieldSize` | Max field value size (in bytes) | 1MB
237 +`fields` | Max number of non-file fields | Infinity
238 +`fileSize` | For multipart forms, the max file size (in bytes) | Infinity
239 +`files` | For multipart forms, the max number of file fields | Infinity
240 +`parts` | For multipart forms, the max number of parts (fields + files) | Infinity
241 +`headerPairs` | For multipart forms, the max number of header key=>value pairs to parse | 2000
242 +
243 +Specifying the limits can help protect your site against denial of service (DoS) attacks.
244 +
245 +### `fileFilter`
246 +
247 +Set this to a function to control which files should be uploaded and which
248 +should be skipped. The function should look like this:
249 +
250 +```javascript
251 +function fileFilter (req, file, cb) {
252 +
253 + // The function should call `cb` with a boolean
254 + // to indicate if the file should be accepted
255 +
256 + // To reject this file pass `false`, like so:
257 + cb(null, false)
258 +
259 + // To accept the file pass `true`, like so:
260 + cb(null, true)
261 +
262 + // You can always pass an error if something goes wrong:
263 + cb(new Error('I don\'t have a clue!'))
264 +
265 +}
266 +```
267 +
268 +## Error handling
269 +
270 +When encountering an error, Multer will delegate the error to Express. You can
271 +display a nice error page using [the standard express way](http://expressjs.com/guide/error-handling.html).
272 +
273 +If you want to catch errors specifically from Multer, you can call the
274 +middleware function by yourself. Also, if you want to catch only [the Multer errors](https://github.com/expressjs/multer/blob/master/lib/multer-error.js), you can use the `MulterError` class that is attached to the `multer` object itself (e.g. `err instanceof multer.MulterError`).
275 +
276 +```javascript
277 +var multer = require('multer')
278 +var upload = multer().single('avatar')
279 +
280 +app.post('/profile', function (req, res) {
281 + upload(req, res, function (err) {
282 + if (err instanceof multer.MulterError) {
283 + // A Multer error occurred when uploading.
284 + } else if (err) {
285 + // An unknown error occurred when uploading.
286 + }
287 +
288 + // Everything went fine.
289 + })
290 +})
291 +```
292 +
293 +## Custom storage engine
294 +
295 +For information on how to build your own storage engine, see [Multer Storage Engine](https://github.com/expressjs/multer/blob/master/StorageEngine.md).
296 +
297 +## License
298 +
299 +[MIT](LICENSE)
1 +var makeMiddleware = require('./lib/make-middleware')
2 +
3 +var diskStorage = require('./storage/disk')
4 +var memoryStorage = require('./storage/memory')
5 +var MulterError = require('./lib/multer-error')
6 +
7 +function allowAll (req, file, cb) {
8 + cb(null, true)
9 +}
10 +
11 +function Multer (options) {
12 + if (options.storage) {
13 + this.storage = options.storage
14 + } else if (options.dest) {
15 + this.storage = diskStorage({ destination: options.dest })
16 + } else {
17 + this.storage = memoryStorage()
18 + }
19 +
20 + this.limits = options.limits
21 + this.preservePath = options.preservePath
22 + this.fileFilter = options.fileFilter || allowAll
23 +}
24 +
25 +Multer.prototype._makeMiddleware = function (fields, fileStrategy) {
26 + function setup () {
27 + var fileFilter = this.fileFilter
28 + var filesLeft = Object.create(null)
29 +
30 + fields.forEach(function (field) {
31 + if (typeof field.maxCount === 'number') {
32 + filesLeft[field.name] = field.maxCount
33 + } else {
34 + filesLeft[field.name] = Infinity
35 + }
36 + })
37 +
38 + function wrappedFileFilter (req, file, cb) {
39 + if ((filesLeft[file.fieldname] || 0) <= 0) {
40 + return cb(new MulterError('LIMIT_UNEXPECTED_FILE', file.fieldname))
41 + }
42 +
43 + filesLeft[file.fieldname] -= 1
44 + fileFilter(req, file, cb)
45 + }
46 +
47 + return {
48 + limits: this.limits,
49 + preservePath: this.preservePath,
50 + storage: this.storage,
51 + fileFilter: wrappedFileFilter,
52 + fileStrategy: fileStrategy
53 + }
54 + }
55 +
56 + return makeMiddleware(setup.bind(this))
57 +}
58 +
59 +Multer.prototype.single = function (name) {
60 + return this._makeMiddleware([{ name: name, maxCount: 1 }], 'VALUE')
61 +}
62 +
63 +Multer.prototype.array = function (name, maxCount) {
64 + return this._makeMiddleware([{ name: name, maxCount: maxCount }], 'ARRAY')
65 +}
66 +
67 +Multer.prototype.fields = function (fields) {
68 + return this._makeMiddleware(fields, 'OBJECT')
69 +}
70 +
71 +Multer.prototype.none = function () {
72 + return this._makeMiddleware([], 'NONE')
73 +}
74 +
75 +Multer.prototype.any = function () {
76 + function setup () {
77 + return {
78 + limits: this.limits,
79 + preservePath: this.preservePath,
80 + storage: this.storage,
81 + fileFilter: this.fileFilter,
82 + fileStrategy: 'ARRAY'
83 + }
84 + }
85 +
86 + return makeMiddleware(setup.bind(this))
87 +}
88 +
89 +function multer (options) {
90 + if (options === undefined) {
91 + return new Multer({})
92 + }
93 +
94 + if (typeof options === 'object' && options !== null) {
95 + return new Multer(options)
96 + }
97 +
98 + throw new TypeError('Expected object for argument options')
99 +}
100 +
101 +module.exports = multer
102 +module.exports.diskStorage = diskStorage
103 +module.exports.memoryStorage = memoryStorage
104 +module.exports.MulterError = MulterError
1 +var EventEmitter = require('events').EventEmitter
2 +
3 +function Counter () {
4 + EventEmitter.call(this)
5 + this.value = 0
6 +}
7 +
8 +Counter.prototype = Object.create(EventEmitter.prototype)
9 +
10 +Counter.prototype.increment = function increment () {
11 + this.value++
12 +}
13 +
14 +Counter.prototype.decrement = function decrement () {
15 + if (--this.value === 0) this.emit('zero')
16 +}
17 +
18 +Counter.prototype.isZero = function isZero () {
19 + return (this.value === 0)
20 +}
21 +
22 +Counter.prototype.onceZero = function onceZero (fn) {
23 + if (this.isZero()) return fn()
24 +
25 + this.once('zero', fn)
26 +}
27 +
28 +module.exports = Counter
1 +var objectAssign = require('object-assign')
2 +
3 +function arrayRemove (arr, item) {
4 + var idx = arr.indexOf(item)
5 + if (~idx) arr.splice(idx, 1)
6 +}
7 +
8 +function FileAppender (strategy, req) {
9 + this.strategy = strategy
10 + this.req = req
11 +
12 + switch (strategy) {
13 + case 'NONE': break
14 + case 'VALUE': break
15 + case 'ARRAY': req.files = []; break
16 + case 'OBJECT': req.files = Object.create(null); break
17 + default: throw new Error('Unknown file strategy: ' + strategy)
18 + }
19 +}
20 +
21 +FileAppender.prototype.insertPlaceholder = function (file) {
22 + var placeholder = {
23 + fieldname: file.fieldname
24 + }
25 +
26 + switch (this.strategy) {
27 + case 'NONE': break
28 + case 'VALUE': break
29 + case 'ARRAY': this.req.files.push(placeholder); break
30 + case 'OBJECT':
31 + if (this.req.files[file.fieldname]) {
32 + this.req.files[file.fieldname].push(placeholder)
33 + } else {
34 + this.req.files[file.fieldname] = [placeholder]
35 + }
36 + break
37 + }
38 +
39 + return placeholder
40 +}
41 +
42 +FileAppender.prototype.removePlaceholder = function (placeholder) {
43 + switch (this.strategy) {
44 + case 'NONE': break
45 + case 'VALUE': break
46 + case 'ARRAY': arrayRemove(this.req.files, placeholder); break
47 + case 'OBJECT':
48 + if (this.req.files[placeholder.fieldname].length === 1) {
49 + delete this.req.files[placeholder.fieldname]
50 + } else {
51 + arrayRemove(this.req.files[placeholder.fieldname], placeholder)
52 + }
53 + break
54 + }
55 +}
56 +
57 +FileAppender.prototype.replacePlaceholder = function (placeholder, file) {
58 + if (this.strategy === 'VALUE') {
59 + this.req.file = file
60 + return
61 + }
62 +
63 + delete placeholder.fieldname
64 + objectAssign(placeholder, file)
65 +}
66 +
67 +module.exports = FileAppender
1 +var is = require('type-is')
2 +var Busboy = require('busboy')
3 +var extend = require('xtend')
4 +var onFinished = require('on-finished')
5 +var appendField = require('append-field')
6 +
7 +var Counter = require('./counter')
8 +var MulterError = require('./multer-error')
9 +var FileAppender = require('./file-appender')
10 +var removeUploadedFiles = require('./remove-uploaded-files')
11 +
12 +function drainStream (stream) {
13 + stream.on('readable', stream.read.bind(stream))
14 +}
15 +
16 +function makeMiddleware (setup) {
17 + return function multerMiddleware (req, res, next) {
18 + if (!is(req, ['multipart'])) return next()
19 +
20 + var options = setup()
21 +
22 + var limits = options.limits
23 + var storage = options.storage
24 + var fileFilter = options.fileFilter
25 + var fileStrategy = options.fileStrategy
26 + var preservePath = options.preservePath
27 +
28 + req.body = Object.create(null)
29 +
30 + var busboy
31 +
32 + try {
33 + busboy = new Busboy({ headers: req.headers, limits: limits, preservePath: preservePath })
34 + } catch (err) {
35 + return next(err)
36 + }
37 +
38 + var appender = new FileAppender(fileStrategy, req)
39 + var isDone = false
40 + var readFinished = false
41 + var errorOccured = false
42 + var pendingWrites = new Counter()
43 + var uploadedFiles = []
44 +
45 + function done (err) {
46 + if (isDone) return
47 + isDone = true
48 +
49 + req.unpipe(busboy)
50 + drainStream(req)
51 + busboy.removeAllListeners()
52 +
53 + onFinished(req, function () { next(err) })
54 + }
55 +
56 + function indicateDone () {
57 + if (readFinished && pendingWrites.isZero() && !errorOccured) done()
58 + }
59 +
60 + function abortWithError (uploadError) {
61 + if (errorOccured) return
62 + errorOccured = true
63 +
64 + pendingWrites.onceZero(function () {
65 + function remove (file, cb) {
66 + storage._removeFile(req, file, cb)
67 + }
68 +
69 + removeUploadedFiles(uploadedFiles, remove, function (err, storageErrors) {
70 + if (err) return done(err)
71 +
72 + uploadError.storageErrors = storageErrors
73 + done(uploadError)
74 + })
75 + })
76 + }
77 +
78 + function abortWithCode (code, optionalField) {
79 + abortWithError(new MulterError(code, optionalField))
80 + }
81 +
82 + // handle text field data
83 + busboy.on('field', function (fieldname, value, fieldnameTruncated, valueTruncated) {
84 + if (fieldnameTruncated) return abortWithCode('LIMIT_FIELD_KEY')
85 + if (valueTruncated) return abortWithCode('LIMIT_FIELD_VALUE', fieldname)
86 +
87 + // Work around bug in Busboy (https://github.com/mscdex/busboy/issues/6)
88 + if (limits && limits.hasOwnProperty('fieldNameSize')) {
89 + if (fieldname.length > limits.fieldNameSize) return abortWithCode('LIMIT_FIELD_KEY')
90 + }
91 +
92 + appendField(req.body, fieldname, value)
93 + })
94 +
95 + // handle files
96 + busboy.on('file', function (fieldname, fileStream, filename, encoding, mimetype) {
97 + // don't attach to the files object, if there is no file
98 + if (!filename) return fileStream.resume()
99 +
100 + // Work around bug in Busboy (https://github.com/mscdex/busboy/issues/6)
101 + if (limits && limits.hasOwnProperty('fieldNameSize')) {
102 + if (fieldname.length > limits.fieldNameSize) return abortWithCode('LIMIT_FIELD_KEY')
103 + }
104 +
105 + var file = {
106 + fieldname: fieldname,
107 + originalname: filename,
108 + encoding: encoding,
109 + mimetype: mimetype
110 + }
111 +
112 + var placeholder = appender.insertPlaceholder(file)
113 +
114 + fileFilter(req, file, function (err, includeFile) {
115 + if (err) {
116 + appender.removePlaceholder(placeholder)
117 + return abortWithError(err)
118 + }
119 +
120 + if (!includeFile) {
121 + appender.removePlaceholder(placeholder)
122 + return fileStream.resume()
123 + }
124 +
125 + var aborting = false
126 + pendingWrites.increment()
127 +
128 + Object.defineProperty(file, 'stream', {
129 + configurable: true,
130 + enumerable: false,
131 + value: fileStream
132 + })
133 +
134 + fileStream.on('error', function (err) {
135 + pendingWrites.decrement()
136 + abortWithError(err)
137 + })
138 +
139 + fileStream.on('limit', function () {
140 + aborting = true
141 + abortWithCode('LIMIT_FILE_SIZE', fieldname)
142 + })
143 +
144 + storage._handleFile(req, file, function (err, info) {
145 + if (aborting) {
146 + appender.removePlaceholder(placeholder)
147 + uploadedFiles.push(extend(file, info))
148 + return pendingWrites.decrement()
149 + }
150 +
151 + if (err) {
152 + appender.removePlaceholder(placeholder)
153 + pendingWrites.decrement()
154 + return abortWithError(err)
155 + }
156 +
157 + var fileInfo = extend(file, info)
158 +
159 + appender.replacePlaceholder(placeholder, fileInfo)
160 + uploadedFiles.push(fileInfo)
161 + pendingWrites.decrement()
162 + indicateDone()
163 + })
164 + })
165 + })
166 +
167 + busboy.on('error', function (err) { abortWithError(err) })
168 + busboy.on('partsLimit', function () { abortWithCode('LIMIT_PART_COUNT') })
169 + busboy.on('filesLimit', function () { abortWithCode('LIMIT_FILE_COUNT') })
170 + busboy.on('fieldsLimit', function () { abortWithCode('LIMIT_FIELD_COUNT') })
171 + busboy.on('finish', function () {
172 + readFinished = true
173 + indicateDone()
174 + })
175 +
176 + req.pipe(busboy)
177 + }
178 +}
179 +
180 +module.exports = makeMiddleware
1 +var util = require('util')
2 +
3 +var errorMessages = {
4 + 'LIMIT_PART_COUNT': 'Too many parts',
5 + 'LIMIT_FILE_SIZE': 'File too large',
6 + 'LIMIT_FILE_COUNT': 'Too many files',
7 + 'LIMIT_FIELD_KEY': 'Field name too long',
8 + 'LIMIT_FIELD_VALUE': 'Field value too long',
9 + 'LIMIT_FIELD_COUNT': 'Too many fields',
10 + 'LIMIT_UNEXPECTED_FILE': 'Unexpected field'
11 +}
12 +
13 +function MulterError (code, field) {
14 + Error.captureStackTrace(this, this.constructor)
15 + this.name = this.constructor.name
16 + this.message = errorMessages[code]
17 + this.code = code
18 + if (field) this.field = field
19 +}
20 +
21 +util.inherits(MulterError, Error)
22 +
23 +module.exports = MulterError
1 +function removeUploadedFiles (uploadedFiles, remove, cb) {
2 + var length = uploadedFiles.length
3 + var errors = []
4 +
5 + if (length === 0) return cb(null, errors)
6 +
7 + function handleFile (idx) {
8 + var file = uploadedFiles[idx]
9 +
10 + remove(file, function (err) {
11 + if (err) {
12 + err.file = file
13 + err.field = file.fieldname
14 + errors.push(err)
15 + }
16 +
17 + if (idx < length - 1) {
18 + handleFile(idx + 1)
19 + } else {
20 + cb(null, errors)
21 + }
22 + })
23 + }
24 +
25 + handleFile(0)
26 +}
27 +
28 +module.exports = removeUploadedFiles
1 +{
2 + "_from": "multer",
3 + "_id": "multer@1.4.2",
4 + "_inBundle": false,
5 + "_integrity": "sha512-xY8pX7V+ybyUpbYMxtjM9KAiD9ixtg5/JkeKUTD6xilfDv0vzzOFcCp4Ljb1UU3tSOM3VTZtKo63OmzOrGi3Cg==",
6 + "_location": "/multer",
7 + "_phantomChildren": {},
8 + "_requested": {
9 + "type": "tag",
10 + "registry": true,
11 + "raw": "multer",
12 + "name": "multer",
13 + "escapedName": "multer",
14 + "rawSpec": "",
15 + "saveSpec": null,
16 + "fetchSpec": "latest"
17 + },
18 + "_requiredBy": [
19 + "#USER",
20 + "/"
21 + ],
22 + "_resolved": "https://registry.npmjs.org/multer/-/multer-1.4.2.tgz",
23 + "_shasum": "2f1f4d12dbaeeba74cb37e623f234bf4d3d2057a",
24 + "_spec": "multer",
25 + "_where": "C:\\Users\\1000c\\이것저것\\옾소\\Voicoding",
26 + "bugs": {
27 + "url": "https://github.com/expressjs/multer/issues"
28 + },
29 + "bundleDependencies": false,
30 + "contributors": [
31 + {
32 + "name": "Hage Yaapa",
33 + "email": "captain@hacksparrow.com",
34 + "url": "http://www.hacksparrow.com"
35 + },
36 + {
37 + "name": "Jaret Pfluger",
38 + "email": "https://github.com/jpfluger"
39 + },
40 + {
41 + "name": "Linus Unnebäck",
42 + "email": "linus@folkdatorn.se"
43 + }
44 + ],
45 + "dependencies": {
46 + "append-field": "^1.0.0",
47 + "busboy": "^0.2.11",
48 + "concat-stream": "^1.5.2",
49 + "mkdirp": "^0.5.1",
50 + "object-assign": "^4.1.1",
51 + "on-finished": "^2.3.0",
52 + "type-is": "^1.6.4",
53 + "xtend": "^4.0.0"
54 + },
55 + "deprecated": false,
56 + "description": "Middleware for handling `multipart/form-data`.",
57 + "devDependencies": {
58 + "express": "^4.13.1",
59 + "form-data": "^1.0.0-rc1",
60 + "fs-temp": "^1.1.2",
61 + "mocha": "^3.5.3",
62 + "rimraf": "^2.4.1",
63 + "standard": "^11.0.1",
64 + "testdata-w3c-json-form": "^1.0.0"
65 + },
66 + "engines": {
67 + "node": ">= 0.10.0"
68 + },
69 + "files": [
70 + "LICENSE",
71 + "index.js",
72 + "storage/",
73 + "lib/"
74 + ],
75 + "homepage": "https://github.com/expressjs/multer#readme",
76 + "keywords": [
77 + "form",
78 + "post",
79 + "multipart",
80 + "form-data",
81 + "formdata",
82 + "express",
83 + "middleware"
84 + ],
85 + "license": "MIT",
86 + "name": "multer",
87 + "repository": {
88 + "type": "git",
89 + "url": "git+https://github.com/expressjs/multer.git"
90 + },
91 + "scripts": {
92 + "test": "standard && mocha"
93 + },
94 + "version": "1.4.2"
95 +}
1 +var fs = require('fs')
2 +var os = require('os')
3 +var path = require('path')
4 +var crypto = require('crypto')
5 +var mkdirp = require('mkdirp')
6 +
7 +function getFilename (req, file, cb) {
8 + crypto.pseudoRandomBytes(16, function (err, raw) {
9 + cb(err, err ? undefined : raw.toString('hex'))
10 + })
11 +}
12 +
13 +function getDestination (req, file, cb) {
14 + cb(null, os.tmpdir())
15 +}
16 +
17 +function DiskStorage (opts) {
18 + this.getFilename = (opts.filename || getFilename)
19 +
20 + if (typeof opts.destination === 'string') {
21 + mkdirp.sync(opts.destination)
22 + this.getDestination = function ($0, $1, cb) { cb(null, opts.destination) }
23 + } else {
24 + this.getDestination = (opts.destination || getDestination)
25 + }
26 +}
27 +
28 +DiskStorage.prototype._handleFile = function _handleFile (req, file, cb) {
29 + var that = this
30 +
31 + that.getDestination(req, file, function (err, destination) {
32 + if (err) return cb(err)
33 +
34 + that.getFilename(req, file, function (err, filename) {
35 + if (err) return cb(err)
36 +
37 + var finalPath = path.join(destination, filename)
38 + var outStream = fs.createWriteStream(finalPath)
39 +
40 + file.stream.pipe(outStream)
41 + outStream.on('error', cb)
42 + outStream.on('finish', function () {
43 + cb(null, {
44 + destination: destination,
45 + filename: filename,
46 + path: finalPath,
47 + size: outStream.bytesWritten
48 + })
49 + })
50 + })
51 + })
52 +}
53 +
54 +DiskStorage.prototype._removeFile = function _removeFile (req, file, cb) {
55 + var path = file.path
56 +
57 + delete file.destination
58 + delete file.filename
59 + delete file.path
60 +
61 + fs.unlink(path, cb)
62 +}
63 +
64 +module.exports = function (opts) {
65 + return new DiskStorage(opts)
66 +}
1 +var concat = require('concat-stream')
2 +
3 +function MemoryStorage (opts) {}
4 +
5 +MemoryStorage.prototype._handleFile = function _handleFile (req, file, cb) {
6 + file.stream.pipe(concat({ encoding: 'buffer' }, function (data) {
7 + cb(null, {
8 + buffer: data,
9 + size: data.length
10 + })
11 + }))
12 +}
13 +
14 +MemoryStorage.prototype._removeFile = function _removeFile (req, file, cb) {
15 + delete file.buffer
16 + cb(null)
17 +}
18 +
19 +module.exports = function (opts) {
20 + return new MemoryStorage(opts)
21 +}
1 +/*
2 +object-assign
3 +(c) Sindre Sorhus
4 +@license MIT
5 +*/
6 +
7 +'use strict';
8 +/* eslint-disable no-unused-vars */
9 +var getOwnPropertySymbols = Object.getOwnPropertySymbols;
10 +var hasOwnProperty = Object.prototype.hasOwnProperty;
11 +var propIsEnumerable = Object.prototype.propertyIsEnumerable;
12 +
13 +function toObject(val) {
14 + if (val === null || val === undefined) {
15 + throw new TypeError('Object.assign cannot be called with null or undefined');
16 + }
17 +
18 + return Object(val);
19 +}
20 +
21 +function shouldUseNative() {
22 + try {
23 + if (!Object.assign) {
24 + return false;
25 + }
26 +
27 + // Detect buggy property enumeration order in older V8 versions.
28 +
29 + // https://bugs.chromium.org/p/v8/issues/detail?id=4118
30 + var test1 = new String('abc'); // eslint-disable-line no-new-wrappers
31 + test1[5] = 'de';
32 + if (Object.getOwnPropertyNames(test1)[0] === '5') {
33 + return false;
34 + }
35 +
36 + // https://bugs.chromium.org/p/v8/issues/detail?id=3056
37 + var test2 = {};
38 + for (var i = 0; i < 10; i++) {
39 + test2['_' + String.fromCharCode(i)] = i;
40 + }
41 + var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
42 + return test2[n];
43 + });
44 + if (order2.join('') !== '0123456789') {
45 + return false;
46 + }
47 +
48 + // https://bugs.chromium.org/p/v8/issues/detail?id=3056
49 + var test3 = {};
50 + 'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
51 + test3[letter] = letter;
52 + });
53 + if (Object.keys(Object.assign({}, test3)).join('') !==
54 + 'abcdefghijklmnopqrst') {
55 + return false;
56 + }
57 +
58 + return true;
59 + } catch (err) {
60 + // We don't expect any of the above to throw, but better to be safe.
61 + return false;
62 + }
63 +}
64 +
65 +module.exports = shouldUseNative() ? Object.assign : function (target, source) {
66 + var from;
67 + var to = toObject(target);
68 + var symbols;
69 +
70 + for (var s = 1; s < arguments.length; s++) {
71 + from = Object(arguments[s]);
72 +
73 + for (var key in from) {
74 + if (hasOwnProperty.call(from, key)) {
75 + to[key] = from[key];
76 + }
77 + }
78 +
79 + if (getOwnPropertySymbols) {
80 + symbols = getOwnPropertySymbols(from);
81 + for (var i = 0; i < symbols.length; i++) {
82 + if (propIsEnumerable.call(from, symbols[i])) {
83 + to[symbols[i]] = from[symbols[i]];
84 + }
85 + }
86 + }
87 + }
88 +
89 + return to;
90 +};
1 +The MIT License (MIT)
2 +
3 +Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
4 +
5 +Permission is hereby granted, free of charge, to any person obtaining a copy
6 +of this software and associated documentation files (the "Software"), to deal
7 +in the Software without restriction, including without limitation the rights
8 +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 +copies of the Software, and to permit persons to whom the Software is
10 +furnished to do so, subject to the following conditions:
11 +
12 +The above copyright notice and this permission notice shall be included in
13 +all copies or substantial portions of the Software.
14 +
15 +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21 +THE SOFTWARE.
1 +{
2 + "_from": "object-assign@^4.1.1",
3 + "_id": "object-assign@4.1.1",
4 + "_inBundle": false,
5 + "_integrity": "sha1-IQmtx5ZYh8/AXLvUQsrIv7s2CGM=",
6 + "_location": "/object-assign",
7 + "_phantomChildren": {},
8 + "_requested": {
9 + "type": "range",
10 + "registry": true,
11 + "raw": "object-assign@^4.1.1",
12 + "name": "object-assign",
13 + "escapedName": "object-assign",
14 + "rawSpec": "^4.1.1",
15 + "saveSpec": null,
16 + "fetchSpec": "^4.1.1"
17 + },
18 + "_requiredBy": [
19 + "/multer"
20 + ],
21 + "_resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
22 + "_shasum": "2109adc7965887cfc05cbbd442cac8bfbb360863",
23 + "_spec": "object-assign@^4.1.1",
24 + "_where": "C:\\Users\\1000c\\이것저것\\옾소\\Voicoding\\node_modules\\multer",
25 + "author": {
26 + "name": "Sindre Sorhus",
27 + "email": "sindresorhus@gmail.com",
28 + "url": "sindresorhus.com"
29 + },
30 + "bugs": {
31 + "url": "https://github.com/sindresorhus/object-assign/issues"
32 + },
33 + "bundleDependencies": false,
34 + "deprecated": false,
35 + "description": "ES2015 `Object.assign()` ponyfill",
36 + "devDependencies": {
37 + "ava": "^0.16.0",
38 + "lodash": "^4.16.4",
39 + "matcha": "^0.7.0",
40 + "xo": "^0.16.0"
41 + },
42 + "engines": {
43 + "node": ">=0.10.0"
44 + },
45 + "files": [
46 + "index.js"
47 + ],
48 + "homepage": "https://github.com/sindresorhus/object-assign#readme",
49 + "keywords": [
50 + "object",
51 + "assign",
52 + "extend",
53 + "properties",
54 + "es2015",
55 + "ecmascript",
56 + "harmony",
57 + "ponyfill",
58 + "prollyfill",
59 + "polyfill",
60 + "shim",
61 + "browser"
62 + ],
63 + "license": "MIT",
64 + "name": "object-assign",
65 + "repository": {
66 + "type": "git",
67 + "url": "git+https://github.com/sindresorhus/object-assign.git"
68 + },
69 + "scripts": {
70 + "bench": "matcha bench.js",
71 + "test": "xo && ava"
72 + },
73 + "version": "4.1.1"
74 +}
1 +# object-assign [![Build Status](https://travis-ci.org/sindresorhus/object-assign.svg?branch=master)](https://travis-ci.org/sindresorhus/object-assign)
2 +
3 +> ES2015 [`Object.assign()`](http://www.2ality.com/2014/01/object-assign.html) [ponyfill](https://ponyfill.com)
4 +
5 +
6 +## Use the built-in
7 +
8 +Node.js 4 and up, as well as every evergreen browser (Chrome, Edge, Firefox, Opera, Safari),
9 +support `Object.assign()` :tada:. If you target only those environments, then by all
10 +means, use `Object.assign()` instead of this package.
11 +
12 +
13 +## Install
14 +
15 +```
16 +$ npm install --save object-assign
17 +```
18 +
19 +
20 +## Usage
21 +
22 +```js
23 +const objectAssign = require('object-assign');
24 +
25 +objectAssign({foo: 0}, {bar: 1});
26 +//=> {foo: 0, bar: 1}
27 +
28 +// multiple sources
29 +objectAssign({foo: 0}, {bar: 1}, {baz: 2});
30 +//=> {foo: 0, bar: 1, baz: 2}
31 +
32 +// overwrites equal keys
33 +objectAssign({foo: 0}, {foo: 1}, {foo: 2});
34 +//=> {foo: 2}
35 +
36 +// ignores null and undefined sources
37 +objectAssign({foo: 0}, null, {bar: 1}, undefined);
38 +//=> {foo: 0, bar: 1}
39 +```
40 +
41 +
42 +## API
43 +
44 +### objectAssign(target, [source, ...])
45 +
46 +Assigns enumerable own properties of `source` objects to the `target` object and returns the `target` object. Additional `source` objects will overwrite previous ones.
47 +
48 +
49 +## Resources
50 +
51 +- [ES2015 spec - Object.assign](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.assign)
52 +
53 +
54 +## Related
55 +
56 +- [deep-assign](https://github.com/sindresorhus/deep-assign) - Recursive `Object.assign()`
57 +
58 +
59 +## License
60 +
61 +MIT © [Sindre Sorhus](https://sindresorhus.com)
1 -!function(e){var t;"object"==typeof exports?module.exports=e():"function"==typeof define&&define.amd?define(e):("undefined"!=typeof window?t=window:"undefined"!=typeof global?t=global:"undefined"!=typeof self&&(t=self),t.objectHash=e())}(function(){return function o(i,u,a){function s(n,e){if(!u[n]){if(!i[n]){var t="function"==typeof require&&require;if(!e&&t)return t(n,!0);if(f)return f(n,!0);throw new Error("Cannot find module '"+n+"'")}var r=u[n]={exports:{}};i[n][0].call(r.exports,function(e){var t=i[n][1][e];return s(t||e)},r,r.exports,o,i,u,a)}return u[n].exports}for(var f="function"==typeof require&&require,e=0;e<a.length;e++)s(a[e]);return s}({1:[function(w,b,m){(function(e,t,f,n,r,o,i,u,a){"use strict";var s=w("crypto");function l(e,t){return function(e,t){var n;n="passthrough"!==t.algorithm?s.createHash(t.algorithm):new y;void 0===n.write&&(n.write=n.update,n.end=n.update);g(t,n).dispatch(e),n.update||n.end("");if(n.digest)return n.digest("buffer"===t.encoding?void 0:t.encoding);var r=n.read();return"buffer"!==t.encoding?r.toString(t.encoding):r}(e,t=h(e,t))}(m=b.exports=l).sha1=function(e){return l(e)},m.keys=function(e){return l(e,{excludeValues:!0,algorithm:"sha1",encoding:"hex"})},m.MD5=function(e){return l(e,{algorithm:"md5",encoding:"hex"})},m.keysMD5=function(e){return l(e,{algorithm:"md5",encoding:"hex",excludeValues:!0})};var c=s.getHashes?s.getHashes().slice():["sha1","md5"];c.push("passthrough");var d=["buffer","hex","binary","base64"];function h(e,t){t=t||{};var n={};if(n.algorithm=t.algorithm||"sha1",n.encoding=t.encoding||"hex",n.excludeValues=!!t.excludeValues,n.algorithm=n.algorithm.toLowerCase(),n.encoding=n.encoding.toLowerCase(),n.ignoreUnknown=!0===t.ignoreUnknown,n.respectType=!1!==t.respectType,n.respectFunctionNames=!1!==t.respectFunctionNames,n.respectFunctionProperties=!1!==t.respectFunctionProperties,n.unorderedArrays=!0===t.unorderedArrays,n.unorderedSets=!1!==t.unorderedSets,n.unorderedObjects=!1!==t.unorderedObjects,n.replacer=t.replacer||void 0,n.excludeKeys=t.excludeKeys||void 0,void 0===e)throw new Error("Object argument required.");for(var r=0;r<c.length;++r)c[r].toLowerCase()===n.algorithm.toLowerCase()&&(n.algorithm=c[r]);if(-1===c.indexOf(n.algorithm))throw new Error('Algorithm "'+n.algorithm+'" not supported. supported values: '+c.join(", "));if(-1===d.indexOf(n.encoding)&&"passthrough"!==n.algorithm)throw new Error('Encoding "'+n.encoding+'" not supported. supported values: '+d.join(", "));return n}function p(e){if("function"==typeof e){return null!=/^function\s+\w*\s*\(\s*\)\s*{\s+\[native code\]\s+}$/i.exec(Function.prototype.toString.call(e))}}function g(u,t,a){a=a||[];function s(e){return t.update?t.update(e,"utf8"):t.write(e,"utf8")}return{dispatch:function(e){return u.replacer&&(e=u.replacer(e)),this["_"+(null===e?"null":typeof e)](e)},_object:function(t){var e=Object.prototype.toString.call(t),n=/\[object (.*)\]/i.exec(e);n=(n=n?n[1]:"unknown:["+e+"]").toLowerCase();var r;if(0<=(r=a.indexOf(t)))return this.dispatch("[CIRCULAR:"+r+"]");if(a.push(t),void 0!==f&&f.isBuffer&&f.isBuffer(t))return s("buffer:"),s(t);if("object"===n||"function"===n||"asyncfunction"===n){var o=Object.keys(t);u.unorderedObjects&&(o=o.sort()),!1===u.respectType||p(t)||o.splice(0,0,"prototype","__proto__","constructor"),u.excludeKeys&&(o=o.filter(function(e){return!u.excludeKeys(e)})),s("object:"+o.length+":");var i=this;return o.forEach(function(e){i.dispatch(e),s(":"),u.excludeValues||i.dispatch(t[e]),s(",")})}if(!this["_"+n]){if(u.ignoreUnknown)return s("["+n+"]");throw new Error('Unknown object type "'+n+'"')}this["_"+n](t)},_array:function(e,t){t=void 0!==t?t:!1!==u.unorderedArrays;var n=this;if(s("array:"+e.length+":"),!t||e.length<=1)return e.forEach(function(e){return n.dispatch(e)});var r=[],o=e.map(function(e){var t=new y,n=a.slice();return g(u,t,n).dispatch(e),r=r.concat(n.slice(a.length)),t.read().toString()});return a=a.concat(r),o.sort(),this._array(o,!1)},_date:function(e){return s("date:"+e.toJSON())},_symbol:function(e){return s("symbol:"+e.toString())},_error:function(e){return s("error:"+e.toString())},_boolean:function(e){return s("bool:"+e.toString())},_string:function(e){s("string:"+e.length+":"),s(e.toString())},_function:function(e){s("fn:"),p(e)?this.dispatch("[native]"):this.dispatch(e.toString()),!1!==u.respectFunctionNames&&this.dispatch("function-name:"+String(e.name)),u.respectFunctionProperties&&this._object(e)},_number:function(e){return s("number:"+e.toString())},_xml:function(e){return s("xml:"+e.toString())},_null:function(){return s("Null")},_undefined:function(){return s("Undefined")},_regexp:function(e){return s("regex:"+e.toString())},_uint8array:function(e){return s("uint8array:"),this.dispatch(Array.prototype.slice.call(e))},_uint8clampedarray:function(e){return s("uint8clampedarray:"),this.dispatch(Array.prototype.slice.call(e))},_int8array:function(e){return s("uint8array:"),this.dispatch(Array.prototype.slice.call(e))},_uint16array:function(e){return s("uint16array:"),this.dispatch(Array.prototype.slice.call(e))},_int16array:function(e){return s("uint16array:"),this.dispatch(Array.prototype.slice.call(e))},_uint32array:function(e){return s("uint32array:"),this.dispatch(Array.prototype.slice.call(e))},_int32array:function(e){return s("uint32array:"),this.dispatch(Array.prototype.slice.call(e))},_float32array:function(e){return s("float32array:"),this.dispatch(Array.prototype.slice.call(e))},_float64array:function(e){return s("float64array:"),this.dispatch(Array.prototype.slice.call(e))},_arraybuffer:function(e){return s("arraybuffer:"),this.dispatch(new Uint8Array(e))},_url:function(e){return s("url:"+e.toString())},_map:function(e){s("map:");var t=Array.from(e);return this._array(t,!1!==u.unorderedSets)},_set:function(e){s("set:");var t=Array.from(e);return this._array(t,!1!==u.unorderedSets)},_file:function(e){return s("file:"),this.dispatch([e.name,e.size,e.type,e.lastModfied])},_blob:function(){if(u.ignoreUnknown)return s("[blob]");throw Error('Hashing Blob objects is currently not supported\n(see https://github.com/puleos/object-hash/issues/26)\nUse "options.replacer" or "options.ignoreUnknown"\n')},_domwindow:function(){return s("domwindow")},_process:function(){return s("process")},_timer:function(){return s("timer")},_pipe:function(){return s("pipe")},_tcp:function(){return s("tcp")},_udp:function(){return s("udp")},_tty:function(){return s("tty")},_statwatcher:function(){return s("statwatcher")},_securecontext:function(){return s("securecontext")},_connection:function(){return s("connection")},_zlib:function(){return s("zlib")},_context:function(){return s("context")},_nodescript:function(){return s("nodescript")},_httpparser:function(){return s("httpparser")},_dataview:function(){return s("dataview")},_signal:function(){return s("signal")},_fsevent:function(){return s("fsevent")},_tlswrap:function(){return s("tlswrap")}}}function y(){return{buf:"",write:function(e){this.buf+=e},end:function(e){this.buf+=e},read:function(){return this.buf}}}m.writeToStream=function(e,t,n){return void 0===n&&(n=t,t={}),g(t=h(e,t),n).dispatch(e)}}).call(this,w("lYpoI2"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},w("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/fake_5812b7fb.js","/")},{buffer:3,crypto:5,lYpoI2:10}],2:[function(e,t,f){(function(e,t,n,r,o,i,u,a,s){!function(e){"use strict";var f="undefined"!=typeof Uint8Array?Uint8Array:Array,n="+".charCodeAt(0),r="/".charCodeAt(0),o="0".charCodeAt(0),i="a".charCodeAt(0),u="A".charCodeAt(0),a="-".charCodeAt(0),s="_".charCodeAt(0);function l(e){var t=e.charCodeAt(0);return t===n||t===a?62:t===r||t===s?63:t<o?-1:t<o+10?t-o+26+26:t<u+26?t-u:t<i+26?t-i+26:void 0}e.toByteArray=function(e){var t,n;if(0<e.length%4)throw new Error("Invalid string. Length must be a multiple of 4");var r=e.length,o="="===e.charAt(r-2)?2:"="===e.charAt(r-1)?1:0,i=new f(3*e.length/4-o),u=0<o?e.length-4:e.length,a=0;function s(e){i[a++]=e}for(t=0;t<u;t+=4,0)s((16711680&(n=l(e.charAt(t))<<18|l(e.charAt(t+1))<<12|l(e.charAt(t+2))<<6|l(e.charAt(t+3))))>>16),s((65280&n)>>8),s(255&n);return 2==o?s(255&(n=l(e.charAt(t))<<2|l(e.charAt(t+1))>>4)):1==o&&(s((n=l(e.charAt(t))<<10|l(e.charAt(t+1))<<4|l(e.charAt(t+2))>>2)>>8&255),s(255&n)),i},e.fromByteArray=function(e){var t,n,r,o,i=e.length%3,u="";function a(e){return"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(e)}for(t=0,r=e.length-i;t<r;t+=3)n=(e[t]<<16)+(e[t+1]<<8)+e[t+2],u+=a((o=n)>>18&63)+a(o>>12&63)+a(o>>6&63)+a(63&o);switch(i){case 1:u+=a((n=e[e.length-1])>>2),u+=a(n<<4&63),u+="==";break;case 2:u+=a((n=(e[e.length-2]<<8)+e[e.length-1])>>10),u+=a(n>>4&63),u+=a(n<<2&63),u+="="}return u}}(void 0===f?this.base64js={}:f)}).call(this,e("lYpoI2"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/base64-js/lib/b64.js","/node_modules/gulp-browserify/node_modules/base64-js/lib")},{buffer:3,lYpoI2:10}],3:[function(O,e,H){(function(e,t,g,n,r,o,i,u,a){var s=O("base64-js"),f=O("ieee754");function g(e,t,n){if(!(this instanceof g))return new g(e,t,n);var r,o,i,u,a,s=typeof e;if("base64"===t&&"string"==s)for(e=(r=e).trim?r.trim():r.replace(/^\s+|\s+$/g,"");e.length%4!=0;)e+="=";if("number"==s)o=x(e);else if("string"==s)o=g.byteLength(e,t);else{if("object"!=s)throw new Error("First argument needs to be a number, array or string.");o=x(e.length)}if(g._useTypedArrays?i=g._augment(new Uint8Array(o)):((i=this).length=o,i._isBuffer=!0),g._useTypedArrays&&"number"==typeof e.byteLength)i._set(e);else if(S(a=e)||g.isBuffer(a)||a&&"object"==typeof a&&"number"==typeof a.length)for(u=0;u<o;u++)g.isBuffer(e)?i[u]=e.readUInt8(u):i[u]=e[u];else if("string"==s)i.write(e,0,t);else if("number"==s&&!g._useTypedArrays&&!n)for(u=0;u<o;u++)i[u]=0;return i}function y(e,t,n,r){return g._charsWritten=T(function(e){for(var t=[],n=0;n<e.length;n++)t.push(255&e.charCodeAt(n));return t}(t),e,n,r)}function w(e,t,n,r){return g._charsWritten=T(function(e){for(var t,n,r,o=[],i=0;i<e.length;i++)t=e.charCodeAt(i),n=t>>8,r=t%256,o.push(r),o.push(n);return o}(t),e,n,r)}function l(e,t,n){var r="";n=Math.min(e.length,n);for(var o=t;o<n;o++)r+=String.fromCharCode(e[o]);return r}function c(e,t,n,r){r||(D("boolean"==typeof n,"missing or invalid endian"),D(null!=t,"missing offset"),D(t+1<e.length,"Trying to read beyond buffer length"));var o,i=e.length;if(!(i<=t))return n?(o=e[t],t+1<i&&(o|=e[t+1]<<8)):(o=e[t]<<8,t+1<i&&(o|=e[t+1])),o}function d(e,t,n,r){r||(D("boolean"==typeof n,"missing or invalid endian"),D(null!=t,"missing offset"),D(t+3<e.length,"Trying to read beyond buffer length"));var o,i=e.length;if(!(i<=t))return n?(t+2<i&&(o=e[t+2]<<16),t+1<i&&(o|=e[t+1]<<8),o|=e[t],t+3<i&&(o+=e[t+3]<<24>>>0)):(t+1<i&&(o=e[t+1]<<16),t+2<i&&(o|=e[t+2]<<8),t+3<i&&(o|=e[t+3]),o+=e[t]<<24>>>0),o}function h(e,t,n,r){if(r||(D("boolean"==typeof n,"missing or invalid endian"),D(null!=t,"missing offset"),D(t+1<e.length,"Trying to read beyond buffer length")),!(e.length<=t)){var o=c(e,t,n,!0);return 32768&o?-1*(65535-o+1):o}}function p(e,t,n,r){if(r||(D("boolean"==typeof n,"missing or invalid endian"),D(null!=t,"missing offset"),D(t+3<e.length,"Trying to read beyond buffer length")),!(e.length<=t)){var o=d(e,t,n,!0);return 2147483648&o?-1*(4294967295-o+1):o}}function b(e,t,n,r){return r||(D("boolean"==typeof n,"missing or invalid endian"),D(t+3<e.length,"Trying to read beyond buffer length")),f.read(e,t,n,23,4)}function m(e,t,n,r){return r||(D("boolean"==typeof n,"missing or invalid endian"),D(t+7<e.length,"Trying to read beyond buffer length")),f.read(e,t,n,52,8)}function v(e,t,n,r,o){o||(D(null!=t,"missing value"),D("boolean"==typeof r,"missing or invalid endian"),D(null!=n,"missing offset"),D(n+1<e.length,"trying to write beyond buffer length"),N(t,65535));var i=e.length;if(!(i<=n))for(var u=0,a=Math.min(i-n,2);u<a;u++)e[n+u]=(t&255<<8*(r?u:1-u))>>>8*(r?u:1-u)}function _(e,t,n,r,o){o||(D(null!=t,"missing value"),D("boolean"==typeof r,"missing or invalid endian"),D(null!=n,"missing offset"),D(n+3<e.length,"trying to write beyond buffer length"),N(t,4294967295));var i=e.length;if(!(i<=n))for(var u=0,a=Math.min(i-n,4);u<a;u++)e[n+u]=t>>>8*(r?u:3-u)&255}function E(e,t,n,r,o){o||(D(null!=t,"missing value"),D("boolean"==typeof r,"missing or invalid endian"),D(null!=n,"missing offset"),D(n+1<e.length,"Trying to write beyond buffer length"),Y(t,32767,-32768)),e.length<=n||v(e,0<=t?t:65535+t+1,n,r,o)}function I(e,t,n,r,o){o||(D(null!=t,"missing value"),D("boolean"==typeof r,"missing or invalid endian"),D(null!=n,"missing offset"),D(n+3<e.length,"Trying to write beyond buffer length"),Y(t,2147483647,-2147483648)),e.length<=n||_(e,0<=t?t:4294967295+t+1,n,r,o)}function A(e,t,n,r,o){o||(D(null!=t,"missing value"),D("boolean"==typeof r,"missing or invalid endian"),D(null!=n,"missing offset"),D(n+3<e.length,"Trying to write beyond buffer length"),F(t,34028234663852886e22,-34028234663852886e22)),e.length<=n||f.write(e,t,n,r,23,4)}function B(e,t,n,r,o){o||(D(null!=t,"missing value"),D("boolean"==typeof r,"missing or invalid endian"),D(null!=n,"missing offset"),D(n+7<e.length,"Trying to write beyond buffer length"),F(t,17976931348623157e292,-17976931348623157e292)),e.length<=n||f.write(e,t,n,r,52,8)}H.Buffer=g,H.SlowBuffer=g,H.INSPECT_MAX_BYTES=50,g.poolSize=8192,g._useTypedArrays=function(){try{var e=new ArrayBuffer(0),t=new Uint8Array(e);return t.foo=function(){return 42},42===t.foo()&&"function"==typeof t.subarray}catch(e){return!1}}(),g.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"raw":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},g.isBuffer=function(e){return!(null==e||!e._isBuffer)},g.byteLength=function(e,t){var n;switch(e+="",t||"utf8"){case"hex":n=e.length/2;break;case"utf8":case"utf-8":n=C(e).length;break;case"ascii":case"binary":case"raw":n=e.length;break;case"base64":n=k(e).length;break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":n=2*e.length;break;default:throw new Error("Unknown encoding")}return n},g.concat=function(e,t){if(D(S(e),"Usage: Buffer.concat(list, [totalLength])\nlist should be an Array."),0===e.length)return new g(0);if(1===e.length)return e[0];if("number"!=typeof t)for(o=t=0;o<e.length;o++)t+=e[o].length;for(var n=new g(t),r=0,o=0;o<e.length;o++){var i=e[o];i.copy(n,r),r+=i.length}return n},g.prototype.write=function(e,t,n,r){var o;isFinite(t)?isFinite(n)||(r=n,n=void 0):(o=r,r=t,t=n,n=o),t=Number(t)||0;var i,u,a,s,f,l,c,d,h,p=this.length-t;switch((!n||p<(n=Number(n)))&&(n=p),r=String(r||"utf8").toLowerCase()){case"hex":i=function(e,t,n,r){n=Number(n)||0;var o=e.length-n;(!r||o<(r=Number(r)))&&(r=o);var i=t.length;D(i%2==0,"Invalid hex string"),i/2<r&&(r=i/2);for(var u=0;u<r;u++){var a=parseInt(t.substr(2*u,2),16);D(!isNaN(a),"Invalid hex string"),e[n+u]=a}return g._charsWritten=2*u,u}(this,e,t,n);break;case"utf8":case"utf-8":l=this,c=e,d=t,h=n,i=g._charsWritten=T(C(c),l,d,h);break;case"ascii":case"binary":i=y(this,e,t,n);break;case"base64":u=this,a=e,s=t,f=n,i=g._charsWritten=T(k(a),u,s,f);break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":i=w(this,e,t,n);break;default:throw new Error("Unknown encoding")}return i},g.prototype.toString=function(e,t,n){var r,o,i,u,a=this;if(e=String(e||"utf8").toLowerCase(),t=Number(t)||0,(n=void 0!==n?Number(n):n=a.length)===t)return"";switch(e){case"hex":r=function(e,t,n){var r=e.length;(!t||t<0)&&(t=0);(!n||n<0||r<n)&&(n=r);for(var o="",i=t;i<n;i++)o+=j(e[i]);return o}(a,t,n);break;case"utf8":case"utf-8":r=function(e,t,n){var r="",o="";n=Math.min(e.length,n);for(var i=t;i<n;i++)e[i]<=127?(r+=M(o)+String.fromCharCode(e[i]),o=""):o+="%"+e[i].toString(16);return r+M(o)}(a,t,n);break;case"ascii":case"binary":r=l(a,t,n);break;case"base64":o=a,u=n,r=0===(i=t)&&u===o.length?s.fromByteArray(o):s.fromByteArray(o.slice(i,u));break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":r=function(e,t,n){for(var r=e.slice(t,n),o="",i=0;i<r.length;i+=2)o+=String.fromCharCode(r[i]+256*r[i+1]);return o}(a,t,n);break;default:throw new Error("Unknown encoding")}return r},g.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}},g.prototype.copy=function(e,t,n,r){if(n=n||0,r||0===r||(r=this.length),t=t||0,r!==n&&0!==e.length&&0!==this.length){D(n<=r,"sourceEnd < sourceStart"),D(0<=t&&t<e.length,"targetStart out of bounds"),D(0<=n&&n<this.length,"sourceStart out of bounds"),D(0<=r&&r<=this.length,"sourceEnd out of bounds"),r>this.length&&(r=this.length),e.length-t<r-n&&(r=e.length-t+n);var o=r-n;if(o<100||!g._useTypedArrays)for(var i=0;i<o;i++)e[i+t]=this[i+n];else e._set(this.subarray(n,n+o),t)}},g.prototype.slice=function(e,t){var n=this.length;if(e=U(e,n,0),t=U(t,n,n),g._useTypedArrays)return g._augment(this.subarray(e,t));for(var r=t-e,o=new g(r,void 0,!0),i=0;i<r;i++)o[i]=this[i+e];return o},g.prototype.get=function(e){return console.log(".get() is deprecated. Access using array indexes instead."),this.readUInt8(e)},g.prototype.set=function(e,t){return console.log(".set() is deprecated. Access using array indexes instead."),this.writeUInt8(e,t)},g.prototype.readUInt8=function(e,t){if(t||(D(null!=e,"missing offset"),D(e<this.length,"Trying to read beyond buffer length")),!(e>=this.length))return this[e]},g.prototype.readUInt16LE=function(e,t){return c(this,e,!0,t)},g.prototype.readUInt16BE=function(e,t){return c(this,e,!1,t)},g.prototype.readUInt32LE=function(e,t){return d(this,e,!0,t)},g.prototype.readUInt32BE=function(e,t){return d(this,e,!1,t)},g.prototype.readInt8=function(e,t){if(t||(D(null!=e,"missing offset"),D(e<this.length,"Trying to read beyond buffer length")),!(e>=this.length))return 128&this[e]?-1*(255-this[e]+1):this[e]},g.prototype.readInt16LE=function(e,t){return h(this,e,!0,t)},g.prototype.readInt16BE=function(e,t){return h(this,e,!1,t)},g.prototype.readInt32LE=function(e,t){return p(this,e,!0,t)},g.prototype.readInt32BE=function(e,t){return p(this,e,!1,t)},g.prototype.readFloatLE=function(e,t){return b(this,e,!0,t)},g.prototype.readFloatBE=function(e,t){return b(this,e,!1,t)},g.prototype.readDoubleLE=function(e,t){return m(this,e,!0,t)},g.prototype.readDoubleBE=function(e,t){return m(this,e,!1,t)},g.prototype.writeUInt8=function(e,t,n){n||(D(null!=e,"missing value"),D(null!=t,"missing offset"),D(t<this.length,"trying to write beyond buffer length"),N(e,255)),t>=this.length||(this[t]=e)},g.prototype.writeUInt16LE=function(e,t,n){v(this,e,t,!0,n)},g.prototype.writeUInt16BE=function(e,t,n){v(this,e,t,!1,n)},g.prototype.writeUInt32LE=function(e,t,n){_(this,e,t,!0,n)},g.prototype.writeUInt32BE=function(e,t,n){_(this,e,t,!1,n)},g.prototype.writeInt8=function(e,t,n){n||(D(null!=e,"missing value"),D(null!=t,"missing offset"),D(t<this.length,"Trying to write beyond buffer length"),Y(e,127,-128)),t>=this.length||(0<=e?this.writeUInt8(e,t,n):this.writeUInt8(255+e+1,t,n))},g.prototype.writeInt16LE=function(e,t,n){E(this,e,t,!0,n)},g.prototype.writeInt16BE=function(e,t,n){E(this,e,t,!1,n)},g.prototype.writeInt32LE=function(e,t,n){I(this,e,t,!0,n)},g.prototype.writeInt32BE=function(e,t,n){I(this,e,t,!1,n)},g.prototype.writeFloatLE=function(e,t,n){A(this,e,t,!0,n)},g.prototype.writeFloatBE=function(e,t,n){A(this,e,t,!1,n)},g.prototype.writeDoubleLE=function(e,t,n){B(this,e,t,!0,n)},g.prototype.writeDoubleBE=function(e,t,n){B(this,e,t,!1,n)},g.prototype.fill=function(e,t,n){if(e=e||0,t=t||0,n=n||this.length,"string"==typeof e&&(e=e.charCodeAt(0)),D("number"==typeof e&&!isNaN(e),"value is not a number"),D(t<=n,"end < start"),n!==t&&0!==this.length){D(0<=t&&t<this.length,"start out of bounds"),D(0<=n&&n<=this.length,"end out of bounds");for(var r=t;r<n;r++)this[r]=e}},g.prototype.inspect=function(){for(var e=[],t=this.length,n=0;n<t;n++)if(e[n]=j(this[n]),n===H.INSPECT_MAX_BYTES){e[n+1]="...";break}return"<Buffer "+e.join(" ")+">"},g.prototype.toArrayBuffer=function(){if("undefined"==typeof Uint8Array)throw new Error("Buffer.toArrayBuffer not supported in this browser");if(g._useTypedArrays)return new g(this).buffer;for(var e=new Uint8Array(this.length),t=0,n=e.length;t<n;t+=1)e[t]=this[t];return e.buffer};var L=g.prototype;function U(e,t,n){return"number"!=typeof e?n:t<=(e=~~e)?t:0<=e||0<=(e+=t)?e:0}function x(e){return(e=~~Math.ceil(+e))<0?0:e}function S(e){return(Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)})(e)}function j(e){return e<16?"0"+e.toString(16):e.toString(16)}function C(e){for(var t=[],n=0;n<e.length;n++){var r=e.charCodeAt(n);if(r<=127)t.push(e.charCodeAt(n));else{var o=n;55296<=r&&r<=57343&&n++;for(var i=encodeURIComponent(e.slice(o,n+1)).substr(1).split("%"),u=0;u<i.length;u++)t.push(parseInt(i[u],16))}}return t}function k(e){return s.toByteArray(e)}function T(e,t,n,r){for(var o=0;o<r&&!(o+n>=t.length||o>=e.length);o++)t[o+n]=e[o];return o}function M(e){try{return decodeURIComponent(e)}catch(e){return String.fromCharCode(65533)}}function N(e,t){D("number"==typeof e,"cannot write a non-number as a number"),D(0<=e,"specified a negative value for writing an unsigned value"),D(e<=t,"value is larger than maximum value for type"),D(Math.floor(e)===e,"value has a fractional component")}function Y(e,t,n){D("number"==typeof e,"cannot write a non-number as a number"),D(e<=t,"value larger than maximum allowed value"),D(n<=e,"value smaller than minimum allowed value"),D(Math.floor(e)===e,"value has a fractional component")}function F(e,t,n){D("number"==typeof e,"cannot write a non-number as a number"),D(e<=t,"value larger than maximum allowed value"),D(n<=e,"value smaller than minimum allowed value")}function D(e,t){if(!e)throw new Error(t||"Failed assertion")}g._augment=function(e){return e._isBuffer=!0,e._get=e.get,e._set=e.set,e.get=L.get,e.set=L.set,e.write=L.write,e.toString=L.toString,e.toLocaleString=L.toString,e.toJSON=L.toJSON,e.copy=L.copy,e.slice=L.slice,e.readUInt8=L.readUInt8,e.readUInt16LE=L.readUInt16LE,e.readUInt16BE=L.readUInt16BE,e.readUInt32LE=L.readUInt32LE,e.readUInt32BE=L.readUInt32BE,e.readInt8=L.readInt8,e.readInt16LE=L.readInt16LE,e.readInt16BE=L.readInt16BE,e.readInt32LE=L.readInt32LE,e.readInt32BE=L.readInt32BE,e.readFloatLE=L.readFloatLE,e.readFloatBE=L.readFloatBE,e.readDoubleLE=L.readDoubleLE,e.readDoubleBE=L.readDoubleBE,e.writeUInt8=L.writeUInt8,e.writeUInt16LE=L.writeUInt16LE,e.writeUInt16BE=L.writeUInt16BE,e.writeUInt32LE=L.writeUInt32LE,e.writeUInt32BE=L.writeUInt32BE,e.writeInt8=L.writeInt8,e.writeInt16LE=L.writeInt16LE,e.writeInt16BE=L.writeInt16BE,e.writeInt32LE=L.writeInt32LE,e.writeInt32BE=L.writeInt32BE,e.writeFloatLE=L.writeFloatLE,e.writeFloatBE=L.writeFloatBE,e.writeDoubleLE=L.writeDoubleLE,e.writeDoubleBE=L.writeDoubleBE,e.fill=L.fill,e.inspect=L.inspect,e.toArrayBuffer=L.toArrayBuffer,e}}).call(this,O("lYpoI2"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},O("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/buffer/index.js","/node_modules/gulp-browserify/node_modules/buffer")},{"base64-js":2,buffer:3,ieee754:11,lYpoI2:10}],4:[function(c,d,e){(function(e,t,u,n,r,o,i,a,s){var u=c("buffer").Buffer,f=4,l=new u(f);l.fill(0);d.exports={hash:function(e,t,n,r){return u.isBuffer(e)||(e=new u(e)),function(e,t,n){for(var r=new u(t),o=n?r.writeInt32BE:r.writeInt32LE,i=0;i<e.length;i++)o.call(r,e[i],4*i,!0);return r}(t(function(e,t){var n;e.length%f!=0&&(n=e.length+(f-e.length%f),e=u.concat([e,l],n));for(var r=[],o=t?e.readInt32BE:e.readInt32LE,i=0;i<e.length;i+=f)r.push(o.call(e,i));return r}(e,r),8*e.length),n,r)}}}).call(this,c("lYpoI2"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},c("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/helpers.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{buffer:3,lYpoI2:10}],5:[function(w,e,b){(function(e,t,a,n,r,o,i,u,s){var a=w("buffer").Buffer,f=w("./sha"),l=w("./sha256"),c=w("./rng"),d={sha1:f,sha256:l,md5:w("./md5")},h=64,p=new a(h);function g(e,r){var o=d[e=e||"sha1"],i=[];return o||y("algorithm:",e,"is not yet supported"),{update:function(e){return a.isBuffer(e)||(e=new a(e)),i.push(e),e.length,this},digest:function(e){var t=a.concat(i),n=r?function(e,t,n){a.isBuffer(t)||(t=new a(t)),a.isBuffer(n)||(n=new a(n)),t.length>h?t=e(t):t.length<h&&(t=a.concat([t,p],h));for(var r=new a(h),o=new a(h),i=0;i<h;i++)r[i]=54^t[i],o[i]=92^t[i];var u=e(a.concat([r,n]));return e(a.concat([o,u]))}(o,r,t):o(t);return i=null,e?n.toString(e):n}}}function y(){var e=[].slice.call(arguments).join(" ");throw new Error([e,"we accept pull requests","http://github.com/dominictarr/crypto-browserify"].join("\n"))}p.fill(0),b.createHash=function(e){return g(e)},b.createHmac=g,b.randomBytes=function(e,t){if(!t||!t.call)return new a(c(e));try{t.call(this,void 0,new a(c(e)))}catch(e){t(e)}},function(e,t){for(var n in e)t(e[n],n)}(["createCredentials","createCipher","createCipheriv","createDecipher","createDecipheriv","createSign","createVerify","createDiffieHellman","pbkdf2"],function(e){b[e]=function(){y("sorry,",e,"is not implemented yet")}})}).call(this,w("lYpoI2"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},w("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/index.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./md5":6,"./rng":7,"./sha":8,"./sha256":9,buffer:3,lYpoI2:10}],6:[function(w,b,e){(function(e,t,n,r,o,i,u,a,s){var f=w("./helpers");function l(e,t){e[t>>5]|=128<<t%32,e[14+(t+64>>>9<<4)]=t;for(var n=1732584193,r=-271733879,o=-1732584194,i=271733878,u=0;u<e.length;u+=16){var a=n,s=r,f=o,l=i,n=d(n,r,o,i,e[u+0],7,-680876936),i=d(i,n,r,o,e[u+1],12,-389564586),o=d(o,i,n,r,e[u+2],17,606105819),r=d(r,o,i,n,e[u+3],22,-1044525330);n=d(n,r,o,i,e[u+4],7,-176418897),i=d(i,n,r,o,e[u+5],12,1200080426),o=d(o,i,n,r,e[u+6],17,-1473231341),r=d(r,o,i,n,e[u+7],22,-45705983),n=d(n,r,o,i,e[u+8],7,1770035416),i=d(i,n,r,o,e[u+9],12,-1958414417),o=d(o,i,n,r,e[u+10],17,-42063),r=d(r,o,i,n,e[u+11],22,-1990404162),n=d(n,r,o,i,e[u+12],7,1804603682),i=d(i,n,r,o,e[u+13],12,-40341101),o=d(o,i,n,r,e[u+14],17,-1502002290),n=h(n,r=d(r,o,i,n,e[u+15],22,1236535329),o,i,e[u+1],5,-165796510),i=h(i,n,r,o,e[u+6],9,-1069501632),o=h(o,i,n,r,e[u+11],14,643717713),r=h(r,o,i,n,e[u+0],20,-373897302),n=h(n,r,o,i,e[u+5],5,-701558691),i=h(i,n,r,o,e[u+10],9,38016083),o=h(o,i,n,r,e[u+15],14,-660478335),r=h(r,o,i,n,e[u+4],20,-405537848),n=h(n,r,o,i,e[u+9],5,568446438),i=h(i,n,r,o,e[u+14],9,-1019803690),o=h(o,i,n,r,e[u+3],14,-187363961),r=h(r,o,i,n,e[u+8],20,1163531501),n=h(n,r,o,i,e[u+13],5,-1444681467),i=h(i,n,r,o,e[u+2],9,-51403784),o=h(o,i,n,r,e[u+7],14,1735328473),n=p(n,r=h(r,o,i,n,e[u+12],20,-1926607734),o,i,e[u+5],4,-378558),i=p(i,n,r,o,e[u+8],11,-2022574463),o=p(o,i,n,r,e[u+11],16,1839030562),r=p(r,o,i,n,e[u+14],23,-35309556),n=p(n,r,o,i,e[u+1],4,-1530992060),i=p(i,n,r,o,e[u+4],11,1272893353),o=p(o,i,n,r,e[u+7],16,-155497632),r=p(r,o,i,n,e[u+10],23,-1094730640),n=p(n,r,o,i,e[u+13],4,681279174),i=p(i,n,r,o,e[u+0],11,-358537222),o=p(o,i,n,r,e[u+3],16,-722521979),r=p(r,o,i,n,e[u+6],23,76029189),n=p(n,r,o,i,e[u+9],4,-640364487),i=p(i,n,r,o,e[u+12],11,-421815835),o=p(o,i,n,r,e[u+15],16,530742520),n=g(n,r=p(r,o,i,n,e[u+2],23,-995338651),o,i,e[u+0],6,-198630844),i=g(i,n,r,o,e[u+7],10,1126891415),o=g(o,i,n,r,e[u+14],15,-1416354905),r=g(r,o,i,n,e[u+5],21,-57434055),n=g(n,r,o,i,e[u+12],6,1700485571),i=g(i,n,r,o,e[u+3],10,-1894986606),o=g(o,i,n,r,e[u+10],15,-1051523),r=g(r,o,i,n,e[u+1],21,-2054922799),n=g(n,r,o,i,e[u+8],6,1873313359),i=g(i,n,r,o,e[u+15],10,-30611744),o=g(o,i,n,r,e[u+6],15,-1560198380),r=g(r,o,i,n,e[u+13],21,1309151649),n=g(n,r,o,i,e[u+4],6,-145523070),i=g(i,n,r,o,e[u+11],10,-1120210379),o=g(o,i,n,r,e[u+2],15,718787259),r=g(r,o,i,n,e[u+9],21,-343485551),n=y(n,a),r=y(r,s),o=y(o,f),i=y(i,l)}return Array(n,r,o,i)}function c(e,t,n,r,o,i){return y((u=y(y(t,e),y(r,i)))<<(a=o)|u>>>32-a,n);var u,a}function d(e,t,n,r,o,i,u){return c(t&n|~t&r,e,t,o,i,u)}function h(e,t,n,r,o,i,u){return c(t&r|n&~r,e,t,o,i,u)}function p(e,t,n,r,o,i,u){return c(t^n^r,e,t,o,i,u)}function g(e,t,n,r,o,i,u){return c(n^(t|~r),e,t,o,i,u)}function y(e,t){var n=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(n>>16)<<16|65535&n}b.exports=function(e){return f.hash(e,l,16)}}).call(this,w("lYpoI2"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},w("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/md5.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./helpers":4,buffer:3,lYpoI2:10}],7:[function(e,c,t){(function(e,t,n,r,o,i,u,a,s){var f,l;l=function(e){for(var t,n=new Array(e),r=0;r<e;r++)0==(3&r)&&(t=4294967296*Math.random()),n[r]=t>>>((3&r)<<3)&255;return n},c.exports=f||l}).call(this,e("lYpoI2"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/rng.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{buffer:3,lYpoI2:10}],8:[function(c,d,e){(function(e,t,n,r,o,i,u,a,s){var f=c("./helpers");function l(e,t){e[t>>5]|=128<<24-t%32,e[15+(t+64>>9<<4)]=t;for(var n,r,o,i,u,a=Array(80),s=1732584193,f=-271733879,l=-1732584194,c=271733878,d=-1009589776,h=0;h<e.length;h+=16){for(var p=s,g=f,y=l,w=c,b=d,m=0;m<80;m++){a[m]=m<16?e[h+m]:E(a[m-3]^a[m-8]^a[m-14]^a[m-16],1);var v=_(_(E(s,5),(o=f,i=l,u=c,(r=m)<20?o&i|~o&u:!(r<40)&&r<60?o&i|o&u|i&u:o^i^u)),_(_(d,a[m]),(n=m)<20?1518500249:n<40?1859775393:n<60?-1894007588:-899497514)),d=c,c=l,l=E(f,30),f=s,s=v}s=_(s,p),f=_(f,g),l=_(l,y),c=_(c,w),d=_(d,b)}return Array(s,f,l,c,d)}function _(e,t){var n=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(n>>16)<<16|65535&n}function E(e,t){return e<<t|e>>>32-t}d.exports=function(e){return f.hash(e,l,20,!0)}}).call(this,c("lYpoI2"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},c("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/sha.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./helpers":4,buffer:3,lYpoI2:10}],9:[function(c,d,e){(function(e,t,n,r,o,i,u,a,s){function B(e,t){var n=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(n>>16)<<16|65535&n}function L(e,t){return e>>>t|e<<32-t}function f(e,t){var n,r,o,i,u,a,s,f,l,c,d=new Array(1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298),h=new Array(1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225),p=new Array(64);e[t>>5]|=128<<24-t%32,e[15+(t+64>>9<<4)]=t;for(var g,y,w,b,m,v,_,E,I=0;I<e.length;I+=16){n=h[0],r=h[1],o=h[2],i=h[3],u=h[4],a=h[5],s=h[6],f=h[7];for(var A=0;A<64;A++)p[A]=A<16?e[A+I]:B(B(B((E=p[A-2],L(E,17)^L(E,19)^E>>>10),p[A-7]),(_=p[A-15],L(_,7)^L(_,18)^_>>>3)),p[A-16]),l=B(B(B(B(f,L(v=u,6)^L(v,11)^L(v,25)),(m=u)&a^~m&s),d[A]),p[A]),c=B(L(b=n,2)^L(b,13)^L(b,22),(g=n)&(y=r)^g&(w=o)^y&w),f=s,s=a,a=u,u=B(i,l),i=o,o=r,r=n,n=B(l,c);h[0]=B(n,h[0]),h[1]=B(r,h[1]),h[2]=B(o,h[2]),h[3]=B(i,h[3]),h[4]=B(u,h[4]),h[5]=B(a,h[5]),h[6]=B(s,h[6]),h[7]=B(f,h[7])}return h}var l=c("./helpers");d.exports=function(e){return l.hash(e,f,32,!0)}}).call(this,c("lYpoI2"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},c("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/sha256.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./helpers":4,buffer:3,lYpoI2:10}],10:[function(e,l,t){(function(e,t,n,r,o,i,u,a,s){function f(){}(e=l.exports={}).nextTick=function(){var e="undefined"!=typeof window&&window.setImmediate,t="undefined"!=typeof window&&window.postMessage&&window.addEventListener;if(e)return function(e){return window.setImmediate(e)};if(t){var n=[];return window.addEventListener("message",function(e){var t=e.source;t!==window&&null!==t||"process-tick"!==e.data||(e.stopPropagation(),0<n.length&&n.shift()())},!0),function(e){n.push(e),window.postMessage("process-tick","*")}}return function(e){setTimeout(e,0)}}(),e.title="browser",e.browser=!0,e.env={},e.argv=[],e.on=f,e.addListener=f,e.once=f,e.off=f,e.removeListener=f,e.removeAllListeners=f,e.emit=f,e.binding=function(e){throw new Error("process.binding is not supported")},e.cwd=function(){return"/"},e.chdir=function(e){throw new Error("process.chdir is not supported")}}).call(this,e("lYpoI2"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/process/browser.js","/node_modules/gulp-browserify/node_modules/process")},{buffer:3,lYpoI2:10}],11:[function(e,t,f){(function(e,t,n,r,o,i,u,a,s){f.read=function(e,t,n,r,o){var i,u,a=8*o-r-1,s=(1<<a)-1,f=s>>1,l=-7,c=n?o-1:0,d=n?-1:1,h=e[t+c];for(c+=d,i=h&(1<<-l)-1,h>>=-l,l+=a;0<l;i=256*i+e[t+c],c+=d,l-=8);for(u=i&(1<<-l)-1,i>>=-l,l+=r;0<l;u=256*u+e[t+c],c+=d,l-=8);if(0===i)i=1-f;else{if(i===s)return u?NaN:1/0*(h?-1:1);u+=Math.pow(2,r),i-=f}return(h?-1:1)*u*Math.pow(2,i-r)},f.write=function(e,t,n,r,o,i){var u,a,s,f=8*i-o-1,l=(1<<f)-1,c=l>>1,d=23===o?Math.pow(2,-24)-Math.pow(2,-77):0,h=r?0:i-1,p=r?1:-1,g=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,u=l):(u=Math.floor(Math.log(t)/Math.LN2),t*(s=Math.pow(2,-u))<1&&(u--,s*=2),2<=(t+=1<=u+c?d/s:d*Math.pow(2,1-c))*s&&(u++,s/=2),l<=u+c?(a=0,u=l):1<=u+c?(a=(t*s-1)*Math.pow(2,o),u+=c):(a=t*Math.pow(2,c-1)*Math.pow(2,o),u=0));8<=o;e[n+h]=255&a,h+=p,a/=256,o-=8);for(u=u<<o|a,f+=o;0<f;e[n+h]=255&u,h+=p,u/=256,f-=8);e[n+h-p]|=128*g}}).call(this,e("lYpoI2"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/ieee754/index.js","/node_modules/ieee754")},{buffer:3,lYpoI2:10}]},{},[1])(1)});
...\ No newline at end of file ...\ No newline at end of file
1 +!function(e){var t;"object"==typeof exports?module.exports=e():"function"==typeof define&&define.amd?define(e):("undefined"!=typeof window?t=window:"undefined"!=typeof global?t=global:"undefined"!=typeof self&&(t=self),t.objectHash=e())}(function(){return function o(i,u,a){function s(n,e){if(!u[n]){if(!i[n]){var t="function"==typeof require&&require;if(!e&&t)return t(n,!0);if(f)return f(n,!0);throw new Error("Cannot find module '"+n+"'")}var r=u[n]={exports:{}};i[n][0].call(r.exports,function(e){var t=i[n][1][e];return s(t||e)},r,r.exports,o,i,u,a)}return u[n].exports}for(var f="function"==typeof require&&require,e=0;e<a.length;e++)s(a[e]);return s}({1:[function(w,b,m){(function(e,t,f,n,r,o,i,u,a){"use strict";var s=w("crypto");function c(e,t){return function(e,t){var n;n="passthrough"!==t.algorithm?s.createHash(t.algorithm):new y;void 0===n.write&&(n.write=n.update,n.end=n.update);g(t,n).dispatch(e),n.update||n.end("");if(n.digest)return n.digest("buffer"===t.encoding?void 0:t.encoding);var r=n.read();return"buffer"!==t.encoding?r.toString(t.encoding):r}(e,t=h(e,t))}(m=b.exports=c).sha1=function(e){return c(e)},m.keys=function(e){return c(e,{excludeValues:!0,algorithm:"sha1",encoding:"hex"})},m.MD5=function(e){return c(e,{algorithm:"md5",encoding:"hex"})},m.keysMD5=function(e){return c(e,{algorithm:"md5",encoding:"hex",excludeValues:!0})};var l=s.getHashes?s.getHashes().slice():["sha1","md5"];l.push("passthrough");var d=["buffer","hex","binary","base64"];function h(e,t){t=t||{};var n={};if(n.algorithm=t.algorithm||"sha1",n.encoding=t.encoding||"hex",n.excludeValues=!!t.excludeValues,n.algorithm=n.algorithm.toLowerCase(),n.encoding=n.encoding.toLowerCase(),n.ignoreUnknown=!0===t.ignoreUnknown,n.respectType=!1!==t.respectType,n.respectFunctionNames=!1!==t.respectFunctionNames,n.respectFunctionProperties=!1!==t.respectFunctionProperties,n.unorderedArrays=!0===t.unorderedArrays,n.unorderedSets=!1!==t.unorderedSets,n.unorderedObjects=!1!==t.unorderedObjects,n.replacer=t.replacer||void 0,n.excludeKeys=t.excludeKeys||void 0,void 0===e)throw new Error("Object argument required.");for(var r=0;r<l.length;++r)l[r].toLowerCase()===n.algorithm.toLowerCase()&&(n.algorithm=l[r]);if(-1===l.indexOf(n.algorithm))throw new Error('Algorithm "'+n.algorithm+'" not supported. supported values: '+l.join(", "));if(-1===d.indexOf(n.encoding)&&"passthrough"!==n.algorithm)throw new Error('Encoding "'+n.encoding+'" not supported. supported values: '+d.join(", "));return n}function p(e){if("function"==typeof e){return null!=/^function\s+\w*\s*\(\s*\)\s*{\s+\[native code\]\s+}$/i.exec(Function.prototype.toString.call(e))}}function g(u,t,a){a=a||[];function s(e){return t.update?t.update(e,"utf8"):t.write(e,"utf8")}return{dispatch:function(e){return u.replacer&&(e=u.replacer(e)),this["_"+(null===e?"null":typeof e)](e)},_object:function(t){var e=Object.prototype.toString.call(t),n=/\[object (.*)\]/i.exec(e);n=(n=n?n[1]:"unknown:["+e+"]").toLowerCase();var r;if(0<=(r=a.indexOf(t)))return this.dispatch("[CIRCULAR:"+r+"]");if(a.push(t),void 0!==f&&f.isBuffer&&f.isBuffer(t))return s("buffer:"),s(t);if("object"===n||"function"===n||"asyncfunction"===n){var o=Object.keys(t);u.unorderedObjects&&(o=o.sort()),!1===u.respectType||p(t)||o.splice(0,0,"prototype","__proto__","constructor"),u.excludeKeys&&(o=o.filter(function(e){return!u.excludeKeys(e)})),s("object:"+o.length+":");var i=this;return o.forEach(function(e){i.dispatch(e),s(":"),u.excludeValues||i.dispatch(t[e]),s(",")})}if(!this["_"+n]){if(u.ignoreUnknown)return s("["+n+"]");throw new Error('Unknown object type "'+n+'"')}this["_"+n](t)},_array:function(e,t){t=void 0!==t?t:!1!==u.unorderedArrays;var n=this;if(s("array:"+e.length+":"),!t||e.length<=1)return e.forEach(function(e){return n.dispatch(e)});var r=[],o=e.map(function(e){var t=new y,n=a.slice();return g(u,t,n).dispatch(e),r=r.concat(n.slice(a.length)),t.read().toString()});return a=a.concat(r),o.sort(),this._array(o,!1)},_date:function(e){return s("date:"+e.toJSON())},_symbol:function(e){return s("symbol:"+e.toString())},_error:function(e){return s("error:"+e.toString())},_boolean:function(e){return s("bool:"+e.toString())},_string:function(e){s("string:"+e.length+":"),s(e.toString())},_function:function(e){s("fn:"),p(e)?this.dispatch("[native]"):this.dispatch(e.toString()),!1!==u.respectFunctionNames&&this.dispatch("function-name:"+String(e.name)),u.respectFunctionProperties&&this._object(e)},_number:function(e){return s("number:"+e.toString())},_xml:function(e){return s("xml:"+e.toString())},_null:function(){return s("Null")},_undefined:function(){return s("Undefined")},_regexp:function(e){return s("regex:"+e.toString())},_uint8array:function(e){return s("uint8array:"),this.dispatch(Array.prototype.slice.call(e))},_uint8clampedarray:function(e){return s("uint8clampedarray:"),this.dispatch(Array.prototype.slice.call(e))},_int8array:function(e){return s("uint8array:"),this.dispatch(Array.prototype.slice.call(e))},_uint16array:function(e){return s("uint16array:"),this.dispatch(Array.prototype.slice.call(e))},_int16array:function(e){return s("uint16array:"),this.dispatch(Array.prototype.slice.call(e))},_uint32array:function(e){return s("uint32array:"),this.dispatch(Array.prototype.slice.call(e))},_int32array:function(e){return s("uint32array:"),this.dispatch(Array.prototype.slice.call(e))},_float32array:function(e){return s("float32array:"),this.dispatch(Array.prototype.slice.call(e))},_float64array:function(e){return s("float64array:"),this.dispatch(Array.prototype.slice.call(e))},_arraybuffer:function(e){return s("arraybuffer:"),this.dispatch(new Uint8Array(e))},_url:function(e){return s("url:"+e.toString())},_map:function(e){s("map:");var t=Array.from(e);return this._array(t,!1!==u.unorderedSets)},_set:function(e){s("set:");var t=Array.from(e);return this._array(t,!1!==u.unorderedSets)},_file:function(e){return s("file:"),this.dispatch([e.name,e.size,e.type,e.lastModfied])},_blob:function(){if(u.ignoreUnknown)return s("[blob]");throw Error('Hashing Blob objects is currently not supported\n(see https://github.com/puleos/object-hash/issues/26)\nUse "options.replacer" or "options.ignoreUnknown"\n')},_domwindow:function(){return s("domwindow")},_bigint:function(e){return s("bigint:"+e.toString())},_process:function(){return s("process")},_timer:function(){return s("timer")},_pipe:function(){return s("pipe")},_tcp:function(){return s("tcp")},_udp:function(){return s("udp")},_tty:function(){return s("tty")},_statwatcher:function(){return s("statwatcher")},_securecontext:function(){return s("securecontext")},_connection:function(){return s("connection")},_zlib:function(){return s("zlib")},_context:function(){return s("context")},_nodescript:function(){return s("nodescript")},_httpparser:function(){return s("httpparser")},_dataview:function(){return s("dataview")},_signal:function(){return s("signal")},_fsevent:function(){return s("fsevent")},_tlswrap:function(){return s("tlswrap")}}}function y(){return{buf:"",write:function(e){this.buf+=e},end:function(e){this.buf+=e},read:function(){return this.buf}}}m.writeToStream=function(e,t,n){return void 0===n&&(n=t,t={}),g(t=h(e,t),n).dispatch(e)}}).call(this,w("lYpoI2"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},w("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/fake_7eac155c.js","/")},{buffer:3,crypto:5,lYpoI2:10}],2:[function(e,t,f){(function(e,t,n,r,o,i,u,a,s){!function(e){"use strict";var f="undefined"!=typeof Uint8Array?Uint8Array:Array,n="+".charCodeAt(0),r="/".charCodeAt(0),o="0".charCodeAt(0),i="a".charCodeAt(0),u="A".charCodeAt(0),a="-".charCodeAt(0),s="_".charCodeAt(0);function c(e){var t=e.charCodeAt(0);return t===n||t===a?62:t===r||t===s?63:t<o?-1:t<o+10?t-o+26+26:t<u+26?t-u:t<i+26?t-i+26:void 0}e.toByteArray=function(e){var t,n;if(0<e.length%4)throw new Error("Invalid string. Length must be a multiple of 4");var r=e.length,o="="===e.charAt(r-2)?2:"="===e.charAt(r-1)?1:0,i=new f(3*e.length/4-o),u=0<o?e.length-4:e.length,a=0;function s(e){i[a++]=e}for(t=0;t<u;t+=4,0)s((16711680&(n=c(e.charAt(t))<<18|c(e.charAt(t+1))<<12|c(e.charAt(t+2))<<6|c(e.charAt(t+3))))>>16),s((65280&n)>>8),s(255&n);return 2==o?s(255&(n=c(e.charAt(t))<<2|c(e.charAt(t+1))>>4)):1==o&&(s((n=c(e.charAt(t))<<10|c(e.charAt(t+1))<<4|c(e.charAt(t+2))>>2)>>8&255),s(255&n)),i},e.fromByteArray=function(e){var t,n,r,o,i=e.length%3,u="";function a(e){return"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(e)}for(t=0,r=e.length-i;t<r;t+=3)n=(e[t]<<16)+(e[t+1]<<8)+e[t+2],u+=a((o=n)>>18&63)+a(o>>12&63)+a(o>>6&63)+a(63&o);switch(i){case 1:u+=a((n=e[e.length-1])>>2),u+=a(n<<4&63),u+="==";break;case 2:u+=a((n=(e[e.length-2]<<8)+e[e.length-1])>>10),u+=a(n>>4&63),u+=a(n<<2&63),u+="="}return u}}(void 0===f?this.base64js={}:f)}).call(this,e("lYpoI2"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/base64-js/lib/b64.js","/node_modules/gulp-browserify/node_modules/base64-js/lib")},{buffer:3,lYpoI2:10}],3:[function(O,e,H){(function(e,t,g,n,r,o,i,u,a){var s=O("base64-js"),f=O("ieee754");function g(e,t,n){if(!(this instanceof g))return new g(e,t,n);var r,o,i,u,a,s=typeof e;if("base64"===t&&"string"==s)for(e=(r=e).trim?r.trim():r.replace(/^\s+|\s+$/g,"");e.length%4!=0;)e+="=";if("number"==s)o=x(e);else if("string"==s)o=g.byteLength(e,t);else{if("object"!=s)throw new Error("First argument needs to be a number, array or string.");o=x(e.length)}if(g._useTypedArrays?i=g._augment(new Uint8Array(o)):((i=this).length=o,i._isBuffer=!0),g._useTypedArrays&&"number"==typeof e.byteLength)i._set(e);else if(S(a=e)||g.isBuffer(a)||a&&"object"==typeof a&&"number"==typeof a.length)for(u=0;u<o;u++)g.isBuffer(e)?i[u]=e.readUInt8(u):i[u]=e[u];else if("string"==s)i.write(e,0,t);else if("number"==s&&!g._useTypedArrays&&!n)for(u=0;u<o;u++)i[u]=0;return i}function y(e,t,n,r){return g._charsWritten=T(function(e){for(var t=[],n=0;n<e.length;n++)t.push(255&e.charCodeAt(n));return t}(t),e,n,r)}function w(e,t,n,r){return g._charsWritten=T(function(e){for(var t,n,r,o=[],i=0;i<e.length;i++)t=e.charCodeAt(i),n=t>>8,r=t%256,o.push(r),o.push(n);return o}(t),e,n,r)}function c(e,t,n){var r="";n=Math.min(e.length,n);for(var o=t;o<n;o++)r+=String.fromCharCode(e[o]);return r}function l(e,t,n,r){r||(D("boolean"==typeof n,"missing or invalid endian"),D(null!=t,"missing offset"),D(t+1<e.length,"Trying to read beyond buffer length"));var o,i=e.length;if(!(i<=t))return n?(o=e[t],t+1<i&&(o|=e[t+1]<<8)):(o=e[t]<<8,t+1<i&&(o|=e[t+1])),o}function d(e,t,n,r){r||(D("boolean"==typeof n,"missing or invalid endian"),D(null!=t,"missing offset"),D(t+3<e.length,"Trying to read beyond buffer length"));var o,i=e.length;if(!(i<=t))return n?(t+2<i&&(o=e[t+2]<<16),t+1<i&&(o|=e[t+1]<<8),o|=e[t],t+3<i&&(o+=e[t+3]<<24>>>0)):(t+1<i&&(o=e[t+1]<<16),t+2<i&&(o|=e[t+2]<<8),t+3<i&&(o|=e[t+3]),o+=e[t]<<24>>>0),o}function h(e,t,n,r){if(r||(D("boolean"==typeof n,"missing or invalid endian"),D(null!=t,"missing offset"),D(t+1<e.length,"Trying to read beyond buffer length")),!(e.length<=t)){var o=l(e,t,n,!0);return 32768&o?-1*(65535-o+1):o}}function p(e,t,n,r){if(r||(D("boolean"==typeof n,"missing or invalid endian"),D(null!=t,"missing offset"),D(t+3<e.length,"Trying to read beyond buffer length")),!(e.length<=t)){var o=d(e,t,n,!0);return 2147483648&o?-1*(4294967295-o+1):o}}function b(e,t,n,r){return r||(D("boolean"==typeof n,"missing or invalid endian"),D(t+3<e.length,"Trying to read beyond buffer length")),f.read(e,t,n,23,4)}function m(e,t,n,r){return r||(D("boolean"==typeof n,"missing or invalid endian"),D(t+7<e.length,"Trying to read beyond buffer length")),f.read(e,t,n,52,8)}function v(e,t,n,r,o){o||(D(null!=t,"missing value"),D("boolean"==typeof r,"missing or invalid endian"),D(null!=n,"missing offset"),D(n+1<e.length,"trying to write beyond buffer length"),N(t,65535));var i=e.length;if(!(i<=n))for(var u=0,a=Math.min(i-n,2);u<a;u++)e[n+u]=(t&255<<8*(r?u:1-u))>>>8*(r?u:1-u)}function _(e,t,n,r,o){o||(D(null!=t,"missing value"),D("boolean"==typeof r,"missing or invalid endian"),D(null!=n,"missing offset"),D(n+3<e.length,"trying to write beyond buffer length"),N(t,4294967295));var i=e.length;if(!(i<=n))for(var u=0,a=Math.min(i-n,4);u<a;u++)e[n+u]=t>>>8*(r?u:3-u)&255}function E(e,t,n,r,o){o||(D(null!=t,"missing value"),D("boolean"==typeof r,"missing or invalid endian"),D(null!=n,"missing offset"),D(n+1<e.length,"Trying to write beyond buffer length"),Y(t,32767,-32768)),e.length<=n||v(e,0<=t?t:65535+t+1,n,r,o)}function I(e,t,n,r,o){o||(D(null!=t,"missing value"),D("boolean"==typeof r,"missing or invalid endian"),D(null!=n,"missing offset"),D(n+3<e.length,"Trying to write beyond buffer length"),Y(t,2147483647,-2147483648)),e.length<=n||_(e,0<=t?t:4294967295+t+1,n,r,o)}function A(e,t,n,r,o){o||(D(null!=t,"missing value"),D("boolean"==typeof r,"missing or invalid endian"),D(null!=n,"missing offset"),D(n+3<e.length,"Trying to write beyond buffer length"),F(t,34028234663852886e22,-34028234663852886e22)),e.length<=n||f.write(e,t,n,r,23,4)}function B(e,t,n,r,o){o||(D(null!=t,"missing value"),D("boolean"==typeof r,"missing or invalid endian"),D(null!=n,"missing offset"),D(n+7<e.length,"Trying to write beyond buffer length"),F(t,17976931348623157e292,-17976931348623157e292)),e.length<=n||f.write(e,t,n,r,52,8)}H.Buffer=g,H.SlowBuffer=g,H.INSPECT_MAX_BYTES=50,g.poolSize=8192,g._useTypedArrays=function(){try{var e=new ArrayBuffer(0),t=new Uint8Array(e);return t.foo=function(){return 42},42===t.foo()&&"function"==typeof t.subarray}catch(e){return!1}}(),g.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"raw":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},g.isBuffer=function(e){return!(null==e||!e._isBuffer)},g.byteLength=function(e,t){var n;switch(e+="",t||"utf8"){case"hex":n=e.length/2;break;case"utf8":case"utf-8":n=C(e).length;break;case"ascii":case"binary":case"raw":n=e.length;break;case"base64":n=k(e).length;break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":n=2*e.length;break;default:throw new Error("Unknown encoding")}return n},g.concat=function(e,t){if(D(S(e),"Usage: Buffer.concat(list, [totalLength])\nlist should be an Array."),0===e.length)return new g(0);if(1===e.length)return e[0];if("number"!=typeof t)for(o=t=0;o<e.length;o++)t+=e[o].length;for(var n=new g(t),r=0,o=0;o<e.length;o++){var i=e[o];i.copy(n,r),r+=i.length}return n},g.prototype.write=function(e,t,n,r){var o;isFinite(t)?isFinite(n)||(r=n,n=void 0):(o=r,r=t,t=n,n=o),t=Number(t)||0;var i,u,a,s,f,c,l,d,h,p=this.length-t;switch((!n||p<(n=Number(n)))&&(n=p),r=String(r||"utf8").toLowerCase()){case"hex":i=function(e,t,n,r){n=Number(n)||0;var o=e.length-n;(!r||o<(r=Number(r)))&&(r=o);var i=t.length;D(i%2==0,"Invalid hex string"),i/2<r&&(r=i/2);for(var u=0;u<r;u++){var a=parseInt(t.substr(2*u,2),16);D(!isNaN(a),"Invalid hex string"),e[n+u]=a}return g._charsWritten=2*u,u}(this,e,t,n);break;case"utf8":case"utf-8":c=this,l=e,d=t,h=n,i=g._charsWritten=T(C(l),c,d,h);break;case"ascii":case"binary":i=y(this,e,t,n);break;case"base64":u=this,a=e,s=t,f=n,i=g._charsWritten=T(k(a),u,s,f);break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":i=w(this,e,t,n);break;default:throw new Error("Unknown encoding")}return i},g.prototype.toString=function(e,t,n){var r,o,i,u,a=this;if(e=String(e||"utf8").toLowerCase(),t=Number(t)||0,(n=void 0!==n?Number(n):n=a.length)===t)return"";switch(e){case"hex":r=function(e,t,n){var r=e.length;(!t||t<0)&&(t=0);(!n||n<0||r<n)&&(n=r);for(var o="",i=t;i<n;i++)o+=j(e[i]);return o}(a,t,n);break;case"utf8":case"utf-8":r=function(e,t,n){var r="",o="";n=Math.min(e.length,n);for(var i=t;i<n;i++)e[i]<=127?(r+=M(o)+String.fromCharCode(e[i]),o=""):o+="%"+e[i].toString(16);return r+M(o)}(a,t,n);break;case"ascii":case"binary":r=c(a,t,n);break;case"base64":o=a,u=n,r=0===(i=t)&&u===o.length?s.fromByteArray(o):s.fromByteArray(o.slice(i,u));break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":r=function(e,t,n){for(var r=e.slice(t,n),o="",i=0;i<r.length;i+=2)o+=String.fromCharCode(r[i]+256*r[i+1]);return o}(a,t,n);break;default:throw new Error("Unknown encoding")}return r},g.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}},g.prototype.copy=function(e,t,n,r){if(n=n||0,r||0===r||(r=this.length),t=t||0,r!==n&&0!==e.length&&0!==this.length){D(n<=r,"sourceEnd < sourceStart"),D(0<=t&&t<e.length,"targetStart out of bounds"),D(0<=n&&n<this.length,"sourceStart out of bounds"),D(0<=r&&r<=this.length,"sourceEnd out of bounds"),r>this.length&&(r=this.length),e.length-t<r-n&&(r=e.length-t+n);var o=r-n;if(o<100||!g._useTypedArrays)for(var i=0;i<o;i++)e[i+t]=this[i+n];else e._set(this.subarray(n,n+o),t)}},g.prototype.slice=function(e,t){var n=this.length;if(e=U(e,n,0),t=U(t,n,n),g._useTypedArrays)return g._augment(this.subarray(e,t));for(var r=t-e,o=new g(r,void 0,!0),i=0;i<r;i++)o[i]=this[i+e];return o},g.prototype.get=function(e){return console.log(".get() is deprecated. Access using array indexes instead."),this.readUInt8(e)},g.prototype.set=function(e,t){return console.log(".set() is deprecated. Access using array indexes instead."),this.writeUInt8(e,t)},g.prototype.readUInt8=function(e,t){if(t||(D(null!=e,"missing offset"),D(e<this.length,"Trying to read beyond buffer length")),!(e>=this.length))return this[e]},g.prototype.readUInt16LE=function(e,t){return l(this,e,!0,t)},g.prototype.readUInt16BE=function(e,t){return l(this,e,!1,t)},g.prototype.readUInt32LE=function(e,t){return d(this,e,!0,t)},g.prototype.readUInt32BE=function(e,t){return d(this,e,!1,t)},g.prototype.readInt8=function(e,t){if(t||(D(null!=e,"missing offset"),D(e<this.length,"Trying to read beyond buffer length")),!(e>=this.length))return 128&this[e]?-1*(255-this[e]+1):this[e]},g.prototype.readInt16LE=function(e,t){return h(this,e,!0,t)},g.prototype.readInt16BE=function(e,t){return h(this,e,!1,t)},g.prototype.readInt32LE=function(e,t){return p(this,e,!0,t)},g.prototype.readInt32BE=function(e,t){return p(this,e,!1,t)},g.prototype.readFloatLE=function(e,t){return b(this,e,!0,t)},g.prototype.readFloatBE=function(e,t){return b(this,e,!1,t)},g.prototype.readDoubleLE=function(e,t){return m(this,e,!0,t)},g.prototype.readDoubleBE=function(e,t){return m(this,e,!1,t)},g.prototype.writeUInt8=function(e,t,n){n||(D(null!=e,"missing value"),D(null!=t,"missing offset"),D(t<this.length,"trying to write beyond buffer length"),N(e,255)),t>=this.length||(this[t]=e)},g.prototype.writeUInt16LE=function(e,t,n){v(this,e,t,!0,n)},g.prototype.writeUInt16BE=function(e,t,n){v(this,e,t,!1,n)},g.prototype.writeUInt32LE=function(e,t,n){_(this,e,t,!0,n)},g.prototype.writeUInt32BE=function(e,t,n){_(this,e,t,!1,n)},g.prototype.writeInt8=function(e,t,n){n||(D(null!=e,"missing value"),D(null!=t,"missing offset"),D(t<this.length,"Trying to write beyond buffer length"),Y(e,127,-128)),t>=this.length||(0<=e?this.writeUInt8(e,t,n):this.writeUInt8(255+e+1,t,n))},g.prototype.writeInt16LE=function(e,t,n){E(this,e,t,!0,n)},g.prototype.writeInt16BE=function(e,t,n){E(this,e,t,!1,n)},g.prototype.writeInt32LE=function(e,t,n){I(this,e,t,!0,n)},g.prototype.writeInt32BE=function(e,t,n){I(this,e,t,!1,n)},g.prototype.writeFloatLE=function(e,t,n){A(this,e,t,!0,n)},g.prototype.writeFloatBE=function(e,t,n){A(this,e,t,!1,n)},g.prototype.writeDoubleLE=function(e,t,n){B(this,e,t,!0,n)},g.prototype.writeDoubleBE=function(e,t,n){B(this,e,t,!1,n)},g.prototype.fill=function(e,t,n){if(e=e||0,t=t||0,n=n||this.length,"string"==typeof e&&(e=e.charCodeAt(0)),D("number"==typeof e&&!isNaN(e),"value is not a number"),D(t<=n,"end < start"),n!==t&&0!==this.length){D(0<=t&&t<this.length,"start out of bounds"),D(0<=n&&n<=this.length,"end out of bounds");for(var r=t;r<n;r++)this[r]=e}},g.prototype.inspect=function(){for(var e=[],t=this.length,n=0;n<t;n++)if(e[n]=j(this[n]),n===H.INSPECT_MAX_BYTES){e[n+1]="...";break}return"<Buffer "+e.join(" ")+">"},g.prototype.toArrayBuffer=function(){if("undefined"==typeof Uint8Array)throw new Error("Buffer.toArrayBuffer not supported in this browser");if(g._useTypedArrays)return new g(this).buffer;for(var e=new Uint8Array(this.length),t=0,n=e.length;t<n;t+=1)e[t]=this[t];return e.buffer};var L=g.prototype;function U(e,t,n){return"number"!=typeof e?n:t<=(e=~~e)?t:0<=e||0<=(e+=t)?e:0}function x(e){return(e=~~Math.ceil(+e))<0?0:e}function S(e){return(Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)})(e)}function j(e){return e<16?"0"+e.toString(16):e.toString(16)}function C(e){for(var t=[],n=0;n<e.length;n++){var r=e.charCodeAt(n);if(r<=127)t.push(e.charCodeAt(n));else{var o=n;55296<=r&&r<=57343&&n++;for(var i=encodeURIComponent(e.slice(o,n+1)).substr(1).split("%"),u=0;u<i.length;u++)t.push(parseInt(i[u],16))}}return t}function k(e){return s.toByteArray(e)}function T(e,t,n,r){for(var o=0;o<r&&!(o+n>=t.length||o>=e.length);o++)t[o+n]=e[o];return o}function M(e){try{return decodeURIComponent(e)}catch(e){return String.fromCharCode(65533)}}function N(e,t){D("number"==typeof e,"cannot write a non-number as a number"),D(0<=e,"specified a negative value for writing an unsigned value"),D(e<=t,"value is larger than maximum value for type"),D(Math.floor(e)===e,"value has a fractional component")}function Y(e,t,n){D("number"==typeof e,"cannot write a non-number as a number"),D(e<=t,"value larger than maximum allowed value"),D(n<=e,"value smaller than minimum allowed value"),D(Math.floor(e)===e,"value has a fractional component")}function F(e,t,n){D("number"==typeof e,"cannot write a non-number as a number"),D(e<=t,"value larger than maximum allowed value"),D(n<=e,"value smaller than minimum allowed value")}function D(e,t){if(!e)throw new Error(t||"Failed assertion")}g._augment=function(e){return e._isBuffer=!0,e._get=e.get,e._set=e.set,e.get=L.get,e.set=L.set,e.write=L.write,e.toString=L.toString,e.toLocaleString=L.toString,e.toJSON=L.toJSON,e.copy=L.copy,e.slice=L.slice,e.readUInt8=L.readUInt8,e.readUInt16LE=L.readUInt16LE,e.readUInt16BE=L.readUInt16BE,e.readUInt32LE=L.readUInt32LE,e.readUInt32BE=L.readUInt32BE,e.readInt8=L.readInt8,e.readInt16LE=L.readInt16LE,e.readInt16BE=L.readInt16BE,e.readInt32LE=L.readInt32LE,e.readInt32BE=L.readInt32BE,e.readFloatLE=L.readFloatLE,e.readFloatBE=L.readFloatBE,e.readDoubleLE=L.readDoubleLE,e.readDoubleBE=L.readDoubleBE,e.writeUInt8=L.writeUInt8,e.writeUInt16LE=L.writeUInt16LE,e.writeUInt16BE=L.writeUInt16BE,e.writeUInt32LE=L.writeUInt32LE,e.writeUInt32BE=L.writeUInt32BE,e.writeInt8=L.writeInt8,e.writeInt16LE=L.writeInt16LE,e.writeInt16BE=L.writeInt16BE,e.writeInt32LE=L.writeInt32LE,e.writeInt32BE=L.writeInt32BE,e.writeFloatLE=L.writeFloatLE,e.writeFloatBE=L.writeFloatBE,e.writeDoubleLE=L.writeDoubleLE,e.writeDoubleBE=L.writeDoubleBE,e.fill=L.fill,e.inspect=L.inspect,e.toArrayBuffer=L.toArrayBuffer,e}}).call(this,O("lYpoI2"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},O("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/buffer/index.js","/node_modules/gulp-browserify/node_modules/buffer")},{"base64-js":2,buffer:3,ieee754:11,lYpoI2:10}],4:[function(l,d,e){(function(e,t,u,n,r,o,i,a,s){var u=l("buffer").Buffer,f=4,c=new u(f);c.fill(0);d.exports={hash:function(e,t,n,r){return u.isBuffer(e)||(e=new u(e)),function(e,t,n){for(var r=new u(t),o=n?r.writeInt32BE:r.writeInt32LE,i=0;i<e.length;i++)o.call(r,e[i],4*i,!0);return r}(t(function(e,t){var n;e.length%f!=0&&(n=e.length+(f-e.length%f),e=u.concat([e,c],n));for(var r=[],o=t?e.readInt32BE:e.readInt32LE,i=0;i<e.length;i+=f)r.push(o.call(e,i));return r}(e,r),8*e.length),n,r)}}}).call(this,l("lYpoI2"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},l("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/helpers.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{buffer:3,lYpoI2:10}],5:[function(w,e,b){(function(e,t,a,n,r,o,i,u,s){var a=w("buffer").Buffer,f=w("./sha"),c=w("./sha256"),l=w("./rng"),d={sha1:f,sha256:c,md5:w("./md5")},h=64,p=new a(h);function g(e,r){var o=d[e=e||"sha1"],i=[];return o||y("algorithm:",e,"is not yet supported"),{update:function(e){return a.isBuffer(e)||(e=new a(e)),i.push(e),e.length,this},digest:function(e){var t=a.concat(i),n=r?function(e,t,n){a.isBuffer(t)||(t=new a(t)),a.isBuffer(n)||(n=new a(n)),t.length>h?t=e(t):t.length<h&&(t=a.concat([t,p],h));for(var r=new a(h),o=new a(h),i=0;i<h;i++)r[i]=54^t[i],o[i]=92^t[i];var u=e(a.concat([r,n]));return e(a.concat([o,u]))}(o,r,t):o(t);return i=null,e?n.toString(e):n}}}function y(){var e=[].slice.call(arguments).join(" ");throw new Error([e,"we accept pull requests","http://github.com/dominictarr/crypto-browserify"].join("\n"))}p.fill(0),b.createHash=function(e){return g(e)},b.createHmac=g,b.randomBytes=function(e,t){if(!t||!t.call)return new a(l(e));try{t.call(this,void 0,new a(l(e)))}catch(e){t(e)}},function(e,t){for(var n in e)t(e[n],n)}(["createCredentials","createCipher","createCipheriv","createDecipher","createDecipheriv","createSign","createVerify","createDiffieHellman","pbkdf2"],function(e){b[e]=function(){y("sorry,",e,"is not implemented yet")}})}).call(this,w("lYpoI2"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},w("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/index.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./md5":6,"./rng":7,"./sha":8,"./sha256":9,buffer:3,lYpoI2:10}],6:[function(w,b,e){(function(e,t,n,r,o,i,u,a,s){var f=w("./helpers");function c(e,t){e[t>>5]|=128<<t%32,e[14+(t+64>>>9<<4)]=t;for(var n=1732584193,r=-271733879,o=-1732584194,i=271733878,u=0;u<e.length;u+=16){var a=n,s=r,f=o,c=i,n=d(n,r,o,i,e[u+0],7,-680876936),i=d(i,n,r,o,e[u+1],12,-389564586),o=d(o,i,n,r,e[u+2],17,606105819),r=d(r,o,i,n,e[u+3],22,-1044525330);n=d(n,r,o,i,e[u+4],7,-176418897),i=d(i,n,r,o,e[u+5],12,1200080426),o=d(o,i,n,r,e[u+6],17,-1473231341),r=d(r,o,i,n,e[u+7],22,-45705983),n=d(n,r,o,i,e[u+8],7,1770035416),i=d(i,n,r,o,e[u+9],12,-1958414417),o=d(o,i,n,r,e[u+10],17,-42063),r=d(r,o,i,n,e[u+11],22,-1990404162),n=d(n,r,o,i,e[u+12],7,1804603682),i=d(i,n,r,o,e[u+13],12,-40341101),o=d(o,i,n,r,e[u+14],17,-1502002290),n=h(n,r=d(r,o,i,n,e[u+15],22,1236535329),o,i,e[u+1],5,-165796510),i=h(i,n,r,o,e[u+6],9,-1069501632),o=h(o,i,n,r,e[u+11],14,643717713),r=h(r,o,i,n,e[u+0],20,-373897302),n=h(n,r,o,i,e[u+5],5,-701558691),i=h(i,n,r,o,e[u+10],9,38016083),o=h(o,i,n,r,e[u+15],14,-660478335),r=h(r,o,i,n,e[u+4],20,-405537848),n=h(n,r,o,i,e[u+9],5,568446438),i=h(i,n,r,o,e[u+14],9,-1019803690),o=h(o,i,n,r,e[u+3],14,-187363961),r=h(r,o,i,n,e[u+8],20,1163531501),n=h(n,r,o,i,e[u+13],5,-1444681467),i=h(i,n,r,o,e[u+2],9,-51403784),o=h(o,i,n,r,e[u+7],14,1735328473),n=p(n,r=h(r,o,i,n,e[u+12],20,-1926607734),o,i,e[u+5],4,-378558),i=p(i,n,r,o,e[u+8],11,-2022574463),o=p(o,i,n,r,e[u+11],16,1839030562),r=p(r,o,i,n,e[u+14],23,-35309556),n=p(n,r,o,i,e[u+1],4,-1530992060),i=p(i,n,r,o,e[u+4],11,1272893353),o=p(o,i,n,r,e[u+7],16,-155497632),r=p(r,o,i,n,e[u+10],23,-1094730640),n=p(n,r,o,i,e[u+13],4,681279174),i=p(i,n,r,o,e[u+0],11,-358537222),o=p(o,i,n,r,e[u+3],16,-722521979),r=p(r,o,i,n,e[u+6],23,76029189),n=p(n,r,o,i,e[u+9],4,-640364487),i=p(i,n,r,o,e[u+12],11,-421815835),o=p(o,i,n,r,e[u+15],16,530742520),n=g(n,r=p(r,o,i,n,e[u+2],23,-995338651),o,i,e[u+0],6,-198630844),i=g(i,n,r,o,e[u+7],10,1126891415),o=g(o,i,n,r,e[u+14],15,-1416354905),r=g(r,o,i,n,e[u+5],21,-57434055),n=g(n,r,o,i,e[u+12],6,1700485571),i=g(i,n,r,o,e[u+3],10,-1894986606),o=g(o,i,n,r,e[u+10],15,-1051523),r=g(r,o,i,n,e[u+1],21,-2054922799),n=g(n,r,o,i,e[u+8],6,1873313359),i=g(i,n,r,o,e[u+15],10,-30611744),o=g(o,i,n,r,e[u+6],15,-1560198380),r=g(r,o,i,n,e[u+13],21,1309151649),n=g(n,r,o,i,e[u+4],6,-145523070),i=g(i,n,r,o,e[u+11],10,-1120210379),o=g(o,i,n,r,e[u+2],15,718787259),r=g(r,o,i,n,e[u+9],21,-343485551),n=y(n,a),r=y(r,s),o=y(o,f),i=y(i,c)}return Array(n,r,o,i)}function l(e,t,n,r,o,i){return y((u=y(y(t,e),y(r,i)))<<(a=o)|u>>>32-a,n);var u,a}function d(e,t,n,r,o,i,u){return l(t&n|~t&r,e,t,o,i,u)}function h(e,t,n,r,o,i,u){return l(t&r|n&~r,e,t,o,i,u)}function p(e,t,n,r,o,i,u){return l(t^n^r,e,t,o,i,u)}function g(e,t,n,r,o,i,u){return l(n^(t|~r),e,t,o,i,u)}function y(e,t){var n=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(n>>16)<<16|65535&n}b.exports=function(e){return f.hash(e,c,16)}}).call(this,w("lYpoI2"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},w("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/md5.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./helpers":4,buffer:3,lYpoI2:10}],7:[function(e,l,t){(function(e,t,n,r,o,i,u,a,s){var f,c;c=function(e){for(var t,n=new Array(e),r=0;r<e;r++)0==(3&r)&&(t=4294967296*Math.random()),n[r]=t>>>((3&r)<<3)&255;return n},l.exports=f||c}).call(this,e("lYpoI2"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/rng.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{buffer:3,lYpoI2:10}],8:[function(l,d,e){(function(e,t,n,r,o,i,u,a,s){var f=l("./helpers");function c(e,t){e[t>>5]|=128<<24-t%32,e[15+(t+64>>9<<4)]=t;for(var n,r,o,i,u,a=Array(80),s=1732584193,f=-271733879,c=-1732584194,l=271733878,d=-1009589776,h=0;h<e.length;h+=16){for(var p=s,g=f,y=c,w=l,b=d,m=0;m<80;m++){a[m]=m<16?e[h+m]:E(a[m-3]^a[m-8]^a[m-14]^a[m-16],1);var v=_(_(E(s,5),(o=f,i=c,u=l,(r=m)<20?o&i|~o&u:!(r<40)&&r<60?o&i|o&u|i&u:o^i^u)),_(_(d,a[m]),(n=m)<20?1518500249:n<40?1859775393:n<60?-1894007588:-899497514)),d=l,l=c,c=E(f,30),f=s,s=v}s=_(s,p),f=_(f,g),c=_(c,y),l=_(l,w),d=_(d,b)}return Array(s,f,c,l,d)}function _(e,t){var n=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(n>>16)<<16|65535&n}function E(e,t){return e<<t|e>>>32-t}d.exports=function(e){return f.hash(e,c,20,!0)}}).call(this,l("lYpoI2"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},l("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/sha.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./helpers":4,buffer:3,lYpoI2:10}],9:[function(l,d,e){(function(e,t,n,r,o,i,u,a,s){function B(e,t){var n=(65535&e)+(65535&t);return(e>>16)+(t>>16)+(n>>16)<<16|65535&n}function L(e,t){return e>>>t|e<<32-t}function f(e,t){var n,r,o,i,u,a,s,f,c,l,d=new Array(1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298),h=new Array(1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225),p=new Array(64);e[t>>5]|=128<<24-t%32,e[15+(t+64>>9<<4)]=t;for(var g,y,w,b,m,v,_,E,I=0;I<e.length;I+=16){n=h[0],r=h[1],o=h[2],i=h[3],u=h[4],a=h[5],s=h[6],f=h[7];for(var A=0;A<64;A++)p[A]=A<16?e[A+I]:B(B(B((E=p[A-2],L(E,17)^L(E,19)^E>>>10),p[A-7]),(_=p[A-15],L(_,7)^L(_,18)^_>>>3)),p[A-16]),c=B(B(B(B(f,L(v=u,6)^L(v,11)^L(v,25)),(m=u)&a^~m&s),d[A]),p[A]),l=B(L(b=n,2)^L(b,13)^L(b,22),(g=n)&(y=r)^g&(w=o)^y&w),f=s,s=a,a=u,u=B(i,c),i=o,o=r,r=n,n=B(c,l);h[0]=B(n,h[0]),h[1]=B(r,h[1]),h[2]=B(o,h[2]),h[3]=B(i,h[3]),h[4]=B(u,h[4]),h[5]=B(a,h[5]),h[6]=B(s,h[6]),h[7]=B(f,h[7])}return h}var c=l("./helpers");d.exports=function(e){return c.hash(e,f,32,!0)}}).call(this,l("lYpoI2"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},l("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/sha256.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./helpers":4,buffer:3,lYpoI2:10}],10:[function(e,c,t){(function(e,t,n,r,o,i,u,a,s){function f(){}(e=c.exports={}).nextTick=function(){var e="undefined"!=typeof window&&window.setImmediate,t="undefined"!=typeof window&&window.postMessage&&window.addEventListener;if(e)return function(e){return window.setImmediate(e)};if(t){var n=[];return window.addEventListener("message",function(e){var t=e.source;t!==window&&null!==t||"process-tick"!==e.data||(e.stopPropagation(),0<n.length&&n.shift()())},!0),function(e){n.push(e),window.postMessage("process-tick","*")}}return function(e){setTimeout(e,0)}}(),e.title="browser",e.browser=!0,e.env={},e.argv=[],e.on=f,e.addListener=f,e.once=f,e.off=f,e.removeListener=f,e.removeAllListeners=f,e.emit=f,e.binding=function(e){throw new Error("process.binding is not supported")},e.cwd=function(){return"/"},e.chdir=function(e){throw new Error("process.chdir is not supported")}}).call(this,e("lYpoI2"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/process/browser.js","/node_modules/gulp-browserify/node_modules/process")},{buffer:3,lYpoI2:10}],11:[function(e,t,f){(function(e,t,n,r,o,i,u,a,s){f.read=function(e,t,n,r,o){var i,u,a=8*o-r-1,s=(1<<a)-1,f=s>>1,c=-7,l=n?o-1:0,d=n?-1:1,h=e[t+l];for(l+=d,i=h&(1<<-c)-1,h>>=-c,c+=a;0<c;i=256*i+e[t+l],l+=d,c-=8);for(u=i&(1<<-c)-1,i>>=-c,c+=r;0<c;u=256*u+e[t+l],l+=d,c-=8);if(0===i)i=1-f;else{if(i===s)return u?NaN:1/0*(h?-1:1);u+=Math.pow(2,r),i-=f}return(h?-1:1)*u*Math.pow(2,i-r)},f.write=function(e,t,n,r,o,i){var u,a,s,f=8*i-o-1,c=(1<<f)-1,l=c>>1,d=23===o?Math.pow(2,-24)-Math.pow(2,-77):0,h=r?0:i-1,p=r?1:-1,g=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,u=c):(u=Math.floor(Math.log(t)/Math.LN2),t*(s=Math.pow(2,-u))<1&&(u--,s*=2),2<=(t+=1<=u+l?d/s:d*Math.pow(2,1-l))*s&&(u++,s/=2),c<=u+l?(a=0,u=c):1<=u+l?(a=(t*s-1)*Math.pow(2,o),u+=l):(a=t*Math.pow(2,l-1)*Math.pow(2,o),u=0));8<=o;e[n+h]=255&a,h+=p,a/=256,o-=8);for(u=u<<o|a,f+=o;0<f;e[n+h]=255&u,h+=p,u/=256,f-=8);e[n+h-p]|=128*g}}).call(this,e("lYpoI2"),"undefined"!=typeof self?self:"undefined"!=typeof window?window:{},e("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/ieee754/index.js","/node_modules/ieee754")},{buffer:3,lYpoI2:10}]},{},[1])(1)});
...\ No newline at end of file ...\ No newline at end of file
......
...@@ -406,6 +406,9 @@ function typeHasher(options, writeTo, context){ ...@@ -406,6 +406,9 @@ function typeHasher(options, writeTo, context){
406 'Use "options.replacer" or "options.ignoreUnknown"\n'); 406 'Use "options.replacer" or "options.ignoreUnknown"\n');
407 }, 407 },
408 _domwindow: function() { return write('domwindow'); }, 408 _domwindow: function() { return write('domwindow'); },
409 + _bigint: function(number){
410 + return write('bigint:' + number.toString());
411 + },
409 /* Node.js standard native objects */ 412 /* Node.js standard native objects */
410 _process: function() { return write('process'); }, 413 _process: function() { return write('process'); },
411 _timer: function() { return write('timer'); }, 414 _timer: function() { return write('timer'); },
......
1 { 1 {
2 "_from": "object-hash@^2.1.1", 2 "_from": "object-hash@^2.1.1",
3 - "_id": "object-hash@2.1.1", 3 + "_id": "object-hash@2.2.0",
4 "_inBundle": false, 4 "_inBundle": false,
5 - "_integrity": "sha512-VOJmgmS+7wvXf8CjbQmimtCnEx3IAoLxI3fp2fbWehxrWBcAQFbk+vcwb6vzR0VZv/eNCJ/27j151ZTwqW/JeQ==", 5 + "_integrity": "sha512-gScRMn0bS5fH+IuwyIFgnh9zBdo4DV+6GhygmWM9HyNJSgS0hScp1f5vjtm7oIIOiT9trXrShAkLFSc2IqKNgw==",
6 "_location": "/object-hash", 6 "_location": "/object-hash",
7 "_phantomChildren": {}, 7 "_phantomChildren": {},
8 "_requested": { 8 "_requested": {
...@@ -18,8 +18,8 @@ ...@@ -18,8 +18,8 @@
18 "_requiredBy": [ 18 "_requiredBy": [
19 "/google-gax" 19 "/google-gax"
20 ], 20 ],
21 - "_resolved": "https://registry.npmjs.org/object-hash/-/object-hash-2.1.1.tgz", 21 + "_resolved": "https://registry.npmjs.org/object-hash/-/object-hash-2.2.0.tgz",
22 - "_shasum": "9447d0279b4fcf80cff3259bf66a1dc73afabe09", 22 + "_shasum": "5ad518581eefc443bd763472b8ff2e9c2c0d54a5",
23 "_spec": "object-hash@^2.1.1", 23 "_spec": "object-hash@^2.1.1",
24 "_where": "C:\\Users\\1000c\\이것저것\\옾소\\Voicoding\\node_modules\\google-gax", 24 "_where": "C:\\Users\\1000c\\이것저것\\옾소\\Voicoding\\node_modules\\google-gax",
25 "author": { 25 "author": {
...@@ -77,5 +77,5 @@ ...@@ -77,5 +77,5 @@
77 "prepublish": "gulp dist", 77 "prepublish": "gulp dist",
78 "test": "node ./node_modules/.bin/mocha test" 78 "test": "node ./node_modules/.bin/mocha test"
79 }, 79 },
80 - "version": "2.1.1" 80 + "version": "2.2.0"
81 } 81 }
......
...@@ -30,8 +30,9 @@ For more information, see [this discussion](https://github.com/puleos/object-has ...@@ -30,8 +30,9 @@ For more information, see [this discussion](https://github.com/puleos/object-has
30 30
31 ## hash(value, options); 31 ## hash(value, options);
32 Generate a hash from any object or type. Defaults to sha1 with hex encoding. 32 Generate a hash from any object or type. Defaults to sha1 with hex encoding.
33 -* `algorithm` hash algo to be used: 'sha1', 'md5'. default: sha1 33 +* `algorithm` hash algo to be used: 'sha1', 'md5', 'passthrough'. default: sha1
34 * This supports the algorithms returned by `crypto.getHashes()`. Note that the default of SHA-1 is not considered secure, and a stronger algorithm should be used if a cryptographical hash is desired. 34 * This supports the algorithms returned by `crypto.getHashes()`. Note that the default of SHA-1 is not considered secure, and a stronger algorithm should be used if a cryptographical hash is desired.
35 + * This also supports the `passthrough` algorith, which will return the information that would otherwise have been hashed.
35 * `excludeValues` {true|false} hash object keys, values ignored. default: false 36 * `excludeValues` {true|false} hash object keys, values ignored. default: false
36 * `encoding` hash encoding, supports 'buffer', 'hex', 'binary', 'base64'. default: hex 37 * `encoding` hash encoding, supports 'buffer', 'hex', 'binary', 'base64'. default: hex
37 * `ignoreUnknown` {true|*false} ignore unknown object types. default: false 38 * `ignoreUnknown` {true|*false} ignore unknown object types. default: false
......
1 +'use strict';
2 +
3 +if (typeof process === 'undefined' ||
4 + !process.version ||
5 + process.version.indexOf('v0.') === 0 ||
6 + process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {
7 + module.exports = { nextTick: nextTick };
8 +} else {
9 + module.exports = process
10 +}
11 +
12 +function nextTick(fn, arg1, arg2, arg3) {
13 + if (typeof fn !== 'function') {
14 + throw new TypeError('"callback" argument must be a function');
15 + }
16 + var len = arguments.length;
17 + var args, i;
18 + switch (len) {
19 + case 0:
20 + case 1:
21 + return process.nextTick(fn);
22 + case 2:
23 + return process.nextTick(function afterTickOne() {
24 + fn.call(null, arg1);
25 + });
26 + case 3:
27 + return process.nextTick(function afterTickTwo() {
28 + fn.call(null, arg1, arg2);
29 + });
30 + case 4:
31 + return process.nextTick(function afterTickThree() {
32 + fn.call(null, arg1, arg2, arg3);
33 + });
34 + default:
35 + args = new Array(len - 1);
36 + i = 0;
37 + while (i < args.length) {
38 + args[i++] = arguments[i];
39 + }
40 + return process.nextTick(function afterTick() {
41 + fn.apply(null, args);
42 + });
43 + }
44 +}
45 +
1 +# Copyright (c) 2015 Calvin Metcalf
2 +
3 +Permission is hereby granted, free of charge, to any person obtaining a copy
4 +of this software and associated documentation files (the "Software"), to deal
5 +in the Software without restriction, including without limitation the rights
6 +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7 +copies of the Software, and to permit persons to whom the Software is
8 +furnished to do so, subject to the following conditions:
9 +
10 +The above copyright notice and this permission notice shall be included in all
11 +copies or substantial portions of the Software.
12 +
13 +**THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18 +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19 +SOFTWARE.**
1 +{
2 + "_from": "process-nextick-args@~2.0.0",
3 + "_id": "process-nextick-args@2.0.1",
4 + "_inBundle": false,
5 + "_integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==",
6 + "_location": "/process-nextick-args",
7 + "_phantomChildren": {},
8 + "_requested": {
9 + "type": "range",
10 + "registry": true,
11 + "raw": "process-nextick-args@~2.0.0",
12 + "name": "process-nextick-args",
13 + "escapedName": "process-nextick-args",
14 + "rawSpec": "~2.0.0",
15 + "saveSpec": null,
16 + "fetchSpec": "~2.0.0"
17 + },
18 + "_requiredBy": [
19 + "/concat-stream/readable-stream"
20 + ],
21 + "_resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz",
22 + "_shasum": "7820d9b16120cc55ca9ae7792680ae7dba6d7fe2",
23 + "_spec": "process-nextick-args@~2.0.0",
24 + "_where": "C:\\Users\\1000c\\이것저것\\옾소\\Voicoding\\node_modules\\concat-stream\\node_modules\\readable-stream",
25 + "author": "",
26 + "bugs": {
27 + "url": "https://github.com/calvinmetcalf/process-nextick-args/issues"
28 + },
29 + "bundleDependencies": false,
30 + "deprecated": false,
31 + "description": "process.nextTick but always with args",
32 + "devDependencies": {
33 + "tap": "~0.2.6"
34 + },
35 + "files": [
36 + "index.js"
37 + ],
38 + "homepage": "https://github.com/calvinmetcalf/process-nextick-args",
39 + "license": "MIT",
40 + "main": "index.js",
41 + "name": "process-nextick-args",
42 + "repository": {
43 + "type": "git",
44 + "url": "git+https://github.com/calvinmetcalf/process-nextick-args.git"
45 + },
46 + "scripts": {
47 + "test": "node test.js"
48 + },
49 + "version": "2.0.1"
50 +}
1 +process-nextick-args
2 +=====
3 +
4 +[![Build Status](https://travis-ci.org/calvinmetcalf/process-nextick-args.svg?branch=master)](https://travis-ci.org/calvinmetcalf/process-nextick-args)
5 +
6 +```bash
7 +npm install --save process-nextick-args
8 +```
9 +
10 +Always be able to pass arguments to process.nextTick, no matter the platform
11 +
12 +```js
13 +var pna = require('process-nextick-args');
14 +
15 +pna.nextTick(function (a, b, c) {
16 + console.log(a, b, c);
17 +}, 'step', 3, 'profit');
18 +```
1 +build/
2 +test/
3 +examples/
4 +fs.js
5 +zlib.js
...\ No newline at end of file ...\ No newline at end of file
1 -Node.js is licensed for use as follows:
2 -
3 -"""
4 -Copyright Node.js contributors. All rights reserved.
5 -
6 -Permission is hereby granted, free of charge, to any person obtaining a copy
7 -of this software and associated documentation files (the "Software"), to
8 -deal in the Software without restriction, including without limitation the
9 -rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
10 -sell copies of the Software, and to permit persons to whom the Software is
11 -furnished to do so, subject to the following conditions:
12 -
13 -The above copyright notice and this permission notice shall be included in
14 -all copies or substantial portions of the Software.
15 -
16 -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21 -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
22 -IN THE SOFTWARE.
23 -"""
24 -
25 -This license applies to parts of Node.js originating from the
26 -https://github.com/joyent/node repository:
27 -
28 -"""
29 Copyright Joyent, Inc. and other Node contributors. All rights reserved. 1 Copyright Joyent, Inc. and other Node contributors. All rights reserved.
30 Permission is hereby granted, free of charge, to any person obtaining a copy 2 Permission is hereby granted, free of charge, to any person obtaining a copy
31 of this software and associated documentation files (the "Software"), to 3 of this software and associated documentation files (the "Software"), to
...@@ -44,4 +16,3 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ...@@ -44,4 +16,3 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
44 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 16 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
45 FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS 17 FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
46 IN THE SOFTWARE. 18 IN THE SOFTWARE.
47 -"""
......
1 # readable-stream 1 # readable-stream
2 2
3 -***Node.js core streams for userland*** [![Build Status](https://travis-ci.com/nodejs/readable-stream.svg?branch=master)](https://travis-ci.com/nodejs/readable-stream) 3 +***Node-core streams for userland***
4 -
5 4
6 [![NPM](https://nodei.co/npm/readable-stream.png?downloads=true&downloadRank=true)](https://nodei.co/npm/readable-stream/) 5 [![NPM](https://nodei.co/npm/readable-stream.png?downloads=true&downloadRank=true)](https://nodei.co/npm/readable-stream/)
7 -[![NPM](https://nodei.co/npm-dl/readable-stream.png?&months=6&height=3)](https://nodei.co/npm/readable-stream/) 6 +[![NPM](https://nodei.co/npm-dl/readable-stream.png&months=6&height=3)](https://nodei.co/npm/readable-stream/)
8 -
9 -
10 -[![Sauce Test Status](https://saucelabs.com/browser-matrix/readabe-stream.svg)](https://saucelabs.com/u/readabe-stream)
11 -
12 -```bash
13 -npm install --save readable-stream
14 -```
15 -
16 -This package is a mirror of the streams implementations in Node.js.
17 -
18 -Full documentation may be found on the [Node.js website](https://nodejs.org/dist/v10.19.0/docs/api/stream.html).
19 -
20 -If you want to guarantee a stable streams base, regardless of what version of
21 -Node you, or the users of your libraries are using, use **readable-stream** *only* and avoid the *"stream"* module in Node-core, for background see [this blogpost](http://r.va.gg/2014/06/why-i-dont-use-nodes-core-stream-module.html).
22 -
23 -As of version 2.0.0 **readable-stream** uses semantic versioning.
24 -
25 -## Version 3.x.x
26 -
27 -v3.x.x of `readable-stream` is a cut from Node 10. This version supports Node 6, 8, and 10, as well as evergreen browsers, IE 11 and latest Safari. The breaking changes introduced by v3 are composed by the combined breaking changes in [Node v9](https://nodejs.org/en/blog/release/v9.0.0/) and [Node v10](https://nodejs.org/en/blog/release/v10.0.0/), as follows:
28 -
29 -1. Error codes: https://github.com/nodejs/node/pull/13310,
30 - https://github.com/nodejs/node/pull/13291,
31 - https://github.com/nodejs/node/pull/16589,
32 - https://github.com/nodejs/node/pull/15042,
33 - https://github.com/nodejs/node/pull/15665,
34 - https://github.com/nodejs/readable-stream/pull/344
35 -2. 'readable' have precedence over flowing
36 - https://github.com/nodejs/node/pull/18994
37 -3. make virtual methods errors consistent
38 - https://github.com/nodejs/node/pull/18813
39 -4. updated streams error handling
40 - https://github.com/nodejs/node/pull/18438
41 -5. writable.end should return this.
42 - https://github.com/nodejs/node/pull/18780
43 -6. readable continues to read when push('')
44 - https://github.com/nodejs/node/pull/18211
45 -7. add custom inspect to BufferList
46 - https://github.com/nodejs/node/pull/17907
47 -8. always defer 'readable' with nextTick
48 - https://github.com/nodejs/node/pull/17979
49 -
50 -## Version 2.x.x
51 -v2.x.x of `readable-stream` is a cut of the stream module from Node 8 (there have been no semver-major changes from Node 4 to 8). This version supports all Node.js versions from 0.8, as well as evergreen browsers and IE 10 & 11.
52 -
53 -### Big Thanks
54 -
55 -Cross-browser Testing Platform and Open Source <3 Provided by [Sauce Labs][sauce]
56 -
57 -# Usage
58 -
59 -You can swap your `require('stream')` with `require('readable-stream')`
60 -without any changes, if you are just using one of the main classes and
61 -functions.
62 -
63 -```js
64 -const {
65 - Readable,
66 - Writable,
67 - Transform,
68 - Duplex,
69 - pipeline,
70 - finished
71 -} = require('readable-stream')
72 -````
73 -
74 -Note that `require('stream')` will return `Stream`, while
75 -`require('readable-stream')` will return `Readable`. We discourage using
76 -whatever is exported directly, but rather use one of the properties as
77 -shown in the example above.
78 -
79 -# Streams Working Group
80 7
81 -`readable-stream` is maintained by the Streams Working Group, which 8 +This package is a mirror of the Streams2 and Streams3 implementations in Node-core.
82 -oversees the development and maintenance of the Streams API within
83 -Node.js. The responsibilities of the Streams Working Group include:
84 9
85 -* Addressing stream issues on the Node.js issue tracker. 10 +If you want to guarantee a stable streams base, regardless of what version of Node you, or the users of your libraries are using, use **readable-stream** *only* and avoid the *"stream"* module in Node-core.
86 -* Authoring and editing stream documentation within the Node.js project.
87 -* Reviewing changes to stream subclasses within the Node.js project.
88 -* Redirecting changes to streams from the Node.js project to this
89 - project.
90 -* Assisting in the implementation of stream providers within Node.js.
91 -* Recommending versions of `readable-stream` to be included in Node.js.
92 -* Messaging about the future of streams to give the community advance
93 - notice of changes.
94 11
95 -<a name="members"></a> 12 +**readable-stream** comes in two major versions, v1.0.x and v1.1.x. The former tracks the Streams2 implementation in Node 0.10, including bug-fixes and minor improvements as they are added. The latter tracks Streams3 as it develops in Node 0.11; we will likely see a v1.2.x branch for Node 0.12.
96 -## Team Members
97 13
98 -* **Calvin Metcalf** ([@calvinmetcalf](https://github.com/calvinmetcalf)) &lt;calvin.metcalf@gmail.com&gt; 14 +**readable-stream** uses proper patch-level versioning so if you pin to `"~1.0.0"` you’ll get the latest Node 0.10 Streams2 implementation, including any fixes and minor non-breaking improvements. The patch-level versions of 1.0.x and 1.1.x should mirror the patch-level versions of Node-core releases. You should prefer the **1.0.x** releases for now and when you’re ready to start using Streams3, pin to `"~1.1.0"`
99 - - Release GPG key: F3EF5F62A87FC27A22E643F714CE4FF5015AA242
100 -* **Mathias Buus** ([@mafintosh](https://github.com/mafintosh)) &lt;mathiasbuus@gmail.com&gt;
101 -* **Matteo Collina** ([@mcollina](https://github.com/mcollina)) &lt;matteo.collina@gmail.com&gt;
102 - - Release GPG key: 3ABC01543F22DD2239285CDD818674489FBC127E
103 -* **Irina Shestak** ([@lrlna](https://github.com/lrlna)) &lt;shestak.irina@gmail.com&gt;
104 -* **Yoshua Wyuts** ([@yoshuawuyts](https://github.com/yoshuawuyts)) &lt;yoshuawuyts@gmail.com&gt;
105 15
106 -[sauce]: https://saucelabs.com
......
1 +module.exports = require("./lib/_stream_duplex.js")
1 +diff --git a/lib/_stream_duplex.js b/lib/_stream_duplex.js
2 +index c5a741c..a2e0d8e 100644
3 +--- a/lib/_stream_duplex.js
4 ++++ b/lib/_stream_duplex.js
5 +@@ -26,8 +26,8 @@
6 +
7 + module.exports = Duplex;
8 + var util = require('util');
9 +-var Readable = require('_stream_readable');
10 +-var Writable = require('_stream_writable');
11 ++var Readable = require('./_stream_readable');
12 ++var Writable = require('./_stream_writable');
13 +
14 + util.inherits(Duplex, Readable);
15 +
16 +diff --git a/lib/_stream_passthrough.js b/lib/_stream_passthrough.js
17 +index a5e9864..330c247 100644
18 +--- a/lib/_stream_passthrough.js
19 ++++ b/lib/_stream_passthrough.js
20 +@@ -25,7 +25,7 @@
21 +
22 + module.exports = PassThrough;
23 +
24 +-var Transform = require('_stream_transform');
25 ++var Transform = require('./_stream_transform');
26 + var util = require('util');
27 + util.inherits(PassThrough, Transform);
28 +
29 +diff --git a/lib/_stream_readable.js b/lib/_stream_readable.js
30 +index 0c3fe3e..90a8298 100644
31 +--- a/lib/_stream_readable.js
32 ++++ b/lib/_stream_readable.js
33 +@@ -23,10 +23,34 @@ module.exports = Readable;
34 + Readable.ReadableState = ReadableState;
35 +
36 + var EE = require('events').EventEmitter;
37 ++if (!EE.listenerCount) EE.listenerCount = function(emitter, type) {
38 ++ return emitter.listeners(type).length;
39 ++};
40 ++
41 ++if (!global.setImmediate) global.setImmediate = function setImmediate(fn) {
42 ++ return setTimeout(fn, 0);
43 ++};
44 ++if (!global.clearImmediate) global.clearImmediate = function clearImmediate(i) {
45 ++ return clearTimeout(i);
46 ++};
47 ++
48 + var Stream = require('stream');
49 + var util = require('util');
50 ++if (!util.isUndefined) {
51 ++ var utilIs = require('core-util-is');
52 ++ for (var f in utilIs) {
53 ++ util[f] = utilIs[f];
54 ++ }
55 ++}
56 + var StringDecoder;
57 +-var debug = util.debuglog('stream');
58 ++var debug;
59 ++if (util.debuglog)
60 ++ debug = util.debuglog('stream');
61 ++else try {
62 ++ debug = require('debuglog')('stream');
63 ++} catch (er) {
64 ++ debug = function() {};
65 ++}
66 +
67 + util.inherits(Readable, Stream);
68 +
69 +@@ -380,7 +404,7 @@ function chunkInvalid(state, chunk) {
70 +
71 +
72 + function onEofChunk(stream, state) {
73 +- if (state.decoder && !state.ended) {
74 ++ if (state.decoder && !state.ended && state.decoder.end) {
75 + var chunk = state.decoder.end();
76 + if (chunk && chunk.length) {
77 + state.buffer.push(chunk);
78 +diff --git a/lib/_stream_transform.js b/lib/_stream_transform.js
79 +index b1f9fcc..b0caf57 100644
80 +--- a/lib/_stream_transform.js
81 ++++ b/lib/_stream_transform.js
82 +@@ -64,8 +64,14 @@
83 +
84 + module.exports = Transform;
85 +
86 +-var Duplex = require('_stream_duplex');
87 ++var Duplex = require('./_stream_duplex');
88 + var util = require('util');
89 ++if (!util.isUndefined) {
90 ++ var utilIs = require('core-util-is');
91 ++ for (var f in utilIs) {
92 ++ util[f] = utilIs[f];
93 ++ }
94 ++}
95 + util.inherits(Transform, Duplex);
96 +
97 +
98 +diff --git a/lib/_stream_writable.js b/lib/_stream_writable.js
99 +index ba2e920..f49288b 100644
100 +--- a/lib/_stream_writable.js
101 ++++ b/lib/_stream_writable.js
102 +@@ -27,6 +27,12 @@ module.exports = Writable;
103 + Writable.WritableState = WritableState;
104 +
105 + var util = require('util');
106 ++if (!util.isUndefined) {
107 ++ var utilIs = require('core-util-is');
108 ++ for (var f in utilIs) {
109 ++ util[f] = utilIs[f];
110 ++ }
111 ++}
112 + var Stream = require('stream');
113 +
114 + util.inherits(Writable, Stream);
115 +@@ -119,7 +125,7 @@ function WritableState(options, stream) {
116 + function Writable(options) {
117 + // Writable ctor is applied to Duplexes, though they're not
118 + // instanceof Writable, they're instanceof Readable.
119 +- if (!(this instanceof Writable) && !(this instanceof Stream.Duplex))
120 ++ if (!(this instanceof Writable) && !(this instanceof require('./_stream_duplex')))
121 + return new Writable(options);
122 +
123 + this._writableState = new WritableState(options, this);
124 +diff --git a/test/simple/test-stream-big-push.js b/test/simple/test-stream-big-push.js
125 +index e3787e4..8cd2127 100644
126 +--- a/test/simple/test-stream-big-push.js
127 ++++ b/test/simple/test-stream-big-push.js
128 +@@ -21,7 +21,7 @@
129 +
130 + var common = require('../common');
131 + var assert = require('assert');
132 +-var stream = require('stream');
133 ++var stream = require('../../');
134 + var str = 'asdfasdfasdfasdfasdf';
135 +
136 + var r = new stream.Readable({
137 +diff --git a/test/simple/test-stream-end-paused.js b/test/simple/test-stream-end-paused.js
138 +index bb73777..d40efc7 100644
139 +--- a/test/simple/test-stream-end-paused.js
140 ++++ b/test/simple/test-stream-end-paused.js
141 +@@ -25,7 +25,7 @@ var gotEnd = false;
142 +
143 + // Make sure we don't miss the end event for paused 0-length streams
144 +
145 +-var Readable = require('stream').Readable;
146 ++var Readable = require('../../').Readable;
147 + var stream = new Readable();
148 + var calledRead = false;
149 + stream._read = function() {
150 +diff --git a/test/simple/test-stream-pipe-after-end.js b/test/simple/test-stream-pipe-after-end.js
151 +index b46ee90..0be8366 100644
152 +--- a/test/simple/test-stream-pipe-after-end.js
153 ++++ b/test/simple/test-stream-pipe-after-end.js
154 +@@ -22,8 +22,8 @@
155 + var common = require('../common');
156 + var assert = require('assert');
157 +
158 +-var Readable = require('_stream_readable');
159 +-var Writable = require('_stream_writable');
160 ++var Readable = require('../../lib/_stream_readable');
161 ++var Writable = require('../../lib/_stream_writable');
162 + var util = require('util');
163 +
164 + util.inherits(TestReadable, Readable);
165 +diff --git a/test/simple/test-stream-pipe-cleanup.js b/test/simple/test-stream-pipe-cleanup.js
166 +deleted file mode 100644
167 +index f689358..0000000
168 +--- a/test/simple/test-stream-pipe-cleanup.js
169 ++++ /dev/null
170 +@@ -1,122 +0,0 @@
171 +-// Copyright Joyent, Inc. and other Node contributors.
172 +-//
173 +-// Permission is hereby granted, free of charge, to any person obtaining a
174 +-// copy of this software and associated documentation files (the
175 +-// "Software"), to deal in the Software without restriction, including
176 +-// without limitation the rights to use, copy, modify, merge, publish,
177 +-// distribute, sublicense, and/or sell copies of the Software, and to permit
178 +-// persons to whom the Software is furnished to do so, subject to the
179 +-// following conditions:
180 +-//
181 +-// The above copyright notice and this permission notice shall be included
182 +-// in all copies or substantial portions of the Software.
183 +-//
184 +-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
185 +-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
186 +-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
187 +-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
188 +-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
189 +-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
190 +-// USE OR OTHER DEALINGS IN THE SOFTWARE.
191 +-
192 +-// This test asserts that Stream.prototype.pipe does not leave listeners
193 +-// hanging on the source or dest.
194 +-
195 +-var common = require('../common');
196 +-var stream = require('stream');
197 +-var assert = require('assert');
198 +-var util = require('util');
199 +-
200 +-function Writable() {
201 +- this.writable = true;
202 +- this.endCalls = 0;
203 +- stream.Stream.call(this);
204 +-}
205 +-util.inherits(Writable, stream.Stream);
206 +-Writable.prototype.end = function() {
207 +- this.endCalls++;
208 +-};
209 +-
210 +-Writable.prototype.destroy = function() {
211 +- this.endCalls++;
212 +-};
213 +-
214 +-function Readable() {
215 +- this.readable = true;
216 +- stream.Stream.call(this);
217 +-}
218 +-util.inherits(Readable, stream.Stream);
219 +-
220 +-function Duplex() {
221 +- this.readable = true;
222 +- Writable.call(this);
223 +-}
224 +-util.inherits(Duplex, Writable);
225 +-
226 +-var i = 0;
227 +-var limit = 100;
228 +-
229 +-var w = new Writable();
230 +-
231 +-var r;
232 +-
233 +-for (i = 0; i < limit; i++) {
234 +- r = new Readable();
235 +- r.pipe(w);
236 +- r.emit('end');
237 +-}
238 +-assert.equal(0, r.listeners('end').length);
239 +-assert.equal(limit, w.endCalls);
240 +-
241 +-w.endCalls = 0;
242 +-
243 +-for (i = 0; i < limit; i++) {
244 +- r = new Readable();
245 +- r.pipe(w);
246 +- r.emit('close');
247 +-}
248 +-assert.equal(0, r.listeners('close').length);
249 +-assert.equal(limit, w.endCalls);
250 +-
251 +-w.endCalls = 0;
252 +-
253 +-r = new Readable();
254 +-
255 +-for (i = 0; i < limit; i++) {
256 +- w = new Writable();
257 +- r.pipe(w);
258 +- w.emit('close');
259 +-}
260 +-assert.equal(0, w.listeners('close').length);
261 +-
262 +-r = new Readable();
263 +-w = new Writable();
264 +-var d = new Duplex();
265 +-r.pipe(d); // pipeline A
266 +-d.pipe(w); // pipeline B
267 +-assert.equal(r.listeners('end').length, 2); // A.onend, A.cleanup
268 +-assert.equal(r.listeners('close').length, 2); // A.onclose, A.cleanup
269 +-assert.equal(d.listeners('end').length, 2); // B.onend, B.cleanup
270 +-assert.equal(d.listeners('close').length, 3); // A.cleanup, B.onclose, B.cleanup
271 +-assert.equal(w.listeners('end').length, 0);
272 +-assert.equal(w.listeners('close').length, 1); // B.cleanup
273 +-
274 +-r.emit('end');
275 +-assert.equal(d.endCalls, 1);
276 +-assert.equal(w.endCalls, 0);
277 +-assert.equal(r.listeners('end').length, 0);
278 +-assert.equal(r.listeners('close').length, 0);
279 +-assert.equal(d.listeners('end').length, 2); // B.onend, B.cleanup
280 +-assert.equal(d.listeners('close').length, 2); // B.onclose, B.cleanup
281 +-assert.equal(w.listeners('end').length, 0);
282 +-assert.equal(w.listeners('close').length, 1); // B.cleanup
283 +-
284 +-d.emit('end');
285 +-assert.equal(d.endCalls, 1);
286 +-assert.equal(w.endCalls, 1);
287 +-assert.equal(r.listeners('end').length, 0);
288 +-assert.equal(r.listeners('close').length, 0);
289 +-assert.equal(d.listeners('end').length, 0);
290 +-assert.equal(d.listeners('close').length, 0);
291 +-assert.equal(w.listeners('end').length, 0);
292 +-assert.equal(w.listeners('close').length, 0);
293 +diff --git a/test/simple/test-stream-pipe-error-handling.js b/test/simple/test-stream-pipe-error-handling.js
294 +index c5d724b..c7d6b7d 100644
295 +--- a/test/simple/test-stream-pipe-error-handling.js
296 ++++ b/test/simple/test-stream-pipe-error-handling.js
297 +@@ -21,7 +21,7 @@
298 +
299 + var common = require('../common');
300 + var assert = require('assert');
301 +-var Stream = require('stream').Stream;
302 ++var Stream = require('../../').Stream;
303 +
304 + (function testErrorListenerCatches() {
305 + var source = new Stream();
306 +diff --git a/test/simple/test-stream-pipe-event.js b/test/simple/test-stream-pipe-event.js
307 +index cb9d5fe..56f8d61 100644
308 +--- a/test/simple/test-stream-pipe-event.js
309 ++++ b/test/simple/test-stream-pipe-event.js
310 +@@ -20,7 +20,7 @@
311 + // USE OR OTHER DEALINGS IN THE SOFTWARE.
312 +
313 + var common = require('../common');
314 +-var stream = require('stream');
315 ++var stream = require('../../');
316 + var assert = require('assert');
317 + var util = require('util');
318 +
319 +diff --git a/test/simple/test-stream-push-order.js b/test/simple/test-stream-push-order.js
320 +index f2e6ec2..a5c9bf9 100644
321 +--- a/test/simple/test-stream-push-order.js
322 ++++ b/test/simple/test-stream-push-order.js
323 +@@ -20,7 +20,7 @@
324 + // USE OR OTHER DEALINGS IN THE SOFTWARE.
325 +
326 + var common = require('../common.js');
327 +-var Readable = require('stream').Readable;
328 ++var Readable = require('../../').Readable;
329 + var assert = require('assert');
330 +
331 + var s = new Readable({
332 +diff --git a/test/simple/test-stream-push-strings.js b/test/simple/test-stream-push-strings.js
333 +index 06f43dc..1701a9a 100644
334 +--- a/test/simple/test-stream-push-strings.js
335 ++++ b/test/simple/test-stream-push-strings.js
336 +@@ -22,7 +22,7 @@
337 + var common = require('../common');
338 + var assert = require('assert');
339 +
340 +-var Readable = require('stream').Readable;
341 ++var Readable = require('../../').Readable;
342 + var util = require('util');
343 +
344 + util.inherits(MyStream, Readable);
345 +diff --git a/test/simple/test-stream-readable-event.js b/test/simple/test-stream-readable-event.js
346 +index ba6a577..a8e6f7b 100644
347 +--- a/test/simple/test-stream-readable-event.js
348 ++++ b/test/simple/test-stream-readable-event.js
349 +@@ -22,7 +22,7 @@
350 + var common = require('../common');
351 + var assert = require('assert');
352 +
353 +-var Readable = require('stream').Readable;
354 ++var Readable = require('../../').Readable;
355 +
356 + (function first() {
357 + // First test, not reading when the readable is added.
358 +diff --git a/test/simple/test-stream-readable-flow-recursion.js b/test/simple/test-stream-readable-flow-recursion.js
359 +index 2891ad6..11689ba 100644
360 +--- a/test/simple/test-stream-readable-flow-recursion.js
361 ++++ b/test/simple/test-stream-readable-flow-recursion.js
362 +@@ -27,7 +27,7 @@ var assert = require('assert');
363 + // more data continuously, but without triggering a nextTick
364 + // warning or RangeError.
365 +
366 +-var Readable = require('stream').Readable;
367 ++var Readable = require('../../').Readable;
368 +
369 + // throw an error if we trigger a nextTick warning.
370 + process.throwDeprecation = true;
371 +diff --git a/test/simple/test-stream-unshift-empty-chunk.js b/test/simple/test-stream-unshift-empty-chunk.js
372 +index 0c96476..7827538 100644
373 +--- a/test/simple/test-stream-unshift-empty-chunk.js
374 ++++ b/test/simple/test-stream-unshift-empty-chunk.js
375 +@@ -24,7 +24,7 @@ var assert = require('assert');
376 +
377 + // This test verifies that stream.unshift(Buffer(0)) or
378 + // stream.unshift('') does not set state.reading=false.
379 +-var Readable = require('stream').Readable;
380 ++var Readable = require('../../').Readable;
381 +
382 + var r = new Readable();
383 + var nChunks = 10;
384 +diff --git a/test/simple/test-stream-unshift-read-race.js b/test/simple/test-stream-unshift-read-race.js
385 +index 83fd9fa..17c18aa 100644
386 +--- a/test/simple/test-stream-unshift-read-race.js
387 ++++ b/test/simple/test-stream-unshift-read-race.js
388 +@@ -29,7 +29,7 @@ var assert = require('assert');
389 + // 3. push() after the EOF signaling null is an error.
390 + // 4. _read() is not called after pushing the EOF null chunk.
391 +
392 +-var stream = require('stream');
393 ++var stream = require('../../');
394 + var hwm = 10;
395 + var r = stream.Readable({ highWaterMark: hwm });
396 + var chunks = 10;
397 +@@ -51,7 +51,14 @@ r._read = function(n) {
398 +
399 + function push(fast) {
400 + assert(!pushedNull, 'push() after null push');
401 +- var c = pos >= data.length ? null : data.slice(pos, pos + n);
402 ++ var c;
403 ++ if (pos >= data.length)
404 ++ c = null;
405 ++ else {
406 ++ if (n + pos > data.length)
407 ++ n = data.length - pos;
408 ++ c = data.slice(pos, pos + n);
409 ++ }
410 + pushedNull = c === null;
411 + if (fast) {
412 + pos += n;
413 +diff --git a/test/simple/test-stream-writev.js b/test/simple/test-stream-writev.js
414 +index 5b49e6e..b5321f3 100644
415 +--- a/test/simple/test-stream-writev.js
416 ++++ b/test/simple/test-stream-writev.js
417 +@@ -22,7 +22,7 @@
418 + var common = require('../common');
419 + var assert = require('assert');
420 +
421 +-var stream = require('stream');
422 ++var stream = require('../../');
423 +
424 + var queue = [];
425 + for (var decode = 0; decode < 2; decode++) {
426 +diff --git a/test/simple/test-stream2-basic.js b/test/simple/test-stream2-basic.js
427 +index 3814bf0..248c1be 100644
428 +--- a/test/simple/test-stream2-basic.js
429 ++++ b/test/simple/test-stream2-basic.js
430 +@@ -21,7 +21,7 @@
431 +
432 +
433 + var common = require('../common.js');
434 +-var R = require('_stream_readable');
435 ++var R = require('../../lib/_stream_readable');
436 + var assert = require('assert');
437 +
438 + var util = require('util');
439 +diff --git a/test/simple/test-stream2-compatibility.js b/test/simple/test-stream2-compatibility.js
440 +index 6cdd4e9..f0fa84b 100644
441 +--- a/test/simple/test-stream2-compatibility.js
442 ++++ b/test/simple/test-stream2-compatibility.js
443 +@@ -21,7 +21,7 @@
444 +
445 +
446 + var common = require('../common.js');
447 +-var R = require('_stream_readable');
448 ++var R = require('../../lib/_stream_readable');
449 + var assert = require('assert');
450 +
451 + var util = require('util');
452 +diff --git a/test/simple/test-stream2-finish-pipe.js b/test/simple/test-stream2-finish-pipe.js
453 +index 39b274f..006a19b 100644
454 +--- a/test/simple/test-stream2-finish-pipe.js
455 ++++ b/test/simple/test-stream2-finish-pipe.js
456 +@@ -20,7 +20,7 @@
457 + // USE OR OTHER DEALINGS IN THE SOFTWARE.
458 +
459 + var common = require('../common.js');
460 +-var stream = require('stream');
461 ++var stream = require('../../');
462 + var Buffer = require('buffer').Buffer;
463 +
464 + var r = new stream.Readable();
465 +diff --git a/test/simple/test-stream2-fs.js b/test/simple/test-stream2-fs.js
466 +deleted file mode 100644
467 +index e162406..0000000
468 +--- a/test/simple/test-stream2-fs.js
469 ++++ /dev/null
470 +@@ -1,72 +0,0 @@
471 +-// Copyright Joyent, Inc. and other Node contributors.
472 +-//
473 +-// Permission is hereby granted, free of charge, to any person obtaining a
474 +-// copy of this software and associated documentation files (the
475 +-// "Software"), to deal in the Software without restriction, including
476 +-// without limitation the rights to use, copy, modify, merge, publish,
477 +-// distribute, sublicense, and/or sell copies of the Software, and to permit
478 +-// persons to whom the Software is furnished to do so, subject to the
479 +-// following conditions:
480 +-//
481 +-// The above copyright notice and this permission notice shall be included
482 +-// in all copies or substantial portions of the Software.
483 +-//
484 +-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
485 +-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
486 +-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
487 +-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
488 +-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
489 +-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
490 +-// USE OR OTHER DEALINGS IN THE SOFTWARE.
491 +-
492 +-
493 +-var common = require('../common.js');
494 +-var R = require('_stream_readable');
495 +-var assert = require('assert');
496 +-
497 +-var fs = require('fs');
498 +-var FSReadable = fs.ReadStream;
499 +-
500 +-var path = require('path');
501 +-var file = path.resolve(common.fixturesDir, 'x1024.txt');
502 +-
503 +-var size = fs.statSync(file).size;
504 +-
505 +-var expectLengths = [1024];
506 +-
507 +-var util = require('util');
508 +-var Stream = require('stream');
509 +-
510 +-util.inherits(TestWriter, Stream);
511 +-
512 +-function TestWriter() {
513 +- Stream.apply(this);
514 +- this.buffer = [];
515 +- this.length = 0;
516 +-}
517 +-
518 +-TestWriter.prototype.write = function(c) {
519 +- this.buffer.push(c.toString());
520 +- this.length += c.length;
521 +- return true;
522 +-};
523 +-
524 +-TestWriter.prototype.end = function(c) {
525 +- if (c) this.buffer.push(c.toString());
526 +- this.emit('results', this.buffer);
527 +-}
528 +-
529 +-var r = new FSReadable(file);
530 +-var w = new TestWriter();
531 +-
532 +-w.on('results', function(res) {
533 +- console.error(res, w.length);
534 +- assert.equal(w.length, size);
535 +- var l = 0;
536 +- assert.deepEqual(res.map(function (c) {
537 +- return c.length;
538 +- }), expectLengths);
539 +- console.log('ok');
540 +-});
541 +-
542 +-r.pipe(w);
543 +diff --git a/test/simple/test-stream2-httpclient-response-end.js b/test/simple/test-stream2-httpclient-response-end.js
544 +deleted file mode 100644
545 +index 15cffc2..0000000
546 +--- a/test/simple/test-stream2-httpclient-response-end.js
547 ++++ /dev/null
548 +@@ -1,52 +0,0 @@
549 +-// Copyright Joyent, Inc. and other Node contributors.
550 +-//
551 +-// Permission is hereby granted, free of charge, to any person obtaining a
552 +-// copy of this software and associated documentation files (the
553 +-// "Software"), to deal in the Software without restriction, including
554 +-// without limitation the rights to use, copy, modify, merge, publish,
555 +-// distribute, sublicense, and/or sell copies of the Software, and to permit
556 +-// persons to whom the Software is furnished to do so, subject to the
557 +-// following conditions:
558 +-//
559 +-// The above copyright notice and this permission notice shall be included
560 +-// in all copies or substantial portions of the Software.
561 +-//
562 +-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
563 +-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
564 +-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
565 +-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
566 +-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
567 +-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
568 +-// USE OR OTHER DEALINGS IN THE SOFTWARE.
569 +-
570 +-var common = require('../common.js');
571 +-var assert = require('assert');
572 +-var http = require('http');
573 +-var msg = 'Hello';
574 +-var readable_event = false;
575 +-var end_event = false;
576 +-var server = http.createServer(function(req, res) {
577 +- res.writeHead(200, {'Content-Type': 'text/plain'});
578 +- res.end(msg);
579 +-}).listen(common.PORT, function() {
580 +- http.get({port: common.PORT}, function(res) {
581 +- var data = '';
582 +- res.on('readable', function() {
583 +- console.log('readable event');
584 +- readable_event = true;
585 +- data += res.read();
586 +- });
587 +- res.on('end', function() {
588 +- console.log('end event');
589 +- end_event = true;
590 +- assert.strictEqual(msg, data);
591 +- server.close();
592 +- });
593 +- });
594 +-});
595 +-
596 +-process.on('exit', function() {
597 +- assert(readable_event);
598 +- assert(end_event);
599 +-});
600 +-
601 +diff --git a/test/simple/test-stream2-large-read-stall.js b/test/simple/test-stream2-large-read-stall.js
602 +index 2fbfbca..667985b 100644
603 +--- a/test/simple/test-stream2-large-read-stall.js
604 ++++ b/test/simple/test-stream2-large-read-stall.js
605 +@@ -30,7 +30,7 @@ var PUSHSIZE = 20;
606 + var PUSHCOUNT = 1000;
607 + var HWM = 50;
608 +
609 +-var Readable = require('stream').Readable;
610 ++var Readable = require('../../').Readable;
611 + var r = new Readable({
612 + highWaterMark: HWM
613 + });
614 +@@ -39,23 +39,23 @@ var rs = r._readableState;
615 + r._read = push;
616 +
617 + r.on('readable', function() {
618 +- console.error('>> readable');
619 ++ //console.error('>> readable');
620 + do {
621 +- console.error(' > read(%d)', READSIZE);
622 ++ //console.error(' > read(%d)', READSIZE);
623 + var ret = r.read(READSIZE);
624 +- console.error(' < %j (%d remain)', ret && ret.length, rs.length);
625 ++ //console.error(' < %j (%d remain)', ret && ret.length, rs.length);
626 + } while (ret && ret.length === READSIZE);
627 +
628 +- console.error('<< after read()',
629 +- ret && ret.length,
630 +- rs.needReadable,
631 +- rs.length);
632 ++ //console.error('<< after read()',
633 ++ // ret && ret.length,
634 ++ // rs.needReadable,
635 ++ // rs.length);
636 + });
637 +
638 + var endEmitted = false;
639 + r.on('end', function() {
640 + endEmitted = true;
641 +- console.error('end');
642 ++ //console.error('end');
643 + });
644 +
645 + var pushes = 0;
646 +@@ -64,11 +64,11 @@ function push() {
647 + return;
648 +
649 + if (pushes++ === PUSHCOUNT) {
650 +- console.error(' push(EOF)');
651 ++ //console.error(' push(EOF)');
652 + return r.push(null);
653 + }
654 +
655 +- console.error(' push #%d', pushes);
656 ++ //console.error(' push #%d', pushes);
657 + if (r.push(new Buffer(PUSHSIZE)))
658 + setTimeout(push);
659 + }
660 +diff --git a/test/simple/test-stream2-objects.js b/test/simple/test-stream2-objects.js
661 +index 3e6931d..ff47d89 100644
662 +--- a/test/simple/test-stream2-objects.js
663 ++++ b/test/simple/test-stream2-objects.js
664 +@@ -21,8 +21,8 @@
665 +
666 +
667 + var common = require('../common.js');
668 +-var Readable = require('_stream_readable');
669 +-var Writable = require('_stream_writable');
670 ++var Readable = require('../../lib/_stream_readable');
671 ++var Writable = require('../../lib/_stream_writable');
672 + var assert = require('assert');
673 +
674 + // tiny node-tap lookalike.
675 +diff --git a/test/simple/test-stream2-pipe-error-handling.js b/test/simple/test-stream2-pipe-error-handling.js
676 +index cf7531c..e3f3e4e 100644
677 +--- a/test/simple/test-stream2-pipe-error-handling.js
678 ++++ b/test/simple/test-stream2-pipe-error-handling.js
679 +@@ -21,7 +21,7 @@
680 +
681 + var common = require('../common');
682 + var assert = require('assert');
683 +-var stream = require('stream');
684 ++var stream = require('../../');
685 +
686 + (function testErrorListenerCatches() {
687 + var count = 1000;
688 +diff --git a/test/simple/test-stream2-pipe-error-once-listener.js b/test/simple/test-stream2-pipe-error-once-listener.js
689 +index 5e8e3cb..53b2616 100755
690 +--- a/test/simple/test-stream2-pipe-error-once-listener.js
691 ++++ b/test/simple/test-stream2-pipe-error-once-listener.js
692 +@@ -24,7 +24,7 @@ var common = require('../common.js');
693 + var assert = require('assert');
694 +
695 + var util = require('util');
696 +-var stream = require('stream');
697 ++var stream = require('../../');
698 +
699 +
700 + var Read = function() {
701 +diff --git a/test/simple/test-stream2-push.js b/test/simple/test-stream2-push.js
702 +index b63edc3..eb2b0e9 100644
703 +--- a/test/simple/test-stream2-push.js
704 ++++ b/test/simple/test-stream2-push.js
705 +@@ -20,7 +20,7 @@
706 + // USE OR OTHER DEALINGS IN THE SOFTWARE.
707 +
708 + var common = require('../common.js');
709 +-var stream = require('stream');
710 ++var stream = require('../../');
711 + var Readable = stream.Readable;
712 + var Writable = stream.Writable;
713 + var assert = require('assert');
714 +diff --git a/test/simple/test-stream2-read-sync-stack.js b/test/simple/test-stream2-read-sync-stack.js
715 +index e8a7305..9740a47 100644
716 +--- a/test/simple/test-stream2-read-sync-stack.js
717 ++++ b/test/simple/test-stream2-read-sync-stack.js
718 +@@ -21,7 +21,7 @@
719 +
720 + var common = require('../common');
721 + var assert = require('assert');
722 +-var Readable = require('stream').Readable;
723 ++var Readable = require('../../').Readable;
724 + var r = new Readable();
725 + var N = 256 * 1024;
726 +
727 +diff --git a/test/simple/test-stream2-readable-empty-buffer-no-eof.js b/test/simple/test-stream2-readable-empty-buffer-no-eof.js
728 +index cd30178..4b1659d 100644
729 +--- a/test/simple/test-stream2-readable-empty-buffer-no-eof.js
730 ++++ b/test/simple/test-stream2-readable-empty-buffer-no-eof.js
731 +@@ -22,10 +22,9 @@
732 + var common = require('../common');
733 + var assert = require('assert');
734 +
735 +-var Readable = require('stream').Readable;
736 ++var Readable = require('../../').Readable;
737 +
738 + test1();
739 +-test2();
740 +
741 + function test1() {
742 + var r = new Readable();
743 +@@ -88,31 +87,3 @@ function test1() {
744 + console.log('ok');
745 + });
746 + }
747 +-
748 +-function test2() {
749 +- var r = new Readable({ encoding: 'base64' });
750 +- var reads = 5;
751 +- r._read = function(n) {
752 +- if (!reads--)
753 +- return r.push(null); // EOF
754 +- else
755 +- return r.push(new Buffer('x'));
756 +- };
757 +-
758 +- var results = [];
759 +- function flow() {
760 +- var chunk;
761 +- while (null !== (chunk = r.read()))
762 +- results.push(chunk + '');
763 +- }
764 +- r.on('readable', flow);
765 +- r.on('end', function() {
766 +- results.push('EOF');
767 +- });
768 +- flow();
769 +-
770 +- process.on('exit', function() {
771 +- assert.deepEqual(results, [ 'eHh4', 'eHg=', 'EOF' ]);
772 +- console.log('ok');
773 +- });
774 +-}
775 +diff --git a/test/simple/test-stream2-readable-from-list.js b/test/simple/test-stream2-readable-from-list.js
776 +index 7c96ffe..04a96f5 100644
777 +--- a/test/simple/test-stream2-readable-from-list.js
778 ++++ b/test/simple/test-stream2-readable-from-list.js
779 +@@ -21,7 +21,7 @@
780 +
781 + var assert = require('assert');
782 + var common = require('../common.js');
783 +-var fromList = require('_stream_readable')._fromList;
784 ++var fromList = require('../../lib/_stream_readable')._fromList;
785 +
786 + // tiny node-tap lookalike.
787 + var tests = [];
788 +diff --git a/test/simple/test-stream2-readable-legacy-drain.js b/test/simple/test-stream2-readable-legacy-drain.js
789 +index 675da8e..51fd3d5 100644
790 +--- a/test/simple/test-stream2-readable-legacy-drain.js
791 ++++ b/test/simple/test-stream2-readable-legacy-drain.js
792 +@@ -22,7 +22,7 @@
793 + var common = require('../common');
794 + var assert = require('assert');
795 +
796 +-var Stream = require('stream');
797 ++var Stream = require('../../');
798 + var Readable = Stream.Readable;
799 +
800 + var r = new Readable();
801 +diff --git a/test/simple/test-stream2-readable-non-empty-end.js b/test/simple/test-stream2-readable-non-empty-end.js
802 +index 7314ae7..c971898 100644
803 +--- a/test/simple/test-stream2-readable-non-empty-end.js
804 ++++ b/test/simple/test-stream2-readable-non-empty-end.js
805 +@@ -21,7 +21,7 @@
806 +
807 + var assert = require('assert');
808 + var common = require('../common.js');
809 +-var Readable = require('_stream_readable');
810 ++var Readable = require('../../lib/_stream_readable');
811 +
812 + var len = 0;
813 + var chunks = new Array(10);
814 +diff --git a/test/simple/test-stream2-readable-wrap-empty.js b/test/simple/test-stream2-readable-wrap-empty.js
815 +index 2e5cf25..fd8a3dc 100644
816 +--- a/test/simple/test-stream2-readable-wrap-empty.js
817 ++++ b/test/simple/test-stream2-readable-wrap-empty.js
818 +@@ -22,7 +22,7 @@
819 + var common = require('../common');
820 + var assert = require('assert');
821 +
822 +-var Readable = require('_stream_readable');
823 ++var Readable = require('../../lib/_stream_readable');
824 + var EE = require('events').EventEmitter;
825 +
826 + var oldStream = new EE();
827 +diff --git a/test/simple/test-stream2-readable-wrap.js b/test/simple/test-stream2-readable-wrap.js
828 +index 90eea01..6b177f7 100644
829 +--- a/test/simple/test-stream2-readable-wrap.js
830 ++++ b/test/simple/test-stream2-readable-wrap.js
831 +@@ -22,8 +22,8 @@
832 + var common = require('../common');
833 + var assert = require('assert');
834 +
835 +-var Readable = require('_stream_readable');
836 +-var Writable = require('_stream_writable');
837 ++var Readable = require('../../lib/_stream_readable');
838 ++var Writable = require('../../lib/_stream_writable');
839 + var EE = require('events').EventEmitter;
840 +
841 + var testRuns = 0, completedRuns = 0;
842 +diff --git a/test/simple/test-stream2-set-encoding.js b/test/simple/test-stream2-set-encoding.js
843 +index 5d2c32a..685531b 100644
844 +--- a/test/simple/test-stream2-set-encoding.js
845 ++++ b/test/simple/test-stream2-set-encoding.js
846 +@@ -22,7 +22,7 @@
847 +
848 + var common = require('../common.js');
849 + var assert = require('assert');
850 +-var R = require('_stream_readable');
851 ++var R = require('../../lib/_stream_readable');
852 + var util = require('util');
853 +
854 + // tiny node-tap lookalike.
855 +diff --git a/test/simple/test-stream2-transform.js b/test/simple/test-stream2-transform.js
856 +index 9c9ddd8..a0cacc6 100644
857 +--- a/test/simple/test-stream2-transform.js
858 ++++ b/test/simple/test-stream2-transform.js
859 +@@ -21,8 +21,8 @@
860 +
861 + var assert = require('assert');
862 + var common = require('../common.js');
863 +-var PassThrough = require('_stream_passthrough');
864 +-var Transform = require('_stream_transform');
865 ++var PassThrough = require('../../').PassThrough;
866 ++var Transform = require('../../').Transform;
867 +
868 + // tiny node-tap lookalike.
869 + var tests = [];
870 +diff --git a/test/simple/test-stream2-unpipe-drain.js b/test/simple/test-stream2-unpipe-drain.js
871 +index d66dc3c..365b327 100644
872 +--- a/test/simple/test-stream2-unpipe-drain.js
873 ++++ b/test/simple/test-stream2-unpipe-drain.js
874 +@@ -22,7 +22,7 @@
875 +
876 + var common = require('../common.js');
877 + var assert = require('assert');
878 +-var stream = require('stream');
879 ++var stream = require('../../');
880 + var crypto = require('crypto');
881 +
882 + var util = require('util');
883 +diff --git a/test/simple/test-stream2-unpipe-leak.js b/test/simple/test-stream2-unpipe-leak.js
884 +index 99f8746..17c92ae 100644
885 +--- a/test/simple/test-stream2-unpipe-leak.js
886 ++++ b/test/simple/test-stream2-unpipe-leak.js
887 +@@ -22,7 +22,7 @@
888 +
889 + var common = require('../common.js');
890 + var assert = require('assert');
891 +-var stream = require('stream');
892 ++var stream = require('../../');
893 +
894 + var chunk = new Buffer('hallo');
895 +
896 +diff --git a/test/simple/test-stream2-writable.js b/test/simple/test-stream2-writable.js
897 +index 704100c..209c3a6 100644
898 +--- a/test/simple/test-stream2-writable.js
899 ++++ b/test/simple/test-stream2-writable.js
900 +@@ -20,8 +20,8 @@
901 + // USE OR OTHER DEALINGS IN THE SOFTWARE.
902 +
903 + var common = require('../common.js');
904 +-var W = require('_stream_writable');
905 +-var D = require('_stream_duplex');
906 ++var W = require('../../').Writable;
907 ++var D = require('../../').Duplex;
908 + var assert = require('assert');
909 +
910 + var util = require('util');
911 +diff --git a/test/simple/test-stream3-pause-then-read.js b/test/simple/test-stream3-pause-then-read.js
912 +index b91bde3..2f72c15 100644
913 +--- a/test/simple/test-stream3-pause-then-read.js
914 ++++ b/test/simple/test-stream3-pause-then-read.js
915 +@@ -22,7 +22,7 @@
916 + var common = require('../common');
917 + var assert = require('assert');
918 +
919 +-var stream = require('stream');
920 ++var stream = require('../../');
921 + var Readable = stream.Readable;
922 + var Writable = stream.Writable;
923 +
...@@ -18,122 +18,72 @@ ...@@ -18,122 +18,72 @@
18 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 18 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE 19 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20 // USE OR OTHER DEALINGS IN THE SOFTWARE. 20 // USE OR OTHER DEALINGS IN THE SOFTWARE.
21 +
21 // a duplex stream is just a stream that is both readable and writable. 22 // a duplex stream is just a stream that is both readable and writable.
22 // Since JS doesn't have multiple prototypal inheritance, this class 23 // Since JS doesn't have multiple prototypal inheritance, this class
23 // prototypally inherits from Readable, and then parasitically from 24 // prototypally inherits from Readable, and then parasitically from
24 // Writable. 25 // Writable.
25 -'use strict';
26 -/*<replacement>*/
27 26
27 +module.exports = Duplex;
28 +
29 +/*<replacement>*/
28 var objectKeys = Object.keys || function (obj) { 30 var objectKeys = Object.keys || function (obj) {
29 var keys = []; 31 var keys = [];
30 - 32 + for (var key in obj) keys.push(key);
31 - for (var key in obj) {
32 - keys.push(key);
33 - }
34 -
35 return keys; 33 return keys;
36 -}; 34 +}
37 /*</replacement>*/ 35 /*</replacement>*/
38 36
39 37
40 -module.exports = Duplex; 38 +/*<replacement>*/
39 +var util = require('core-util-is');
40 +util.inherits = require('inherits');
41 +/*</replacement>*/
41 42
42 var Readable = require('./_stream_readable'); 43 var Readable = require('./_stream_readable');
43 -
44 var Writable = require('./_stream_writable'); 44 var Writable = require('./_stream_writable');
45 45
46 -require('inherits')(Duplex, Readable); 46 +util.inherits(Duplex, Readable);
47 47
48 -{ 48 +forEach(objectKeys(Writable.prototype), function(method) {
49 - // Allow the keys array to be GC'ed. 49 + if (!Duplex.prototype[method])
50 - var keys = objectKeys(Writable.prototype); 50 + Duplex.prototype[method] = Writable.prototype[method];
51 - 51 +});
52 - for (var v = 0; v < keys.length; v++) {
53 - var method = keys[v];
54 - if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
55 - }
56 -}
57 52
58 function Duplex(options) { 53 function Duplex(options) {
59 - if (!(this instanceof Duplex)) return new Duplex(options); 54 + if (!(this instanceof Duplex))
55 + return new Duplex(options);
56 +
60 Readable.call(this, options); 57 Readable.call(this, options);
61 Writable.call(this, options); 58 Writable.call(this, options);
62 - this.allowHalfOpen = true;
63 59
64 - if (options) { 60 + if (options && options.readable === false)
65 - if (options.readable === false) this.readable = false; 61 + this.readable = false;
66 - if (options.writable === false) this.writable = false;
67 62
68 - if (options.allowHalfOpen === false) { 63 + if (options && options.writable === false)
69 - this.allowHalfOpen = false; 64 + this.writable = false;
70 - this.once('end', onend);
71 - }
72 - }
73 -}
74 65
75 -Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', { 66 + this.allowHalfOpen = true;
76 - // making it explicit this property is not enumerable 67 + if (options && options.allowHalfOpen === false)
77 - // because otherwise some prototype manipulation in 68 + this.allowHalfOpen = false;
78 - // userland will fail
79 - enumerable: false,
80 - get: function get() {
81 - return this._writableState.highWaterMark;
82 - }
83 -});
84 -Object.defineProperty(Duplex.prototype, 'writableBuffer', {
85 - // making it explicit this property is not enumerable
86 - // because otherwise some prototype manipulation in
87 - // userland will fail
88 - enumerable: false,
89 - get: function get() {
90 - return this._writableState && this._writableState.getBuffer();
91 - }
92 -});
93 -Object.defineProperty(Duplex.prototype, 'writableLength', {
94 - // making it explicit this property is not enumerable
95 - // because otherwise some prototype manipulation in
96 - // userland will fail
97 - enumerable: false,
98 - get: function get() {
99 - return this._writableState.length;
100 - }
101 -}); // the no-half-open enforcer
102 -
103 -function onend() {
104 - // If the writable side ended, then we're ok.
105 - if (this._writableState.ended) return; // no more data can be written.
106 - // But allow more writes to happen in this tick.
107 69
108 - process.nextTick(onEndNT, this); 70 + this.once('end', onend);
109 } 71 }
110 72
111 -function onEndNT(self) { 73 +// the no-half-open enforcer
112 - self.end(); 74 +function onend() {
75 + // if we allow half-open state, or if the writable side ended,
76 + // then we're ok.
77 + if (this.allowHalfOpen || this._writableState.ended)
78 + return;
79 +
80 + // no more data can be written.
81 + // But allow more writes to happen in this tick.
82 + process.nextTick(this.end.bind(this));
113 } 83 }
114 84
115 -Object.defineProperty(Duplex.prototype, 'destroyed', { 85 +function forEach (xs, f) {
116 - // making it explicit this property is not enumerable 86 + for (var i = 0, l = xs.length; i < l; i++) {
117 - // because otherwise some prototype manipulation in 87 + f(xs[i], i);
118 - // userland will fail
119 - enumerable: false,
120 - get: function get() {
121 - if (this._readableState === undefined || this._writableState === undefined) {
122 - return false;
123 - }
124 -
125 - return this._readableState.destroyed && this._writableState.destroyed;
126 - },
127 - set: function set(value) {
128 - // we ignore the value if the stream
129 - // has not been initialized yet
130 - if (this._readableState === undefined || this._writableState === undefined) {
131 - return;
132 - } // backward compatibility, the user is explicitly
133 - // managing destroyed
134 -
135 -
136 - this._readableState.destroyed = value;
137 - this._writableState.destroyed = value;
138 } 88 }
139 -});
...\ No newline at end of file ...\ No newline at end of file
89 +}
......
...@@ -18,22 +18,29 @@ ...@@ -18,22 +18,29 @@
18 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 18 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE 19 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20 // USE OR OTHER DEALINGS IN THE SOFTWARE. 20 // USE OR OTHER DEALINGS IN THE SOFTWARE.
21 +
21 // a passthrough stream. 22 // a passthrough stream.
22 // basically just the most minimal sort of Transform stream. 23 // basically just the most minimal sort of Transform stream.
23 // Every written chunk gets output as-is. 24 // Every written chunk gets output as-is.
24 -'use strict';
25 25
26 module.exports = PassThrough; 26 module.exports = PassThrough;
27 27
28 var Transform = require('./_stream_transform'); 28 var Transform = require('./_stream_transform');
29 29
30 -require('inherits')(PassThrough, Transform); 30 +/*<replacement>*/
31 +var util = require('core-util-is');
32 +util.inherits = require('inherits');
33 +/*</replacement>*/
34 +
35 +util.inherits(PassThrough, Transform);
31 36
32 function PassThrough(options) { 37 function PassThrough(options) {
33 - if (!(this instanceof PassThrough)) return new PassThrough(options); 38 + if (!(this instanceof PassThrough))
39 + return new PassThrough(options);
40 +
34 Transform.call(this, options); 41 Transform.call(this, options);
35 } 42 }
36 43
37 -PassThrough.prototype._transform = function (chunk, encoding, cb) { 44 +PassThrough.prototype._transform = function(chunk, encoding, cb) {
38 cb(null, chunk); 45 cb(null, chunk);
39 -};
...\ No newline at end of file ...\ No newline at end of file
46 +};
......
...@@ -18,398 +18,312 @@ ...@@ -18,398 +18,312 @@
18 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 18 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE 19 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20 // USE OR OTHER DEALINGS IN THE SOFTWARE. 20 // USE OR OTHER DEALINGS IN THE SOFTWARE.
21 -'use strict';
22 21
23 module.exports = Readable; 22 module.exports = Readable;
23 +
24 /*<replacement>*/ 24 /*<replacement>*/
25 +var isArray = require('isarray');
26 +/*</replacement>*/
27 +
25 28
26 -var Duplex; 29 +/*<replacement>*/
30 +var Buffer = require('buffer').Buffer;
27 /*</replacement>*/ 31 /*</replacement>*/
28 32
29 Readable.ReadableState = ReadableState; 33 Readable.ReadableState = ReadableState;
30 -/*<replacement>*/
31 34
32 var EE = require('events').EventEmitter; 35 var EE = require('events').EventEmitter;
33 36
34 -var EElistenerCount = function EElistenerCount(emitter, type) { 37 +/*<replacement>*/
38 +if (!EE.listenerCount) EE.listenerCount = function(emitter, type) {
35 return emitter.listeners(type).length; 39 return emitter.listeners(type).length;
36 }; 40 };
37 /*</replacement>*/ 41 /*</replacement>*/
38 42
39 -/*<replacement>*/ 43 +var Stream = require('stream');
40 -
41 44
42 -var Stream = require('./internal/streams/stream'); 45 +/*<replacement>*/
46 +var util = require('core-util-is');
47 +util.inherits = require('inherits');
43 /*</replacement>*/ 48 /*</replacement>*/
44 49
50 +var StringDecoder;
45 51
46 -var Buffer = require('buffer').Buffer;
47 -
48 -var OurUint8Array = global.Uint8Array || function () {};
49 52
50 -function _uint8ArrayToBuffer(chunk) {
51 - return Buffer.from(chunk);
52 -}
53 -
54 -function _isUint8Array(obj) {
55 - return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
56 -}
57 /*<replacement>*/ 53 /*<replacement>*/
58 - 54 +var debug = require('util');
59 - 55 +if (debug && debug.debuglog) {
60 -var debugUtil = require('util'); 56 + debug = debug.debuglog('stream');
61 -
62 -var debug;
63 -
64 -if (debugUtil && debugUtil.debuglog) {
65 - debug = debugUtil.debuglog('stream');
66 } else { 57 } else {
67 - debug = function debug() {}; 58 + debug = function () {};
68 } 59 }
69 /*</replacement>*/ 60 /*</replacement>*/
70 61
71 62
72 -var BufferList = require('./internal/streams/buffer_list'); 63 +util.inherits(Readable, Stream);
73 -
74 -var destroyImpl = require('./internal/streams/destroy');
75 -
76 -var _require = require('./internal/streams/state'),
77 - getHighWaterMark = _require.getHighWaterMark;
78 -
79 -var _require$codes = require('../errors').codes,
80 - ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,
81 - ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF,
82 - ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
83 - ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance.
84 -
85 -
86 -var StringDecoder;
87 -var createReadableStreamAsyncIterator;
88 -var from;
89 -
90 -require('inherits')(Readable, Stream);
91 -
92 -var errorOrDestroy = destroyImpl.errorOrDestroy;
93 -var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
94 -
95 -function prependListener(emitter, event, fn) {
96 - // Sadly this is not cacheable as some libraries bundle their own
97 - // event emitter implementation with them.
98 - if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any
99 - // userland ones. NEVER DO THIS. This is here only because this code needs
100 - // to continue to work with older versions of Node.js that do not include
101 - // the prependListener() method. The goal is to eventually remove this hack.
102 64
103 - if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; 65 +function ReadableState(options, stream) {
104 -} 66 + var Duplex = require('./_stream_duplex');
105 67
106 -function ReadableState(options, stream, isDuplex) { 68 + options = options || {};
107 - Duplex = Duplex || require('./_stream_duplex');
108 - options = options || {}; // Duplex streams are both readable and writable, but share
109 - // the same options object.
110 - // However, some cases require setting options to different
111 - // values for the readable and the writable sides of the duplex stream.
112 - // These options can be provided separately as readableXXX and writableXXX.
113 -
114 - if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag. Used to make read(n) ignore n and to
115 - // make all the buffer merging and length checks go away
116 69
117 - this.objectMode = !!options.objectMode; 70 + // the point at which it stops calling _read() to fill the buffer
118 - if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer
119 // Note: 0 is a valid value, means "don't call _read preemptively ever" 71 // Note: 0 is a valid value, means "don't call _read preemptively ever"
72 + var hwm = options.highWaterMark;
73 + var defaultHwm = options.objectMode ? 16 : 16 * 1024;
74 + this.highWaterMark = (hwm || hwm === 0) ? hwm : defaultHwm;
120 75
121 - this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the 76 + // cast to ints.
122 - // linked list can remove elements from the beginning faster than 77 + this.highWaterMark = ~~this.highWaterMark;
123 - // array.shift()
124 78
125 - this.buffer = new BufferList(); 79 + this.buffer = [];
126 this.length = 0; 80 this.length = 0;
127 this.pipes = null; 81 this.pipes = null;
128 this.pipesCount = 0; 82 this.pipesCount = 0;
129 this.flowing = null; 83 this.flowing = null;
130 this.ended = false; 84 this.ended = false;
131 this.endEmitted = false; 85 this.endEmitted = false;
132 - this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted 86 + this.reading = false;
133 - // immediately, or on a later tick. We set this to true at first, because
134 - // any actions that shouldn't happen until "later" should generally also
135 - // not happen before the first read call.
136 87
137 - this.sync = true; // whenever we return null, then we set a flag to say 88 + // a flag to be able to tell if the onwrite cb is called immediately,
138 - // that we're awaiting a 'readable' event emission. 89 + // or on a later tick. We set this to true at first, because any
90 + // actions that shouldn't happen until "later" should generally also
91 + // not happen before the first write call.
92 + this.sync = true;
139 93
94 + // whenever we return null, then we set a flag to say
95 + // that we're awaiting a 'readable' event emission.
140 this.needReadable = false; 96 this.needReadable = false;
141 this.emittedReadable = false; 97 this.emittedReadable = false;
142 this.readableListening = false; 98 this.readableListening = false;
143 - this.resumeScheduled = false;
144 - this.paused = true; // Should close be emitted on destroy. Defaults to true.
145 99
146 - this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'end' (and potentially 'finish')
147 100
148 - this.autoDestroy = !!options.autoDestroy; // has it been destroyed 101 + // object stream flag. Used to make read(n) ignore n and to
102 + // make all the buffer merging and length checks go away
103 + this.objectMode = !!options.objectMode;
104 +
105 + if (stream instanceof Duplex)
106 + this.objectMode = this.objectMode || !!options.readableObjectMode;
149 107
150 - this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string 108 + // Crypto is kind of old and crusty. Historically, its default string
151 // encoding is 'binary' so we have to make this configurable. 109 // encoding is 'binary' so we have to make this configurable.
152 // Everything else in the universe uses 'utf8', though. 110 // Everything else in the universe uses 'utf8', though.
111 + this.defaultEncoding = options.defaultEncoding || 'utf8';
153 112
154 - this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s 113 + // when piping, we only care about 'readable' events that happen
114 + // after read()ing all the bytes and not getting any pushback.
115 + this.ranOut = false;
155 116
156 - this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled 117 + // the number of writers that are awaiting a drain event in .pipe()s
118 + this.awaitDrain = 0;
157 119
120 + // if true, a maybeReadMore has been scheduled
158 this.readingMore = false; 121 this.readingMore = false;
122 +
159 this.decoder = null; 123 this.decoder = null;
160 this.encoding = null; 124 this.encoding = null;
161 -
162 if (options.encoding) { 125 if (options.encoding) {
163 - if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; 126 + if (!StringDecoder)
127 + StringDecoder = require('string_decoder/').StringDecoder;
164 this.decoder = new StringDecoder(options.encoding); 128 this.decoder = new StringDecoder(options.encoding);
165 this.encoding = options.encoding; 129 this.encoding = options.encoding;
166 } 130 }
167 } 131 }
168 132
169 function Readable(options) { 133 function Readable(options) {
170 - Duplex = Duplex || require('./_stream_duplex'); 134 + var Duplex = require('./_stream_duplex');
171 - if (!(this instanceof Readable)) return new Readable(options); // Checking for a Stream.Duplex instance is faster here instead of inside
172 - // the ReadableState constructor, at least with V8 6.5
173 135
174 - var isDuplex = this instanceof Duplex; 136 + if (!(this instanceof Readable))
175 - this._readableState = new ReadableState(options, this, isDuplex); // legacy 137 + return new Readable(options);
176 138
177 - this.readable = true; 139 + this._readableState = new ReadableState(options, this);
178 140
179 - if (options) { 141 + // legacy
180 - if (typeof options.read === 'function') this._read = options.read; 142 + this.readable = true;
181 - if (typeof options.destroy === 'function') this._destroy = options.destroy;
182 - }
183 143
184 Stream.call(this); 144 Stream.call(this);
185 } 145 }
186 146
187 -Object.defineProperty(Readable.prototype, 'destroyed', { 147 +// Manually shove something into the read() buffer.
188 - // making it explicit this property is not enumerable
189 - // because otherwise some prototype manipulation in
190 - // userland will fail
191 - enumerable: false,
192 - get: function get() {
193 - if (this._readableState === undefined) {
194 - return false;
195 - }
196 -
197 - return this._readableState.destroyed;
198 - },
199 - set: function set(value) {
200 - // we ignore the value if the stream
201 - // has not been initialized yet
202 - if (!this._readableState) {
203 - return;
204 - } // backward compatibility, the user is explicitly
205 - // managing destroyed
206 -
207 -
208 - this._readableState.destroyed = value;
209 - }
210 -});
211 -Readable.prototype.destroy = destroyImpl.destroy;
212 -Readable.prototype._undestroy = destroyImpl.undestroy;
213 -
214 -Readable.prototype._destroy = function (err, cb) {
215 - cb(err);
216 -}; // Manually shove something into the read() buffer.
217 // This returns true if the highWaterMark has not been hit yet, 148 // This returns true if the highWaterMark has not been hit yet,
218 // similar to how Writable.write() returns true if you should 149 // similar to how Writable.write() returns true if you should
219 // write() some more. 150 // write() some more.
220 - 151 +Readable.prototype.push = function(chunk, encoding) {
221 -
222 -Readable.prototype.push = function (chunk, encoding) {
223 var state = this._readableState; 152 var state = this._readableState;
224 - var skipChunkCheck;
225 -
226 - if (!state.objectMode) {
227 - if (typeof chunk === 'string') {
228 - encoding = encoding || state.defaultEncoding;
229 -
230 - if (encoding !== state.encoding) {
231 - chunk = Buffer.from(chunk, encoding);
232 - encoding = '';
233 - }
234 153
235 - skipChunkCheck = true; 154 + if (util.isString(chunk) && !state.objectMode) {
155 + encoding = encoding || state.defaultEncoding;
156 + if (encoding !== state.encoding) {
157 + chunk = new Buffer(chunk, encoding);
158 + encoding = '';
236 } 159 }
237 - } else {
238 - skipChunkCheck = true;
239 } 160 }
240 161
241 - return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); 162 + return readableAddChunk(this, state, chunk, encoding, false);
242 -}; // Unshift should *always* be something directly out of read()
243 -
244 -
245 -Readable.prototype.unshift = function (chunk) {
246 - return readableAddChunk(this, chunk, null, true, false);
247 }; 163 };
248 164
249 -function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { 165 +// Unshift should *always* be something directly out of read()
250 - debug('readableAddChunk', chunk); 166 +Readable.prototype.unshift = function(chunk) {
251 - var state = stream._readableState; 167 + var state = this._readableState;
168 + return readableAddChunk(this, state, chunk, '', true);
169 +};
252 170
253 - if (chunk === null) { 171 +function readableAddChunk(stream, state, chunk, encoding, addToFront) {
172 + var er = chunkInvalid(state, chunk);
173 + if (er) {
174 + stream.emit('error', er);
175 + } else if (util.isNullOrUndefined(chunk)) {
254 state.reading = false; 176 state.reading = false;
255 - onEofChunk(stream, state); 177 + if (!state.ended)
256 - } else { 178 + onEofChunk(stream, state);
257 - var er; 179 + } else if (state.objectMode || chunk && chunk.length > 0) {
258 - if (!skipChunkCheck) er = chunkInvalid(state, chunk); 180 + if (state.ended && !addToFront) {
259 - 181 + var e = new Error('stream.push() after EOF');
260 - if (er) { 182 + stream.emit('error', e);
261 - errorOrDestroy(stream, er); 183 + } else if (state.endEmitted && addToFront) {
262 - } else if (state.objectMode || chunk && chunk.length > 0) { 184 + var e = new Error('stream.unshift() after end event');
263 - if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { 185 + stream.emit('error', e);
264 - chunk = _uint8ArrayToBuffer(chunk); 186 + } else {
265 - } 187 + if (state.decoder && !addToFront && !encoding)
266 - 188 + chunk = state.decoder.write(chunk);
267 - if (addToFront) { 189 +
268 - if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true); 190 + if (!addToFront)
269 - } else if (state.ended) {
270 - errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF());
271 - } else if (state.destroyed) {
272 - return false;
273 - } else {
274 state.reading = false; 191 state.reading = false;
275 192
276 - if (state.decoder && !encoding) { 193 + // if we want the data now, just emit it.
277 - chunk = state.decoder.write(chunk); 194 + if (state.flowing && state.length === 0 && !state.sync) {
278 - if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); 195 + stream.emit('data', chunk);
279 - } else { 196 + stream.read(0);
280 - addChunk(stream, state, chunk, false); 197 + } else {
281 - } 198 + // update the buffer info.
199 + state.length += state.objectMode ? 1 : chunk.length;
200 + if (addToFront)
201 + state.buffer.unshift(chunk);
202 + else
203 + state.buffer.push(chunk);
204 +
205 + if (state.needReadable)
206 + emitReadable(stream);
282 } 207 }
283 - } else if (!addToFront) { 208 +
284 - state.reading = false;
285 maybeReadMore(stream, state); 209 maybeReadMore(stream, state);
286 } 210 }
287 - } // We can push more data if we are below the highWaterMark. 211 + } else if (!addToFront) {
288 - // Also, if we have no data yet, we can stand some more bytes. 212 + state.reading = false;
289 - // This is to work around cases where hwm=0, such as the repl.
290 -
291 -
292 - return !state.ended && (state.length < state.highWaterMark || state.length === 0);
293 -}
294 -
295 -function addChunk(stream, state, chunk, addToFront) {
296 - if (state.flowing && state.length === 0 && !state.sync) {
297 - state.awaitDrain = 0;
298 - stream.emit('data', chunk);
299 - } else {
300 - // update the buffer info.
301 - state.length += state.objectMode ? 1 : chunk.length;
302 - if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
303 - if (state.needReadable) emitReadable(stream);
304 } 213 }
305 214
306 - maybeReadMore(stream, state); 215 + return needMoreData(state);
307 } 216 }
308 217
309 -function chunkInvalid(state, chunk) {
310 - var er;
311 218
312 - if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
313 - er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk);
314 - }
315 219
316 - return er; 220 +// if it's past the high water mark, we can push in some more.
221 +// Also, if we have no data yet, we can stand some
222 +// more bytes. This is to work around cases where hwm=0,
223 +// such as the repl. Also, if the push() triggered a
224 +// readable event, and the user called read(largeNumber) such that
225 +// needReadable was set, then we ought to push more, so that another
226 +// 'readable' event will be triggered.
227 +function needMoreData(state) {
228 + return !state.ended &&
229 + (state.needReadable ||
230 + state.length < state.highWaterMark ||
231 + state.length === 0);
317 } 232 }
318 233
319 -Readable.prototype.isPaused = function () { 234 +// backwards compatibility.
320 - return this._readableState.flowing === false; 235 +Readable.prototype.setEncoding = function(enc) {
321 -}; // backwards compatibility. 236 + if (!StringDecoder)
322 - 237 + StringDecoder = require('string_decoder/').StringDecoder;
323 - 238 + this._readableState.decoder = new StringDecoder(enc);
324 -Readable.prototype.setEncoding = function (enc) { 239 + this._readableState.encoding = enc;
325 - if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
326 - var decoder = new StringDecoder(enc);
327 - this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8
328 -
329 - this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers:
330 -
331 - var p = this._readableState.buffer.head;
332 - var content = '';
333 -
334 - while (p !== null) {
335 - content += decoder.write(p.data);
336 - p = p.next;
337 - }
338 -
339 - this._readableState.buffer.clear();
340 -
341 - if (content !== '') this._readableState.buffer.push(content);
342 - this._readableState.length = content.length;
343 return this; 240 return this;
344 -}; // Don't raise the hwm > 1GB 241 +};
345 -
346 -
347 -var MAX_HWM = 0x40000000;
348 242
349 -function computeNewHighWaterMark(n) { 243 +// Don't raise the hwm > 128MB
244 +var MAX_HWM = 0x800000;
245 +function roundUpToNextPowerOf2(n) {
350 if (n >= MAX_HWM) { 246 if (n >= MAX_HWM) {
351 - // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE.
352 n = MAX_HWM; 247 n = MAX_HWM;
353 } else { 248 } else {
354 - // Get the next highest power of 2 to prevent increasing hwm excessively in 249 + // Get the next highest power of 2
355 - // tiny amounts
356 n--; 250 n--;
357 - n |= n >>> 1; 251 + for (var p = 1; p < 32; p <<= 1) n |= n >> p;
358 - n |= n >>> 2;
359 - n |= n >>> 4;
360 - n |= n >>> 8;
361 - n |= n >>> 16;
362 n++; 252 n++;
363 } 253 }
364 -
365 return n; 254 return n;
366 -} // This function is designed to be inlinable, so please take care when making 255 +}
367 -// changes to the function body.
368 -
369 256
370 function howMuchToRead(n, state) { 257 function howMuchToRead(n, state) {
371 - if (n <= 0 || state.length === 0 && state.ended) return 0; 258 + if (state.length === 0 && state.ended)
372 - if (state.objectMode) return 1; 259 + return 0;
373 -
374 - if (n !== n) {
375 - // Only flow one buffer at a time
376 - if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
377 - } // If we're asking for more than the current hwm, then raise the hwm.
378 260
261 + if (state.objectMode)
262 + return n === 0 ? 0 : 1;
379 263
380 - if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); 264 + if (isNaN(n) || util.isNull(n)) {
381 - if (n <= state.length) return n; // Don't have enough 265 + // only flow one buffer at a time
266 + if (state.flowing && state.buffer.length)
267 + return state.buffer[0].length;
268 + else
269 + return state.length;
270 + }
382 271
383 - if (!state.ended) { 272 + if (n <= 0)
384 - state.needReadable = true;
385 return 0; 273 return 0;
386 - }
387 274
388 - return state.length; 275 + // If we're asking for more than the target buffer level,
389 -} // you can override either this method, or the async _read(n) below. 276 + // then raise the water mark. Bump up to the next highest
277 + // power of 2, to prevent increasing it excessively in tiny
278 + // amounts.
279 + if (n > state.highWaterMark)
280 + state.highWaterMark = roundUpToNextPowerOf2(n);
390 281
282 + // don't have that much. return null, unless we've ended.
283 + if (n > state.length) {
284 + if (!state.ended) {
285 + state.needReadable = true;
286 + return 0;
287 + } else
288 + return state.length;
289 + }
290 +
291 + return n;
292 +}
391 293
392 -Readable.prototype.read = function (n) { 294 +// you can override either this method, or the async _read(n) below.
295 +Readable.prototype.read = function(n) {
393 debug('read', n); 296 debug('read', n);
394 - n = parseInt(n, 10);
395 var state = this._readableState; 297 var state = this._readableState;
396 var nOrig = n; 298 var nOrig = n;
397 - if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we 299 +
300 + if (!util.isNumber(n) || n > 0)
301 + state.emittedReadable = false;
302 +
303 + // if we're doing read(0) to trigger a readable event, but we
398 // already have a bunch of data in the buffer, then just trigger 304 // already have a bunch of data in the buffer, then just trigger
399 // the 'readable' event and move on. 305 // the 'readable' event and move on.
400 - 306 + if (n === 0 &&
401 - if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) { 307 + state.needReadable &&
308 + (state.length >= state.highWaterMark || state.ended)) {
402 debug('read: emitReadable', state.length, state.ended); 309 debug('read: emitReadable', state.length, state.ended);
403 - if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); 310 + if (state.length === 0 && state.ended)
311 + endReadable(this);
312 + else
313 + emitReadable(this);
404 return null; 314 return null;
405 } 315 }
406 316
407 - n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up. 317 + n = howMuchToRead(n, state);
408 318
319 + // if we've ended, and we're now clear, then finish it up.
409 if (n === 0 && state.ended) { 320 if (n === 0 && state.ended) {
410 - if (state.length === 0) endReadable(this); 321 + if (state.length === 0)
322 + endReadable(this);
411 return null; 323 return null;
412 - } // All the actual chunk generation logic needs to be 324 + }
325 +
326 + // All the actual chunk generation logic needs to be
413 // *below* the call to _read. The reason is that in certain 327 // *below* the call to _read. The reason is that in certain
414 // synthetic stream cases, such as passthrough streams, _read 328 // synthetic stream cases, such as passthrough streams, _read
415 // may be a completely synchronous operation which may change 329 // may be a completely synchronous operation which may change
...@@ -430,182 +344,159 @@ Readable.prototype.read = function (n) { ...@@ -430,182 +344,159 @@ Readable.prototype.read = function (n) {
430 // 'readable' etc. 344 // 'readable' etc.
431 // 345 //
432 // 3. Actually pull the requested chunks out of the buffer and return. 346 // 3. Actually pull the requested chunks out of the buffer and return.
433 - // if we need a readable event, then we need to do some reading.
434 -
435 347
348 + // if we need a readable event, then we need to do some reading.
436 var doRead = state.needReadable; 349 var doRead = state.needReadable;
437 - debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some 350 + debug('need readable', doRead);
438 351
352 + // if we currently have less than the highWaterMark, then also read some
439 if (state.length === 0 || state.length - n < state.highWaterMark) { 353 if (state.length === 0 || state.length - n < state.highWaterMark) {
440 doRead = true; 354 doRead = true;
441 debug('length less than watermark', doRead); 355 debug('length less than watermark', doRead);
442 - } // however, if we've ended, then there's no point, and if we're already 356 + }
443 - // reading, then it's unnecessary.
444 -
445 357
358 + // however, if we've ended, then there's no point, and if we're already
359 + // reading, then it's unnecessary.
446 if (state.ended || state.reading) { 360 if (state.ended || state.reading) {
447 doRead = false; 361 doRead = false;
448 debug('reading or ended', doRead); 362 debug('reading or ended', doRead);
449 - } else if (doRead) { 363 + }
364 +
365 + if (doRead) {
450 debug('do read'); 366 debug('do read');
451 state.reading = true; 367 state.reading = true;
452 - state.sync = true; // if the length is currently zero, then we *need* a readable event. 368 + state.sync = true;
453 - 369 + // if the length is currently zero, then we *need* a readable event.
454 - if (state.length === 0) state.needReadable = true; // call internal read method 370 + if (state.length === 0)
455 - 371 + state.needReadable = true;
372 + // call internal read method
456 this._read(state.highWaterMark); 373 this._read(state.highWaterMark);
457 - 374 + state.sync = false;
458 - state.sync = false; // If _read pushed data synchronously, then `reading` will be false,
459 - // and we need to re-evaluate how much data we can return to the user.
460 -
461 - if (!state.reading) n = howMuchToRead(nOrig, state);
462 } 375 }
463 376
377 + // If _read pushed data synchronously, then `reading` will be false,
378 + // and we need to re-evaluate how much data we can return to the user.
379 + if (doRead && !state.reading)
380 + n = howMuchToRead(nOrig, state);
381 +
464 var ret; 382 var ret;
465 - if (n > 0) ret = fromList(n, state);else ret = null; 383 + if (n > 0)
384 + ret = fromList(n, state);
385 + else
386 + ret = null;
466 387
467 - if (ret === null) { 388 + if (util.isNull(ret)) {
468 - state.needReadable = state.length <= state.highWaterMark; 389 + state.needReadable = true;
469 n = 0; 390 n = 0;
470 - } else {
471 - state.length -= n;
472 - state.awaitDrain = 0;
473 } 391 }
474 392
475 - if (state.length === 0) { 393 + state.length -= n;
476 - // If we have nothing in the buffer, then we want to know
477 - // as soon as we *do* get something into the buffer.
478 - if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick.
479 394
480 - if (nOrig !== n && state.ended) endReadable(this); 395 + // If we have nothing in the buffer, then we want to know
481 - } 396 + // as soon as we *do* get something into the buffer.
397 + if (state.length === 0 && !state.ended)
398 + state.needReadable = true;
399 +
400 + // If we tried to read() past the EOF, then emit end on the next tick.
401 + if (nOrig !== n && state.ended && state.length === 0)
402 + endReadable(this);
403 +
404 + if (!util.isNull(ret))
405 + this.emit('data', ret);
482 406
483 - if (ret !== null) this.emit('data', ret);
484 return ret; 407 return ret;
485 }; 408 };
486 409
487 -function onEofChunk(stream, state) { 410 +function chunkInvalid(state, chunk) {
488 - debug('onEofChunk'); 411 + var er = null;
489 - if (state.ended) return; 412 + if (!util.isBuffer(chunk) &&
413 + !util.isString(chunk) &&
414 + !util.isNullOrUndefined(chunk) &&
415 + !state.objectMode) {
416 + er = new TypeError('Invalid non-string/buffer chunk');
417 + }
418 + return er;
419 +}
490 420
491 - if (state.decoder) {
492 - var chunk = state.decoder.end();
493 421
422 +function onEofChunk(stream, state) {
423 + if (state.decoder && !state.ended) {
424 + var chunk = state.decoder.end();
494 if (chunk && chunk.length) { 425 if (chunk && chunk.length) {
495 state.buffer.push(chunk); 426 state.buffer.push(chunk);
496 state.length += state.objectMode ? 1 : chunk.length; 427 state.length += state.objectMode ? 1 : chunk.length;
497 } 428 }
498 } 429 }
499 -
500 state.ended = true; 430 state.ended = true;
501 431
502 - if (state.sync) { 432 + // emit 'readable' now to make sure it gets picked up.
503 - // if we are sync, wait until next tick to emit the data. 433 + emitReadable(stream);
504 - // Otherwise we risk emitting data in the flow() 434 +}
505 - // the readable code triggers during a read() call
506 - emitReadable(stream);
507 - } else {
508 - // emit 'readable' now to make sure it gets picked up.
509 - state.needReadable = false;
510 435
511 - if (!state.emittedReadable) { 436 +// Don't emit readable right away in sync mode, because this can trigger
512 - state.emittedReadable = true;
513 - emitReadable_(stream);
514 - }
515 - }
516 -} // Don't emit readable right away in sync mode, because this can trigger
517 // another read() call => stack overflow. This way, it might trigger 437 // another read() call => stack overflow. This way, it might trigger
518 // a nextTick recursion warning, but that's not so bad. 438 // a nextTick recursion warning, but that's not so bad.
519 -
520 -
521 function emitReadable(stream) { 439 function emitReadable(stream) {
522 var state = stream._readableState; 440 var state = stream._readableState;
523 - debug('emitReadable', state.needReadable, state.emittedReadable);
524 state.needReadable = false; 441 state.needReadable = false;
525 -
526 if (!state.emittedReadable) { 442 if (!state.emittedReadable) {
527 debug('emitReadable', state.flowing); 443 debug('emitReadable', state.flowing);
528 state.emittedReadable = true; 444 state.emittedReadable = true;
529 - process.nextTick(emitReadable_, stream); 445 + if (state.sync)
446 + process.nextTick(function() {
447 + emitReadable_(stream);
448 + });
449 + else
450 + emitReadable_(stream);
530 } 451 }
531 } 452 }
532 453
533 function emitReadable_(stream) { 454 function emitReadable_(stream) {
534 - var state = stream._readableState; 455 + debug('emit readable');
535 - debug('emitReadable_', state.destroyed, state.length, state.ended); 456 + stream.emit('readable');
536 - 457 + flow(stream);
537 - if (!state.destroyed && (state.length || state.ended)) { 458 +}
538 - stream.emit('readable');
539 - state.emittedReadable = false;
540 - } // The stream needs another readable event if
541 - // 1. It is not flowing, as the flow mechanism will take
542 - // care of it.
543 - // 2. It is not ended.
544 - // 3. It is below the highWaterMark, so we can schedule
545 - // another readable later.
546 459
547 460
548 - state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark; 461 +// at this point, the user has presumably seen the 'readable' event,
549 - flow(stream);
550 -} // at this point, the user has presumably seen the 'readable' event,
551 // and called read() to consume some data. that may have triggered 462 // and called read() to consume some data. that may have triggered
552 // in turn another _read(n) call, in which case reading = true if 463 // in turn another _read(n) call, in which case reading = true if
553 // it's in progress. 464 // it's in progress.
554 // However, if we're not ended, or reading, and the length < hwm, 465 // However, if we're not ended, or reading, and the length < hwm,
555 // then go ahead and try to read some more preemptively. 466 // then go ahead and try to read some more preemptively.
556 -
557 -
558 function maybeReadMore(stream, state) { 467 function maybeReadMore(stream, state) {
559 if (!state.readingMore) { 468 if (!state.readingMore) {
560 state.readingMore = true; 469 state.readingMore = true;
561 - process.nextTick(maybeReadMore_, stream, state); 470 + process.nextTick(function() {
471 + maybeReadMore_(stream, state);
472 + });
562 } 473 }
563 } 474 }
564 475
565 function maybeReadMore_(stream, state) { 476 function maybeReadMore_(stream, state) {
566 - // Attempt to read more data if we should. 477 + var len = state.length;
567 - // 478 + while (!state.reading && !state.flowing && !state.ended &&
568 - // The conditions for reading more data are (one of): 479 + state.length < state.highWaterMark) {
569 - // - Not enough data buffered (state.length < state.highWaterMark). The loop
570 - // is responsible for filling the buffer with enough data if such data
571 - // is available. If highWaterMark is 0 and we are not in the flowing mode
572 - // we should _not_ attempt to buffer any extra data. We'll get more data
573 - // when the stream consumer calls read() instead.
574 - // - No data in the buffer, and the stream is in flowing mode. In this mode
575 - // the loop below is responsible for ensuring read() is called. Failing to
576 - // call read here would abort the flow and there's no other mechanism for
577 - // continuing the flow if the stream consumer has just subscribed to the
578 - // 'data' event.
579 - //
580 - // In addition to the above conditions to keep reading data, the following
581 - // conditions prevent the data from being read:
582 - // - The stream has ended (state.ended).
583 - // - There is already a pending 'read' operation (state.reading). This is a
584 - // case where the the stream has called the implementation defined _read()
585 - // method, but they are processing the call asynchronously and have _not_
586 - // called push() with new data. In this case we skip performing more
587 - // read()s. The execution ends in this method again after the _read() ends
588 - // up calling push() with more data.
589 - while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) {
590 - var len = state.length;
591 debug('maybeReadMore read 0'); 480 debug('maybeReadMore read 0');
592 stream.read(0); 481 stream.read(0);
593 - if (len === state.length) // didn't get any data, stop spinning. 482 + if (len === state.length)
483 + // didn't get any data, stop spinning.
594 break; 484 break;
485 + else
486 + len = state.length;
595 } 487 }
596 -
597 state.readingMore = false; 488 state.readingMore = false;
598 -} // abstract method. to be overridden in specific implementation classes. 489 +}
490 +
491 +// abstract method. to be overridden in specific implementation classes.
599 // call cb(er, data) where data is <= n in length. 492 // call cb(er, data) where data is <= n in length.
600 // for virtual (non-string, non-buffer) streams, "length" is somewhat 493 // for virtual (non-string, non-buffer) streams, "length" is somewhat
601 // arbitrary, and perhaps not very meaningful. 494 // arbitrary, and perhaps not very meaningful.
602 - 495 +Readable.prototype._read = function(n) {
603 - 496 + this.emit('error', new Error('not implemented'));
604 -Readable.prototype._read = function (n) {
605 - errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()'));
606 }; 497 };
607 498
608 -Readable.prototype.pipe = function (dest, pipeOpts) { 499 +Readable.prototype.pipe = function(dest, pipeOpts) {
609 var src = this; 500 var src = this;
610 var state = this._readableState; 501 var state = this._readableState;
611 502
...@@ -613,123 +504,122 @@ Readable.prototype.pipe = function (dest, pipeOpts) { ...@@ -613,123 +504,122 @@ Readable.prototype.pipe = function (dest, pipeOpts) {
613 case 0: 504 case 0:
614 state.pipes = dest; 505 state.pipes = dest;
615 break; 506 break;
616 -
617 case 1: 507 case 1:
618 state.pipes = [state.pipes, dest]; 508 state.pipes = [state.pipes, dest];
619 break; 509 break;
620 -
621 default: 510 default:
622 state.pipes.push(dest); 511 state.pipes.push(dest);
623 break; 512 break;
624 } 513 }
625 -
626 state.pipesCount += 1; 514 state.pipesCount += 1;
627 debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); 515 debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
628 - var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
629 - var endFn = doEnd ? onend : unpipe;
630 - if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn);
631 - dest.on('unpipe', onunpipe);
632 516
633 - function onunpipe(readable, unpipeInfo) { 517 + var doEnd = (!pipeOpts || pipeOpts.end !== false) &&
634 - debug('onunpipe'); 518 + dest !== process.stdout &&
519 + dest !== process.stderr;
520 +
521 + var endFn = doEnd ? onend : cleanup;
522 + if (state.endEmitted)
523 + process.nextTick(endFn);
524 + else
525 + src.once('end', endFn);
635 526
527 + dest.on('unpipe', onunpipe);
528 + function onunpipe(readable) {
529 + debug('onunpipe');
636 if (readable === src) { 530 if (readable === src) {
637 - if (unpipeInfo && unpipeInfo.hasUnpiped === false) { 531 + cleanup();
638 - unpipeInfo.hasUnpiped = true;
639 - cleanup();
640 - }
641 } 532 }
642 } 533 }
643 534
644 function onend() { 535 function onend() {
645 debug('onend'); 536 debug('onend');
646 dest.end(); 537 dest.end();
647 - } // when the dest drains, it reduces the awaitDrain counter 538 + }
539 +
540 + // when the dest drains, it reduces the awaitDrain counter
648 // on the source. This would be more elegant with a .once() 541 // on the source. This would be more elegant with a .once()
649 // handler in flow(), but adding and removing repeatedly is 542 // handler in flow(), but adding and removing repeatedly is
650 // too slow. 543 // too slow.
651 -
652 -
653 var ondrain = pipeOnDrain(src); 544 var ondrain = pipeOnDrain(src);
654 dest.on('drain', ondrain); 545 dest.on('drain', ondrain);
655 - var cleanedUp = false;
656 546
657 function cleanup() { 547 function cleanup() {
658 - debug('cleanup'); // cleanup event handlers once the pipe is broken 548 + debug('cleanup');
659 - 549 + // cleanup event handlers once the pipe is broken
660 dest.removeListener('close', onclose); 550 dest.removeListener('close', onclose);
661 dest.removeListener('finish', onfinish); 551 dest.removeListener('finish', onfinish);
662 dest.removeListener('drain', ondrain); 552 dest.removeListener('drain', ondrain);
663 dest.removeListener('error', onerror); 553 dest.removeListener('error', onerror);
664 dest.removeListener('unpipe', onunpipe); 554 dest.removeListener('unpipe', onunpipe);
665 src.removeListener('end', onend); 555 src.removeListener('end', onend);
666 - src.removeListener('end', unpipe); 556 + src.removeListener('end', cleanup);
667 src.removeListener('data', ondata); 557 src.removeListener('data', ondata);
668 - cleanedUp = true; // if the reader is waiting for a drain event from this 558 +
559 + // if the reader is waiting for a drain event from this
669 // specific writer, then it would cause it to never start 560 // specific writer, then it would cause it to never start
670 // flowing again. 561 // flowing again.
671 // So, if this is awaiting a drain, then we just call it now. 562 // So, if this is awaiting a drain, then we just call it now.
672 // If we don't know, then assume that we are waiting for one. 563 // If we don't know, then assume that we are waiting for one.
673 - 564 + if (state.awaitDrain &&
674 - if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); 565 + (!dest._writableState || dest._writableState.needDrain))
566 + ondrain();
675 } 567 }
676 568
677 src.on('data', ondata); 569 src.on('data', ondata);
678 -
679 function ondata(chunk) { 570 function ondata(chunk) {
680 debug('ondata'); 571 debug('ondata');
681 var ret = dest.write(chunk); 572 var ret = dest.write(chunk);
682 - debug('dest.write', ret); 573 + if (false === ret) {
683 - 574 + debug('false write response, pause',
684 - if (ret === false) { 575 + src._readableState.awaitDrain);
685 - // If the user unpiped during `dest.write()`, it is possible 576 + src._readableState.awaitDrain++;
686 - // to get stuck in a permanently paused state if that write
687 - // also returned false.
688 - // => Check whether `dest` is still a piping destination.
689 - if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
690 - debug('false write response, pause', state.awaitDrain);
691 - state.awaitDrain++;
692 - }
693 -
694 src.pause(); 577 src.pause();
695 } 578 }
696 - } // if the dest has an error, then stop piping into it. 579 + }
697 - // however, don't suppress the throwing behavior for this.
698 -
699 580
581 + // if the dest has an error, then stop piping into it.
582 + // however, don't suppress the throwing behavior for this.
700 function onerror(er) { 583 function onerror(er) {
701 debug('onerror', er); 584 debug('onerror', er);
702 unpipe(); 585 unpipe();
703 dest.removeListener('error', onerror); 586 dest.removeListener('error', onerror);
704 - if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er); 587 + if (EE.listenerCount(dest, 'error') === 0)
705 - } // Make sure our error handler is attached before userland ones. 588 + dest.emit('error', er);
589 + }
590 + // This is a brutally ugly hack to make sure that our error handler
591 + // is attached before any userland ones. NEVER DO THIS.
592 + if (!dest._events || !dest._events.error)
593 + dest.on('error', onerror);
594 + else if (isArray(dest._events.error))
595 + dest._events.error.unshift(onerror);
596 + else
597 + dest._events.error = [onerror, dest._events.error];
706 598
707 599
708 - prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once.
709 600
601 + // Both close and finish should trigger unpipe, but only once.
710 function onclose() { 602 function onclose() {
711 dest.removeListener('finish', onfinish); 603 dest.removeListener('finish', onfinish);
712 unpipe(); 604 unpipe();
713 } 605 }
714 -
715 dest.once('close', onclose); 606 dest.once('close', onclose);
716 -
717 function onfinish() { 607 function onfinish() {
718 debug('onfinish'); 608 debug('onfinish');
719 dest.removeListener('close', onclose); 609 dest.removeListener('close', onclose);
720 unpipe(); 610 unpipe();
721 } 611 }
722 -
723 dest.once('finish', onfinish); 612 dest.once('finish', onfinish);
724 613
725 function unpipe() { 614 function unpipe() {
726 debug('unpipe'); 615 debug('unpipe');
727 src.unpipe(dest); 616 src.unpipe(dest);
728 - } // tell the dest that it's being piped to 617 + }
729 -
730 618
731 - dest.emit('pipe', src); // start the flow if it hasn't been started already. 619 + // tell the dest that it's being piped to
620 + dest.emit('pipe', src);
732 621
622 + // start the flow if it hasn't been started already.
733 if (!state.flowing) { 623 if (!state.flowing) {
734 debug('pipe resume'); 624 debug('pipe resume');
735 src.resume(); 625 src.resume();
...@@ -739,38 +629,45 @@ Readable.prototype.pipe = function (dest, pipeOpts) { ...@@ -739,38 +629,45 @@ Readable.prototype.pipe = function (dest, pipeOpts) {
739 }; 629 };
740 630
741 function pipeOnDrain(src) { 631 function pipeOnDrain(src) {
742 - return function pipeOnDrainFunctionResult() { 632 + return function() {
743 var state = src._readableState; 633 var state = src._readableState;
744 debug('pipeOnDrain', state.awaitDrain); 634 debug('pipeOnDrain', state.awaitDrain);
745 - if (state.awaitDrain) state.awaitDrain--; 635 + if (state.awaitDrain)
746 - 636 + state.awaitDrain--;
747 - if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { 637 + if (state.awaitDrain === 0 && EE.listenerCount(src, 'data')) {
748 state.flowing = true; 638 state.flowing = true;
749 flow(src); 639 flow(src);
750 } 640 }
751 }; 641 };
752 } 642 }
753 643
754 -Readable.prototype.unpipe = function (dest) { 644 +
645 +Readable.prototype.unpipe = function(dest) {
755 var state = this._readableState; 646 var state = this._readableState;
756 - var unpipeInfo = {
757 - hasUnpiped: false
758 - }; // if we're not piping anywhere, then do nothing.
759 647
760 - if (state.pipesCount === 0) return this; // just one destination. most common case. 648 + // if we're not piping anywhere, then do nothing.
649 + if (state.pipesCount === 0)
650 + return this;
761 651
652 + // just one destination. most common case.
762 if (state.pipesCount === 1) { 653 if (state.pipesCount === 1) {
763 // passed in one, but it's not the right one. 654 // passed in one, but it's not the right one.
764 - if (dest && dest !== state.pipes) return this; 655 + if (dest && dest !== state.pipes)
765 - if (!dest) dest = state.pipes; // got a match. 656 + return this;
657 +
658 + if (!dest)
659 + dest = state.pipes;
766 660
661 + // got a match.
767 state.pipes = null; 662 state.pipes = null;
768 state.pipesCount = 0; 663 state.pipesCount = 0;
769 state.flowing = false; 664 state.flowing = false;
770 - if (dest) dest.emit('unpipe', this, unpipeInfo); 665 + if (dest)
666 + dest.emit('unpipe', this);
771 return this; 667 return this;
772 - } // slow case. multiple pipe destinations. 668 + }
773 669
670 + // slow case. multiple pipe destinations.
774 671
775 if (!dest) { 672 if (!dest) {
776 // remove all. 673 // remove all.
...@@ -780,345 +677,275 @@ Readable.prototype.unpipe = function (dest) { ...@@ -780,345 +677,275 @@ Readable.prototype.unpipe = function (dest) {
780 state.pipesCount = 0; 677 state.pipesCount = 0;
781 state.flowing = false; 678 state.flowing = false;
782 679
783 - for (var i = 0; i < len; i++) { 680 + for (var i = 0; i < len; i++)
784 - dests[i].emit('unpipe', this, { 681 + dests[i].emit('unpipe', this);
785 - hasUnpiped: false
786 - });
787 - }
788 -
789 return this; 682 return this;
790 - } // try to find the right one. 683 + }
791 684
685 + // try to find the right one.
686 + var i = indexOf(state.pipes, dest);
687 + if (i === -1)
688 + return this;
792 689
793 - var index = indexOf(state.pipes, dest); 690 + state.pipes.splice(i, 1);
794 - if (index === -1) return this;
795 - state.pipes.splice(index, 1);
796 state.pipesCount -= 1; 691 state.pipesCount -= 1;
797 - if (state.pipesCount === 1) state.pipes = state.pipes[0]; 692 + if (state.pipesCount === 1)
798 - dest.emit('unpipe', this, unpipeInfo); 693 + state.pipes = state.pipes[0];
799 - return this; 694 +
800 -}; // set up data events if they are asked for 695 + dest.emit('unpipe', this);
801 -// Ensure readable listeners eventually get something
802 696
697 + return this;
698 +};
803 699
804 -Readable.prototype.on = function (ev, fn) { 700 +// set up data events if they are asked for
701 +// Ensure readable listeners eventually get something
702 +Readable.prototype.on = function(ev, fn) {
805 var res = Stream.prototype.on.call(this, ev, fn); 703 var res = Stream.prototype.on.call(this, ev, fn);
806 - var state = this._readableState;
807 704
808 - if (ev === 'data') { 705 + // If listening to data, and it has not explicitly been paused,
809 - // update readableListening so that resume() may be a no-op 706 + // then call resume to start the flow of data on the next tick.
810 - // a few lines down. This is needed to support once('readable'). 707 + if (ev === 'data' && false !== this._readableState.flowing) {
811 - state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused 708 + this.resume();
709 + }
812 710
813 - if (state.flowing !== false) this.resume(); 711 + if (ev === 'readable' && this.readable) {
814 - } else if (ev === 'readable') { 712 + var state = this._readableState;
815 - if (!state.endEmitted && !state.readableListening) { 713 + if (!state.readableListening) {
816 - state.readableListening = state.needReadable = true; 714 + state.readableListening = true;
817 - state.flowing = false;
818 state.emittedReadable = false; 715 state.emittedReadable = false;
819 - debug('on readable', state.length, state.reading); 716 + state.needReadable = true;
820 - 717 + if (!state.reading) {
821 - if (state.length) { 718 + var self = this;
822 - emitReadable(this); 719 + process.nextTick(function() {
823 - } else if (!state.reading) { 720 + debug('readable nexttick read 0');
824 - process.nextTick(nReadingNextTick, this); 721 + self.read(0);
722 + });
723 + } else if (state.length) {
724 + emitReadable(this, state);
825 } 725 }
826 } 726 }
827 } 727 }
828 728
829 return res; 729 return res;
830 }; 730 };
831 -
832 Readable.prototype.addListener = Readable.prototype.on; 731 Readable.prototype.addListener = Readable.prototype.on;
833 732
834 -Readable.prototype.removeListener = function (ev, fn) { 733 +// pause() and resume() are remnants of the legacy readable stream API
835 - var res = Stream.prototype.removeListener.call(this, ev, fn);
836 -
837 - if (ev === 'readable') {
838 - // We need to check if there is someone still listening to
839 - // readable and reset the state. However this needs to happen
840 - // after readable has been emitted but before I/O (nextTick) to
841 - // support once('readable', fn) cycles. This means that calling
842 - // resume within the same tick will have no
843 - // effect.
844 - process.nextTick(updateReadableListening, this);
845 - }
846 -
847 - return res;
848 -};
849 -
850 -Readable.prototype.removeAllListeners = function (ev) {
851 - var res = Stream.prototype.removeAllListeners.apply(this, arguments);
852 -
853 - if (ev === 'readable' || ev === undefined) {
854 - // We need to check if there is someone still listening to
855 - // readable and reset the state. However this needs to happen
856 - // after readable has been emitted but before I/O (nextTick) to
857 - // support once('readable', fn) cycles. This means that calling
858 - // resume within the same tick will have no
859 - // effect.
860 - process.nextTick(updateReadableListening, this);
861 - }
862 -
863 - return res;
864 -};
865 -
866 -function updateReadableListening(self) {
867 - var state = self._readableState;
868 - state.readableListening = self.listenerCount('readable') > 0;
869 -
870 - if (state.resumeScheduled && !state.paused) {
871 - // flowing needs to be set to true now, otherwise
872 - // the upcoming resume will not flow.
873 - state.flowing = true; // crude way to check if we should resume
874 - } else if (self.listenerCount('data') > 0) {
875 - self.resume();
876 - }
877 -}
878 -
879 -function nReadingNextTick(self) {
880 - debug('readable nexttick read 0');
881 - self.read(0);
882 -} // pause() and resume() are remnants of the legacy readable stream API
883 // If the user uses them, then switch into old mode. 734 // If the user uses them, then switch into old mode.
884 - 735 +Readable.prototype.resume = function() {
885 -
886 -Readable.prototype.resume = function () {
887 var state = this._readableState; 736 var state = this._readableState;
888 -
889 if (!state.flowing) { 737 if (!state.flowing) {
890 - debug('resume'); // we flow only if there is no one listening 738 + debug('resume');
891 - // for readable, but we still have to call 739 + state.flowing = true;
892 - // resume() 740 + if (!state.reading) {
893 - 741 + debug('resume read 0');
894 - state.flowing = !state.readableListening; 742 + this.read(0);
743 + }
895 resume(this, state); 744 resume(this, state);
896 } 745 }
897 -
898 - state.paused = false;
899 return this; 746 return this;
900 }; 747 };
901 748
902 function resume(stream, state) { 749 function resume(stream, state) {
903 if (!state.resumeScheduled) { 750 if (!state.resumeScheduled) {
904 state.resumeScheduled = true; 751 state.resumeScheduled = true;
905 - process.nextTick(resume_, stream, state); 752 + process.nextTick(function() {
753 + resume_(stream, state);
754 + });
906 } 755 }
907 } 756 }
908 757
909 function resume_(stream, state) { 758 function resume_(stream, state) {
910 - debug('resume', state.reading);
911 -
912 - if (!state.reading) {
913 - stream.read(0);
914 - }
915 -
916 state.resumeScheduled = false; 759 state.resumeScheduled = false;
917 stream.emit('resume'); 760 stream.emit('resume');
918 flow(stream); 761 flow(stream);
919 - if (state.flowing && !state.reading) stream.read(0); 762 + if (state.flowing && !state.reading)
763 + stream.read(0);
920 } 764 }
921 765
922 -Readable.prototype.pause = function () { 766 +Readable.prototype.pause = function() {
923 debug('call pause flowing=%j', this._readableState.flowing); 767 debug('call pause flowing=%j', this._readableState.flowing);
924 - 768 + if (false !== this._readableState.flowing) {
925 - if (this._readableState.flowing !== false) {
926 debug('pause'); 769 debug('pause');
927 this._readableState.flowing = false; 770 this._readableState.flowing = false;
928 this.emit('pause'); 771 this.emit('pause');
929 } 772 }
930 -
931 - this._readableState.paused = true;
932 return this; 773 return this;
933 }; 774 };
934 775
935 function flow(stream) { 776 function flow(stream) {
936 var state = stream._readableState; 777 var state = stream._readableState;
937 debug('flow', state.flowing); 778 debug('flow', state.flowing);
938 - 779 + if (state.flowing) {
939 - while (state.flowing && stream.read() !== null) { 780 + do {
940 - ; 781 + var chunk = stream.read();
782 + } while (null !== chunk && state.flowing);
941 } 783 }
942 -} // wrap an old-style stream as the async data source. 784 +}
785 +
786 +// wrap an old-style stream as the async data source.
943 // This is *not* part of the readable stream interface. 787 // This is *not* part of the readable stream interface.
944 // It is an ugly unfortunate mess of history. 788 // It is an ugly unfortunate mess of history.
945 - 789 +Readable.prototype.wrap = function(stream) {
946 -
947 -Readable.prototype.wrap = function (stream) {
948 - var _this = this;
949 -
950 var state = this._readableState; 790 var state = this._readableState;
951 var paused = false; 791 var paused = false;
952 - stream.on('end', function () {
953 - debug('wrapped end');
954 792
793 + var self = this;
794 + stream.on('end', function() {
795 + debug('wrapped end');
955 if (state.decoder && !state.ended) { 796 if (state.decoder && !state.ended) {
956 var chunk = state.decoder.end(); 797 var chunk = state.decoder.end();
957 - if (chunk && chunk.length) _this.push(chunk); 798 + if (chunk && chunk.length)
799 + self.push(chunk);
958 } 800 }
959 801
960 - _this.push(null); 802 + self.push(null);
961 }); 803 });
962 - stream.on('data', function (chunk) {
963 - debug('wrapped data');
964 - if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode
965 -
966 - if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
967 804
968 - var ret = _this.push(chunk); 805 + stream.on('data', function(chunk) {
806 + debug('wrapped data');
807 + if (state.decoder)
808 + chunk = state.decoder.write(chunk);
809 + if (!chunk || !state.objectMode && !chunk.length)
810 + return;
969 811
812 + var ret = self.push(chunk);
970 if (!ret) { 813 if (!ret) {
971 paused = true; 814 paused = true;
972 stream.pause(); 815 stream.pause();
973 } 816 }
974 - }); // proxy all the other methods. 817 + });
975 - // important when wrapping filters and duplexes.
976 818
819 + // proxy all the other methods.
820 + // important when wrapping filters and duplexes.
977 for (var i in stream) { 821 for (var i in stream) {
978 - if (this[i] === undefined && typeof stream[i] === 'function') { 822 + if (util.isFunction(stream[i]) && util.isUndefined(this[i])) {
979 - this[i] = function methodWrap(method) { 823 + this[i] = function(method) { return function() {
980 - return function methodWrapReturnFunction() { 824 + return stream[method].apply(stream, arguments);
981 - return stream[method].apply(stream, arguments); 825 + }}(i);
982 - };
983 - }(i);
984 } 826 }
985 - } // proxy certain important events. 827 + }
986 828
829 + // proxy certain important events.
830 + var events = ['error', 'close', 'destroy', 'pause', 'resume'];
831 + forEach(events, function(ev) {
832 + stream.on(ev, self.emit.bind(self, ev));
833 + });
987 834
988 - for (var n = 0; n < kProxyEvents.length; n++) { 835 + // when we try to consume some more bytes, simply unpause the
989 - stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));
990 - } // when we try to consume some more bytes, simply unpause the
991 // underlying stream. 836 // underlying stream.
992 - 837 + self._read = function(n) {
993 -
994 - this._read = function (n) {
995 debug('wrapped _read', n); 838 debug('wrapped _read', n);
996 -
997 if (paused) { 839 if (paused) {
998 paused = false; 840 paused = false;
999 stream.resume(); 841 stream.resume();
1000 } 842 }
1001 }; 843 };
1002 844
1003 - return this; 845 + return self;
1004 }; 846 };
1005 847
1006 -if (typeof Symbol === 'function') {
1007 - Readable.prototype[Symbol.asyncIterator] = function () {
1008 - if (createReadableStreamAsyncIterator === undefined) {
1009 - createReadableStreamAsyncIterator = require('./internal/streams/async_iterator');
1010 - }
1011 848
1012 - return createReadableStreamAsyncIterator(this);
1013 - };
1014 -}
1015 -
1016 -Object.defineProperty(Readable.prototype, 'readableHighWaterMark', {
1017 - // making it explicit this property is not enumerable
1018 - // because otherwise some prototype manipulation in
1019 - // userland will fail
1020 - enumerable: false,
1021 - get: function get() {
1022 - return this._readableState.highWaterMark;
1023 - }
1024 -});
1025 -Object.defineProperty(Readable.prototype, 'readableBuffer', {
1026 - // making it explicit this property is not enumerable
1027 - // because otherwise some prototype manipulation in
1028 - // userland will fail
1029 - enumerable: false,
1030 - get: function get() {
1031 - return this._readableState && this._readableState.buffer;
1032 - }
1033 -});
1034 -Object.defineProperty(Readable.prototype, 'readableFlowing', {
1035 - // making it explicit this property is not enumerable
1036 - // because otherwise some prototype manipulation in
1037 - // userland will fail
1038 - enumerable: false,
1039 - get: function get() {
1040 - return this._readableState.flowing;
1041 - },
1042 - set: function set(state) {
1043 - if (this._readableState) {
1044 - this._readableState.flowing = state;
1045 - }
1046 - }
1047 -}); // exposed for testing purposes only.
1048 849
850 +// exposed for testing purposes only.
1049 Readable._fromList = fromList; 851 Readable._fromList = fromList;
1050 -Object.defineProperty(Readable.prototype, 'readableLength', {
1051 - // making it explicit this property is not enumerable
1052 - // because otherwise some prototype manipulation in
1053 - // userland will fail
1054 - enumerable: false,
1055 - get: function get() {
1056 - return this._readableState.length;
1057 - }
1058 -}); // Pluck off n bytes from an array of buffers.
1059 -// Length is the combined lengths of all the buffers in the list.
1060 -// This function is designed to be inlinable, so please take care when making
1061 -// changes to the function body.
1062 852
853 +// Pluck off n bytes from an array of buffers.
854 +// Length is the combined lengths of all the buffers in the list.
1063 function fromList(n, state) { 855 function fromList(n, state) {
1064 - // nothing buffered 856 + var list = state.buffer;
1065 - if (state.length === 0) return null; 857 + var length = state.length;
858 + var stringMode = !!state.decoder;
859 + var objectMode = !!state.objectMode;
1066 var ret; 860 var ret;
1067 - if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { 861 +
1068 - // read it all, truncate the list 862 + // nothing in the list, definitely empty.
1069 - if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length); 863 + if (list.length === 0)
1070 - state.buffer.clear(); 864 + return null;
865 +
866 + if (length === 0)
867 + ret = null;
868 + else if (objectMode)
869 + ret = list.shift();
870 + else if (!n || n >= length) {
871 + // read it all, truncate the array.
872 + if (stringMode)
873 + ret = list.join('');
874 + else
875 + ret = Buffer.concat(list, length);
876 + list.length = 0;
1071 } else { 877 } else {
1072 - // read part of list 878 + // read just some of it.
1073 - ret = state.buffer.consume(n, state.decoder); 879 + if (n < list[0].length) {
880 + // just take a part of the first list item.
881 + // slice is the same for buffers and strings.
882 + var buf = list[0];
883 + ret = buf.slice(0, n);
884 + list[0] = buf.slice(n);
885 + } else if (n === list[0].length) {
886 + // first list is a perfect match
887 + ret = list.shift();
888 + } else {
889 + // complex case.
890 + // we have enough to cover it, but it spans past the first buffer.
891 + if (stringMode)
892 + ret = '';
893 + else
894 + ret = new Buffer(n);
895 +
896 + var c = 0;
897 + for (var i = 0, l = list.length; i < l && c < n; i++) {
898 + var buf = list[0];
899 + var cpy = Math.min(n - c, buf.length);
900 +
901 + if (stringMode)
902 + ret += buf.slice(0, cpy);
903 + else
904 + buf.copy(ret, c, 0, cpy);
905 +
906 + if (cpy < buf.length)
907 + list[0] = buf.slice(cpy);
908 + else
909 + list.shift();
910 +
911 + c += cpy;
912 + }
913 + }
1074 } 914 }
915 +
1075 return ret; 916 return ret;
1076 } 917 }
1077 918
1078 function endReadable(stream) { 919 function endReadable(stream) {
1079 var state = stream._readableState; 920 var state = stream._readableState;
1080 - debug('endReadable', state.endEmitted); 921 +
922 + // If we get here before consuming all the bytes, then that is a
923 + // bug in node. Should never happen.
924 + if (state.length > 0)
925 + throw new Error('endReadable called on non-empty stream');
1081 926
1082 if (!state.endEmitted) { 927 if (!state.endEmitted) {
1083 state.ended = true; 928 state.ended = true;
1084 - process.nextTick(endReadableNT, state, stream); 929 + process.nextTick(function() {
1085 - } 930 + // Check that we didn't get one last unshift.
1086 -} 931 + if (!state.endEmitted && state.length === 0) {
1087 - 932 + state.endEmitted = true;
1088 -function endReadableNT(state, stream) { 933 + stream.readable = false;
1089 - debug('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift. 934 + stream.emit('end');
1090 -
1091 - if (!state.endEmitted && state.length === 0) {
1092 - state.endEmitted = true;
1093 - stream.readable = false;
1094 - stream.emit('end');
1095 -
1096 - if (state.autoDestroy) {
1097 - // In case of duplex streams we need a way to detect
1098 - // if the writable side is ready for autoDestroy as well
1099 - var wState = stream._writableState;
1100 -
1101 - if (!wState || wState.autoDestroy && wState.finished) {
1102 - stream.destroy();
1103 } 935 }
1104 - } 936 + });
1105 } 937 }
1106 } 938 }
1107 939
1108 -if (typeof Symbol === 'function') { 940 +function forEach (xs, f) {
1109 - Readable.from = function (iterable, opts) { 941 + for (var i = 0, l = xs.length; i < l; i++) {
1110 - if (from === undefined) { 942 + f(xs[i], i);
1111 - from = require('./internal/streams/from'); 943 + }
1112 - }
1113 -
1114 - return from(Readable, iterable, opts);
1115 - };
1116 } 944 }
1117 945
1118 -function indexOf(xs, x) { 946 +function indexOf (xs, x) {
1119 for (var i = 0, l = xs.length; i < l; i++) { 947 for (var i = 0, l = xs.length; i < l; i++) {
1120 if (xs[i] === x) return i; 948 if (xs[i] === x) return i;
1121 } 949 }
1122 -
1123 return -1; 950 return -1;
1124 -}
...\ No newline at end of file ...\ No newline at end of file
951 +}
......
...@@ -18,6 +18,8 @@ ...@@ -18,6 +18,8 @@
18 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 18 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE 19 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20 // USE OR OTHER DEALINGS IN THE SOFTWARE. 20 // USE OR OTHER DEALINGS IN THE SOFTWARE.
21 +
22 +
21 // a transform stream is a readable/writable stream where you do 23 // a transform stream is a readable/writable stream where you do
22 // something with the data. Sometimes it's called a "filter", 24 // something with the data. Sometimes it's called a "filter",
23 // but that's not a great name for it, since that implies a thing where 25 // but that's not a great name for it, since that implies a thing where
...@@ -59,85 +61,91 @@ ...@@ -59,85 +61,91 @@
59 // However, even in such a pathological case, only a single written chunk 61 // However, even in such a pathological case, only a single written chunk
60 // would be consumed, and then the rest would wait (un-transformed) until 62 // would be consumed, and then the rest would wait (un-transformed) until
61 // the results of the previous transformed chunk were consumed. 63 // the results of the previous transformed chunk were consumed.
62 -'use strict';
63 64
64 module.exports = Transform; 65 module.exports = Transform;
65 66
66 -var _require$codes = require('../errors').codes,
67 - ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
68 - ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,
69 - ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING,
70 - ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0;
71 -
72 var Duplex = require('./_stream_duplex'); 67 var Duplex = require('./_stream_duplex');
73 68
74 -require('inherits')(Transform, Duplex); 69 +/*<replacement>*/
70 +var util = require('core-util-is');
71 +util.inherits = require('inherits');
72 +/*</replacement>*/
75 73
76 -function afterTransform(er, data) { 74 +util.inherits(Transform, Duplex);
77 - var ts = this._transformState; 75 +
76 +
77 +function TransformState(options, stream) {
78 + this.afterTransform = function(er, data) {
79 + return afterTransform(stream, er, data);
80 + };
81 +
82 + this.needTransform = false;
83 + this.transforming = false;
84 + this.writecb = null;
85 + this.writechunk = null;
86 +}
87 +
88 +function afterTransform(stream, er, data) {
89 + var ts = stream._transformState;
78 ts.transforming = false; 90 ts.transforming = false;
91 +
79 var cb = ts.writecb; 92 var cb = ts.writecb;
80 93
81 - if (cb === null) { 94 + if (!cb)
82 - return this.emit('error', new ERR_MULTIPLE_CALLBACK()); 95 + return stream.emit('error', new Error('no writecb in Transform class'));
83 - }
84 96
85 ts.writechunk = null; 97 ts.writechunk = null;
86 ts.writecb = null; 98 ts.writecb = null;
87 - if (data != null) // single equals check for both `null` and `undefined`
88 - this.push(data);
89 - cb(er);
90 - var rs = this._readableState;
91 - rs.reading = false;
92 99
100 + if (!util.isNullOrUndefined(data))
101 + stream.push(data);
102 +
103 + if (cb)
104 + cb(er);
105 +
106 + var rs = stream._readableState;
107 + rs.reading = false;
93 if (rs.needReadable || rs.length < rs.highWaterMark) { 108 if (rs.needReadable || rs.length < rs.highWaterMark) {
94 - this._read(rs.highWaterMark); 109 + stream._read(rs.highWaterMark);
95 } 110 }
96 } 111 }
97 112
113 +
98 function Transform(options) { 114 function Transform(options) {
99 - if (!(this instanceof Transform)) return new Transform(options); 115 + if (!(this instanceof Transform))
100 - Duplex.call(this, options); 116 + return new Transform(options);
101 - this._transformState = {
102 - afterTransform: afterTransform.bind(this),
103 - needTransform: false,
104 - transforming: false,
105 - writecb: null,
106 - writechunk: null,
107 - writeencoding: null
108 - }; // start out asking for a readable event once data is transformed.
109 -
110 - this._readableState.needReadable = true; // we have implemented the _read method, and done the other things
111 - // that Readable wants before the first _read call, so unset the
112 - // sync guard flag.
113 117
114 - this._readableState.sync = false; 118 + Duplex.call(this, options);
115 119
116 - if (options) { 120 + this._transformState = new TransformState(options, this);
117 - if (typeof options.transform === 'function') this._transform = options.transform;
118 - if (typeof options.flush === 'function') this._flush = options.flush;
119 - } // When the writable side finishes, then flush out anything remaining.
120 121
122 + // when the writable side finishes, then flush out anything remaining.
123 + var stream = this;
121 124
122 - this.on('prefinish', prefinish); 125 + // start out asking for a readable event once data is transformed.
123 -} 126 + this._readableState.needReadable = true;
124 127
125 -function prefinish() { 128 + // we have implemented the _read method, and done the other things
126 - var _this = this; 129 + // that Readable wants before the first _read call, so unset the
130 + // sync guard flag.
131 + this._readableState.sync = false;
127 132
128 - if (typeof this._flush === 'function' && !this._readableState.destroyed) { 133 + this.once('prefinish', function() {
129 - this._flush(function (er, data) { 134 + if (util.isFunction(this._flush))
130 - done(_this, er, data); 135 + this._flush(function(er) {
131 - }); 136 + done(stream, er);
132 - } else { 137 + });
133 - done(this, null, null); 138 + else
134 - } 139 + done(stream);
140 + });
135 } 141 }
136 142
137 -Transform.prototype.push = function (chunk, encoding) { 143 +Transform.prototype.push = function(chunk, encoding) {
138 this._transformState.needTransform = false; 144 this._transformState.needTransform = false;
139 return Duplex.prototype.push.call(this, chunk, encoding); 145 return Duplex.prototype.push.call(this, chunk, encoding);
140 -}; // This is the part where you do stuff! 146 +};
147 +
148 +// This is the part where you do stuff!
141 // override this function in implementation classes. 149 // override this function in implementation classes.
142 // 'chunk' is an input chunk. 150 // 'chunk' is an input chunk.
143 // 151 //
...@@ -147,33 +155,32 @@ Transform.prototype.push = function (chunk, encoding) { ...@@ -147,33 +155,32 @@ Transform.prototype.push = function (chunk, encoding) {
147 // Call `cb(err)` when you are done with this chunk. If you pass 155 // Call `cb(err)` when you are done with this chunk. If you pass
148 // an error, then that'll put the hurt on the whole operation. If you 156 // an error, then that'll put the hurt on the whole operation. If you
149 // never call cb(), then you'll never get another chunk. 157 // never call cb(), then you'll never get another chunk.
150 - 158 +Transform.prototype._transform = function(chunk, encoding, cb) {
151 - 159 + throw new Error('not implemented');
152 -Transform.prototype._transform = function (chunk, encoding, cb) {
153 - cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()'));
154 }; 160 };
155 161
156 -Transform.prototype._write = function (chunk, encoding, cb) { 162 +Transform.prototype._write = function(chunk, encoding, cb) {
157 var ts = this._transformState; 163 var ts = this._transformState;
158 ts.writecb = cb; 164 ts.writecb = cb;
159 ts.writechunk = chunk; 165 ts.writechunk = chunk;
160 ts.writeencoding = encoding; 166 ts.writeencoding = encoding;
161 -
162 if (!ts.transforming) { 167 if (!ts.transforming) {
163 var rs = this._readableState; 168 var rs = this._readableState;
164 - if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); 169 + if (ts.needTransform ||
170 + rs.needReadable ||
171 + rs.length < rs.highWaterMark)
172 + this._read(rs.highWaterMark);
165 } 173 }
166 -}; // Doesn't matter what the args are here. 174 +};
175 +
176 +// Doesn't matter what the args are here.
167 // _transform does all the work. 177 // _transform does all the work.
168 // That we got here means that the readable side wants more data. 178 // That we got here means that the readable side wants more data.
169 - 179 +Transform.prototype._read = function(n) {
170 -
171 -Transform.prototype._read = function (n) {
172 var ts = this._transformState; 180 var ts = this._transformState;
173 181
174 - if (ts.writechunk !== null && !ts.transforming) { 182 + if (!util.isNull(ts.writechunk) && ts.writecb && !ts.transforming) {
175 ts.transforming = true; 183 ts.transforming = true;
176 -
177 this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); 184 this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
178 } else { 185 } else {
179 // mark that we need a transform, so that any data that comes in 186 // mark that we need a transform, so that any data that comes in
...@@ -182,20 +189,21 @@ Transform.prototype._read = function (n) { ...@@ -182,20 +189,21 @@ Transform.prototype._read = function (n) {
182 } 189 }
183 }; 190 };
184 191
185 -Transform.prototype._destroy = function (err, cb) {
186 - Duplex.prototype._destroy.call(this, err, function (err2) {
187 - cb(err2);
188 - });
189 -};
190 192
191 -function done(stream, er, data) { 193 +function done(stream, er) {
192 - if (er) return stream.emit('error', er); 194 + if (er)
193 - if (data != null) // single equals check for both `null` and `undefined` 195 + return stream.emit('error', er);
194 - stream.push(data); // TODO(BridgeAR): Write a test for these two error cases 196 +
195 // if there's nothing in the write buffer, then that means 197 // if there's nothing in the write buffer, then that means
196 // that nothing more will ever be provided 198 // that nothing more will ever be provided
199 + var ws = stream._writableState;
200 + var ts = stream._transformState;
201 +
202 + if (ws.length)
203 + throw new Error('calling transform done when ws.length != 0');
204 +
205 + if (ts.transforming)
206 + throw new Error('calling transform done when still transforming');
197 207
198 - if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0();
199 - if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING();
200 return stream.push(null); 208 return stream.push(null);
201 -}
...\ No newline at end of file ...\ No newline at end of file
209 +}
......
...@@ -18,385 +18,252 @@ ...@@ -18,385 +18,252 @@
18 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 18 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE 19 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20 // USE OR OTHER DEALINGS IN THE SOFTWARE. 20 // USE OR OTHER DEALINGS IN THE SOFTWARE.
21 +
21 // A bit simpler than readable streams. 22 // A bit simpler than readable streams.
22 -// Implement an async ._write(chunk, encoding, cb), and it'll handle all 23 +// Implement an async ._write(chunk, cb), and it'll handle all
23 // the drain event emission and buffering. 24 // the drain event emission and buffering.
24 -'use strict';
25 25
26 module.exports = Writable; 26 module.exports = Writable;
27 -/* <replacement> */
28 -
29 -function WriteReq(chunk, encoding, cb) {
30 - this.chunk = chunk;
31 - this.encoding = encoding;
32 - this.callback = cb;
33 - this.next = null;
34 -} // It seems a linked list but it is not
35 -// there will be only 2 of these for each stream
36 -
37 -
38 -function CorkedRequest(state) {
39 - var _this = this;
40 -
41 - this.next = null;
42 - this.entry = null;
43 -
44 - this.finish = function () {
45 - onCorkedFinish(_this, state);
46 - };
47 -}
48 -/* </replacement> */
49 27
50 /*<replacement>*/ 28 /*<replacement>*/
51 - 29 +var Buffer = require('buffer').Buffer;
52 -
53 -var Duplex;
54 /*</replacement>*/ 30 /*</replacement>*/
55 31
56 Writable.WritableState = WritableState; 32 Writable.WritableState = WritableState;
57 -/*<replacement>*/
58 33
59 -var internalUtil = {
60 - deprecate: require('util-deprecate')
61 -};
62 -/*</replacement>*/
63 34
64 /*<replacement>*/ 35 /*<replacement>*/
65 - 36 +var util = require('core-util-is');
66 -var Stream = require('./internal/streams/stream'); 37 +util.inherits = require('inherits');
67 /*</replacement>*/ 38 /*</replacement>*/
68 39
40 +var Stream = require('stream');
69 41
70 -var Buffer = require('buffer').Buffer; 42 +util.inherits(Writable, Stream);
71 -
72 -var OurUint8Array = global.Uint8Array || function () {};
73 -
74 -function _uint8ArrayToBuffer(chunk) {
75 - return Buffer.from(chunk);
76 -}
77 43
78 -function _isUint8Array(obj) { 44 +function WriteReq(chunk, encoding, cb) {
79 - return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; 45 + this.chunk = chunk;
46 + this.encoding = encoding;
47 + this.callback = cb;
80 } 48 }
81 49
82 -var destroyImpl = require('./internal/streams/destroy'); 50 +function WritableState(options, stream) {
83 - 51 + var Duplex = require('./_stream_duplex');
84 -var _require = require('./internal/streams/state'),
85 - getHighWaterMark = _require.getHighWaterMark;
86 -
87 -var _require$codes = require('../errors').codes,
88 - ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,
89 - ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
90 - ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,
91 - ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE,
92 - ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED,
93 - ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES,
94 - ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END,
95 - ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING;
96 -
97 -var errorOrDestroy = destroyImpl.errorOrDestroy;
98 -
99 -require('inherits')(Writable, Stream);
100 -
101 -function nop() {}
102 52
103 -function WritableState(options, stream, isDuplex) { 53 + options = options || {};
104 - Duplex = Duplex || require('./_stream_duplex');
105 - options = options || {}; // Duplex streams are both readable and writable, but share
106 - // the same options object.
107 - // However, some cases require setting options to different
108 - // values for the readable and the writable sides of the duplex stream,
109 - // e.g. options.readableObjectMode vs. options.writableObjectMode, etc.
110 54
111 - if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag to indicate whether or not this stream 55 + // the point at which write() starts returning false
112 - // contains buffers or objects.
113 -
114 - this.objectMode = !!options.objectMode;
115 - if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false
116 // Note: 0 is a valid value, means that we always return false if 56 // Note: 0 is a valid value, means that we always return false if
117 // the entire buffer is not flushed immediately on write() 57 // the entire buffer is not flushed immediately on write()
58 + var hwm = options.highWaterMark;
59 + var defaultHwm = options.objectMode ? 16 : 16 * 1024;
60 + this.highWaterMark = (hwm || hwm === 0) ? hwm : defaultHwm;
118 61
119 - this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called 62 + // object stream flag to indicate whether or not this stream
120 - 63 + // contains buffers or objects.
121 - this.finalCalled = false; // drain event flag. 64 + this.objectMode = !!options.objectMode;
122 -
123 - this.needDrain = false; // at the start of calling end()
124 65
125 - this.ending = false; // when end() has been called, and returned 66 + if (stream instanceof Duplex)
67 + this.objectMode = this.objectMode || !!options.writableObjectMode;
126 68
127 - this.ended = false; // when 'finish' is emitted 69 + // cast to ints.
70 + this.highWaterMark = ~~this.highWaterMark;
128 71
129 - this.finished = false; // has it been destroyed 72 + this.needDrain = false;
73 + // at the start of calling end()
74 + this.ending = false;
75 + // when end() has been called, and returned
76 + this.ended = false;
77 + // when 'finish' is emitted
78 + this.finished = false;
130 79
131 - this.destroyed = false; // should we decode strings into buffers before passing to _write? 80 + // should we decode strings into buffers before passing to _write?
132 // this is here so that some node-core streams can optimize string 81 // this is here so that some node-core streams can optimize string
133 // handling at a lower level. 82 // handling at a lower level.
134 -
135 var noDecode = options.decodeStrings === false; 83 var noDecode = options.decodeStrings === false;
136 - this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string 84 + this.decodeStrings = !noDecode;
85 +
86 + // Crypto is kind of old and crusty. Historically, its default string
137 // encoding is 'binary' so we have to make this configurable. 87 // encoding is 'binary' so we have to make this configurable.
138 // Everything else in the universe uses 'utf8', though. 88 // Everything else in the universe uses 'utf8', though.
89 + this.defaultEncoding = options.defaultEncoding || 'utf8';
139 90
140 - this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement 91 + // not an actual buffer we keep track of, but a measurement
141 // of how much we're waiting to get pushed to some underlying 92 // of how much we're waiting to get pushed to some underlying
142 // socket or file. 93 // socket or file.
94 + this.length = 0;
143 95
144 - this.length = 0; // a flag to see when we're in the middle of a write. 96 + // a flag to see when we're in the middle of a write.
97 + this.writing = false;
145 98
146 - this.writing = false; // when true all writes will be buffered until .uncork() call 99 + // when true all writes will be buffered until .uncork() call
100 + this.corked = 0;
147 101
148 - this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately, 102 + // a flag to be able to tell if the onwrite cb is called immediately,
149 // or on a later tick. We set this to true at first, because any 103 // or on a later tick. We set this to true at first, because any
150 // actions that shouldn't happen until "later" should generally also 104 // actions that shouldn't happen until "later" should generally also
151 // not happen before the first write call. 105 // not happen before the first write call.
106 + this.sync = true;
152 107
153 - this.sync = true; // a flag to know if we're processing previously buffered items, which 108 + // a flag to know if we're processing previously buffered items, which
154 // may call the _write() callback in the same tick, so that we don't 109 // may call the _write() callback in the same tick, so that we don't
155 // end up in an overlapped onwrite situation. 110 // end up in an overlapped onwrite situation.
111 + this.bufferProcessing = false;
156 112
157 - this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb) 113 + // the callback that's passed to _write(chunk,cb)
158 - 114 + this.onwrite = function(er) {
159 - this.onwrite = function (er) {
160 onwrite(stream, er); 115 onwrite(stream, er);
161 - }; // the callback that the user supplies to write(chunk,encoding,cb) 116 + };
162 -
163 117
164 - this.writecb = null; // the amount that is being written when _write is called. 118 + // the callback that the user supplies to write(chunk,encoding,cb)
119 + this.writecb = null;
165 120
121 + // the amount that is being written when _write is called.
166 this.writelen = 0; 122 this.writelen = 0;
167 - this.bufferedRequest = null;
168 - this.lastBufferedRequest = null; // number of pending user-supplied write callbacks
169 - // this must be 0 before 'finish' can be emitted
170 -
171 - this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs
172 - // This is relevant for synchronous Transform streams
173 -
174 - this.prefinished = false; // True if the error was already emitted and should not be thrown again
175 123
176 - this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true. 124 + this.buffer = [];
177 125
178 - this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'finish' (and potentially 'end') 126 + // number of pending user-supplied write callbacks
179 - 127 + // this must be 0 before 'finish' can be emitted
180 - this.autoDestroy = !!options.autoDestroy; // count buffered requests 128 + this.pendingcb = 0;
181 129
182 - this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always 130 + // emit prefinish if the only thing we're waiting for is _write cbs
183 - // one allocated and free to use, and we maintain at most two 131 + // This is relevant for synchronous Transform streams
132 + this.prefinished = false;
184 133
185 - this.corkedRequestsFree = new CorkedRequest(this); 134 + // True if the error was already emitted and should not be thrown again
135 + this.errorEmitted = false;
186 } 136 }
187 137
188 -WritableState.prototype.getBuffer = function getBuffer() { 138 +function Writable(options) {
189 - var current = this.bufferedRequest; 139 + var Duplex = require('./_stream_duplex');
190 - var out = [];
191 -
192 - while (current) {
193 - out.push(current);
194 - current = current.next;
195 - }
196 -
197 - return out;
198 -};
199 -
200 -(function () {
201 - try {
202 - Object.defineProperty(WritableState.prototype, 'buffer', {
203 - get: internalUtil.deprecate(function writableStateBufferGetter() {
204 - return this.getBuffer();
205 - }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
206 - });
207 - } catch (_) {}
208 -})(); // Test _writableState for inheritance to account for Duplex streams,
209 -// whose prototype chain only points to Readable.
210 -
211 140
212 -var realHasInstance; 141 + // Writable ctor is applied to Duplexes, though they're not
142 + // instanceof Writable, they're instanceof Readable.
143 + if (!(this instanceof Writable) && !(this instanceof Duplex))
144 + return new Writable(options);
213 145
214 -if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { 146 + this._writableState = new WritableState(options, this);
215 - realHasInstance = Function.prototype[Symbol.hasInstance];
216 - Object.defineProperty(Writable, Symbol.hasInstance, {
217 - value: function value(object) {
218 - if (realHasInstance.call(this, object)) return true;
219 - if (this !== Writable) return false;
220 - return object && object._writableState instanceof WritableState;
221 - }
222 - });
223 -} else {
224 - realHasInstance = function realHasInstance(object) {
225 - return object instanceof this;
226 - };
227 -}
228 -
229 -function Writable(options) {
230 - Duplex = Duplex || require('./_stream_duplex'); // Writable ctor is applied to Duplexes, too.
231 - // `realHasInstance` is necessary because using plain `instanceof`
232 - // would return false, as no `_writableState` property is attached.
233 - // Trying to use the custom `instanceof` for Writable here will also break the
234 - // Node.js LazyTransform implementation, which has a non-trivial getter for
235 - // `_writableState` that would lead to infinite recursion.
236 - // Checking for a Stream.Duplex instance is faster here instead of inside
237 - // the WritableState constructor, at least with V8 6.5
238 -
239 - var isDuplex = this instanceof Duplex;
240 - if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options);
241 - this._writableState = new WritableState(options, this, isDuplex); // legacy.
242 147
148 + // legacy.
243 this.writable = true; 149 this.writable = true;
244 150
245 - if (options) {
246 - if (typeof options.write === 'function') this._write = options.write;
247 - if (typeof options.writev === 'function') this._writev = options.writev;
248 - if (typeof options.destroy === 'function') this._destroy = options.destroy;
249 - if (typeof options.final === 'function') this._final = options.final;
250 - }
251 -
252 Stream.call(this); 151 Stream.call(this);
253 -} // Otherwise people can pipe Writable streams, which is just wrong. 152 +}
254 -
255 153
256 -Writable.prototype.pipe = function () { 154 +// Otherwise people can pipe Writable streams, which is just wrong.
257 - errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE()); 155 +Writable.prototype.pipe = function() {
156 + this.emit('error', new Error('Cannot pipe. Not readable.'));
258 }; 157 };
259 158
260 -function writeAfterEnd(stream, cb) {
261 - var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb
262 -
263 - errorOrDestroy(stream, er);
264 - process.nextTick(cb, er);
265 -} // Checks that a user-supplied chunk is valid, especially for the particular
266 -// mode the stream is in. Currently this means that `null` is never accepted
267 -// and undefined/non-string values are only allowed in object mode.
268 159
160 +function writeAfterEnd(stream, state, cb) {
161 + var er = new Error('write after end');
162 + // TODO: defer error events consistently everywhere, not just the cb
163 + stream.emit('error', er);
164 + process.nextTick(function() {
165 + cb(er);
166 + });
167 +}
269 168
169 +// If we get something that is not a buffer, string, null, or undefined,
170 +// and we're not in objectMode, then that's an error.
171 +// Otherwise stream chunks are all considered to be of length=1, and the
172 +// watermarks determine how many objects to keep in the buffer, rather than
173 +// how many bytes or characters.
270 function validChunk(stream, state, chunk, cb) { 174 function validChunk(stream, state, chunk, cb) {
271 - var er; 175 + var valid = true;
272 - 176 + if (!util.isBuffer(chunk) &&
273 - if (chunk === null) { 177 + !util.isString(chunk) &&
274 - er = new ERR_STREAM_NULL_VALUES(); 178 + !util.isNullOrUndefined(chunk) &&
275 - } else if (typeof chunk !== 'string' && !state.objectMode) { 179 + !state.objectMode) {
276 - er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk); 180 + var er = new TypeError('Invalid non-string/buffer chunk');
277 - } 181 + stream.emit('error', er);
278 - 182 + process.nextTick(function() {
279 - if (er) { 183 + cb(er);
280 - errorOrDestroy(stream, er); 184 + });
281 - process.nextTick(cb, er); 185 + valid = false;
282 - return false;
283 } 186 }
284 - 187 + return valid;
285 - return true;
286 } 188 }
287 189
288 -Writable.prototype.write = function (chunk, encoding, cb) { 190 +Writable.prototype.write = function(chunk, encoding, cb) {
289 var state = this._writableState; 191 var state = this._writableState;
290 var ret = false; 192 var ret = false;
291 193
292 - var isBuf = !state.objectMode && _isUint8Array(chunk); 194 + if (util.isFunction(encoding)) {
293 -
294 - if (isBuf && !Buffer.isBuffer(chunk)) {
295 - chunk = _uint8ArrayToBuffer(chunk);
296 - }
297 -
298 - if (typeof encoding === 'function') {
299 cb = encoding; 195 cb = encoding;
300 encoding = null; 196 encoding = null;
301 } 197 }
302 198
303 - if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; 199 + if (util.isBuffer(chunk))
304 - if (typeof cb !== 'function') cb = nop; 200 + encoding = 'buffer';
305 - if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { 201 + else if (!encoding)
202 + encoding = state.defaultEncoding;
203 +
204 + if (!util.isFunction(cb))
205 + cb = function() {};
206 +
207 + if (state.ended)
208 + writeAfterEnd(this, state, cb);
209 + else if (validChunk(this, state, chunk, cb)) {
306 state.pendingcb++; 210 state.pendingcb++;
307 - ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); 211 + ret = writeOrBuffer(this, state, chunk, encoding, cb);
308 } 212 }
213 +
309 return ret; 214 return ret;
310 }; 215 };
311 216
312 -Writable.prototype.cork = function () { 217 +Writable.prototype.cork = function() {
313 - this._writableState.corked++; 218 + var state = this._writableState;
219 +
220 + state.corked++;
314 }; 221 };
315 222
316 -Writable.prototype.uncork = function () { 223 +Writable.prototype.uncork = function() {
317 var state = this._writableState; 224 var state = this._writableState;
318 225
319 if (state.corked) { 226 if (state.corked) {
320 state.corked--; 227 state.corked--;
321 - if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
322 - }
323 -};
324 228
325 -Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { 229 + if (!state.writing &&
326 - // node::ParseEncoding() requires lower case. 230 + !state.corked &&
327 - if (typeof encoding === 'string') encoding = encoding.toLowerCase(); 231 + !state.finished &&
328 - if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding); 232 + !state.bufferProcessing &&
329 - this._writableState.defaultEncoding = encoding; 233 + state.buffer.length)
330 - return this; 234 + clearBuffer(this, state);
331 -};
332 -
333 -Object.defineProperty(Writable.prototype, 'writableBuffer', {
334 - // making it explicit this property is not enumerable
335 - // because otherwise some prototype manipulation in
336 - // userland will fail
337 - enumerable: false,
338 - get: function get() {
339 - return this._writableState && this._writableState.getBuffer();
340 } 235 }
341 -}); 236 +};
342 237
343 function decodeChunk(state, chunk, encoding) { 238 function decodeChunk(state, chunk, encoding) {
344 - if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { 239 + if (!state.objectMode &&
345 - chunk = Buffer.from(chunk, encoding); 240 + state.decodeStrings !== false &&
241 + util.isString(chunk)) {
242 + chunk = new Buffer(chunk, encoding);
346 } 243 }
347 -
348 return chunk; 244 return chunk;
349 } 245 }
350 246
351 -Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { 247 +// if we're already writing something, then just put this
352 - // making it explicit this property is not enumerable
353 - // because otherwise some prototype manipulation in
354 - // userland will fail
355 - enumerable: false,
356 - get: function get() {
357 - return this._writableState.highWaterMark;
358 - }
359 -}); // if we're already writing something, then just put this
360 // in the queue, and wait our turn. Otherwise, call _write 248 // in the queue, and wait our turn. Otherwise, call _write
361 // If we return false, then we need a drain event, so set that flag. 249 // If we return false, then we need a drain event, so set that flag.
362 - 250 +function writeOrBuffer(stream, state, chunk, encoding, cb) {
363 -function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { 251 + chunk = decodeChunk(state, chunk, encoding);
364 - if (!isBuf) { 252 + if (util.isBuffer(chunk))
365 - var newChunk = decodeChunk(state, chunk, encoding); 253 + encoding = 'buffer';
366 -
367 - if (chunk !== newChunk) {
368 - isBuf = true;
369 - encoding = 'buffer';
370 - chunk = newChunk;
371 - }
372 - }
373 -
374 var len = state.objectMode ? 1 : chunk.length; 254 var len = state.objectMode ? 1 : chunk.length;
255 +
375 state.length += len; 256 state.length += len;
376 - var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false.
377 -
378 - if (!ret) state.needDrain = true;
379 -
380 - if (state.writing || state.corked) {
381 - var last = state.lastBufferedRequest;
382 - state.lastBufferedRequest = {
383 - chunk: chunk,
384 - encoding: encoding,
385 - isBuf: isBuf,
386 - callback: cb,
387 - next: null
388 - };
389 -
390 - if (last) {
391 - last.next = state.lastBufferedRequest;
392 - } else {
393 - state.bufferedRequest = state.lastBufferedRequest;
394 - }
395 257
396 - state.bufferedRequestCount += 1; 258 + var ret = state.length < state.highWaterMark;
397 - } else { 259 + // we must ensure that previous needDrain will not be reset to false.
260 + if (!ret)
261 + state.needDrain = true;
262 +
263 + if (state.writing || state.corked)
264 + state.buffer.push(new WriteReq(chunk, encoding, cb));
265 + else
398 doWrite(stream, state, false, len, chunk, encoding, cb); 266 doWrite(stream, state, false, len, chunk, encoding, cb);
399 - }
400 267
401 return ret; 268 return ret;
402 } 269 }
...@@ -406,32 +273,26 @@ function doWrite(stream, state, writev, len, chunk, encoding, cb) { ...@@ -406,32 +273,26 @@ function doWrite(stream, state, writev, len, chunk, encoding, cb) {
406 state.writecb = cb; 273 state.writecb = cb;
407 state.writing = true; 274 state.writing = true;
408 state.sync = true; 275 state.sync = true;
409 - if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); 276 + if (writev)
277 + stream._writev(chunk, state.onwrite);
278 + else
279 + stream._write(chunk, encoding, state.onwrite);
410 state.sync = false; 280 state.sync = false;
411 } 281 }
412 282
413 function onwriteError(stream, state, sync, er, cb) { 283 function onwriteError(stream, state, sync, er, cb) {
414 - --state.pendingcb; 284 + if (sync)
415 - 285 + process.nextTick(function() {
416 - if (sync) { 286 + state.pendingcb--;
417 - // defer the callback if we are being called synchronously 287 + cb(er);
418 - // to avoid piling up things on the stack 288 + });
419 - process.nextTick(cb, er); // this can emit finish, and it will always happen 289 + else {
420 - // after error 290 + state.pendingcb--;
421 -
422 - process.nextTick(finishMaybe, stream, state);
423 - stream._writableState.errorEmitted = true;
424 - errorOrDestroy(stream, er);
425 - } else {
426 - // the caller expect this to happen before if
427 - // it is async
428 cb(er); 291 cb(er);
429 - stream._writableState.errorEmitted = true;
430 - errorOrDestroy(stream, er); // this can emit finish, but finish must
431 - // always follow error
432 -
433 - finishMaybe(stream, state);
434 } 292 }
293 +
294 + stream._writableState.errorEmitted = true;
295 + stream.emit('error', er);
435 } 296 }
436 297
437 function onwriteStateUpdate(state) { 298 function onwriteStateUpdate(state) {
...@@ -445,18 +306,26 @@ function onwrite(stream, er) { ...@@ -445,18 +306,26 @@ function onwrite(stream, er) {
445 var state = stream._writableState; 306 var state = stream._writableState;
446 var sync = state.sync; 307 var sync = state.sync;
447 var cb = state.writecb; 308 var cb = state.writecb;
448 - if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK(); 309 +
449 onwriteStateUpdate(state); 310 onwriteStateUpdate(state);
450 - if (er) onwriteError(stream, state, sync, er, cb);else { 311 +
312 + if (er)
313 + onwriteError(stream, state, sync, er, cb);
314 + else {
451 // Check if we're actually ready to finish, but don't emit yet 315 // Check if we're actually ready to finish, but don't emit yet
452 - var finished = needFinish(state) || stream.destroyed; 316 + var finished = needFinish(stream, state);
453 317
454 - if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { 318 + if (!finished &&
319 + !state.corked &&
320 + !state.bufferProcessing &&
321 + state.buffer.length) {
455 clearBuffer(stream, state); 322 clearBuffer(stream, state);
456 } 323 }
457 324
458 if (sync) { 325 if (sync) {
459 - process.nextTick(afterWrite, stream, state, finished, cb); 326 + process.nextTick(function() {
327 + afterWrite(stream, state, finished, cb);
328 + });
460 } else { 329 } else {
461 afterWrite(stream, state, finished, cb); 330 afterWrite(stream, state, finished, cb);
462 } 331 }
...@@ -464,234 +333,145 @@ function onwrite(stream, er) { ...@@ -464,234 +333,145 @@ function onwrite(stream, er) {
464 } 333 }
465 334
466 function afterWrite(stream, state, finished, cb) { 335 function afterWrite(stream, state, finished, cb) {
467 - if (!finished) onwriteDrain(stream, state); 336 + if (!finished)
337 + onwriteDrain(stream, state);
468 state.pendingcb--; 338 state.pendingcb--;
469 cb(); 339 cb();
470 finishMaybe(stream, state); 340 finishMaybe(stream, state);
471 -} // Must force callback to be called on nextTick, so that we don't 341 +}
342 +
343 +// Must force callback to be called on nextTick, so that we don't
472 // emit 'drain' before the write() consumer gets the 'false' return 344 // emit 'drain' before the write() consumer gets the 'false' return
473 // value, and has a chance to attach a 'drain' listener. 345 // value, and has a chance to attach a 'drain' listener.
474 -
475 -
476 function onwriteDrain(stream, state) { 346 function onwriteDrain(stream, state) {
477 if (state.length === 0 && state.needDrain) { 347 if (state.length === 0 && state.needDrain) {
478 state.needDrain = false; 348 state.needDrain = false;
479 stream.emit('drain'); 349 stream.emit('drain');
480 } 350 }
481 -} // if there's something in the buffer waiting, then process it 351 +}
482 352
483 353
354 +// if there's something in the buffer waiting, then process it
484 function clearBuffer(stream, state) { 355 function clearBuffer(stream, state) {
485 state.bufferProcessing = true; 356 state.bufferProcessing = true;
486 - var entry = state.bufferedRequest;
487 357
488 - if (stream._writev && entry && entry.next) { 358 + if (stream._writev && state.buffer.length > 1) {
489 // Fast case, write everything using _writev() 359 // Fast case, write everything using _writev()
490 - var l = state.bufferedRequestCount; 360 + var cbs = [];
491 - var buffer = new Array(l); 361 + for (var c = 0; c < state.buffer.length; c++)
492 - var holder = state.corkedRequestsFree; 362 + cbs.push(state.buffer[c].callback);
493 - holder.entry = entry;
494 - var count = 0;
495 - var allBuffers = true;
496 -
497 - while (entry) {
498 - buffer[count] = entry;
499 - if (!entry.isBuf) allBuffers = false;
500 - entry = entry.next;
501 - count += 1;
502 - }
503 -
504 - buffer.allBuffers = allBuffers;
505 - doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time
506 - // as the hot path ends with doWrite
507 363
364 + // count the one we are adding, as well.
365 + // TODO(isaacs) clean this up
508 state.pendingcb++; 366 state.pendingcb++;
509 - state.lastBufferedRequest = null; 367 + doWrite(stream, state, true, state.length, state.buffer, '', function(err) {
510 - 368 + for (var i = 0; i < cbs.length; i++) {
511 - if (holder.next) { 369 + state.pendingcb--;
512 - state.corkedRequestsFree = holder.next; 370 + cbs[i](err);
513 - holder.next = null; 371 + }
514 - } else { 372 + });
515 - state.corkedRequestsFree = new CorkedRequest(state);
516 - }
517 373
518 - state.bufferedRequestCount = 0; 374 + // Clear buffer
375 + state.buffer = [];
519 } else { 376 } else {
520 // Slow case, write chunks one-by-one 377 // Slow case, write chunks one-by-one
521 - while (entry) { 378 + for (var c = 0; c < state.buffer.length; c++) {
379 + var entry = state.buffer[c];
522 var chunk = entry.chunk; 380 var chunk = entry.chunk;
523 var encoding = entry.encoding; 381 var encoding = entry.encoding;
524 var cb = entry.callback; 382 var cb = entry.callback;
525 var len = state.objectMode ? 1 : chunk.length; 383 var len = state.objectMode ? 1 : chunk.length;
384 +
526 doWrite(stream, state, false, len, chunk, encoding, cb); 385 doWrite(stream, state, false, len, chunk, encoding, cb);
527 - entry = entry.next; 386 +
528 - state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then 387 + // if we didn't call the onwrite immediately, then
529 // it means that we need to wait until it does. 388 // it means that we need to wait until it does.
530 // also, that means that the chunk and cb are currently 389 // also, that means that the chunk and cb are currently
531 // being processed, so move the buffer counter past them. 390 // being processed, so move the buffer counter past them.
532 -
533 if (state.writing) { 391 if (state.writing) {
392 + c++;
534 break; 393 break;
535 } 394 }
536 } 395 }
537 396
538 - if (entry === null) state.lastBufferedRequest = null; 397 + if (c < state.buffer.length)
398 + state.buffer = state.buffer.slice(c);
399 + else
400 + state.buffer.length = 0;
539 } 401 }
540 402
541 - state.bufferedRequest = entry;
542 state.bufferProcessing = false; 403 state.bufferProcessing = false;
543 } 404 }
544 405
545 -Writable.prototype._write = function (chunk, encoding, cb) { 406 +Writable.prototype._write = function(chunk, encoding, cb) {
546 - cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()')); 407 + cb(new Error('not implemented'));
408 +
547 }; 409 };
548 410
549 Writable.prototype._writev = null; 411 Writable.prototype._writev = null;
550 412
551 -Writable.prototype.end = function (chunk, encoding, cb) { 413 +Writable.prototype.end = function(chunk, encoding, cb) {
552 var state = this._writableState; 414 var state = this._writableState;
553 415
554 - if (typeof chunk === 'function') { 416 + if (util.isFunction(chunk)) {
555 cb = chunk; 417 cb = chunk;
556 chunk = null; 418 chunk = null;
557 encoding = null; 419 encoding = null;
558 - } else if (typeof encoding === 'function') { 420 + } else if (util.isFunction(encoding)) {
559 cb = encoding; 421 cb = encoding;
560 encoding = null; 422 encoding = null;
561 } 423 }
562 424
563 - if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks 425 + if (!util.isNullOrUndefined(chunk))
426 + this.write(chunk, encoding);
564 427
428 + // .end() fully uncorks
565 if (state.corked) { 429 if (state.corked) {
566 state.corked = 1; 430 state.corked = 1;
567 this.uncork(); 431 this.uncork();
568 - } // ignore unnecessary end() calls. 432 + }
569 -
570 433
571 - if (!state.ending) endWritable(this, state, cb); 434 + // ignore unnecessary end() calls.
572 - return this; 435 + if (!state.ending && !state.finished)
436 + endWritable(this, state, cb);
573 }; 437 };
574 438
575 -Object.defineProperty(Writable.prototype, 'writableLength', {
576 - // making it explicit this property is not enumerable
577 - // because otherwise some prototype manipulation in
578 - // userland will fail
579 - enumerable: false,
580 - get: function get() {
581 - return this._writableState.length;
582 - }
583 -});
584 439
585 -function needFinish(state) { 440 +function needFinish(stream, state) {
586 - return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; 441 + return (state.ending &&
442 + state.length === 0 &&
443 + !state.finished &&
444 + !state.writing);
587 } 445 }
588 446
589 -function callFinal(stream, state) { 447 +function prefinish(stream, state) {
590 - stream._final(function (err) { 448 + if (!state.prefinished) {
591 - state.pendingcb--;
592 -
593 - if (err) {
594 - errorOrDestroy(stream, err);
595 - }
596 -
597 state.prefinished = true; 449 state.prefinished = true;
598 stream.emit('prefinish'); 450 stream.emit('prefinish');
599 - finishMaybe(stream, state);
600 - });
601 -}
602 -
603 -function prefinish(stream, state) {
604 - if (!state.prefinished && !state.finalCalled) {
605 - if (typeof stream._final === 'function' && !state.destroyed) {
606 - state.pendingcb++;
607 - state.finalCalled = true;
608 - process.nextTick(callFinal, stream, state);
609 - } else {
610 - state.prefinished = true;
611 - stream.emit('prefinish');
612 - }
613 } 451 }
614 } 452 }
615 453
616 function finishMaybe(stream, state) { 454 function finishMaybe(stream, state) {
617 - var need = needFinish(state); 455 + var need = needFinish(stream, state);
618 -
619 if (need) { 456 if (need) {
620 - prefinish(stream, state);
621 -
622 if (state.pendingcb === 0) { 457 if (state.pendingcb === 0) {
458 + prefinish(stream, state);
623 state.finished = true; 459 state.finished = true;
624 stream.emit('finish'); 460 stream.emit('finish');
625 - 461 + } else
626 - if (state.autoDestroy) { 462 + prefinish(stream, state);
627 - // In case of duplex streams we need a way to detect
628 - // if the readable side is ready for autoDestroy as well
629 - var rState = stream._readableState;
630 -
631 - if (!rState || rState.autoDestroy && rState.endEmitted) {
632 - stream.destroy();
633 - }
634 - }
635 - }
636 } 463 }
637 -
638 return need; 464 return need;
639 } 465 }
640 466
641 function endWritable(stream, state, cb) { 467 function endWritable(stream, state, cb) {
642 state.ending = true; 468 state.ending = true;
643 finishMaybe(stream, state); 469 finishMaybe(stream, state);
644 -
645 if (cb) { 470 if (cb) {
646 - if (state.finished) process.nextTick(cb);else stream.once('finish', cb); 471 + if (state.finished)
472 + process.nextTick(cb);
473 + else
474 + stream.once('finish', cb);
647 } 475 }
648 -
649 state.ended = true; 476 state.ended = true;
650 - stream.writable = false;
651 -}
652 -
653 -function onCorkedFinish(corkReq, state, err) {
654 - var entry = corkReq.entry;
655 - corkReq.entry = null;
656 -
657 - while (entry) {
658 - var cb = entry.callback;
659 - state.pendingcb--;
660 - cb(err);
661 - entry = entry.next;
662 - } // reuse the free corkReq.
663 -
664 -
665 - state.corkedRequestsFree.next = corkReq;
666 } 477 }
667 -
668 -Object.defineProperty(Writable.prototype, 'destroyed', {
669 - // making it explicit this property is not enumerable
670 - // because otherwise some prototype manipulation in
671 - // userland will fail
672 - enumerable: false,
673 - get: function get() {
674 - if (this._writableState === undefined) {
675 - return false;
676 - }
677 -
678 - return this._writableState.destroyed;
679 - },
680 - set: function set(value) {
681 - // we ignore the value if the stream
682 - // has not been initialized yet
683 - if (!this._writableState) {
684 - return;
685 - } // backward compatibility, the user is explicitly
686 - // managing destroyed
687 -
688 -
689 - this._writableState.destroyed = value;
690 - }
691 -});
692 -Writable.prototype.destroy = destroyImpl.destroy;
693 -Writable.prototype._undestroy = destroyImpl.undestroy;
694 -
695 -Writable.prototype._destroy = function (err, cb) {
696 - cb(err);
697 -};
...\ No newline at end of file ...\ No newline at end of file
......
1 { 1 {
2 - "_from": "readable-stream@^3.1.1", 2 + "_from": "readable-stream@1.1.x",
3 - "_id": "readable-stream@3.6.0", 3 + "_id": "readable-stream@1.1.14",
4 "_inBundle": false, 4 "_inBundle": false,
5 - "_integrity": "sha512-BViHy7LKeTz4oNnkcLJ+lVSL6vpiFeX6/d3oSH8zCW7UxP2onchk+vTGB143xuFjHS3deTgkKoXXymXqymiIdA==", 5 + "_integrity": "sha1-fPTFTvZI44EwhMY23SB54WbAgdk=",
6 "_location": "/readable-stream", 6 "_location": "/readable-stream",
7 "_phantomChildren": {}, 7 "_phantomChildren": {},
8 "_requested": { 8 "_requested": {
9 "type": "range", 9 "type": "range",
10 "registry": true, 10 "registry": true,
11 - "raw": "readable-stream@^3.1.1", 11 + "raw": "readable-stream@1.1.x",
12 "name": "readable-stream", 12 "name": "readable-stream",
13 "escapedName": "readable-stream", 13 "escapedName": "readable-stream",
14 - "rawSpec": "^3.1.1", 14 + "rawSpec": "1.1.x",
15 "saveSpec": null, 15 "saveSpec": null,
16 - "fetchSpec": "^3.1.1" 16 + "fetchSpec": "1.1.x"
17 }, 17 },
18 "_requiredBy": [ 18 "_requiredBy": [
19 - "/duplexify" 19 + "/busboy",
20 + "/dicer"
20 ], 21 ],
21 - "_resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.0.tgz", 22 + "_resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-1.1.14.tgz",
22 - "_shasum": "337bbda3adc0706bd3e024426a286d4b4b2c9198", 23 + "_shasum": "7cf4c54ef648e3813084c636dd2079e166c081d9",
23 - "_spec": "readable-stream@^3.1.1", 24 + "_spec": "readable-stream@1.1.x",
24 - "_where": "C:\\Users\\1000c\\이것저것\\옾소\\Voicoding\\node_modules\\duplexify", 25 + "_where": "C:\\Users\\1000c\\이것저것\\옾소\\Voicoding\\node_modules\\busboy",
26 + "author": {
27 + "name": "Isaac Z. Schlueter",
28 + "email": "i@izs.me",
29 + "url": "http://blog.izs.me/"
30 + },
25 "browser": { 31 "browser": {
26 - "util": false, 32 + "util": false
27 - "worker_threads": false,
28 - "./errors": "./errors-browser.js",
29 - "./readable.js": "./readable-browser.js",
30 - "./lib/internal/streams/from.js": "./lib/internal/streams/from-browser.js",
31 - "./lib/internal/streams/stream.js": "./lib/internal/streams/stream-browser.js"
32 }, 33 },
33 "bugs": { 34 "bugs": {
34 - "url": "https://github.com/nodejs/readable-stream/issues" 35 + "url": "https://github.com/isaacs/readable-stream/issues"
35 }, 36 },
36 "bundleDependencies": false, 37 "bundleDependencies": false,
37 "dependencies": { 38 "dependencies": {
38 - "inherits": "^2.0.3", 39 + "core-util-is": "~1.0.0",
39 - "string_decoder": "^1.1.1", 40 + "inherits": "~2.0.1",
40 - "util-deprecate": "^1.0.1" 41 + "isarray": "0.0.1",
42 + "string_decoder": "~0.10.x"
41 }, 43 },
42 "deprecated": false, 44 "deprecated": false,
43 - "description": "Streams3, a user-land copy of the stream library from Node.js", 45 + "description": "Streams3, a user-land copy of the stream library from Node.js v0.11.x",
44 "devDependencies": { 46 "devDependencies": {
45 - "@babel/cli": "^7.2.0", 47 + "tap": "~0.2.6"
46 - "@babel/core": "^7.2.0",
47 - "@babel/polyfill": "^7.0.0",
48 - "@babel/preset-env": "^7.2.0",
49 - "airtap": "0.0.9",
50 - "assert": "^1.4.0",
51 - "bl": "^2.0.0",
52 - "deep-strict-equal": "^0.2.0",
53 - "events.once": "^2.0.2",
54 - "glob": "^7.1.2",
55 - "gunzip-maybe": "^1.4.1",
56 - "hyperquest": "^2.1.3",
57 - "lolex": "^2.6.0",
58 - "nyc": "^11.0.0",
59 - "pump": "^3.0.0",
60 - "rimraf": "^2.6.2",
61 - "tap": "^12.0.0",
62 - "tape": "^4.9.0",
63 - "tar-fs": "^1.16.2",
64 - "util-promisify": "^2.1.0"
65 - },
66 - "engines": {
67 - "node": ">= 6"
68 }, 48 },
69 - "homepage": "https://github.com/nodejs/readable-stream#readme", 49 + "homepage": "https://github.com/isaacs/readable-stream#readme",
70 "keywords": [ 50 "keywords": [
71 "readable", 51 "readable",
72 "stream", 52 "stream",
...@@ -75,23 +55,12 @@ ...@@ -75,23 +55,12 @@
75 "license": "MIT", 55 "license": "MIT",
76 "main": "readable.js", 56 "main": "readable.js",
77 "name": "readable-stream", 57 "name": "readable-stream",
78 - "nyc": {
79 - "include": [
80 - "lib/**.js"
81 - ]
82 - },
83 "repository": { 58 "repository": {
84 "type": "git", 59 "type": "git",
85 - "url": "git://github.com/nodejs/readable-stream.git" 60 + "url": "git://github.com/isaacs/readable-stream.git"
86 }, 61 },
87 "scripts": { 62 "scripts": {
88 - "ci": "TAP=1 tap --no-esm test/parallel/*.js test/ours/*.js | tee test.tap", 63 + "test": "tap test/simple/*.js"
89 - "cover": "nyc npm test",
90 - "report": "nyc report --reporter=lcov",
91 - "test": "tap -J --no-esm test/parallel/*.js test/ours/*.js",
92 - "test-browser-local": "airtap --open --local -- test/browser.js",
93 - "test-browsers": "airtap --sauce-connect --loopback airtap.local -- test/browser.js",
94 - "update-browser-errors": "babel -o errors-browser.js errors.js"
95 }, 64 },
96 - "version": "3.6.0" 65 + "version": "1.1.14"
97 } 66 }
......
1 +module.exports = require("./lib/_stream_passthrough.js")
1 -var Stream = require('stream'); 1 +exports = module.exports = require('./lib/_stream_readable.js');
2 -if (process.env.READABLE_STREAM === 'disable' && Stream) { 2 +exports.Stream = require('stream');
3 - module.exports = Stream.Readable; 3 +exports.Readable = exports;
4 - Object.assign(module.exports, Stream); 4 +exports.Writable = require('./lib/_stream_writable.js');
5 - module.exports.Stream = Stream; 5 +exports.Duplex = require('./lib/_stream_duplex.js');
6 -} else { 6 +exports.Transform = require('./lib/_stream_transform.js');
7 - exports = module.exports = require('./lib/_stream_readable.js'); 7 +exports.PassThrough = require('./lib/_stream_passthrough.js');
8 - exports.Stream = Stream || exports; 8 +if (!process.browser && process.env.READABLE_STREAM === 'disable') {
9 - exports.Readable = exports; 9 + module.exports = require('stream');
10 - exports.Writable = require('./lib/_stream_writable.js');
11 - exports.Duplex = require('./lib/_stream_duplex.js');
12 - exports.Transform = require('./lib/_stream_transform.js');
13 - exports.PassThrough = require('./lib/_stream_passthrough.js');
14 - exports.finished = require('./lib/internal/streams/end-of-stream.js');
15 - exports.pipeline = require('./lib/internal/streams/pipeline.js');
16 } 10 }
......
1 +module.exports = require("./lib/_stream_transform.js")
1 +module.exports = require("./lib/_stream_writable.js")
1 -/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
2 /* eslint-disable node/no-deprecated-api */ 1 /* eslint-disable node/no-deprecated-api */
3 var buffer = require('buffer') 2 var buffer = require('buffer')
4 var Buffer = buffer.Buffer 3 var Buffer = buffer.Buffer
...@@ -21,8 +20,6 @@ function SafeBuffer (arg, encodingOrOffset, length) { ...@@ -21,8 +20,6 @@ function SafeBuffer (arg, encodingOrOffset, length) {
21 return Buffer(arg, encodingOrOffset, length) 20 return Buffer(arg, encodingOrOffset, length)
22 } 21 }
23 22
24 -SafeBuffer.prototype = Object.create(Buffer.prototype)
25 -
26 // Copy static methods from Buffer 23 // Copy static methods from Buffer
27 copyProps(Buffer, SafeBuffer) 24 copyProps(Buffer, SafeBuffer)
28 25
......
1 { 1 {
2 - "_from": "safe-buffer@~5.2.0", 2 + "_from": "safe-buffer@~5.1.1",
3 - "_id": "safe-buffer@5.2.1", 3 + "_id": "safe-buffer@5.1.2",
4 "_inBundle": false, 4 "_inBundle": false,
5 - "_integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", 5 + "_integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==",
6 "_location": "/safe-buffer", 6 "_location": "/safe-buffer",
7 "_phantomChildren": {}, 7 "_phantomChildren": {},
8 "_requested": { 8 "_requested": {
9 "type": "range", 9 "type": "range",
10 "registry": true, 10 "registry": true,
11 - "raw": "safe-buffer@~5.2.0", 11 + "raw": "safe-buffer@~5.1.1",
12 "name": "safe-buffer", 12 "name": "safe-buffer",
13 "escapedName": "safe-buffer", 13 "escapedName": "safe-buffer",
14 - "rawSpec": "~5.2.0", 14 + "rawSpec": "~5.1.1",
15 "saveSpec": null, 15 "saveSpec": null,
16 - "fetchSpec": "~5.2.0" 16 + "fetchSpec": "~5.1.1"
17 }, 17 },
18 "_requiredBy": [ 18 "_requiredBy": [
19 - "/ecdsa-sig-formatter", 19 + "/concat-stream/readable-stream",
20 - "/jwa", 20 + "/concat-stream/string_decoder"
21 - "/jws",
22 - "/string_decoder"
23 ], 21 ],
24 - "_resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", 22 + "_resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz",
25 - "_shasum": "1eaf9fa9bdb1fdd4ec75f58f9cdb4e6b7827eec6", 23 + "_shasum": "991ec69d296e0313747d59bdfd2b745c35f8828d",
26 - "_spec": "safe-buffer@~5.2.0", 24 + "_spec": "safe-buffer@~5.1.1",
27 - "_where": "C:\\Users\\1000c\\이것저것\\옾소\\Voicoding\\node_modules\\string_decoder", 25 + "_where": "C:\\Users\\1000c\\이것저것\\옾소\\Voicoding\\node_modules\\concat-stream\\node_modules\\readable-stream",
28 "author": { 26 "author": {
29 "name": "Feross Aboukhadijeh", 27 "name": "Feross Aboukhadijeh",
30 "email": "feross@feross.org", 28 "email": "feross@feross.org",
31 - "url": "https://feross.org" 29 + "url": "http://feross.org"
32 }, 30 },
33 "bugs": { 31 "bugs": {
34 "url": "https://github.com/feross/safe-buffer/issues" 32 "url": "https://github.com/feross/safe-buffer/issues"
...@@ -38,22 +36,8 @@ ...@@ -38,22 +36,8 @@
38 "description": "Safer Node.js Buffer API", 36 "description": "Safer Node.js Buffer API",
39 "devDependencies": { 37 "devDependencies": {
40 "standard": "*", 38 "standard": "*",
41 - "tape": "^5.0.0" 39 + "tape": "^4.0.0"
42 }, 40 },
43 - "funding": [
44 - {
45 - "type": "github",
46 - "url": "https://github.com/sponsors/feross"
47 - },
48 - {
49 - "type": "patreon",
50 - "url": "https://www.patreon.com/feross"
51 - },
52 - {
53 - "type": "consulting",
54 - "url": "https://feross.org/support"
55 - }
56 - ],
57 "homepage": "https://github.com/feross/safe-buffer", 41 "homepage": "https://github.com/feross/safe-buffer",
58 "keywords": [ 42 "keywords": [
59 "buffer", 43 "buffer",
...@@ -75,5 +59,5 @@ ...@@ -75,5 +59,5 @@
75 "test": "standard && tape test/*.js" 59 "test": "standard && tape test/*.js"
76 }, 60 },
77 "types": "index.d.ts", 61 "types": "index.d.ts",
78 - "version": "5.2.1" 62 + "version": "5.1.2"
79 } 63 }
......
1 +Copyright Brian White. All rights reserved.
2 +
3 +Permission is hereby granted, free of charge, to any person obtaining a copy
4 +of this software and associated documentation files (the "Software"), to
5 +deal in the Software without restriction, including without limitation the
6 +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
7 +sell copies of the Software, and to permit persons to whom the Software is
8 +furnished to do so, subject to the following conditions:
9 +
10 +The above copyright notice and this permission notice shall be included in
11 +all copies or substantial portions of the Software.
12 +
13 +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
18 +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
19 +IN THE SOFTWARE.
...\ No newline at end of file ...\ No newline at end of file
1 +Description
2 +===========
3 +
4 +streamsearch is a module for [node.js](http://nodejs.org/) that allows searching a stream using the Boyer-Moore-Horspool algorithm.
5 +
6 +This module is based heavily on the Streaming Boyer-Moore-Horspool C++ implementation by Hongli Lai [here](https://github.com/FooBarWidget/boyer-moore-horspool).
7 +
8 +
9 +Requirements
10 +============
11 +
12 +* [node.js](http://nodejs.org/) -- v0.8.0 or newer
13 +
14 +
15 +Installation
16 +============
17 +
18 + npm install streamsearch
19 +
20 +Example
21 +=======
22 +
23 +```javascript
24 + var StreamSearch = require('streamsearch'),
25 + inspect = require('util').inspect;
26 +
27 + var needle = new Buffer([13, 10]), // CRLF
28 + s = new StreamSearch(needle),
29 + chunks = [
30 + new Buffer('foo'),
31 + new Buffer(' bar'),
32 + new Buffer('\r'),
33 + new Buffer('\n'),
34 + new Buffer('baz, hello\r'),
35 + new Buffer('\n world.'),
36 + new Buffer('\r\n Node.JS rules!!\r\n\r\n')
37 + ];
38 + s.on('info', function(isMatch, data, start, end) {
39 + if (data)
40 + console.log('data: ' + inspect(data.toString('ascii', start, end)));
41 + if (isMatch)
42 + console.log('match!');
43 + });
44 + for (var i = 0, len = chunks.length; i < len; ++i)
45 + s.push(chunks[i]);
46 +
47 + // output:
48 + //
49 + // data: 'foo'
50 + // data: ' bar'
51 + // match!
52 + // data: 'baz, hello'
53 + // match!
54 + // data: ' world.'
55 + // match!
56 + // data: ' Node.JS rules!!'
57 + // match!
58 + // data: ''
59 + // match!
60 +```
61 +
62 +
63 +API
64 +===
65 +
66 +Events
67 +------
68 +
69 +* **info**(< _boolean_ >isMatch[, < _Buffer_ >chunk, < _integer_ >start, < _integer_ >end]) - A match _may_ or _may not_ have been made. In either case, a preceding `chunk` of data _may_ be available that did not match the needle. Data (if available) is in `chunk` between `start` (inclusive) and `end` (exclusive).
70 +
71 +
72 +Properties
73 +----------
74 +
75 +* **maxMatches** - < _integer_ > - The maximum number of matches. Defaults to Infinity.
76 +
77 +* **matches** - < _integer_ > - The current match count.
78 +
79 +
80 +Functions
81 +---------
82 +
83 +* **(constructor)**(< _mixed_ >needle) - Creates and returns a new instance for searching for a _Buffer_ or _string_ `needle`.
84 +
85 +* **push**(< _Buffer_ >chunk) - _integer_ - Processes `chunk`. The return value is the last processed index in `chunk` + 1.
86 +
87 +* **reset**() - _(void)_ - Resets internal state. Useful for when you wish to start searching a new/different stream for example.
1 +/*
2 + Based heavily on the Streaming Boyer-Moore-Horspool C++ implementation
3 + by Hongli Lai at: https://github.com/FooBarWidget/boyer-moore-horspool
4 +*/
5 +var EventEmitter = require('events').EventEmitter,
6 + inherits = require('util').inherits;
7 +
8 +function jsmemcmp(buf1, pos1, buf2, pos2, num) {
9 + for (var i = 0; i < num; ++i, ++pos1, ++pos2)
10 + if (buf1[pos1] !== buf2[pos2])
11 + return false;
12 + return true;
13 +}
14 +
15 +function SBMH(needle) {
16 + if (typeof needle === 'string')
17 + needle = new Buffer(needle);
18 + var i, j, needle_len = needle.length;
19 +
20 + this.maxMatches = Infinity;
21 + this.matches = 0;
22 +
23 + this._occ = new Array(256);
24 + this._lookbehind_size = 0;
25 + this._needle = needle;
26 + this._bufpos = 0;
27 +
28 + this._lookbehind = new Buffer(needle_len);
29 +
30 + // Initialize occurrence table.
31 + for (j = 0; j < 256; ++j)
32 + this._occ[j] = needle_len;
33 +
34 + // Populate occurrence table with analysis of the needle,
35 + // ignoring last letter.
36 + if (needle_len >= 1) {
37 + for (i = 0; i < needle_len - 1; ++i)
38 + this._occ[needle[i]] = needle_len - 1 - i;
39 + }
40 +}
41 +inherits(SBMH, EventEmitter);
42 +
43 +SBMH.prototype.reset = function() {
44 + this._lookbehind_size = 0;
45 + this.matches = 0;
46 + this._bufpos = 0;
47 +};
48 +
49 +SBMH.prototype.push = function(chunk, pos) {
50 + var r, chlen;
51 + if (!Buffer.isBuffer(chunk))
52 + chunk = new Buffer(chunk, 'binary');
53 + chlen = chunk.length;
54 + this._bufpos = pos || 0;
55 + while (r !== chlen && this.matches < this.maxMatches)
56 + r = this._sbmh_feed(chunk);
57 + return r;
58 +};
59 +
60 +SBMH.prototype._sbmh_feed = function(data) {
61 + var len = data.length, needle = this._needle, needle_len = needle.length;
62 +
63 + // Positive: points to a position in `data`
64 + // pos == 3 points to data[3]
65 + // Negative: points to a position in the lookbehind buffer
66 + // pos == -2 points to lookbehind[lookbehind_size - 2]
67 + var pos = -this._lookbehind_size,
68 + last_needle_char = needle[needle_len - 1],
69 + occ = this._occ,
70 + lookbehind = this._lookbehind;
71 +
72 + if (pos < 0) {
73 + // Lookbehind buffer is not empty. Perform Boyer-Moore-Horspool
74 + // search with character lookup code that considers both the
75 + // lookbehind buffer and the current round's haystack data.
76 + //
77 + // Loop until
78 + // there is a match.
79 + // or until
80 + // we've moved past the position that requires the
81 + // lookbehind buffer. In this case we switch to the
82 + // optimized loop.
83 + // or until
84 + // the character to look at lies outside the haystack.
85 + while (pos < 0 && pos <= len - needle_len) {
86 + var ch = this._sbmh_lookup_char(data, pos + needle_len - 1);
87 +
88 + if (ch === last_needle_char
89 + && this._sbmh_memcmp(data, pos, needle_len - 1)) {
90 + this._lookbehind_size = 0;
91 + ++this.matches;
92 + if (pos > -this._lookbehind_size)
93 + this.emit('info', true, lookbehind, 0, this._lookbehind_size + pos);
94 + else
95 + this.emit('info', true);
96 +
97 + this._bufpos = pos + needle_len;
98 + return pos + needle_len;
99 + } else
100 + pos += occ[ch];
101 + }
102 +
103 + // No match.
104 +
105 + if (pos < 0) {
106 + // There's too few data for Boyer-Moore-Horspool to run,
107 + // so let's use a different algorithm to skip as much as
108 + // we can.
109 + // Forward pos until
110 + // the trailing part of lookbehind + data
111 + // looks like the beginning of the needle
112 + // or until
113 + // pos == 0
114 + while (pos < 0 && !this._sbmh_memcmp(data, pos, len - pos))
115 + pos++;
116 + }
117 +
118 + if (pos >= 0) {
119 + // Discard lookbehind buffer.
120 + this.emit('info', false, lookbehind, 0, this._lookbehind_size);
121 + this._lookbehind_size = 0;
122 + } else {
123 + // Cut off part of the lookbehind buffer that has
124 + // been processed and append the entire haystack
125 + // into it.
126 + var bytesToCutOff = this._lookbehind_size + pos;
127 +
128 + if (bytesToCutOff > 0) {
129 + // The cut off data is guaranteed not to contain the needle.
130 + this.emit('info', false, lookbehind, 0, bytesToCutOff);
131 + }
132 +
133 + lookbehind.copy(lookbehind, 0, bytesToCutOff,
134 + this._lookbehind_size - bytesToCutOff);
135 + this._lookbehind_size -= bytesToCutOff;
136 +
137 + data.copy(lookbehind, this._lookbehind_size);
138 + this._lookbehind_size += len;
139 +
140 + this._bufpos = len;
141 + return len;
142 + }
143 + }
144 +
145 + if (pos >= 0)
146 + pos += this._bufpos;
147 +
148 + // Lookbehind buffer is now empty. Perform Boyer-Moore-Horspool
149 + // search with optimized character lookup code that only considers
150 + // the current round's haystack data.
151 + while (pos <= len - needle_len) {
152 + var ch = data[pos + needle_len - 1];
153 +
154 + if (ch === last_needle_char
155 + && data[pos] === needle[0]
156 + && jsmemcmp(needle, 0, data, pos, needle_len - 1)) {
157 + ++this.matches;
158 + if (pos > 0)
159 + this.emit('info', true, data, this._bufpos, pos);
160 + else
161 + this.emit('info', true);
162 +
163 + this._bufpos = pos + needle_len;
164 + return pos + needle_len;
165 + } else
166 + pos += occ[ch];
167 + }
168 +
169 + // There was no match. If there's trailing haystack data that we cannot
170 + // match yet using the Boyer-Moore-Horspool algorithm (because the trailing
171 + // data is less than the needle size) then match using a modified
172 + // algorithm that starts matching from the beginning instead of the end.
173 + // Whatever trailing data is left after running this algorithm is added to
174 + // the lookbehind buffer.
175 + if (pos < len) {
176 + while (pos < len && (data[pos] !== needle[0]
177 + || !jsmemcmp(data, pos, needle, 0, len - pos))) {
178 + ++pos;
179 + }
180 + if (pos < len) {
181 + data.copy(lookbehind, 0, pos, pos + (len - pos));
182 + this._lookbehind_size = len - pos;
183 + }
184 + }
185 +
186 + // Everything until pos is guaranteed not to contain needle data.
187 + if (pos > 0)
188 + this.emit('info', false, data, this._bufpos, pos < len ? pos : len);
189 +
190 + this._bufpos = len;
191 + return len;
192 +};
193 +
194 +SBMH.prototype._sbmh_lookup_char = function(data, pos) {
195 + if (pos < 0)
196 + return this._lookbehind[this._lookbehind_size + pos];
197 + else
198 + return data[pos];
199 +}
200 +
201 +SBMH.prototype._sbmh_memcmp = function(data, pos, len) {
202 + var i = 0;
203 +
204 + while (i < len) {
205 + if (this._sbmh_lookup_char(data, pos + i) === this._needle[i])
206 + ++i;
207 + else
208 + return false;
209 + }
210 + return true;
211 +}
212 +
213 +module.exports = SBMH;
1 +{
2 + "_from": "streamsearch@0.1.2",
3 + "_id": "streamsearch@0.1.2",
4 + "_inBundle": false,
5 + "_integrity": "sha1-gIudDlb8Jz2Am6VzOOkpkZoanxo=",
6 + "_location": "/streamsearch",
7 + "_phantomChildren": {},
8 + "_requested": {
9 + "type": "version",
10 + "registry": true,
11 + "raw": "streamsearch@0.1.2",
12 + "name": "streamsearch",
13 + "escapedName": "streamsearch",
14 + "rawSpec": "0.1.2",
15 + "saveSpec": null,
16 + "fetchSpec": "0.1.2"
17 + },
18 + "_requiredBy": [
19 + "/dicer"
20 + ],
21 + "_resolved": "https://registry.npmjs.org/streamsearch/-/streamsearch-0.1.2.tgz",
22 + "_shasum": "808b9d0e56fc273d809ba57338e929919a1a9f1a",
23 + "_spec": "streamsearch@0.1.2",
24 + "_where": "C:\\Users\\1000c\\이것저것\\옾소\\Voicoding\\node_modules\\dicer",
25 + "author": {
26 + "name": "Brian White",
27 + "email": "mscdex@mscdex.net"
28 + },
29 + "bugs": {
30 + "url": "https://github.com/mscdex/streamsearch/issues"
31 + },
32 + "bundleDependencies": false,
33 + "deprecated": false,
34 + "description": "Streaming Boyer-Moore-Horspool searching for node.js",
35 + "engines": {
36 + "node": ">=0.8.0"
37 + },
38 + "homepage": "https://github.com/mscdex/streamsearch#readme",
39 + "keywords": [
40 + "stream",
41 + "horspool",
42 + "boyer-moore-horspool",
43 + "boyer-moore",
44 + "search"
45 + ],
46 + "licenses": [
47 + {
48 + "type": "MIT",
49 + "url": "http://github.com/mscdex/streamsearch/raw/master/LICENSE"
50 + }
51 + ],
52 + "main": "./lib/sbmh",
53 + "name": "streamsearch",
54 + "repository": {
55 + "type": "git",
56 + "url": "git+ssh://git@github.com/mscdex/streamsearch.git"
57 + },
58 + "version": "0.1.2"
59 +}
1 -Node.js is licensed for use as follows: 1 +Copyright Joyent, Inc. and other Node contributors.
2 - 2 +
3 -""" 3 +Permission is hereby granted, free of charge, to any person obtaining a
4 -Copyright Node.js contributors. All rights reserved. 4 +copy of this software and associated documentation files (the
5 - 5 +"Software"), to deal in the Software without restriction, including
6 -Permission is hereby granted, free of charge, to any person obtaining a copy 6 +without limitation the rights to use, copy, modify, merge, publish,
7 -of this software and associated documentation files (the "Software"), to 7 +distribute, sublicense, and/or sell copies of the Software, and to permit
8 -deal in the Software without restriction, including without limitation the 8 +persons to whom the Software is furnished to do so, subject to the
9 -rights to use, copy, modify, merge, publish, distribute, sublicense, and/or 9 +following conditions:
10 -sell copies of the Software, and to permit persons to whom the Software is 10 +
11 -furnished to do so, subject to the following conditions: 11 +The above copyright notice and this permission notice shall be included
12 - 12 +in all copies or substantial portions of the Software.
13 -The above copyright notice and this permission notice shall be included in 13 +
14 -all copies or substantial portions of the Software. 14 +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15 - 15 +OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17 -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 +NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18 -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19 -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 +OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20 -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 20 +USE OR OTHER DEALINGS IN THE SOFTWARE.
21 -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
22 -IN THE SOFTWARE.
23 -"""
24 -
25 -This license applies to parts of Node.js originating from the
26 -https://github.com/joyent/node repository:
27 -
28 -"""
29 -Copyright Joyent, Inc. and other Node contributors. All rights reserved.
30 -Permission is hereby granted, free of charge, to any person obtaining a copy
31 -of this software and associated documentation files (the "Software"), to
32 -deal in the Software without restriction, including without limitation the
33 -rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
34 -sell copies of the Software, and to permit persons to whom the Software is
35 -furnished to do so, subject to the following conditions:
36 -
37 -The above copyright notice and this permission notice shall be included in
38 -all copies or substantial portions of the Software.
39 -
40 -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
41 -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
42 -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
43 -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
44 -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
45 -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
46 -IN THE SOFTWARE.
47 -"""
48 -
......
1 -# string_decoder 1 +**string_decoder.js** (`require('string_decoder')`) from Node.js core
2 2
3 -***Node-core v8.9.4 string_decoder for userland*** 3 +Copyright Joyent, Inc. and other Node contributors. See LICENCE file for details.
4 4
5 +Version numbers match the versions found in Node core, e.g. 0.10.24 matches Node 0.10.24, likewise 0.11.10 matches Node 0.11.10. **Prefer the stable version over the unstable.**
5 6
6 -[![NPM](https://nodei.co/npm/string_decoder.png?downloads=true&downloadRank=true)](https://nodei.co/npm/string_decoder/) 7 +The *build/* directory contains a build script that will scrape the source from the [joyent/node](https://github.com/joyent/node) repo given a specific Node version.
7 -[![NPM](https://nodei.co/npm-dl/string_decoder.png?&months=6&height=3)](https://nodei.co/npm/string_decoder/)
8 -
9 -
10 -```bash
11 -npm install --save string_decoder
12 -```
13 -
14 -***Node-core string_decoder for userland***
15 -
16 -This package is a mirror of the string_decoder implementation in Node-core.
17 -
18 -Full documentation may be found on the [Node.js website](https://nodejs.org/dist/v8.9.4/docs/api/).
19 -
20 -As of version 1.0.0 **string_decoder** uses semantic versioning.
21 -
22 -## Previous versions
23 -
24 -Previous version numbers match the versions found in Node core, e.g. 0.10.24 matches Node 0.10.24, likewise 0.11.10 matches Node 0.11.10.
25 -
26 -## Update
27 -
28 -The *build/* directory contains a build script that will scrape the source from the [nodejs/node](https://github.com/nodejs/node) repo given a specific Node version.
29 -
30 -## Streams Working Group
31 -
32 -`string_decoder` is maintained by the Streams Working Group, which
33 -oversees the development and maintenance of the Streams API within
34 -Node.js. The responsibilities of the Streams Working Group include:
35 -
36 -* Addressing stream issues on the Node.js issue tracker.
37 -* Authoring and editing stream documentation within the Node.js project.
38 -* Reviewing changes to stream subclasses within the Node.js project.
39 -* Redirecting changes to streams from the Node.js project to this
40 - project.
41 -* Assisting in the implementation of stream providers within Node.js.
42 -* Recommending versions of `readable-stream` to be included in Node.js.
43 -* Messaging about the future of streams to give the community advance
44 - notice of changes.
45 -
46 -See [readable-stream](https://github.com/nodejs/readable-stream) for
47 -more details.
...\ No newline at end of file ...\ No newline at end of file
......
1 +// Copyright Joyent, Inc. and other Node contributors.
2 +//
3 +// Permission is hereby granted, free of charge, to any person obtaining a
4 +// copy of this software and associated documentation files (the
5 +// "Software"), to deal in the Software without restriction, including
6 +// without limitation the rights to use, copy, modify, merge, publish,
7 +// distribute, sublicense, and/or sell copies of the Software, and to permit
8 +// persons to whom the Software is furnished to do so, subject to the
9 +// following conditions:
10 +//
11 +// The above copyright notice and this permission notice shall be included
12 +// in all copies or substantial portions of the Software.
13 +//
14 +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15 +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17 +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18 +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19 +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20 +// USE OR OTHER DEALINGS IN THE SOFTWARE.
21 +
22 +var Buffer = require('buffer').Buffer;
23 +
24 +var isBufferEncoding = Buffer.isEncoding
25 + || function(encoding) {
26 + switch (encoding && encoding.toLowerCase()) {
27 + 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;
28 + default: return false;
29 + }
30 + }
31 +
32 +
33 +function assertEncoding(encoding) {
34 + if (encoding && !isBufferEncoding(encoding)) {
35 + throw new Error('Unknown encoding: ' + encoding);
36 + }
37 +}
38 +
39 +// StringDecoder provides an interface for efficiently splitting a series of
40 +// buffers into a series of JS strings without breaking apart multi-byte
41 +// characters. CESU-8 is handled as part of the UTF-8 encoding.
42 +//
43 +// @TODO Handling all encodings inside a single object makes it very difficult
44 +// to reason about this code, so it should be split up in the future.
45 +// @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code
46 +// points as used by CESU-8.
47 +var StringDecoder = exports.StringDecoder = function(encoding) {
48 + this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, '');
49 + assertEncoding(encoding);
50 + switch (this.encoding) {
51 + case 'utf8':
52 + // CESU-8 represents each of Surrogate Pair by 3-bytes
53 + this.surrogateSize = 3;
54 + break;
55 + case 'ucs2':
56 + case 'utf16le':
57 + // UTF-16 represents each of Surrogate Pair by 2-bytes
58 + this.surrogateSize = 2;
59 + this.detectIncompleteChar = utf16DetectIncompleteChar;
60 + break;
61 + case 'base64':
62 + // Base-64 stores 3 bytes in 4 chars, and pads the remainder.
63 + this.surrogateSize = 3;
64 + this.detectIncompleteChar = base64DetectIncompleteChar;
65 + break;
66 + default:
67 + this.write = passThroughWrite;
68 + return;
69 + }
70 +
71 + // Enough space to store all bytes of a single character. UTF-8 needs 4
72 + // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate).
73 + this.charBuffer = new Buffer(6);
74 + // Number of bytes received for the current incomplete multi-byte character.
75 + this.charReceived = 0;
76 + // Number of bytes expected for the current incomplete multi-byte character.
77 + this.charLength = 0;
78 +};
79 +
80 +
81 +// write decodes the given buffer and returns it as JS string that is
82 +// guaranteed to not contain any partial multi-byte characters. Any partial
83 +// character found at the end of the buffer is buffered up, and will be
84 +// returned when calling write again with the remaining bytes.
85 +//
86 +// Note: Converting a Buffer containing an orphan surrogate to a String
87 +// currently works, but converting a String to a Buffer (via `new Buffer`, or
88 +// Buffer#write) will replace incomplete surrogates with the unicode
89 +// replacement character. See https://codereview.chromium.org/121173009/ .
90 +StringDecoder.prototype.write = function(buffer) {
91 + var charStr = '';
92 + // if our last write ended with an incomplete multibyte character
93 + while (this.charLength) {
94 + // determine how many remaining bytes this buffer has to offer for this char
95 + var available = (buffer.length >= this.charLength - this.charReceived) ?
96 + this.charLength - this.charReceived :
97 + buffer.length;
98 +
99 + // add the new bytes to the char buffer
100 + buffer.copy(this.charBuffer, this.charReceived, 0, available);
101 + this.charReceived += available;
102 +
103 + if (this.charReceived < this.charLength) {
104 + // still not enough chars in this buffer? wait for more ...
105 + return '';
106 + }
107 +
108 + // remove bytes belonging to the current character from the buffer
109 + buffer = buffer.slice(available, buffer.length);
110 +
111 + // get the character that was split
112 + charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding);
113 +
114 + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
115 + var charCode = charStr.charCodeAt(charStr.length - 1);
116 + if (charCode >= 0xD800 && charCode <= 0xDBFF) {
117 + this.charLength += this.surrogateSize;
118 + charStr = '';
119 + continue;
120 + }
121 + this.charReceived = this.charLength = 0;
122 +
123 + // if there are no more bytes in this buffer, just emit our char
124 + if (buffer.length === 0) {
125 + return charStr;
126 + }
127 + break;
128 + }
129 +
130 + // determine and set charLength / charReceived
131 + this.detectIncompleteChar(buffer);
132 +
133 + var end = buffer.length;
134 + if (this.charLength) {
135 + // buffer the incomplete character bytes we got
136 + buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end);
137 + end -= this.charReceived;
138 + }
139 +
140 + charStr += buffer.toString(this.encoding, 0, end);
141 +
142 + var end = charStr.length - 1;
143 + var charCode = charStr.charCodeAt(end);
144 + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
145 + if (charCode >= 0xD800 && charCode <= 0xDBFF) {
146 + var size = this.surrogateSize;
147 + this.charLength += size;
148 + this.charReceived += size;
149 + this.charBuffer.copy(this.charBuffer, size, 0, size);
150 + buffer.copy(this.charBuffer, 0, 0, size);
151 + return charStr.substring(0, end);
152 + }
153 +
154 + // or just emit the charStr
155 + return charStr;
156 +};
157 +
158 +// detectIncompleteChar determines if there is an incomplete UTF-8 character at
159 +// the end of the given buffer. If so, it sets this.charLength to the byte
160 +// length that character, and sets this.charReceived to the number of bytes
161 +// that are available for this character.
162 +StringDecoder.prototype.detectIncompleteChar = function(buffer) {
163 + // determine how many bytes we have to check at the end of this buffer
164 + var i = (buffer.length >= 3) ? 3 : buffer.length;
165 +
166 + // Figure out if one of the last i bytes of our buffer announces an
167 + // incomplete char.
168 + for (; i > 0; i--) {
169 + var c = buffer[buffer.length - i];
170 +
171 + // See http://en.wikipedia.org/wiki/UTF-8#Description
172 +
173 + // 110XXXXX
174 + if (i == 1 && c >> 5 == 0x06) {
175 + this.charLength = 2;
176 + break;
177 + }
178 +
179 + // 1110XXXX
180 + if (i <= 2 && c >> 4 == 0x0E) {
181 + this.charLength = 3;
182 + break;
183 + }
184 +
185 + // 11110XXX
186 + if (i <= 3 && c >> 3 == 0x1E) {
187 + this.charLength = 4;
188 + break;
189 + }
190 + }
191 + this.charReceived = i;
192 +};
193 +
194 +StringDecoder.prototype.end = function(buffer) {
195 + var res = '';
196 + if (buffer && buffer.length)
197 + res = this.write(buffer);
198 +
199 + if (this.charReceived) {
200 + var cr = this.charReceived;
201 + var buf = this.charBuffer;
202 + var enc = this.encoding;
203 + res += buf.slice(0, cr).toString(enc);
204 + }
205 +
206 + return res;
207 +};
208 +
209 +function passThroughWrite(buffer) {
210 + return buffer.toString(this.encoding);
211 +}
212 +
213 +function utf16DetectIncompleteChar(buffer) {
214 + this.charReceived = buffer.length % 2;
215 + this.charLength = this.charReceived ? 2 : 0;
216 +}
217 +
218 +function base64DetectIncompleteChar(buffer) {
219 + this.charReceived = buffer.length % 3;
220 + this.charLength = this.charReceived ? 3 : 0;
221 +}
1 { 1 {
2 - "_from": "string_decoder@^1.1.1", 2 + "_from": "string_decoder@~0.10.x",
3 - "_id": "string_decoder@1.3.0", 3 + "_id": "string_decoder@0.10.31",
4 "_inBundle": false, 4 "_inBundle": false,
5 - "_integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", 5 + "_integrity": "sha1-YuIDvEF2bGwoyfyEMB2rHFMQ+pQ=",
6 "_location": "/string_decoder", 6 "_location": "/string_decoder",
7 "_phantomChildren": {}, 7 "_phantomChildren": {},
8 "_requested": { 8 "_requested": {
9 "type": "range", 9 "type": "range",
10 "registry": true, 10 "registry": true,
11 - "raw": "string_decoder@^1.1.1", 11 + "raw": "string_decoder@~0.10.x",
12 "name": "string_decoder", 12 "name": "string_decoder",
13 "escapedName": "string_decoder", 13 "escapedName": "string_decoder",
14 - "rawSpec": "^1.1.1", 14 + "rawSpec": "~0.10.x",
15 "saveSpec": null, 15 "saveSpec": null,
16 - "fetchSpec": "^1.1.1" 16 + "fetchSpec": "~0.10.x"
17 }, 17 },
18 "_requiredBy": [ 18 "_requiredBy": [
19 "/readable-stream" 19 "/readable-stream"
20 ], 20 ],
21 - "_resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", 21 + "_resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-0.10.31.tgz",
22 - "_shasum": "42f114594a46cf1a8e30b0a84f56c78c3edac21e", 22 + "_shasum": "62e203bc41766c6c28c9fc84301dab1c5310fa94",
23 - "_spec": "string_decoder@^1.1.1", 23 + "_spec": "string_decoder@~0.10.x",
24 "_where": "C:\\Users\\1000c\\이것저것\\옾소\\Voicoding\\node_modules\\readable-stream", 24 "_where": "C:\\Users\\1000c\\이것저것\\옾소\\Voicoding\\node_modules\\readable-stream",
25 "bugs": { 25 "bugs": {
26 - "url": "https://github.com/nodejs/string_decoder/issues" 26 + "url": "https://github.com/rvagg/string_decoder/issues"
27 }, 27 },
28 "bundleDependencies": false, 28 "bundleDependencies": false,
29 - "dependencies": { 29 + "dependencies": {},
30 - "safe-buffer": "~5.2.0"
31 - },
32 "deprecated": false, 30 "deprecated": false,
33 "description": "The string_decoder module from Node core", 31 "description": "The string_decoder module from Node core",
34 "devDependencies": { 32 "devDependencies": {
35 - "babel-polyfill": "^6.23.0",
36 - "core-util-is": "^1.0.2",
37 - "inherits": "^2.0.3",
38 "tap": "~0.4.8" 33 "tap": "~0.4.8"
39 }, 34 },
40 - "files": [ 35 + "homepage": "https://github.com/rvagg/string_decoder",
41 - "lib"
42 - ],
43 - "homepage": "https://github.com/nodejs/string_decoder",
44 "keywords": [ 36 "keywords": [
45 "string", 37 "string",
46 "decoder", 38 "decoder",
...@@ -48,15 +40,14 @@ ...@@ -48,15 +40,14 @@
48 "browserify" 40 "browserify"
49 ], 41 ],
50 "license": "MIT", 42 "license": "MIT",
51 - "main": "lib/string_decoder.js", 43 + "main": "index.js",
52 "name": "string_decoder", 44 "name": "string_decoder",
53 "repository": { 45 "repository": {
54 "type": "git", 46 "type": "git",
55 - "url": "git://github.com/nodejs/string_decoder.git" 47 + "url": "git://github.com/rvagg/string_decoder.git"
56 }, 48 },
57 "scripts": { 49 "scripts": {
58 - "ci": "tap test/parallel/*.js test/ours/*.js --tap | tee test.tap && node test/verify-dependencies.js", 50 + "test": "tap test/simple/*.js"
59 - "test": "tap test/parallel/*.js && node test/verify-dependencies"
60 }, 51 },
61 - "version": "1.3.0" 52 + "version": "0.10.31"
62 } 53 }
......
1 +language: node_js
2 +node_js:
3 + - "0.8"
4 + - "0.10"
1 +/*
2 + Copyright (c) 2010, Linden Research, Inc.
3 + Copyright (c) 2012, Joshua Bell
4 +
5 + Permission is hereby granted, free of charge, to any person obtaining a copy
6 + of this software and associated documentation files (the "Software"), to deal
7 + in the Software without restriction, including without limitation the rights
8 + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 + copies of the Software, and to permit persons to whom the Software is
10 + furnished to do so, subject to the following conditions:
11 +
12 + The above copyright notice and this permission notice shall be included in
13 + all copies or substantial portions of the Software.
14 +
15 + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21 + THE SOFTWARE.
22 + $/LicenseInfo$
23 + */
24 +
25 +// Original can be found at:
26 +// https://bitbucket.org/lindenlab/llsd
27 +// Modifications by Joshua Bell inexorabletash@gmail.com
28 +// https://github.com/inexorabletash/polyfill
29 +
30 +// ES3/ES5 implementation of the Krhonos Typed Array Specification
31 +// Ref: http://www.khronos.org/registry/typedarray/specs/latest/
32 +// Date: 2011-02-01
33 +//
34 +// Variations:
35 +// * Allows typed_array.get/set() as alias for subscripts (typed_array[])
1 +var Uint8Array = require('../').Uint8Array;
2 +var ua = new Uint8Array(5);
3 +ua[1] = 256 + 55;
4 +console.log(ua[1]);
1 +var undefined = (void 0); // Paranoia
2 +
3 +// Beyond this value, index getters/setters (i.e. array[0], array[1]) are so slow to
4 +// create, and consume so much memory, that the browser appears frozen.
5 +var MAX_ARRAY_LENGTH = 1e5;
6 +
7 +// Approximations of internal ECMAScript conversion functions
8 +var ECMAScript = (function() {
9 + // Stash a copy in case other scripts modify these
10 + var opts = Object.prototype.toString,
11 + ophop = Object.prototype.hasOwnProperty;
12 +
13 + return {
14 + // Class returns internal [[Class]] property, used to avoid cross-frame instanceof issues:
15 + Class: function(v) { return opts.call(v).replace(/^\[object *|\]$/g, ''); },
16 + HasProperty: function(o, p) { return p in o; },
17 + HasOwnProperty: function(o, p) { return ophop.call(o, p); },
18 + IsCallable: function(o) { return typeof o === 'function'; },
19 + ToInt32: function(v) { return v >> 0; },
20 + ToUint32: function(v) { return v >>> 0; }
21 + };
22 +}());
23 +
24 +// Snapshot intrinsics
25 +var LN2 = Math.LN2,
26 + abs = Math.abs,
27 + floor = Math.floor,
28 + log = Math.log,
29 + min = Math.min,
30 + pow = Math.pow,
31 + round = Math.round;
32 +
33 +// ES5: lock down object properties
34 +function configureProperties(obj) {
35 + if (getOwnPropNames && defineProp) {
36 + var props = getOwnPropNames(obj), i;
37 + for (i = 0; i < props.length; i += 1) {
38 + defineProp(obj, props[i], {
39 + value: obj[props[i]],
40 + writable: false,
41 + enumerable: false,
42 + configurable: false
43 + });
44 + }
45 + }
46 +}
47 +
48 +// emulate ES5 getter/setter API using legacy APIs
49 +// http://blogs.msdn.com/b/ie/archive/2010/09/07/transitioning-existing-code-to-the-es5-getter-setter-apis.aspx
50 +// (second clause tests for Object.defineProperty() in IE<9 that only supports extending DOM prototypes, but
51 +// note that IE<9 does not support __defineGetter__ or __defineSetter__ so it just renders the method harmless)
52 +var defineProp
53 +if (Object.defineProperty && (function() {
54 + try {
55 + Object.defineProperty({}, 'x', {});
56 + return true;
57 + } catch (e) {
58 + return false;
59 + }
60 + })()) {
61 + defineProp = Object.defineProperty;
62 +} else {
63 + defineProp = function(o, p, desc) {
64 + if (!o === Object(o)) throw new TypeError("Object.defineProperty called on non-object");
65 + if (ECMAScript.HasProperty(desc, 'get') && Object.prototype.__defineGetter__) { Object.prototype.__defineGetter__.call(o, p, desc.get); }
66 + if (ECMAScript.HasProperty(desc, 'set') && Object.prototype.__defineSetter__) { Object.prototype.__defineSetter__.call(o, p, desc.set); }
67 + if (ECMAScript.HasProperty(desc, 'value')) { o[p] = desc.value; }
68 + return o;
69 + };
70 +}
71 +
72 +var getOwnPropNames = Object.getOwnPropertyNames || function (o) {
73 + if (o !== Object(o)) throw new TypeError("Object.getOwnPropertyNames called on non-object");
74 + var props = [], p;
75 + for (p in o) {
76 + if (ECMAScript.HasOwnProperty(o, p)) {
77 + props.push(p);
78 + }
79 + }
80 + return props;
81 +};
82 +
83 +// ES5: Make obj[index] an alias for obj._getter(index)/obj._setter(index, value)
84 +// for index in 0 ... obj.length
85 +function makeArrayAccessors(obj) {
86 + if (!defineProp) { return; }
87 +
88 + if (obj.length > MAX_ARRAY_LENGTH) throw new RangeError("Array too large for polyfill");
89 +
90 + function makeArrayAccessor(index) {
91 + defineProp(obj, index, {
92 + 'get': function() { return obj._getter(index); },
93 + 'set': function(v) { obj._setter(index, v); },
94 + enumerable: true,
95 + configurable: false
96 + });
97 + }
98 +
99 + var i;
100 + for (i = 0; i < obj.length; i += 1) {
101 + makeArrayAccessor(i);
102 + }
103 +}
104 +
105 +// Internal conversion functions:
106 +// pack<Type>() - take a number (interpreted as Type), output a byte array
107 +// unpack<Type>() - take a byte array, output a Type-like number
108 +
109 +function as_signed(value, bits) { var s = 32 - bits; return (value << s) >> s; }
110 +function as_unsigned(value, bits) { var s = 32 - bits; return (value << s) >>> s; }
111 +
112 +function packI8(n) { return [n & 0xff]; }
113 +function unpackI8(bytes) { return as_signed(bytes[0], 8); }
114 +
115 +function packU8(n) { return [n & 0xff]; }
116 +function unpackU8(bytes) { return as_unsigned(bytes[0], 8); }
117 +
118 +function packU8Clamped(n) { n = round(Number(n)); return [n < 0 ? 0 : n > 0xff ? 0xff : n & 0xff]; }
119 +
120 +function packI16(n) { return [(n >> 8) & 0xff, n & 0xff]; }
121 +function unpackI16(bytes) { return as_signed(bytes[0] << 8 | bytes[1], 16); }
122 +
123 +function packU16(n) { return [(n >> 8) & 0xff, n & 0xff]; }
124 +function unpackU16(bytes) { return as_unsigned(bytes[0] << 8 | bytes[1], 16); }
125 +
126 +function packI32(n) { return [(n >> 24) & 0xff, (n >> 16) & 0xff, (n >> 8) & 0xff, n & 0xff]; }
127 +function unpackI32(bytes) { return as_signed(bytes[0] << 24 | bytes[1] << 16 | bytes[2] << 8 | bytes[3], 32); }
128 +
129 +function packU32(n) { return [(n >> 24) & 0xff, (n >> 16) & 0xff, (n >> 8) & 0xff, n & 0xff]; }
130 +function unpackU32(bytes) { return as_unsigned(bytes[0] << 24 | bytes[1] << 16 | bytes[2] << 8 | bytes[3], 32); }
131 +
132 +function packIEEE754(v, ebits, fbits) {
133 +
134 + var bias = (1 << (ebits - 1)) - 1,
135 + s, e, f, ln,
136 + i, bits, str, bytes;
137 +
138 + function roundToEven(n) {
139 + var w = floor(n), f = n - w;
140 + if (f < 0.5)
141 + return w;
142 + if (f > 0.5)
143 + return w + 1;
144 + return w % 2 ? w + 1 : w;
145 + }
146 +
147 + // Compute sign, exponent, fraction
148 + if (v !== v) {
149 + // NaN
150 + // http://dev.w3.org/2006/webapi/WebIDL/#es-type-mapping
151 + e = (1 << ebits) - 1; f = pow(2, fbits - 1); s = 0;
152 + } else if (v === Infinity || v === -Infinity) {
153 + e = (1 << ebits) - 1; f = 0; s = (v < 0) ? 1 : 0;
154 + } else if (v === 0) {
155 + e = 0; f = 0; s = (1 / v === -Infinity) ? 1 : 0;
156 + } else {
157 + s = v < 0;
158 + v = abs(v);
159 +
160 + if (v >= pow(2, 1 - bias)) {
161 + e = min(floor(log(v) / LN2), 1023);
162 + f = roundToEven(v / pow(2, e) * pow(2, fbits));
163 + if (f / pow(2, fbits) >= 2) {
164 + e = e + 1;
165 + f = 1;
166 + }
167 + if (e > bias) {
168 + // Overflow
169 + e = (1 << ebits) - 1;
170 + f = 0;
171 + } else {
172 + // Normalized
173 + e = e + bias;
174 + f = f - pow(2, fbits);
175 + }
176 + } else {
177 + // Denormalized
178 + e = 0;
179 + f = roundToEven(v / pow(2, 1 - bias - fbits));
180 + }
181 + }
182 +
183 + // Pack sign, exponent, fraction
184 + bits = [];
185 + for (i = fbits; i; i -= 1) { bits.push(f % 2 ? 1 : 0); f = floor(f / 2); }
186 + for (i = ebits; i; i -= 1) { bits.push(e % 2 ? 1 : 0); e = floor(e / 2); }
187 + bits.push(s ? 1 : 0);
188 + bits.reverse();
189 + str = bits.join('');
190 +
191 + // Bits to bytes
192 + bytes = [];
193 + while (str.length) {
194 + bytes.push(parseInt(str.substring(0, 8), 2));
195 + str = str.substring(8);
196 + }
197 + return bytes;
198 +}
199 +
200 +function unpackIEEE754(bytes, ebits, fbits) {
201 +
202 + // Bytes to bits
203 + var bits = [], i, j, b, str,
204 + bias, s, e, f;
205 +
206 + for (i = bytes.length; i; i -= 1) {
207 + b = bytes[i - 1];
208 + for (j = 8; j; j -= 1) {
209 + bits.push(b % 2 ? 1 : 0); b = b >> 1;
210 + }
211 + }
212 + bits.reverse();
213 + str = bits.join('');
214 +
215 + // Unpack sign, exponent, fraction
216 + bias = (1 << (ebits - 1)) - 1;
217 + s = parseInt(str.substring(0, 1), 2) ? -1 : 1;
218 + e = parseInt(str.substring(1, 1 + ebits), 2);
219 + f = parseInt(str.substring(1 + ebits), 2);
220 +
221 + // Produce number
222 + if (e === (1 << ebits) - 1) {
223 + return f !== 0 ? NaN : s * Infinity;
224 + } else if (e > 0) {
225 + // Normalized
226 + return s * pow(2, e - bias) * (1 + f / pow(2, fbits));
227 + } else if (f !== 0) {
228 + // Denormalized
229 + return s * pow(2, -(bias - 1)) * (f / pow(2, fbits));
230 + } else {
231 + return s < 0 ? -0 : 0;
232 + }
233 +}
234 +
235 +function unpackF64(b) { return unpackIEEE754(b, 11, 52); }
236 +function packF64(v) { return packIEEE754(v, 11, 52); }
237 +function unpackF32(b) { return unpackIEEE754(b, 8, 23); }
238 +function packF32(v) { return packIEEE754(v, 8, 23); }
239 +
240 +
241 +//
242 +// 3 The ArrayBuffer Type
243 +//
244 +
245 +(function() {
246 +
247 + /** @constructor */
248 + var ArrayBuffer = function ArrayBuffer(length) {
249 + length = ECMAScript.ToInt32(length);
250 + if (length < 0) throw new RangeError('ArrayBuffer size is not a small enough positive integer');
251 +
252 + this.byteLength = length;
253 + this._bytes = [];
254 + this._bytes.length = length;
255 +
256 + var i;
257 + for (i = 0; i < this.byteLength; i += 1) {
258 + this._bytes[i] = 0;
259 + }
260 +
261 + configureProperties(this);
262 + };
263 +
264 + exports.ArrayBuffer = exports.ArrayBuffer || ArrayBuffer;
265 +
266 + //
267 + // 4 The ArrayBufferView Type
268 + //
269 +
270 + // NOTE: this constructor is not exported
271 + /** @constructor */
272 + var ArrayBufferView = function ArrayBufferView() {
273 + //this.buffer = null;
274 + //this.byteOffset = 0;
275 + //this.byteLength = 0;
276 + };
277 +
278 + //
279 + // 5 The Typed Array View Types
280 + //
281 +
282 + function makeConstructor(bytesPerElement, pack, unpack) {
283 + // Each TypedArray type requires a distinct constructor instance with
284 + // identical logic, which this produces.
285 +
286 + var ctor;
287 + ctor = function(buffer, byteOffset, length) {
288 + var array, sequence, i, s;
289 +
290 + if (!arguments.length || typeof arguments[0] === 'number') {
291 + // Constructor(unsigned long length)
292 + this.length = ECMAScript.ToInt32(arguments[0]);
293 + if (length < 0) throw new RangeError('ArrayBufferView size is not a small enough positive integer');
294 +
295 + this.byteLength = this.length * this.BYTES_PER_ELEMENT;
296 + this.buffer = new ArrayBuffer(this.byteLength);
297 + this.byteOffset = 0;
298 + } else if (typeof arguments[0] === 'object' && arguments[0].constructor === ctor) {
299 + // Constructor(TypedArray array)
300 + array = arguments[0];
301 +
302 + this.length = array.length;
303 + this.byteLength = this.length * this.BYTES_PER_ELEMENT;
304 + this.buffer = new ArrayBuffer(this.byteLength);
305 + this.byteOffset = 0;
306 +
307 + for (i = 0; i < this.length; i += 1) {
308 + this._setter(i, array._getter(i));
309 + }
310 + } else if (typeof arguments[0] === 'object' &&
311 + !(arguments[0] instanceof ArrayBuffer || ECMAScript.Class(arguments[0]) === 'ArrayBuffer')) {
312 + // Constructor(sequence<type> array)
313 + sequence = arguments[0];
314 +
315 + this.length = ECMAScript.ToUint32(sequence.length);
316 + this.byteLength = this.length * this.BYTES_PER_ELEMENT;
317 + this.buffer = new ArrayBuffer(this.byteLength);
318 + this.byteOffset = 0;
319 +
320 + for (i = 0; i < this.length; i += 1) {
321 + s = sequence[i];
322 + this._setter(i, Number(s));
323 + }
324 + } else if (typeof arguments[0] === 'object' &&
325 + (arguments[0] instanceof ArrayBuffer || ECMAScript.Class(arguments[0]) === 'ArrayBuffer')) {
326 + // Constructor(ArrayBuffer buffer,
327 + // optional unsigned long byteOffset, optional unsigned long length)
328 + this.buffer = buffer;
329 +
330 + this.byteOffset = ECMAScript.ToUint32(byteOffset);
331 + if (this.byteOffset > this.buffer.byteLength) {
332 + throw new RangeError("byteOffset out of range");
333 + }
334 +
335 + if (this.byteOffset % this.BYTES_PER_ELEMENT) {
336 + // The given byteOffset must be a multiple of the element
337 + // size of the specific type, otherwise an exception is raised.
338 + throw new RangeError("ArrayBuffer length minus the byteOffset is not a multiple of the element size.");
339 + }
340 +
341 + if (arguments.length < 3) {
342 + this.byteLength = this.buffer.byteLength - this.byteOffset;
343 +
344 + if (this.byteLength % this.BYTES_PER_ELEMENT) {
345 + throw new RangeError("length of buffer minus byteOffset not a multiple of the element size");
346 + }
347 + this.length = this.byteLength / this.BYTES_PER_ELEMENT;
348 + } else {
349 + this.length = ECMAScript.ToUint32(length);
350 + this.byteLength = this.length * this.BYTES_PER_ELEMENT;
351 + }
352 +
353 + if ((this.byteOffset + this.byteLength) > this.buffer.byteLength) {
354 + throw new RangeError("byteOffset and length reference an area beyond the end of the buffer");
355 + }
356 + } else {
357 + throw new TypeError("Unexpected argument type(s)");
358 + }
359 +
360 + this.constructor = ctor;
361 +
362 + configureProperties(this);
363 + makeArrayAccessors(this);
364 + };
365 +
366 + ctor.prototype = new ArrayBufferView();
367 + ctor.prototype.BYTES_PER_ELEMENT = bytesPerElement;
368 + ctor.prototype._pack = pack;
369 + ctor.prototype._unpack = unpack;
370 + ctor.BYTES_PER_ELEMENT = bytesPerElement;
371 +
372 + // getter type (unsigned long index);
373 + ctor.prototype._getter = function(index) {
374 + if (arguments.length < 1) throw new SyntaxError("Not enough arguments");
375 +
376 + index = ECMAScript.ToUint32(index);
377 + if (index >= this.length) {
378 + return undefined;
379 + }
380 +
381 + var bytes = [], i, o;
382 + for (i = 0, o = this.byteOffset + index * this.BYTES_PER_ELEMENT;
383 + i < this.BYTES_PER_ELEMENT;
384 + i += 1, o += 1) {
385 + bytes.push(this.buffer._bytes[o]);
386 + }
387 + return this._unpack(bytes);
388 + };
389 +
390 + // NONSTANDARD: convenience alias for getter: type get(unsigned long index);
391 + ctor.prototype.get = ctor.prototype._getter;
392 +
393 + // setter void (unsigned long index, type value);
394 + ctor.prototype._setter = function(index, value) {
395 + if (arguments.length < 2) throw new SyntaxError("Not enough arguments");
396 +
397 + index = ECMAScript.ToUint32(index);
398 + if (index >= this.length) {
399 + return undefined;
400 + }
401 +
402 + var bytes = this._pack(value), i, o;
403 + for (i = 0, o = this.byteOffset + index * this.BYTES_PER_ELEMENT;
404 + i < this.BYTES_PER_ELEMENT;
405 + i += 1, o += 1) {
406 + this.buffer._bytes[o] = bytes[i];
407 + }
408 + };
409 +
410 + // void set(TypedArray array, optional unsigned long offset);
411 + // void set(sequence<type> array, optional unsigned long offset);
412 + ctor.prototype.set = function(index, value) {
413 + if (arguments.length < 1) throw new SyntaxError("Not enough arguments");
414 + var array, sequence, offset, len,
415 + i, s, d,
416 + byteOffset, byteLength, tmp;
417 +
418 + if (typeof arguments[0] === 'object' && arguments[0].constructor === this.constructor) {
419 + // void set(TypedArray array, optional unsigned long offset);
420 + array = arguments[0];
421 + offset = ECMAScript.ToUint32(arguments[1]);
422 +
423 + if (offset + array.length > this.length) {
424 + throw new RangeError("Offset plus length of array is out of range");
425 + }
426 +
427 + byteOffset = this.byteOffset + offset * this.BYTES_PER_ELEMENT;
428 + byteLength = array.length * this.BYTES_PER_ELEMENT;
429 +
430 + if (array.buffer === this.buffer) {
431 + tmp = [];
432 + for (i = 0, s = array.byteOffset; i < byteLength; i += 1, s += 1) {
433 + tmp[i] = array.buffer._bytes[s];
434 + }
435 + for (i = 0, d = byteOffset; i < byteLength; i += 1, d += 1) {
436 + this.buffer._bytes[d] = tmp[i];
437 + }
438 + } else {
439 + for (i = 0, s = array.byteOffset, d = byteOffset;
440 + i < byteLength; i += 1, s += 1, d += 1) {
441 + this.buffer._bytes[d] = array.buffer._bytes[s];
442 + }
443 + }
444 + } else if (typeof arguments[0] === 'object' && typeof arguments[0].length !== 'undefined') {
445 + // void set(sequence<type> array, optional unsigned long offset);
446 + sequence = arguments[0];
447 + len = ECMAScript.ToUint32(sequence.length);
448 + offset = ECMAScript.ToUint32(arguments[1]);
449 +
450 + if (offset + len > this.length) {
451 + throw new RangeError("Offset plus length of array is out of range");
452 + }
453 +
454 + for (i = 0; i < len; i += 1) {
455 + s = sequence[i];
456 + this._setter(offset + i, Number(s));
457 + }
458 + } else {
459 + throw new TypeError("Unexpected argument type(s)");
460 + }
461 + };
462 +
463 + // TypedArray subarray(long begin, optional long end);
464 + ctor.prototype.subarray = function(start, end) {
465 + function clamp(v, min, max) { return v < min ? min : v > max ? max : v; }
466 +
467 + start = ECMAScript.ToInt32(start);
468 + end = ECMAScript.ToInt32(end);
469 +
470 + if (arguments.length < 1) { start = 0; }
471 + if (arguments.length < 2) { end = this.length; }
472 +
473 + if (start < 0) { start = this.length + start; }
474 + if (end < 0) { end = this.length + end; }
475 +
476 + start = clamp(start, 0, this.length);
477 + end = clamp(end, 0, this.length);
478 +
479 + var len = end - start;
480 + if (len < 0) {
481 + len = 0;
482 + }
483 +
484 + return new this.constructor(
485 + this.buffer, this.byteOffset + start * this.BYTES_PER_ELEMENT, len);
486 + };
487 +
488 + return ctor;
489 + }
490 +
491 + var Int8Array = makeConstructor(1, packI8, unpackI8);
492 + var Uint8Array = makeConstructor(1, packU8, unpackU8);
493 + var Uint8ClampedArray = makeConstructor(1, packU8Clamped, unpackU8);
494 + var Int16Array = makeConstructor(2, packI16, unpackI16);
495 + var Uint16Array = makeConstructor(2, packU16, unpackU16);
496 + var Int32Array = makeConstructor(4, packI32, unpackI32);
497 + var Uint32Array = makeConstructor(4, packU32, unpackU32);
498 + var Float32Array = makeConstructor(4, packF32, unpackF32);
499 + var Float64Array = makeConstructor(8, packF64, unpackF64);
500 +
501 + exports.Int8Array = exports.Int8Array || Int8Array;
502 + exports.Uint8Array = exports.Uint8Array || Uint8Array;
503 + exports.Uint8ClampedArray = exports.Uint8ClampedArray || Uint8ClampedArray;
504 + exports.Int16Array = exports.Int16Array || Int16Array;
505 + exports.Uint16Array = exports.Uint16Array || Uint16Array;
506 + exports.Int32Array = exports.Int32Array || Int32Array;
507 + exports.Uint32Array = exports.Uint32Array || Uint32Array;
508 + exports.Float32Array = exports.Float32Array || Float32Array;
509 + exports.Float64Array = exports.Float64Array || Float64Array;
510 +}());
511 +
512 +//
513 +// 6 The DataView View Type
514 +//
515 +
516 +(function() {
517 + function r(array, index) {
518 + return ECMAScript.IsCallable(array.get) ? array.get(index) : array[index];
519 + }
520 +
521 + var IS_BIG_ENDIAN = (function() {
522 + var u16array = new(exports.Uint16Array)([0x1234]),
523 + u8array = new(exports.Uint8Array)(u16array.buffer);
524 + return r(u8array, 0) === 0x12;
525 + }());
526 +
527 + // Constructor(ArrayBuffer buffer,
528 + // optional unsigned long byteOffset,
529 + // optional unsigned long byteLength)
530 + /** @constructor */
531 + var DataView = function DataView(buffer, byteOffset, byteLength) {
532 + if (arguments.length === 0) {
533 + buffer = new exports.ArrayBuffer(0);
534 + } else if (!(buffer instanceof exports.ArrayBuffer || ECMAScript.Class(buffer) === 'ArrayBuffer')) {
535 + throw new TypeError("TypeError");
536 + }
537 +
538 + this.buffer = buffer || new exports.ArrayBuffer(0);
539 +
540 + this.byteOffset = ECMAScript.ToUint32(byteOffset);
541 + if (this.byteOffset > this.buffer.byteLength) {
542 + throw new RangeError("byteOffset out of range");
543 + }
544 +
545 + if (arguments.length < 3) {
546 + this.byteLength = this.buffer.byteLength - this.byteOffset;
547 + } else {
548 + this.byteLength = ECMAScript.ToUint32(byteLength);
549 + }
550 +
551 + if ((this.byteOffset + this.byteLength) > this.buffer.byteLength) {
552 + throw new RangeError("byteOffset and length reference an area beyond the end of the buffer");
553 + }
554 +
555 + configureProperties(this);
556 + };
557 +
558 + function makeGetter(arrayType) {
559 + return function(byteOffset, littleEndian) {
560 +
561 + byteOffset = ECMAScript.ToUint32(byteOffset);
562 +
563 + if (byteOffset + arrayType.BYTES_PER_ELEMENT > this.byteLength) {
564 + throw new RangeError("Array index out of range");
565 + }
566 + byteOffset += this.byteOffset;
567 +
568 + var uint8Array = new exports.Uint8Array(this.buffer, byteOffset, arrayType.BYTES_PER_ELEMENT),
569 + bytes = [], i;
570 + for (i = 0; i < arrayType.BYTES_PER_ELEMENT; i += 1) {
571 + bytes.push(r(uint8Array, i));
572 + }
573 +
574 + if (Boolean(littleEndian) === Boolean(IS_BIG_ENDIAN)) {
575 + bytes.reverse();
576 + }
577 +
578 + return r(new arrayType(new exports.Uint8Array(bytes).buffer), 0);
579 + };
580 + }
581 +
582 + DataView.prototype.getUint8 = makeGetter(exports.Uint8Array);
583 + DataView.prototype.getInt8 = makeGetter(exports.Int8Array);
584 + DataView.prototype.getUint16 = makeGetter(exports.Uint16Array);
585 + DataView.prototype.getInt16 = makeGetter(exports.Int16Array);
586 + DataView.prototype.getUint32 = makeGetter(exports.Uint32Array);
587 + DataView.prototype.getInt32 = makeGetter(exports.Int32Array);
588 + DataView.prototype.getFloat32 = makeGetter(exports.Float32Array);
589 + DataView.prototype.getFloat64 = makeGetter(exports.Float64Array);
590 +
591 + function makeSetter(arrayType) {
592 + return function(byteOffset, value, littleEndian) {
593 +
594 + byteOffset = ECMAScript.ToUint32(byteOffset);
595 + if (byteOffset + arrayType.BYTES_PER_ELEMENT > this.byteLength) {
596 + throw new RangeError("Array index out of range");
597 + }
598 +
599 + // Get bytes
600 + var typeArray = new arrayType([value]),
601 + byteArray = new exports.Uint8Array(typeArray.buffer),
602 + bytes = [], i, byteView;
603 +
604 + for (i = 0; i < arrayType.BYTES_PER_ELEMENT; i += 1) {
605 + bytes.push(r(byteArray, i));
606 + }
607 +
608 + // Flip if necessary
609 + if (Boolean(littleEndian) === Boolean(IS_BIG_ENDIAN)) {
610 + bytes.reverse();
611 + }
612 +
613 + // Write them
614 + byteView = new exports.Uint8Array(this.buffer, byteOffset, arrayType.BYTES_PER_ELEMENT);
615 + byteView.set(bytes);
616 + };
617 + }
618 +
619 + DataView.prototype.setUint8 = makeSetter(exports.Uint8Array);
620 + DataView.prototype.setInt8 = makeSetter(exports.Int8Array);
621 + DataView.prototype.setUint16 = makeSetter(exports.Uint16Array);
622 + DataView.prototype.setInt16 = makeSetter(exports.Int16Array);
623 + DataView.prototype.setUint32 = makeSetter(exports.Uint32Array);
624 + DataView.prototype.setInt32 = makeSetter(exports.Int32Array);
625 + DataView.prototype.setFloat32 = makeSetter(exports.Float32Array);
626 + DataView.prototype.setFloat64 = makeSetter(exports.Float64Array);
627 +
628 + exports.DataView = exports.DataView || DataView;
629 +
630 +}());
1 +{
2 + "_from": "typedarray@^0.0.6",
3 + "_id": "typedarray@0.0.6",
4 + "_inBundle": false,
5 + "_integrity": "sha1-hnrHTjhkGHsdPUfZlqeOxciDB3c=",
6 + "_location": "/typedarray",
7 + "_phantomChildren": {},
8 + "_requested": {
9 + "type": "range",
10 + "registry": true,
11 + "raw": "typedarray@^0.0.6",
12 + "name": "typedarray",
13 + "escapedName": "typedarray",
14 + "rawSpec": "^0.0.6",
15 + "saveSpec": null,
16 + "fetchSpec": "^0.0.6"
17 + },
18 + "_requiredBy": [
19 + "/concat-stream"
20 + ],
21 + "_resolved": "https://registry.npmjs.org/typedarray/-/typedarray-0.0.6.tgz",
22 + "_shasum": "867ac74e3864187b1d3d47d996a78ec5c8830777",
23 + "_spec": "typedarray@^0.0.6",
24 + "_where": "C:\\Users\\1000c\\이것저것\\옾소\\Voicoding\\node_modules\\concat-stream",
25 + "author": {
26 + "name": "James Halliday",
27 + "email": "mail@substack.net",
28 + "url": "http://substack.net"
29 + },
30 + "bugs": {
31 + "url": "https://github.com/substack/typedarray/issues"
32 + },
33 + "bundleDependencies": false,
34 + "deprecated": false,
35 + "description": "TypedArray polyfill for old browsers",
36 + "devDependencies": {
37 + "tape": "~2.3.2"
38 + },
39 + "homepage": "https://github.com/substack/typedarray",
40 + "keywords": [
41 + "ArrayBuffer",
42 + "DataView",
43 + "Float32Array",
44 + "Float64Array",
45 + "Int8Array",
46 + "Int16Array",
47 + "Int32Array",
48 + "Uint8Array",
49 + "Uint8ClampedArray",
50 + "Uint16Array",
51 + "Uint32Array",
52 + "typed",
53 + "array",
54 + "polyfill"
55 + ],
56 + "license": "MIT",
57 + "main": "index.js",
58 + "name": "typedarray",
59 + "repository": {
60 + "type": "git",
61 + "url": "git://github.com/substack/typedarray.git"
62 + },
63 + "scripts": {
64 + "test": "tape test/*.js test/server/*.js"
65 + },
66 + "testling": {
67 + "files": "test/*.js",
68 + "browsers": [
69 + "ie/6..latest",
70 + "firefox/16..latest",
71 + "firefox/nightly",
72 + "chrome/22..latest",
73 + "chrome/canary",
74 + "opera/12..latest",
75 + "opera/next",
76 + "safari/5.1..latest",
77 + "ipad/6.0..latest",
78 + "iphone/6.0..latest",
79 + "android-browser/4.2..latest"
80 + ]
81 + },
82 + "version": "0.0.6"
83 +}
1 +# typedarray
2 +
3 +TypedArray polyfill ripped from [this
4 +module](https://raw.github.com/inexorabletash/polyfill).
5 +
6 +[![build status](https://secure.travis-ci.org/substack/typedarray.png)](http://travis-ci.org/substack/typedarray)
7 +
8 +[![testling badge](https://ci.testling.com/substack/typedarray.png)](https://ci.testling.com/substack/typedarray)
9 +
10 +# example
11 +
12 +``` js
13 +var Uint8Array = require('typedarray').Uint8Array;
14 +var ua = new Uint8Array(5);
15 +ua[1] = 256 + 55;
16 +console.log(ua[1]);
17 +```
18 +
19 +output:
20 +
21 +```
22 +55
23 +```
24 +
25 +# methods
26 +
27 +``` js
28 +var TA = require('typedarray')
29 +```
30 +
31 +The `TA` object has the following constructors:
32 +
33 +* TA.ArrayBuffer
34 +* TA.DataView
35 +* TA.Float32Array
36 +* TA.Float64Array
37 +* TA.Int8Array
38 +* TA.Int16Array
39 +* TA.Int32Array
40 +* TA.Uint8Array
41 +* TA.Uint8ClampedArray
42 +* TA.Uint16Array
43 +* TA.Uint32Array
44 +
45 +# install
46 +
47 +With [npm](https://npmjs.org) do:
48 +
49 +```
50 +npm install typedarray
51 +```
52 +
53 +To use this module in the browser, compile with
54 +[browserify](http://browserify.org)
55 +or download a UMD build from browserify CDN:
56 +
57 +http://wzrd.in/standalone/typedarray@latest
58 +
59 +# license
60 +
61 +MIT
1 +var test = require('tape');
2 +var vm = require('vm');
3 +var fs = require('fs');
4 +var src = fs.readFileSync(__dirname + '/../../index.js', 'utf8');
5 +
6 +test('u8a without globals', function (t) {
7 + var c = {
8 + module: { exports: {} },
9 + };
10 + c.exports = c.module.exports;
11 + vm.runInNewContext(src, c);
12 + var TA = c.module.exports;
13 + var ua = new(TA.Uint8Array)(5);
14 +
15 + t.equal(ua.length, 5);
16 + ua[1] = 256 + 55;
17 + t.equal(ua[1], 55);
18 + t.end();
19 +});
1 +var TA = require('../');
2 +var test = require('tape');
3 +
4 +test('tiny u8a test', function (t) {
5 + var ua = new(TA.Uint8Array)(5);
6 + t.equal(ua.length, 5);
7 + ua[1] = 256 + 55;
8 + t.equal(ua[1], 55);
9 + t.end();
10 +});
1 { 1 {
2 - "_from": "util-deprecate@^1.0.1", 2 + "_from": "util-deprecate@~1.0.1",
3 "_id": "util-deprecate@1.0.2", 3 "_id": "util-deprecate@1.0.2",
4 "_inBundle": false, 4 "_inBundle": false,
5 "_integrity": "sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8=", 5 "_integrity": "sha1-RQ1Nyfpw3nMnYvvS1KKJgUGaDM8=",
...@@ -8,20 +8,20 @@ ...@@ -8,20 +8,20 @@
8 "_requested": { 8 "_requested": {
9 "type": "range", 9 "type": "range",
10 "registry": true, 10 "registry": true,
11 - "raw": "util-deprecate@^1.0.1", 11 + "raw": "util-deprecate@~1.0.1",
12 "name": "util-deprecate", 12 "name": "util-deprecate",
13 "escapedName": "util-deprecate", 13 "escapedName": "util-deprecate",
14 - "rawSpec": "^1.0.1", 14 + "rawSpec": "~1.0.1",
15 "saveSpec": null, 15 "saveSpec": null,
16 - "fetchSpec": "^1.0.1" 16 + "fetchSpec": "~1.0.1"
17 }, 17 },
18 "_requiredBy": [ 18 "_requiredBy": [
19 - "/readable-stream" 19 + "/concat-stream/readable-stream"
20 ], 20 ],
21 "_resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", 21 "_resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",
22 "_shasum": "450d4dc9fa70de732762fbd2d4a28981419a0ccf", 22 "_shasum": "450d4dc9fa70de732762fbd2d4a28981419a0ccf",
23 - "_spec": "util-deprecate@^1.0.1", 23 + "_spec": "util-deprecate@~1.0.1",
24 - "_where": "C:\\Users\\1000c\\이것저것\\옾소\\Voicoding\\node_modules\\readable-stream", 24 + "_where": "C:\\Users\\1000c\\이것저것\\옾소\\Voicoding\\node_modules\\concat-stream\\node_modules\\readable-stream",
25 "author": { 25 "author": {
26 "name": "Nathan Rajlich", 26 "name": "Nathan Rajlich",
27 "email": "nathan@tootallnate.net", 27 "email": "nathan@tootallnate.net",
......
1 +{
2 + "maxdepth": 4,
3 + "maxstatements": 200,
4 + "maxcomplexity": 12,
5 + "maxlen": 80,
6 + "maxparams": 5,
7 +
8 + "curly": true,
9 + "eqeqeq": true,
10 + "immed": true,
11 + "latedef": false,
12 + "noarg": true,
13 + "noempty": true,
14 + "nonew": true,
15 + "undef": true,
16 + "unused": "vars",
17 + "trailing": true,
18 +
19 + "quotmark": true,
20 + "expr": true,
21 + "asi": true,
22 +
23 + "browser": false,
24 + "esnext": true,
25 + "devel": false,
26 + "node": false,
27 + "nonstandard": false,
28 +
29 + "predef": ["require", "module", "__dirname", "__filename"]
30 +}
1 +The MIT License (MIT)
2 +Copyright (c) 2012-2014 Raynos.
3 +
4 +Permission is hereby granted, free of charge, to any person obtaining a copy
5 +of this software and associated documentation files (the "Software"), to deal
6 +in the Software without restriction, including without limitation the rights
7 +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 +copies of the Software, and to permit persons to whom the Software is
9 +furnished to do so, subject to the following conditions:
10 +
11 +The above copyright notice and this permission notice shall be included in
12 +all copies or substantial portions of the Software.
13 +
14 +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 +THE SOFTWARE.
1 +# xtend
2 +
3 +[![browser support][3]][4]
4 +
5 +[![locked](http://badges.github.io/stability-badges/dist/locked.svg)](http://github.com/badges/stability-badges)
6 +
7 +Extend like a boss
8 +
9 +xtend is a basic utility library which allows you to extend an object by appending all of the properties from each object in a list. When there are identical properties, the right-most property takes precedence.
10 +
11 +## Examples
12 +
13 +```js
14 +var extend = require("xtend")
15 +
16 +// extend returns a new object. Does not mutate arguments
17 +var combination = extend({
18 + a: "a",
19 + b: "c"
20 +}, {
21 + b: "b"
22 +})
23 +// { a: "a", b: "b" }
24 +```
25 +
26 +## Stability status: Locked
27 +
28 +## MIT Licensed
29 +
30 +
31 + [3]: http://ci.testling.com/Raynos/xtend.png
32 + [4]: http://ci.testling.com/Raynos/xtend
1 +module.exports = extend
2 +
3 +var hasOwnProperty = Object.prototype.hasOwnProperty;
4 +
5 +function extend() {
6 + var target = {}
7 +
8 + for (var i = 0; i < arguments.length; i++) {
9 + var source = arguments[i]
10 +
11 + for (var key in source) {
12 + if (hasOwnProperty.call(source, key)) {
13 + target[key] = source[key]
14 + }
15 + }
16 + }
17 +
18 + return target
19 +}
1 +module.exports = extend
2 +
3 +var hasOwnProperty = Object.prototype.hasOwnProperty;
4 +
5 +function extend(target) {
6 + for (var i = 1; i < arguments.length; i++) {
7 + var source = arguments[i]
8 +
9 + for (var key in source) {
10 + if (hasOwnProperty.call(source, key)) {
11 + target[key] = source[key]
12 + }
13 + }
14 + }
15 +
16 + return target
17 +}
1 +{
2 + "_from": "xtend@^4.0.0",
3 + "_id": "xtend@4.0.2",
4 + "_inBundle": false,
5 + "_integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==",
6 + "_location": "/xtend",
7 + "_phantomChildren": {},
8 + "_requested": {
9 + "type": "range",
10 + "registry": true,
11 + "raw": "xtend@^4.0.0",
12 + "name": "xtend",
13 + "escapedName": "xtend",
14 + "rawSpec": "^4.0.0",
15 + "saveSpec": null,
16 + "fetchSpec": "^4.0.0"
17 + },
18 + "_requiredBy": [
19 + "/multer"
20 + ],
21 + "_resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz",
22 + "_shasum": "bb72779f5fa465186b1f438f674fa347fdb5db54",
23 + "_spec": "xtend@^4.0.0",
24 + "_where": "C:\\Users\\1000c\\이것저것\\옾소\\Voicoding\\node_modules\\multer",
25 + "author": {
26 + "name": "Raynos",
27 + "email": "raynos2@gmail.com"
28 + },
29 + "bugs": {
30 + "url": "https://github.com/Raynos/xtend/issues",
31 + "email": "raynos2@gmail.com"
32 + },
33 + "bundleDependencies": false,
34 + "contributors": [
35 + {
36 + "name": "Jake Verbaten"
37 + },
38 + {
39 + "name": "Matt Esch"
40 + }
41 + ],
42 + "dependencies": {},
43 + "deprecated": false,
44 + "description": "extend like a boss",
45 + "devDependencies": {
46 + "tape": "~1.1.0"
47 + },
48 + "engines": {
49 + "node": ">=0.4"
50 + },
51 + "homepage": "https://github.com/Raynos/xtend",
52 + "keywords": [
53 + "extend",
54 + "merge",
55 + "options",
56 + "opts",
57 + "object",
58 + "array"
59 + ],
60 + "license": "MIT",
61 + "main": "immutable",
62 + "name": "xtend",
63 + "repository": {
64 + "type": "git",
65 + "url": "git://github.com/Raynos/xtend.git"
66 + },
67 + "scripts": {
68 + "test": "node test"
69 + },
70 + "testling": {
71 + "files": "test.js",
72 + "browsers": [
73 + "ie/7..latest",
74 + "firefox/16..latest",
75 + "firefox/nightly",
76 + "chrome/22..latest",
77 + "chrome/canary",
78 + "opera/12..latest",
79 + "opera/next",
80 + "safari/5.1..latest",
81 + "ipad/6.0..latest",
82 + "iphone/6.0..latest"
83 + ]
84 + },
85 + "version": "4.0.2"
86 +}
1 +var test = require("tape")
2 +var extend = require("./")
3 +var mutableExtend = require("./mutable")
4 +
5 +test("merge", function(assert) {
6 + var a = { a: "foo" }
7 + var b = { b: "bar" }
8 +
9 + assert.deepEqual(extend(a, b), { a: "foo", b: "bar" })
10 + assert.end()
11 +})
12 +
13 +test("replace", function(assert) {
14 + var a = { a: "foo" }
15 + var b = { a: "bar" }
16 +
17 + assert.deepEqual(extend(a, b), { a: "bar" })
18 + assert.end()
19 +})
20 +
21 +test("undefined", function(assert) {
22 + var a = { a: undefined }
23 + var b = { b: "foo" }
24 +
25 + assert.deepEqual(extend(a, b), { a: undefined, b: "foo" })
26 + assert.deepEqual(extend(b, a), { a: undefined, b: "foo" })
27 + assert.end()
28 +})
29 +
30 +test("handle 0", function(assert) {
31 + var a = { a: "default" }
32 + var b = { a: 0 }
33 +
34 + assert.deepEqual(extend(a, b), { a: 0 })
35 + assert.deepEqual(extend(b, a), { a: "default" })
36 + assert.end()
37 +})
38 +
39 +test("is immutable", function (assert) {
40 + var record = {}
41 +
42 + extend(record, { foo: "bar" })
43 + assert.equal(record.foo, undefined)
44 + assert.end()
45 +})
46 +
47 +test("null as argument", function (assert) {
48 + var a = { foo: "bar" }
49 + var b = null
50 + var c = void 0
51 +
52 + assert.deepEqual(extend(b, a, c), { foo: "bar" })
53 + assert.end()
54 +})
55 +
56 +test("mutable", function (assert) {
57 + var a = { foo: "bar" }
58 +
59 + mutableExtend(a, { bar: "baz" })
60 +
61 + assert.equal(a.bar, "baz")
62 + assert.end()
63 +})
64 +
65 +test("null prototype", function(assert) {
66 + var a = { a: "foo" }
67 + var b = Object.create(null)
68 + b.b = "bar";
69 +
70 + assert.deepEqual(extend(a, b), { a: "foo", b: "bar" })
71 + assert.end()
72 +})
73 +
74 +test("null prototype mutable", function (assert) {
75 + var a = { foo: "bar" }
76 + var b = Object.create(null)
77 + b.bar = "baz";
78 +
79 + mutableExtend(a, b)
80 +
81 + assert.equal(a.bar, "baz")
82 + assert.end()
83 +})
84 +
85 +test("prototype pollution", function (assert) {
86 + var a = {}
87 + var maliciousPayload = '{"__proto__":{"oops":"It works!"}}'
88 +
89 + assert.strictEqual(a.oops, undefined)
90 + extend({}, maliciousPayload)
91 + assert.strictEqual(a.oops, undefined)
92 + assert.end()
93 +})
94 +
95 +test("prototype pollution mutable", function (assert) {
96 + var a = {}
97 + var maliciousPayload = '{"__proto__":{"oops":"It works!"}}'
98 +
99 + assert.strictEqual(a.oops, undefined)
100 + mutableExtend({}, maliciousPayload)
101 + assert.strictEqual(a.oops, undefined)
102 + assert.end()
103 +})
...@@ -135,9 +135,9 @@ ...@@ -135,9 +135,9 @@
135 "integrity": "sha512-5tXH6Bx/kNGd3MgffdmP4dy2Z+G4eaXw0SE81Tq3BNadtnMR5/ySMzX4SLEzHJzSmPNn4HIdpQsBvXMUykr58w==" 135 "integrity": "sha512-5tXH6Bx/kNGd3MgffdmP4dy2Z+G4eaXw0SE81Tq3BNadtnMR5/ySMzX4SLEzHJzSmPNn4HIdpQsBvXMUykr58w=="
136 }, 136 },
137 "@types/node": { 137 "@types/node": {
138 - "version": "15.6.0", 138 + "version": "15.6.2",
139 - "resolved": "https://registry.npmjs.org/@types/node/-/node-15.6.0.tgz", 139 + "resolved": "https://registry.npmjs.org/@types/node/-/node-15.6.2.tgz",
140 - "integrity": "sha512-gCYSfQpy+LYhOFTKAeE8BkyGqaxmlFxe+n4DKM6DR0wzw/HISUE/hAmkC/KT8Sw5PCJblqg062b3z9gucv3k0A==" 140 + "integrity": "sha512-dxcOx8801kMo3KlU+C+/ctWrzREAH7YvoF3aoVpRdqgs+Kf7flp+PJDN/EX5bME3suDUZHsxes9hpvBmzYlWbA=="
141 }, 141 },
142 "@types/pumpify": { 142 "@types/pumpify": {
143 "version": "1.4.1", 143 "version": "1.4.1",
...@@ -186,6 +186,11 @@ ...@@ -186,6 +186,11 @@
186 "color-convert": "^2.0.1" 186 "color-convert": "^2.0.1"
187 } 187 }
188 }, 188 },
189 + "append-field": {
190 + "version": "1.0.0",
191 + "resolved": "https://registry.npmjs.org/append-field/-/append-field-1.0.0.tgz",
192 + "integrity": "sha1-HjRA6RXwsSA9I3SOeO3XubW0PlY="
193 + },
189 "array-flatten": { 194 "array-flatten": {
190 "version": "1.1.1", 195 "version": "1.1.1",
191 "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz", 196 "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz",
...@@ -243,6 +248,20 @@ ...@@ -243,6 +248,20 @@
243 "resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz", 248 "resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz",
244 "integrity": "sha1-+OcRMvf/5uAaXJaXpMbz5I1cyBk=" 249 "integrity": "sha1-+OcRMvf/5uAaXJaXpMbz5I1cyBk="
245 }, 250 },
251 + "buffer-from": {
252 + "version": "1.1.1",
253 + "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.1.tgz",
254 + "integrity": "sha512-MQcXEUbCKtEo7bhqEs6560Hyd4XaovZlO/k9V3hjVUF/zwW7KBVdSK4gIt/bzwS9MbR5qob+F5jusZsb0YQK2A=="
255 + },
256 + "busboy": {
257 + "version": "0.2.14",
258 + "resolved": "https://registry.npmjs.org/busboy/-/busboy-0.2.14.tgz",
259 + "integrity": "sha1-bCpiLvz0fFe7vh4qnDetNseSVFM=",
260 + "requires": {
261 + "dicer": "0.2.5",
262 + "readable-stream": "1.1.x"
263 + }
264 + },
246 "bytes": { 265 "bytes": {
247 "version": "3.1.0", 266 "version": "3.1.0",
248 "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.0.tgz", 267 "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.0.tgz",
...@@ -271,6 +290,46 @@ ...@@ -271,6 +290,46 @@
271 "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", 290 "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz",
272 "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==" 291 "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA=="
273 }, 292 },
293 + "concat-stream": {
294 + "version": "1.6.2",
295 + "resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-1.6.2.tgz",
296 + "integrity": "sha512-27HBghJxjiZtIk3Ycvn/4kbJk/1uZuJFfuPEns6LaEvpvG1f0hTea8lilrouyo9mVc2GWdcEZ8OLoGmSADlrCw==",
297 + "requires": {
298 + "buffer-from": "^1.0.0",
299 + "inherits": "^2.0.3",
300 + "readable-stream": "^2.2.2",
301 + "typedarray": "^0.0.6"
302 + },
303 + "dependencies": {
304 + "isarray": {
305 + "version": "1.0.0",
306 + "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz",
307 + "integrity": "sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE="
308 + },
309 + "readable-stream": {
310 + "version": "2.3.7",
311 + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.7.tgz",
312 + "integrity": "sha512-Ebho8K4jIbHAxnuxi7o42OrZgF/ZTNcsZj6nRKyUmkhLFq8CHItp/fy6hQZuZmP/n3yZ9VBUbp4zz/mX8hmYPw==",
313 + "requires": {
314 + "core-util-is": "~1.0.0",
315 + "inherits": "~2.0.3",
316 + "isarray": "~1.0.0",
317 + "process-nextick-args": "~2.0.0",
318 + "safe-buffer": "~5.1.1",
319 + "string_decoder": "~1.1.1",
320 + "util-deprecate": "~1.0.1"
321 + }
322 + },
323 + "string_decoder": {
324 + "version": "1.1.1",
325 + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz",
326 + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==",
327 + "requires": {
328 + "safe-buffer": "~5.1.0"
329 + }
330 + }
331 + }
332 + },
274 "content-disposition": { 333 "content-disposition": {
275 "version": "0.5.3", 334 "version": "0.5.3",
276 "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.3.tgz", 335 "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.3.tgz",
...@@ -301,6 +360,11 @@ ...@@ -301,6 +360,11 @@
301 "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz", 360 "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz",
302 "integrity": "sha1-4wOogrNCzD7oylE6eZmXNNqzriw=" 361 "integrity": "sha1-4wOogrNCzD7oylE6eZmXNNqzriw="
303 }, 362 },
363 + "core-util-is": {
364 + "version": "1.0.2",
365 + "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz",
366 + "integrity": "sha1-tf1UIgqivFq1eqtxQMlAdUUDwac="
367 + },
304 "debug": { 368 "debug": {
305 "version": "4.3.1", 369 "version": "4.3.1",
306 "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.1.tgz", 370 "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.1.tgz",
...@@ -319,6 +383,15 @@ ...@@ -319,6 +383,15 @@
319 "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.0.4.tgz", 383 "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.0.4.tgz",
320 "integrity": "sha1-l4hXRCxEdJ5CBmE+N5RiBYJqvYA=" 384 "integrity": "sha1-l4hXRCxEdJ5CBmE+N5RiBYJqvYA="
321 }, 385 },
386 + "dicer": {
387 + "version": "0.2.5",
388 + "resolved": "https://registry.npmjs.org/dicer/-/dicer-0.2.5.tgz",
389 + "integrity": "sha1-WZbAhrszIYyBLAkL3cCc0S+stw8=",
390 + "requires": {
391 + "readable-stream": "1.1.x",
392 + "streamsearch": "0.1.2"
393 + }
394 + },
322 "duplexify": { 395 "duplexify": {
323 "version": "4.1.1", 396 "version": "4.1.1",
324 "resolved": "https://registry.npmjs.org/duplexify/-/duplexify-4.1.1.tgz", 397 "resolved": "https://registry.npmjs.org/duplexify/-/duplexify-4.1.1.tgz",
...@@ -328,6 +401,31 @@ ...@@ -328,6 +401,31 @@
328 "inherits": "^2.0.3", 401 "inherits": "^2.0.3",
329 "readable-stream": "^3.1.1", 402 "readable-stream": "^3.1.1",
330 "stream-shift": "^1.0.0" 403 "stream-shift": "^1.0.0"
404 + },
405 + "dependencies": {
406 + "readable-stream": {
407 + "version": "3.6.0",
408 + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.0.tgz",
409 + "integrity": "sha512-BViHy7LKeTz4oNnkcLJ+lVSL6vpiFeX6/d3oSH8zCW7UxP2onchk+vTGB143xuFjHS3deTgkKoXXymXqymiIdA==",
410 + "requires": {
411 + "inherits": "^2.0.3",
412 + "string_decoder": "^1.1.1",
413 + "util-deprecate": "^1.0.1"
414 + }
415 + },
416 + "safe-buffer": {
417 + "version": "5.2.1",
418 + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
419 + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ=="
420 + },
421 + "string_decoder": {
422 + "version": "1.3.0",
423 + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz",
424 + "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==",
425 + "requires": {
426 + "safe-buffer": "~5.2.0"
427 + }
428 + }
331 } 429 }
332 }, 430 },
333 "ecdsa-sig-formatter": { 431 "ecdsa-sig-formatter": {
...@@ -492,10 +590,15 @@ ...@@ -492,10 +590,15 @@
492 "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz", 590 "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz",
493 "integrity": "sha1-PYyt2Q2XZWn6g1qx+OSyOhBWBac=" 591 "integrity": "sha1-PYyt2Q2XZWn6g1qx+OSyOhBWBac="
494 }, 592 },
593 + "fs": {
594 + "version": "0.0.1-security",
595 + "resolved": "https://registry.npmjs.org/fs/-/fs-0.0.1-security.tgz",
596 + "integrity": "sha1-invTcYa23d84E/I4WLV+yq9eQdQ="
597 + },
495 "gaxios": { 598 "gaxios": {
496 - "version": "4.2.1", 599 + "version": "4.3.0",
497 - "resolved": "https://registry.npmjs.org/gaxios/-/gaxios-4.2.1.tgz", 600 + "resolved": "https://registry.npmjs.org/gaxios/-/gaxios-4.3.0.tgz",
498 - "integrity": "sha512-s+rTywpw6CmfB8r9TXYkpix7YFeuRjnR/AqhaJrQqsNhsAqej+IAiCc3hadzQH3gHyWth30tvYjxH8EVjQt/8Q==", 601 + "integrity": "sha512-pHplNbslpwCLMyII/lHPWFQbJWOX0B3R1hwBEOvzYi1GmdKZruuEHK4N9V6f7tf1EaPYyF80mui1+344p6SmLg==",
499 "requires": { 602 "requires": {
500 "abort-controller": "^3.0.0", 603 "abort-controller": "^3.0.0",
501 "extend": "^3.0.2", 604 "extend": "^3.0.2",
...@@ -519,9 +622,9 @@ ...@@ -519,9 +622,9 @@
519 "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==" 622 "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg=="
520 }, 623 },
521 "google-auth-library": { 624 "google-auth-library": {
522 - "version": "7.0.4", 625 + "version": "7.1.0",
523 - "resolved": "https://registry.npmjs.org/google-auth-library/-/google-auth-library-7.0.4.tgz", 626 + "resolved": "https://registry.npmjs.org/google-auth-library/-/google-auth-library-7.1.0.tgz",
524 - "integrity": "sha512-o8irYyeijEiecTXeoEe8UKNEzV1X+uhR4b2oNdapDMZixypp0J+eHimGOyx5Joa3UAeokGngdtDLXtq9vDqG2Q==", 627 + "integrity": "sha512-X+gbkGjnLN3HUZP2W3KBREuA603BXd80ITvL0PeS0QpyDNYz/u0pIZ7aRuGnrSuUc0grk/qxEgtVTFt1ogbP+A==",
525 "requires": { 628 "requires": {
526 "arrify": "^2.0.0", 629 "arrify": "^2.0.0",
527 "base64-js": "^1.3.0", 630 "base64-js": "^1.3.0",
...@@ -535,9 +638,9 @@ ...@@ -535,9 +638,9 @@
535 } 638 }
536 }, 639 },
537 "google-gax": { 640 "google-gax": {
538 - "version": "2.13.0", 641 + "version": "2.14.1",
539 - "resolved": "https://registry.npmjs.org/google-gax/-/google-gax-2.13.0.tgz", 642 + "resolved": "https://registry.npmjs.org/google-gax/-/google-gax-2.14.1.tgz",
540 - "integrity": "sha512-aKNJy2+Vv2I7flyNYbwpq0aYBHp6Qv32HZn+wr6ZhZ8xlSCLS9K9k7izfh2nd1rCJQcsqB6KMxHV0Vwny6Rc1g==", 643 + "integrity": "sha512-I5RDEN7MEptrCxeHX3ht7nKFGfyjgYX4hQKI9eVMBohMzVbFSwWUndo0CcKXu8es7NhB4gt2XYLm1AHkXhtHpA==",
541 "requires": { 644 "requires": {
542 "@grpc/grpc-js": "~1.3.0", 645 "@grpc/grpc-js": "~1.3.0",
543 "@grpc/proto-loader": "^0.6.1", 646 "@grpc/proto-loader": "^0.6.1",
...@@ -642,6 +745,11 @@ ...@@ -642,6 +745,11 @@
642 "resolved": "https://registry.npmjs.org/is-stream-ended/-/is-stream-ended-0.1.4.tgz", 745 "resolved": "https://registry.npmjs.org/is-stream-ended/-/is-stream-ended-0.1.4.tgz",
643 "integrity": "sha512-xj0XPvmr7bQFTvirqnFr50o0hQIh6ZItDqloxt5aJrR4NQsYeSsyFQERYGCAzfindAcnKjINnwEEgLx4IqVzQw==" 746 "integrity": "sha512-xj0XPvmr7bQFTvirqnFr50o0hQIh6ZItDqloxt5aJrR4NQsYeSsyFQERYGCAzfindAcnKjINnwEEgLx4IqVzQw=="
644 }, 747 },
748 + "isarray": {
749 + "version": "0.0.1",
750 + "resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz",
751 + "integrity": "sha1-ihis/Kmo9Bd+Cav8YDiTmwXR7t8="
752 + },
645 "json-bigint": { 753 "json-bigint": {
646 "version": "1.0.0", 754 "version": "1.0.0",
647 "resolved": "https://registry.npmjs.org/json-bigint/-/json-bigint-1.0.0.tgz", 755 "resolved": "https://registry.npmjs.org/json-bigint/-/json-bigint-1.0.0.tgz",
...@@ -720,11 +828,39 @@ ...@@ -720,11 +828,39 @@
720 "mime-db": "1.47.0" 828 "mime-db": "1.47.0"
721 } 829 }
722 }, 830 },
831 + "minimist": {
832 + "version": "1.2.5",
833 + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.5.tgz",
834 + "integrity": "sha512-FM9nNUYrRBAELZQT3xeZQ7fmMOBg6nWNmJKTcgsJeaLstP/UODVpGsr5OhXhhXg6f+qtJ8uiZ+PUxkDWcgIXLw=="
835 + },
836 + "mkdirp": {
837 + "version": "0.5.5",
838 + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.5.tgz",
839 + "integrity": "sha512-NKmAlESf6jMGym1++R0Ra7wvhV+wFW63FaSOFPwRahvea0gMUcGUhVeAg/0BC0wiv9ih5NYPB1Wn1UEI1/L+xQ==",
840 + "requires": {
841 + "minimist": "^1.2.5"
842 + }
843 + },
723 "ms": { 844 "ms": {
724 "version": "2.1.2", 845 "version": "2.1.2",
725 "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", 846 "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz",
726 "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" 847 "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w=="
727 }, 848 },
849 + "multer": {
850 + "version": "1.4.2",
851 + "resolved": "https://registry.npmjs.org/multer/-/multer-1.4.2.tgz",
852 + "integrity": "sha512-xY8pX7V+ybyUpbYMxtjM9KAiD9ixtg5/JkeKUTD6xilfDv0vzzOFcCp4Ljb1UU3tSOM3VTZtKo63OmzOrGi3Cg==",
853 + "requires": {
854 + "append-field": "^1.0.0",
855 + "busboy": "^0.2.11",
856 + "concat-stream": "^1.5.2",
857 + "mkdirp": "^0.5.1",
858 + "object-assign": "^4.1.1",
859 + "on-finished": "^2.3.0",
860 + "type-is": "^1.6.4",
861 + "xtend": "^4.0.0"
862 + }
863 + },
728 "negotiator": { 864 "negotiator": {
729 "version": "0.6.2", 865 "version": "0.6.2",
730 "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.2.tgz", 866 "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.2.tgz",
...@@ -763,10 +899,15 @@ ...@@ -763,10 +899,15 @@
763 } 899 }
764 } 900 }
765 }, 901 },
902 + "object-assign": {
903 + "version": "4.1.1",
904 + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
905 + "integrity": "sha1-IQmtx5ZYh8/AXLvUQsrIv7s2CGM="
906 + },
766 "object-hash": { 907 "object-hash": {
767 - "version": "2.1.1", 908 + "version": "2.2.0",
768 - "resolved": "https://registry.npmjs.org/object-hash/-/object-hash-2.1.1.tgz", 909 + "resolved": "https://registry.npmjs.org/object-hash/-/object-hash-2.2.0.tgz",
769 - "integrity": "sha512-VOJmgmS+7wvXf8CjbQmimtCnEx3IAoLxI3fp2fbWehxrWBcAQFbk+vcwb6vzR0VZv/eNCJ/27j151ZTwqW/JeQ==" 910 + "integrity": "sha512-gScRMn0bS5fH+IuwyIFgnh9zBdo4DV+6GhygmWM9HyNJSgS0hScp1f5vjtm7oIIOiT9trXrShAkLFSc2IqKNgw=="
770 }, 911 },
771 "on-finished": { 912 "on-finished": {
772 "version": "2.3.0", 913 "version": "2.3.0",
...@@ -794,6 +935,11 @@ ...@@ -794,6 +935,11 @@
794 "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.7.tgz", 935 "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.7.tgz",
795 "integrity": "sha1-32BBeABfUi8V60SQ5yR6G/qmf4w=" 936 "integrity": "sha1-32BBeABfUi8V60SQ5yR6G/qmf4w="
796 }, 937 },
938 + "process-nextick-args": {
939 + "version": "2.0.1",
940 + "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz",
941 + "integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag=="
942 + },
797 "protobufjs": { 943 "protobufjs": {
798 "version": "6.11.2", 944 "version": "6.11.2",
799 "resolved": "https://registry.npmjs.org/protobufjs/-/protobufjs-6.11.2.tgz", 945 "resolved": "https://registry.npmjs.org/protobufjs/-/protobufjs-6.11.2.tgz",
...@@ -864,13 +1010,14 @@ ...@@ -864,13 +1010,14 @@
864 } 1010 }
865 }, 1011 },
866 "readable-stream": { 1012 "readable-stream": {
867 - "version": "3.6.0", 1013 + "version": "1.1.14",
868 - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.0.tgz", 1014 + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-1.1.14.tgz",
869 - "integrity": "sha512-BViHy7LKeTz4oNnkcLJ+lVSL6vpiFeX6/d3oSH8zCW7UxP2onchk+vTGB143xuFjHS3deTgkKoXXymXqymiIdA==", 1015 + "integrity": "sha1-fPTFTvZI44EwhMY23SB54WbAgdk=",
870 "requires": { 1016 "requires": {
871 - "inherits": "^2.0.3", 1017 + "core-util-is": "~1.0.0",
872 - "string_decoder": "^1.1.1", 1018 + "inherits": "~2.0.1",
873 - "util-deprecate": "^1.0.1" 1019 + "isarray": "0.0.1",
1020 + "string_decoder": "~0.10.x"
874 } 1021 }
875 }, 1022 },
876 "require-directory": { 1023 "require-directory": {
...@@ -887,9 +1034,9 @@ ...@@ -887,9 +1034,9 @@
887 } 1034 }
888 }, 1035 },
889 "safe-buffer": { 1036 "safe-buffer": {
890 - "version": "5.2.1", 1037 + "version": "5.1.2",
891 - "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", 1038 + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz",
892 - "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==" 1039 + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g=="
893 }, 1040 },
894 "safer-buffer": { 1041 "safer-buffer": {
895 "version": "2.1.2", 1042 "version": "2.1.2",
...@@ -972,6 +1119,11 @@ ...@@ -972,6 +1119,11 @@
972 "resolved": "https://registry.npmjs.org/stream-shift/-/stream-shift-1.0.1.tgz", 1119 "resolved": "https://registry.npmjs.org/stream-shift/-/stream-shift-1.0.1.tgz",
973 "integrity": "sha512-AiisoFqQ0vbGcZgQPY1cdP2I76glaVA/RauYR4G4thNFgkTqr90yXTo4LYX60Jl+sIlPNHHdGSwo01AvbKUSVQ==" 1120 "integrity": "sha512-AiisoFqQ0vbGcZgQPY1cdP2I76glaVA/RauYR4G4thNFgkTqr90yXTo4LYX60Jl+sIlPNHHdGSwo01AvbKUSVQ=="
974 }, 1121 },
1122 + "streamsearch": {
1123 + "version": "0.1.2",
1124 + "resolved": "https://registry.npmjs.org/streamsearch/-/streamsearch-0.1.2.tgz",
1125 + "integrity": "sha1-gIudDlb8Jz2Am6VzOOkpkZoanxo="
1126 + },
975 "string-width": { 1127 "string-width": {
976 "version": "4.2.2", 1128 "version": "4.2.2",
977 "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.2.tgz", 1129 "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.2.tgz",
...@@ -983,12 +1135,9 @@ ...@@ -983,12 +1135,9 @@
983 } 1135 }
984 }, 1136 },
985 "string_decoder": { 1137 "string_decoder": {
986 - "version": "1.3.0", 1138 + "version": "0.10.31",
987 - "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", 1139 + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-0.10.31.tgz",
988 - "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", 1140 + "integrity": "sha1-YuIDvEF2bGwoyfyEMB2rHFMQ+pQ="
989 - "requires": {
990 - "safe-buffer": "~5.2.0"
991 - }
992 }, 1141 },
993 "strip-ansi": { 1142 "strip-ansi": {
994 "version": "6.0.0", 1143 "version": "6.0.0",
...@@ -1029,6 +1178,11 @@ ...@@ -1029,6 +1178,11 @@
1029 "mime-types": "~2.1.24" 1178 "mime-types": "~2.1.24"
1030 } 1179 }
1031 }, 1180 },
1181 + "typedarray": {
1182 + "version": "0.0.6",
1183 + "resolved": "https://registry.npmjs.org/typedarray/-/typedarray-0.0.6.tgz",
1184 + "integrity": "sha1-hnrHTjhkGHsdPUfZlqeOxciDB3c="
1185 + },
1032 "unpipe": { 1186 "unpipe": {
1033 "version": "1.0.0", 1187 "version": "1.0.0",
1034 "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", 1188 "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz",
...@@ -1069,6 +1223,11 @@ ...@@ -1069,6 +1223,11 @@
1069 "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", 1223 "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
1070 "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=" 1224 "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8="
1071 }, 1225 },
1226 + "xtend": {
1227 + "version": "4.0.2",
1228 + "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz",
1229 + "integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ=="
1230 + },
1072 "y18n": { 1231 "y18n": {
1073 "version": "5.0.8", 1232 "version": "5.0.8",
1074 "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", 1233 "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz",
......