j?j:g+f));return 1===d?(b=a[c-1],e.push(k[b>>2]+k[63&b<<4]+"==")):2===d&&(b=(a[c-2]<<8)+a[c-1],e.push(k[b>>10]+k[63&b>>4]+k[63&b<<2]+"=")),e.join("")}c.byteLength=function(a){var b=d(a),c=b[0],e=b[1];return 3*(c+e)/4-e},c.toByteArray=f,c.fromByteArray=j;for(var k=[],l=[],m="undefined"==typeof Uint8Array?Array:Uint8Array,n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",o=0,p=n.length;o 0) {
+ throw new Error('Invalid string. Length must be a multiple of 4')
+ }
+
+ // Trim off extra bytes after placeholder bytes are found
+ // See: https://github.com/beatgammit/base64-js/issues/42
+ var validLen = b64.indexOf('=')
+ if (validLen === -1) validLen = len
+
+ var placeHoldersLen = validLen === len
+ ? 0
+ : 4 - (validLen % 4)
+
+ return [validLen, placeHoldersLen]
+}
+
+// base64 is 4/3 + up to two characters of the original data
+function byteLength (b64) {
+ var lens = getLens(b64)
+ var validLen = lens[0]
+ var placeHoldersLen = lens[1]
+ return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
+}
+
+function _byteLength (b64, validLen, placeHoldersLen) {
+ return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
+}
+
+function toByteArray (b64) {
+ var tmp
+ var lens = getLens(b64)
+ var validLen = lens[0]
+ var placeHoldersLen = lens[1]
+
+ var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))
+
+ var curByte = 0
+
+ // if there are placeholders, only get up to the last complete 4 chars
+ var len = placeHoldersLen > 0
+ ? validLen - 4
+ : validLen
+
+ var i
+ for (i = 0; i < len; i += 4) {
+ tmp =
+ (revLookup[b64.charCodeAt(i)] << 18) |
+ (revLookup[b64.charCodeAt(i + 1)] << 12) |
+ (revLookup[b64.charCodeAt(i + 2)] << 6) |
+ revLookup[b64.charCodeAt(i + 3)]
+ arr[curByte++] = (tmp >> 16) & 0xFF
+ arr[curByte++] = (tmp >> 8) & 0xFF
+ arr[curByte++] = tmp & 0xFF
+ }
+
+ if (placeHoldersLen === 2) {
+ tmp =
+ (revLookup[b64.charCodeAt(i)] << 2) |
+ (revLookup[b64.charCodeAt(i + 1)] >> 4)
+ arr[curByte++] = tmp & 0xFF
+ }
+
+ if (placeHoldersLen === 1) {
+ tmp =
+ (revLookup[b64.charCodeAt(i)] << 10) |
+ (revLookup[b64.charCodeAt(i + 1)] << 4) |
+ (revLookup[b64.charCodeAt(i + 2)] >> 2)
+ arr[curByte++] = (tmp >> 8) & 0xFF
+ arr[curByte++] = tmp & 0xFF
+ }
+
+ return arr
+}
+
+function tripletToBase64 (num) {
+ return lookup[num >> 18 & 0x3F] +
+ lookup[num >> 12 & 0x3F] +
+ lookup[num >> 6 & 0x3F] +
+ lookup[num & 0x3F]
+}
+
+function encodeChunk (uint8, start, end) {
+ var tmp
+ var output = []
+ for (var i = start; i < end; i += 3) {
+ tmp =
+ ((uint8[i] << 16) & 0xFF0000) +
+ ((uint8[i + 1] << 8) & 0xFF00) +
+ (uint8[i + 2] & 0xFF)
+ output.push(tripletToBase64(tmp))
+ }
+ return output.join('')
+}
+
+function fromByteArray (uint8) {
+ var tmp
+ var len = uint8.length
+ var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
+ var parts = []
+ var maxChunkLength = 16383 // must be multiple of 3
+
+ // go through the array every three bytes, we'll deal with trailing stuff later
+ for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
+ parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
+ }
+
+ // pad the end with zeros, but make sure to not forget the extra bytes
+ if (extraBytes === 1) {
+ tmp = uint8[len - 1]
+ parts.push(
+ lookup[tmp >> 2] +
+ lookup[(tmp << 4) & 0x3F] +
+ '=='
+ )
+ } else if (extraBytes === 2) {
+ tmp = (uint8[len - 2] << 8) + uint8[len - 1]
+ parts.push(
+ lookup[tmp >> 10] +
+ lookup[(tmp >> 4) & 0x3F] +
+ lookup[(tmp << 2) & 0x3F] +
+ '='
+ )
+ }
+
+ return parts.join('')
+}
diff --git a/temporary_modules/trezor-connect/node_modules/base64-js/package.json b/temporary_modules/trezor-connect/node_modules/base64-js/package.json
new file mode 100644
index 00000000..c3972e39
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/base64-js/package.json
@@ -0,0 +1,47 @@
+{
+ "name": "base64-js",
+ "description": "Base64 encoding/decoding in pure JS",
+ "version": "1.5.1",
+ "author": "T. Jameson Little ",
+ "typings": "index.d.ts",
+ "bugs": {
+ "url": "https://github.com/beatgammit/base64-js/issues"
+ },
+ "devDependencies": {
+ "babel-minify": "^0.5.1",
+ "benchmark": "^2.1.4",
+ "browserify": "^16.3.0",
+ "standard": "*",
+ "tape": "4.x"
+ },
+ "homepage": "https://github.com/beatgammit/base64-js",
+ "keywords": [
+ "base64"
+ ],
+ "license": "MIT",
+ "main": "index.js",
+ "repository": {
+ "type": "git",
+ "url": "git://github.com/beatgammit/base64-js.git"
+ },
+ "scripts": {
+ "build": "browserify -s base64js -r ./ | minify > base64js.min.js",
+ "lint": "standard",
+ "test": "npm run lint && npm run unit",
+ "unit": "tape test/*.js"
+ },
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ]
+}
diff --git a/temporary_modules/trezor-connect/node_modules/big-integer/BigInteger.d.ts b/temporary_modules/trezor-connect/node_modules/big-integer/BigInteger.d.ts
new file mode 100644
index 00000000..168ba5f4
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/big-integer/BigInteger.d.ts
@@ -0,0 +1,2393 @@
+/**
+ * Type definitions for BigInteger.js
+ * Definitions by: Tommy Frazier
+ */
+export = bigInt;
+export as namespace bigInt;
+
+declare var bigInt: bigInt.BigIntegerStatic;
+
+declare namespace bigInt {
+ type BigNumber = number | bigint | string | BigInteger;
+
+ interface BigIntegerStatic {
+ /**
+ * Equivalent to bigInt(0).
+ */
+ (): BigInteger;
+
+ /**
+ * Parse a Javascript number into a bigInt.
+ */
+ (number: number): BigInteger;
+
+ /**
+ * Parse a Javascript native bigint into a bigInt.
+ */
+ (number: bigint): BigInteger;
+
+ /**
+ * Parse a string into a bigInt.
+ * Default base is 10.
+ * Default alphabet is "0123456789abcdefghijklmnopqrstuvwxyz".
+ * caseSensitive defaults to false.
+ */
+ (string: string, base?: BigNumber, alphabet?: string, caseSensitive?: boolean): BigInteger;
+
+ /**
+ * no-op.
+ */
+ (bigInt: BigInteger): BigInteger;
+
+ /**
+ * Constructs a bigInt from an array of digits in specified base.
+ * The optional isNegative flag will make the number negative.
+ */
+ fromArray: (digits: BigNumber[], base?: BigNumber, isNegative?: boolean) => BigInteger;
+
+ /**
+ * Finds the greatest common denominator of a and b.
+ */
+ gcd: (a: BigNumber, b: BigNumber) => BigInteger;
+
+
+ /**
+ * Returns true if x is a BigInteger, false otherwise.
+ */
+ isInstance: (x: any) => x is BigInteger;
+
+ /**
+ * Finds the least common multiple of a and b.
+ */
+ lcm: (a: BigNumber, b: BigNumber) => BigInteger;
+
+ /**
+ * Returns the largest of a and b.
+ */
+ max: (a: BigNumber, b: BigNumber) => BigInteger;
+
+ /**
+ * Returns the smallest of a and b.
+ */
+ min: (a: BigNumber, b: BigNumber) => BigInteger;
+
+ /**
+ * Equivalent to bigInt(-1).
+ */
+ minusOne: BigInteger;
+
+ /**
+ * Equivalent to bigInt(1).
+ */
+ one: BigInteger;
+
+ /**
+ * Returns a random number between min and max.
+ */
+ randBetween: (min: BigNumber, max: BigNumber, rng?: () => number) => BigInteger;
+
+ /**
+ * Equivalent to bigInt(0).
+ */
+ zero: BigInteger;
+ }
+
+ interface BigInteger {
+ /**
+ * Returns the absolute value of a bigInt.
+ */
+ abs(): BigInteger;
+
+ /**
+ * Performs addition.
+ */
+ add(number: BigNumber): BigInteger;
+
+ /**
+ * Performs the bitwise AND operation.
+ */
+ and(number: BigNumber): BigInteger;
+
+ /**
+ * Returns the number of digits required to represent a bigInt in binary.
+ */
+ bitLength(): BigInteger;
+
+ /**
+ * Performs a comparison between two numbers. If the numbers are equal, it returns 0.
+ * If the first number is greater, it returns 1. If the first number is lesser, it returns -1.
+ */
+ compare(number: BigNumber): number;
+
+ /**
+ * Performs a comparison between the absolute value of two numbers.
+ */
+ compareAbs(number: BigNumber): number;
+
+ /**
+ * Alias for the compare method.
+ */
+ compareTo(number: BigNumber): number;
+
+ /**
+ * Performs integer division, disregarding the remainder.
+ */
+ divide(number: BigNumber): BigInteger;
+
+ /**
+ * Performs division and returns an object with two properties: quotient and remainder.
+ * The sign of the remainder will match the sign of the dividend.
+ */
+ divmod(number: BigNumber): { quotient: BigInteger, remainder: BigInteger };
+
+ /**
+ * Alias for the equals method.
+ */
+ eq(number: BigNumber): boolean;
+
+ /**
+ * Checks if two numbers are equal.
+ */
+ equals(number: BigNumber): boolean;
+
+ /**
+ * Alias for the greaterOrEquals method.
+ */
+ geq(number: BigNumber): boolean;
+
+ /**
+ * Checks if the first number is greater than the second.
+ */
+ greater(number: BigNumber): boolean;
+
+ /**
+ * Checks if the first number is greater than or equal to the second.
+ */
+ greaterOrEquals(number: BigNumber): boolean;
+
+ /**
+ * Alias for the greater method.
+ */
+ gt(number: BigNumber): boolean;
+
+ /**
+ * Returns true if the first number is divisible by the second number, false otherwise.
+ */
+ isDivisibleBy(number: BigNumber): boolean;
+
+ /**
+ * Returns true if the number is even, false otherwise.
+ */
+ isEven(): boolean;
+
+ /**
+ * Returns true if the number is negative, false otherwise.
+ * Returns false for 0 and true for -0.
+ */
+ isNegative(): boolean;
+
+ /**
+ * Returns true if the number is odd, false otherwise.
+ */
+ isOdd(): boolean;
+
+ /**
+ * Return true if the number is positive, false otherwise.
+ * Returns true for 0 and false for -0.
+ */
+ isPositive(): boolean;
+
+ /**
+ * Returns true if the number is prime, false otherwise.
+ */
+ isPrime(strict?: boolean): boolean;
+
+ /**
+ * Returns true if the number is very likely to be prime, false otherwise.
+ */
+ isProbablePrime(iterations?: number, rng?: () => number): boolean;
+
+ /**
+ * Returns true if the number is 1 or -1, false otherwise.
+ */
+ isUnit(): boolean;
+
+ /**
+ * Return true if the number is 0 or -0, false otherwise.
+ */
+ isZero(): boolean;
+
+ /**
+ * Alias for the lesserOrEquals method.
+ */
+ leq(number: BigNumber): boolean;
+
+ /**
+ * Checks if the first number is lesser than the second.
+ */
+ lesser(number: BigNumber): boolean;
+
+ /**
+ * Checks if the first number is less than or equal to the second.
+ */
+ lesserOrEquals(number: BigNumber): boolean;
+
+ /**
+ * Alias for the lesser method.
+ */
+ lt(number: BigNumber): boolean;
+
+ /**
+ * Alias for the subtract method.
+ */
+ minus(number: BigNumber): BigInteger;
+
+ /**
+ * Performs division and returns the remainder, disregarding the quotient.
+ * The sign of the remainder will match the sign of the dividend.
+ */
+ mod(number: BigNumber): BigInteger;
+
+ /**
+ * Finds the multiplicative inverse of the number modulo mod.
+ */
+ modInv(number: BigNumber): BigInteger;
+
+ /**
+ * Takes the number to the power exp modulo mod.
+ */
+ modPow(exp: BigNumber, mod: BigNumber): BigInteger;
+
+ /**
+ * Performs multiplication.
+ */
+ multiply(number: BigNumber): BigInteger;
+
+ /**
+ * Reverses the sign of the number.
+ */
+ negate(): BigInteger;
+
+ /**
+ * Alias for the notEquals method.
+ */
+ neq(number: BigNumber): boolean;
+
+ /**
+ * Adds one to the number.
+ */
+ next(): BigInteger;
+
+ /**
+ * Performs the bitwise NOT operation.
+ */
+ not(): BigInteger;
+
+ /**
+ * Checks if two numbers are not equal.
+ */
+ notEquals(number: BigNumber): boolean;
+
+ /**
+ * Performs the bitwise OR operation.
+ */
+ or(number: BigNumber): BigInteger;
+
+ /**
+ * Alias for the divide method.
+ */
+ over(number: BigNumber): BigInteger;
+
+ /**
+ * Alias for the add method.
+ */
+ plus(number: BigNumber): BigInteger;
+
+ /**
+ * Performs exponentiation. If the exponent is less than 0, pow returns 0.
+ * bigInt.zero.pow(0) returns 1.
+ */
+ pow(number: BigNumber): BigInteger;
+
+ /**
+ * Subtracts one from the number.
+ */
+ prev(): BigInteger;
+
+ /**
+ * Alias for the mod method.
+ */
+ remainder(number: BigNumber): BigInteger;
+
+ /**
+ * Shifts the number left by n places in its binary representation.
+ * If a negative number is provided, it will shift right.
+ *
+ * Throws an error if number is outside of the range [-9007199254740992, 9007199254740992].
+ */
+ shiftLeft(number: BigNumber): BigInteger;
+
+ /**
+ * Shifts the number right by n places in its binary representation.
+ * If a negative number is provided, it will shift left.
+ *
+ * Throws an error if number is outside of the range [-9007199254740992, 9007199254740992].
+ */
+ shiftRight(number: BigNumber): BigInteger;
+
+ /**
+ * Squares the number.
+ */
+ square(): BigInteger;
+
+ /**
+ * Performs subtraction.
+ */
+ subtract(number: BigNumber): BigInteger;
+
+ /**
+ * Alias for the multiply method.
+ */
+ times(number: BigNumber): BigInteger;
+
+ /**
+ *
+ * Converts a bigInt to an object representing it as an array of integers module the given radix.
+ */
+ toArray(radix: number): BaseArray;
+
+ /**
+ * Converts a bigInt into a native Javascript number. Loses precision for numbers outside the range.
+ */
+ toJSNumber(): number;
+
+ /**
+ * Converts a bigInt to a string.
+ */
+ toString(radix?: number, alphabet?: string): string;
+
+ /**
+ * Converts a bigInt to a string. This method is called behind the scenes in JSON.stringify.
+ */
+ toJSON(): string;
+
+ /**
+ * Converts a bigInt to a native Javascript number. This override allows you to use native
+ * arithmetic operators without explicit conversion.
+ */
+ valueOf(): number;
+
+ /**
+ * Performs the bitwise XOR operation.
+ */
+ xor(number: BigNumber): BigInteger;
+ }
+
+ // Array constant accessors
+ interface BigIntegerStatic {
+ '-999': BigInteger;
+ '-998': BigInteger;
+ '-997': BigInteger;
+ '-996': BigInteger;
+ '-995': BigInteger;
+ '-994': BigInteger;
+ '-993': BigInteger;
+ '-992': BigInteger;
+ '-991': BigInteger;
+ '-990': BigInteger;
+ '-989': BigInteger;
+ '-988': BigInteger;
+ '-987': BigInteger;
+ '-986': BigInteger;
+ '-985': BigInteger;
+ '-984': BigInteger;
+ '-983': BigInteger;
+ '-982': BigInteger;
+ '-981': BigInteger;
+ '-980': BigInteger;
+ '-979': BigInteger;
+ '-978': BigInteger;
+ '-977': BigInteger;
+ '-976': BigInteger;
+ '-975': BigInteger;
+ '-974': BigInteger;
+ '-973': BigInteger;
+ '-972': BigInteger;
+ '-971': BigInteger;
+ '-970': BigInteger;
+ '-969': BigInteger;
+ '-968': BigInteger;
+ '-967': BigInteger;
+ '-966': BigInteger;
+ '-965': BigInteger;
+ '-964': BigInteger;
+ '-963': BigInteger;
+ '-962': BigInteger;
+ '-961': BigInteger;
+ '-960': BigInteger;
+ '-959': BigInteger;
+ '-958': BigInteger;
+ '-957': BigInteger;
+ '-956': BigInteger;
+ '-955': BigInteger;
+ '-954': BigInteger;
+ '-953': BigInteger;
+ '-952': BigInteger;
+ '-951': BigInteger;
+ '-950': BigInteger;
+ '-949': BigInteger;
+ '-948': BigInteger;
+ '-947': BigInteger;
+ '-946': BigInteger;
+ '-945': BigInteger;
+ '-944': BigInteger;
+ '-943': BigInteger;
+ '-942': BigInteger;
+ '-941': BigInteger;
+ '-940': BigInteger;
+ '-939': BigInteger;
+ '-938': BigInteger;
+ '-937': BigInteger;
+ '-936': BigInteger;
+ '-935': BigInteger;
+ '-934': BigInteger;
+ '-933': BigInteger;
+ '-932': BigInteger;
+ '-931': BigInteger;
+ '-930': BigInteger;
+ '-929': BigInteger;
+ '-928': BigInteger;
+ '-927': BigInteger;
+ '-926': BigInteger;
+ '-925': BigInteger;
+ '-924': BigInteger;
+ '-923': BigInteger;
+ '-922': BigInteger;
+ '-921': BigInteger;
+ '-920': BigInteger;
+ '-919': BigInteger;
+ '-918': BigInteger;
+ '-917': BigInteger;
+ '-916': BigInteger;
+ '-915': BigInteger;
+ '-914': BigInteger;
+ '-913': BigInteger;
+ '-912': BigInteger;
+ '-911': BigInteger;
+ '-910': BigInteger;
+ '-909': BigInteger;
+ '-908': BigInteger;
+ '-907': BigInteger;
+ '-906': BigInteger;
+ '-905': BigInteger;
+ '-904': BigInteger;
+ '-903': BigInteger;
+ '-902': BigInteger;
+ '-901': BigInteger;
+ '-900': BigInteger;
+ '-899': BigInteger;
+ '-898': BigInteger;
+ '-897': BigInteger;
+ '-896': BigInteger;
+ '-895': BigInteger;
+ '-894': BigInteger;
+ '-893': BigInteger;
+ '-892': BigInteger;
+ '-891': BigInteger;
+ '-890': BigInteger;
+ '-889': BigInteger;
+ '-888': BigInteger;
+ '-887': BigInteger;
+ '-886': BigInteger;
+ '-885': BigInteger;
+ '-884': BigInteger;
+ '-883': BigInteger;
+ '-882': BigInteger;
+ '-881': BigInteger;
+ '-880': BigInteger;
+ '-879': BigInteger;
+ '-878': BigInteger;
+ '-877': BigInteger;
+ '-876': BigInteger;
+ '-875': BigInteger;
+ '-874': BigInteger;
+ '-873': BigInteger;
+ '-872': BigInteger;
+ '-871': BigInteger;
+ '-870': BigInteger;
+ '-869': BigInteger;
+ '-868': BigInteger;
+ '-867': BigInteger;
+ '-866': BigInteger;
+ '-865': BigInteger;
+ '-864': BigInteger;
+ '-863': BigInteger;
+ '-862': BigInteger;
+ '-861': BigInteger;
+ '-860': BigInteger;
+ '-859': BigInteger;
+ '-858': BigInteger;
+ '-857': BigInteger;
+ '-856': BigInteger;
+ '-855': BigInteger;
+ '-854': BigInteger;
+ '-853': BigInteger;
+ '-852': BigInteger;
+ '-851': BigInteger;
+ '-850': BigInteger;
+ '-849': BigInteger;
+ '-848': BigInteger;
+ '-847': BigInteger;
+ '-846': BigInteger;
+ '-845': BigInteger;
+ '-844': BigInteger;
+ '-843': BigInteger;
+ '-842': BigInteger;
+ '-841': BigInteger;
+ '-840': BigInteger;
+ '-839': BigInteger;
+ '-838': BigInteger;
+ '-837': BigInteger;
+ '-836': BigInteger;
+ '-835': BigInteger;
+ '-834': BigInteger;
+ '-833': BigInteger;
+ '-832': BigInteger;
+ '-831': BigInteger;
+ '-830': BigInteger;
+ '-829': BigInteger;
+ '-828': BigInteger;
+ '-827': BigInteger;
+ '-826': BigInteger;
+ '-825': BigInteger;
+ '-824': BigInteger;
+ '-823': BigInteger;
+ '-822': BigInteger;
+ '-821': BigInteger;
+ '-820': BigInteger;
+ '-819': BigInteger;
+ '-818': BigInteger;
+ '-817': BigInteger;
+ '-816': BigInteger;
+ '-815': BigInteger;
+ '-814': BigInteger;
+ '-813': BigInteger;
+ '-812': BigInteger;
+ '-811': BigInteger;
+ '-810': BigInteger;
+ '-809': BigInteger;
+ '-808': BigInteger;
+ '-807': BigInteger;
+ '-806': BigInteger;
+ '-805': BigInteger;
+ '-804': BigInteger;
+ '-803': BigInteger;
+ '-802': BigInteger;
+ '-801': BigInteger;
+ '-800': BigInteger;
+ '-799': BigInteger;
+ '-798': BigInteger;
+ '-797': BigInteger;
+ '-796': BigInteger;
+ '-795': BigInteger;
+ '-794': BigInteger;
+ '-793': BigInteger;
+ '-792': BigInteger;
+ '-791': BigInteger;
+ '-790': BigInteger;
+ '-789': BigInteger;
+ '-788': BigInteger;
+ '-787': BigInteger;
+ '-786': BigInteger;
+ '-785': BigInteger;
+ '-784': BigInteger;
+ '-783': BigInteger;
+ '-782': BigInteger;
+ '-781': BigInteger;
+ '-780': BigInteger;
+ '-779': BigInteger;
+ '-778': BigInteger;
+ '-777': BigInteger;
+ '-776': BigInteger;
+ '-775': BigInteger;
+ '-774': BigInteger;
+ '-773': BigInteger;
+ '-772': BigInteger;
+ '-771': BigInteger;
+ '-770': BigInteger;
+ '-769': BigInteger;
+ '-768': BigInteger;
+ '-767': BigInteger;
+ '-766': BigInteger;
+ '-765': BigInteger;
+ '-764': BigInteger;
+ '-763': BigInteger;
+ '-762': BigInteger;
+ '-761': BigInteger;
+ '-760': BigInteger;
+ '-759': BigInteger;
+ '-758': BigInteger;
+ '-757': BigInteger;
+ '-756': BigInteger;
+ '-755': BigInteger;
+ '-754': BigInteger;
+ '-753': BigInteger;
+ '-752': BigInteger;
+ '-751': BigInteger;
+ '-750': BigInteger;
+ '-749': BigInteger;
+ '-748': BigInteger;
+ '-747': BigInteger;
+ '-746': BigInteger;
+ '-745': BigInteger;
+ '-744': BigInteger;
+ '-743': BigInteger;
+ '-742': BigInteger;
+ '-741': BigInteger;
+ '-740': BigInteger;
+ '-739': BigInteger;
+ '-738': BigInteger;
+ '-737': BigInteger;
+ '-736': BigInteger;
+ '-735': BigInteger;
+ '-734': BigInteger;
+ '-733': BigInteger;
+ '-732': BigInteger;
+ '-731': BigInteger;
+ '-730': BigInteger;
+ '-729': BigInteger;
+ '-728': BigInteger;
+ '-727': BigInteger;
+ '-726': BigInteger;
+ '-725': BigInteger;
+ '-724': BigInteger;
+ '-723': BigInteger;
+ '-722': BigInteger;
+ '-721': BigInteger;
+ '-720': BigInteger;
+ '-719': BigInteger;
+ '-718': BigInteger;
+ '-717': BigInteger;
+ '-716': BigInteger;
+ '-715': BigInteger;
+ '-714': BigInteger;
+ '-713': BigInteger;
+ '-712': BigInteger;
+ '-711': BigInteger;
+ '-710': BigInteger;
+ '-709': BigInteger;
+ '-708': BigInteger;
+ '-707': BigInteger;
+ '-706': BigInteger;
+ '-705': BigInteger;
+ '-704': BigInteger;
+ '-703': BigInteger;
+ '-702': BigInteger;
+ '-701': BigInteger;
+ '-700': BigInteger;
+ '-699': BigInteger;
+ '-698': BigInteger;
+ '-697': BigInteger;
+ '-696': BigInteger;
+ '-695': BigInteger;
+ '-694': BigInteger;
+ '-693': BigInteger;
+ '-692': BigInteger;
+ '-691': BigInteger;
+ '-690': BigInteger;
+ '-689': BigInteger;
+ '-688': BigInteger;
+ '-687': BigInteger;
+ '-686': BigInteger;
+ '-685': BigInteger;
+ '-684': BigInteger;
+ '-683': BigInteger;
+ '-682': BigInteger;
+ '-681': BigInteger;
+ '-680': BigInteger;
+ '-679': BigInteger;
+ '-678': BigInteger;
+ '-677': BigInteger;
+ '-676': BigInteger;
+ '-675': BigInteger;
+ '-674': BigInteger;
+ '-673': BigInteger;
+ '-672': BigInteger;
+ '-671': BigInteger;
+ '-670': BigInteger;
+ '-669': BigInteger;
+ '-668': BigInteger;
+ '-667': BigInteger;
+ '-666': BigInteger;
+ '-665': BigInteger;
+ '-664': BigInteger;
+ '-663': BigInteger;
+ '-662': BigInteger;
+ '-661': BigInteger;
+ '-660': BigInteger;
+ '-659': BigInteger;
+ '-658': BigInteger;
+ '-657': BigInteger;
+ '-656': BigInteger;
+ '-655': BigInteger;
+ '-654': BigInteger;
+ '-653': BigInteger;
+ '-652': BigInteger;
+ '-651': BigInteger;
+ '-650': BigInteger;
+ '-649': BigInteger;
+ '-648': BigInteger;
+ '-647': BigInteger;
+ '-646': BigInteger;
+ '-645': BigInteger;
+ '-644': BigInteger;
+ '-643': BigInteger;
+ '-642': BigInteger;
+ '-641': BigInteger;
+ '-640': BigInteger;
+ '-639': BigInteger;
+ '-638': BigInteger;
+ '-637': BigInteger;
+ '-636': BigInteger;
+ '-635': BigInteger;
+ '-634': BigInteger;
+ '-633': BigInteger;
+ '-632': BigInteger;
+ '-631': BigInteger;
+ '-630': BigInteger;
+ '-629': BigInteger;
+ '-628': BigInteger;
+ '-627': BigInteger;
+ '-626': BigInteger;
+ '-625': BigInteger;
+ '-624': BigInteger;
+ '-623': BigInteger;
+ '-622': BigInteger;
+ '-621': BigInteger;
+ '-620': BigInteger;
+ '-619': BigInteger;
+ '-618': BigInteger;
+ '-617': BigInteger;
+ '-616': BigInteger;
+ '-615': BigInteger;
+ '-614': BigInteger;
+ '-613': BigInteger;
+ '-612': BigInteger;
+ '-611': BigInteger;
+ '-610': BigInteger;
+ '-609': BigInteger;
+ '-608': BigInteger;
+ '-607': BigInteger;
+ '-606': BigInteger;
+ '-605': BigInteger;
+ '-604': BigInteger;
+ '-603': BigInteger;
+ '-602': BigInteger;
+ '-601': BigInteger;
+ '-600': BigInteger;
+ '-599': BigInteger;
+ '-598': BigInteger;
+ '-597': BigInteger;
+ '-596': BigInteger;
+ '-595': BigInteger;
+ '-594': BigInteger;
+ '-593': BigInteger;
+ '-592': BigInteger;
+ '-591': BigInteger;
+ '-590': BigInteger;
+ '-589': BigInteger;
+ '-588': BigInteger;
+ '-587': BigInteger;
+ '-586': BigInteger;
+ '-585': BigInteger;
+ '-584': BigInteger;
+ '-583': BigInteger;
+ '-582': BigInteger;
+ '-581': BigInteger;
+ '-580': BigInteger;
+ '-579': BigInteger;
+ '-578': BigInteger;
+ '-577': BigInteger;
+ '-576': BigInteger;
+ '-575': BigInteger;
+ '-574': BigInteger;
+ '-573': BigInteger;
+ '-572': BigInteger;
+ '-571': BigInteger;
+ '-570': BigInteger;
+ '-569': BigInteger;
+ '-568': BigInteger;
+ '-567': BigInteger;
+ '-566': BigInteger;
+ '-565': BigInteger;
+ '-564': BigInteger;
+ '-563': BigInteger;
+ '-562': BigInteger;
+ '-561': BigInteger;
+ '-560': BigInteger;
+ '-559': BigInteger;
+ '-558': BigInteger;
+ '-557': BigInteger;
+ '-556': BigInteger;
+ '-555': BigInteger;
+ '-554': BigInteger;
+ '-553': BigInteger;
+ '-552': BigInteger;
+ '-551': BigInteger;
+ '-550': BigInteger;
+ '-549': BigInteger;
+ '-548': BigInteger;
+ '-547': BigInteger;
+ '-546': BigInteger;
+ '-545': BigInteger;
+ '-544': BigInteger;
+ '-543': BigInteger;
+ '-542': BigInteger;
+ '-541': BigInteger;
+ '-540': BigInteger;
+ '-539': BigInteger;
+ '-538': BigInteger;
+ '-537': BigInteger;
+ '-536': BigInteger;
+ '-535': BigInteger;
+ '-534': BigInteger;
+ '-533': BigInteger;
+ '-532': BigInteger;
+ '-531': BigInteger;
+ '-530': BigInteger;
+ '-529': BigInteger;
+ '-528': BigInteger;
+ '-527': BigInteger;
+ '-526': BigInteger;
+ '-525': BigInteger;
+ '-524': BigInteger;
+ '-523': BigInteger;
+ '-522': BigInteger;
+ '-521': BigInteger;
+ '-520': BigInteger;
+ '-519': BigInteger;
+ '-518': BigInteger;
+ '-517': BigInteger;
+ '-516': BigInteger;
+ '-515': BigInteger;
+ '-514': BigInteger;
+ '-513': BigInteger;
+ '-512': BigInteger;
+ '-511': BigInteger;
+ '-510': BigInteger;
+ '-509': BigInteger;
+ '-508': BigInteger;
+ '-507': BigInteger;
+ '-506': BigInteger;
+ '-505': BigInteger;
+ '-504': BigInteger;
+ '-503': BigInteger;
+ '-502': BigInteger;
+ '-501': BigInteger;
+ '-500': BigInteger;
+ '-499': BigInteger;
+ '-498': BigInteger;
+ '-497': BigInteger;
+ '-496': BigInteger;
+ '-495': BigInteger;
+ '-494': BigInteger;
+ '-493': BigInteger;
+ '-492': BigInteger;
+ '-491': BigInteger;
+ '-490': BigInteger;
+ '-489': BigInteger;
+ '-488': BigInteger;
+ '-487': BigInteger;
+ '-486': BigInteger;
+ '-485': BigInteger;
+ '-484': BigInteger;
+ '-483': BigInteger;
+ '-482': BigInteger;
+ '-481': BigInteger;
+ '-480': BigInteger;
+ '-479': BigInteger;
+ '-478': BigInteger;
+ '-477': BigInteger;
+ '-476': BigInteger;
+ '-475': BigInteger;
+ '-474': BigInteger;
+ '-473': BigInteger;
+ '-472': BigInteger;
+ '-471': BigInteger;
+ '-470': BigInteger;
+ '-469': BigInteger;
+ '-468': BigInteger;
+ '-467': BigInteger;
+ '-466': BigInteger;
+ '-465': BigInteger;
+ '-464': BigInteger;
+ '-463': BigInteger;
+ '-462': BigInteger;
+ '-461': BigInteger;
+ '-460': BigInteger;
+ '-459': BigInteger;
+ '-458': BigInteger;
+ '-457': BigInteger;
+ '-456': BigInteger;
+ '-455': BigInteger;
+ '-454': BigInteger;
+ '-453': BigInteger;
+ '-452': BigInteger;
+ '-451': BigInteger;
+ '-450': BigInteger;
+ '-449': BigInteger;
+ '-448': BigInteger;
+ '-447': BigInteger;
+ '-446': BigInteger;
+ '-445': BigInteger;
+ '-444': BigInteger;
+ '-443': BigInteger;
+ '-442': BigInteger;
+ '-441': BigInteger;
+ '-440': BigInteger;
+ '-439': BigInteger;
+ '-438': BigInteger;
+ '-437': BigInteger;
+ '-436': BigInteger;
+ '-435': BigInteger;
+ '-434': BigInteger;
+ '-433': BigInteger;
+ '-432': BigInteger;
+ '-431': BigInteger;
+ '-430': BigInteger;
+ '-429': BigInteger;
+ '-428': BigInteger;
+ '-427': BigInteger;
+ '-426': BigInteger;
+ '-425': BigInteger;
+ '-424': BigInteger;
+ '-423': BigInteger;
+ '-422': BigInteger;
+ '-421': BigInteger;
+ '-420': BigInteger;
+ '-419': BigInteger;
+ '-418': BigInteger;
+ '-417': BigInteger;
+ '-416': BigInteger;
+ '-415': BigInteger;
+ '-414': BigInteger;
+ '-413': BigInteger;
+ '-412': BigInteger;
+ '-411': BigInteger;
+ '-410': BigInteger;
+ '-409': BigInteger;
+ '-408': BigInteger;
+ '-407': BigInteger;
+ '-406': BigInteger;
+ '-405': BigInteger;
+ '-404': BigInteger;
+ '-403': BigInteger;
+ '-402': BigInteger;
+ '-401': BigInteger;
+ '-400': BigInteger;
+ '-399': BigInteger;
+ '-398': BigInteger;
+ '-397': BigInteger;
+ '-396': BigInteger;
+ '-395': BigInteger;
+ '-394': BigInteger;
+ '-393': BigInteger;
+ '-392': BigInteger;
+ '-391': BigInteger;
+ '-390': BigInteger;
+ '-389': BigInteger;
+ '-388': BigInteger;
+ '-387': BigInteger;
+ '-386': BigInteger;
+ '-385': BigInteger;
+ '-384': BigInteger;
+ '-383': BigInteger;
+ '-382': BigInteger;
+ '-381': BigInteger;
+ '-380': BigInteger;
+ '-379': BigInteger;
+ '-378': BigInteger;
+ '-377': BigInteger;
+ '-376': BigInteger;
+ '-375': BigInteger;
+ '-374': BigInteger;
+ '-373': BigInteger;
+ '-372': BigInteger;
+ '-371': BigInteger;
+ '-370': BigInteger;
+ '-369': BigInteger;
+ '-368': BigInteger;
+ '-367': BigInteger;
+ '-366': BigInteger;
+ '-365': BigInteger;
+ '-364': BigInteger;
+ '-363': BigInteger;
+ '-362': BigInteger;
+ '-361': BigInteger;
+ '-360': BigInteger;
+ '-359': BigInteger;
+ '-358': BigInteger;
+ '-357': BigInteger;
+ '-356': BigInteger;
+ '-355': BigInteger;
+ '-354': BigInteger;
+ '-353': BigInteger;
+ '-352': BigInteger;
+ '-351': BigInteger;
+ '-350': BigInteger;
+ '-349': BigInteger;
+ '-348': BigInteger;
+ '-347': BigInteger;
+ '-346': BigInteger;
+ '-345': BigInteger;
+ '-344': BigInteger;
+ '-343': BigInteger;
+ '-342': BigInteger;
+ '-341': BigInteger;
+ '-340': BigInteger;
+ '-339': BigInteger;
+ '-338': BigInteger;
+ '-337': BigInteger;
+ '-336': BigInteger;
+ '-335': BigInteger;
+ '-334': BigInteger;
+ '-333': BigInteger;
+ '-332': BigInteger;
+ '-331': BigInteger;
+ '-330': BigInteger;
+ '-329': BigInteger;
+ '-328': BigInteger;
+ '-327': BigInteger;
+ '-326': BigInteger;
+ '-325': BigInteger;
+ '-324': BigInteger;
+ '-323': BigInteger;
+ '-322': BigInteger;
+ '-321': BigInteger;
+ '-320': BigInteger;
+ '-319': BigInteger;
+ '-318': BigInteger;
+ '-317': BigInteger;
+ '-316': BigInteger;
+ '-315': BigInteger;
+ '-314': BigInteger;
+ '-313': BigInteger;
+ '-312': BigInteger;
+ '-311': BigInteger;
+ '-310': BigInteger;
+ '-309': BigInteger;
+ '-308': BigInteger;
+ '-307': BigInteger;
+ '-306': BigInteger;
+ '-305': BigInteger;
+ '-304': BigInteger;
+ '-303': BigInteger;
+ '-302': BigInteger;
+ '-301': BigInteger;
+ '-300': BigInteger;
+ '-299': BigInteger;
+ '-298': BigInteger;
+ '-297': BigInteger;
+ '-296': BigInteger;
+ '-295': BigInteger;
+ '-294': BigInteger;
+ '-293': BigInteger;
+ '-292': BigInteger;
+ '-291': BigInteger;
+ '-290': BigInteger;
+ '-289': BigInteger;
+ '-288': BigInteger;
+ '-287': BigInteger;
+ '-286': BigInteger;
+ '-285': BigInteger;
+ '-284': BigInteger;
+ '-283': BigInteger;
+ '-282': BigInteger;
+ '-281': BigInteger;
+ '-280': BigInteger;
+ '-279': BigInteger;
+ '-278': BigInteger;
+ '-277': BigInteger;
+ '-276': BigInteger;
+ '-275': BigInteger;
+ '-274': BigInteger;
+ '-273': BigInteger;
+ '-272': BigInteger;
+ '-271': BigInteger;
+ '-270': BigInteger;
+ '-269': BigInteger;
+ '-268': BigInteger;
+ '-267': BigInteger;
+ '-266': BigInteger;
+ '-265': BigInteger;
+ '-264': BigInteger;
+ '-263': BigInteger;
+ '-262': BigInteger;
+ '-261': BigInteger;
+ '-260': BigInteger;
+ '-259': BigInteger;
+ '-258': BigInteger;
+ '-257': BigInteger;
+ '-256': BigInteger;
+ '-255': BigInteger;
+ '-254': BigInteger;
+ '-253': BigInteger;
+ '-252': BigInteger;
+ '-251': BigInteger;
+ '-250': BigInteger;
+ '-249': BigInteger;
+ '-248': BigInteger;
+ '-247': BigInteger;
+ '-246': BigInteger;
+ '-245': BigInteger;
+ '-244': BigInteger;
+ '-243': BigInteger;
+ '-242': BigInteger;
+ '-241': BigInteger;
+ '-240': BigInteger;
+ '-239': BigInteger;
+ '-238': BigInteger;
+ '-237': BigInteger;
+ '-236': BigInteger;
+ '-235': BigInteger;
+ '-234': BigInteger;
+ '-233': BigInteger;
+ '-232': BigInteger;
+ '-231': BigInteger;
+ '-230': BigInteger;
+ '-229': BigInteger;
+ '-228': BigInteger;
+ '-227': BigInteger;
+ '-226': BigInteger;
+ '-225': BigInteger;
+ '-224': BigInteger;
+ '-223': BigInteger;
+ '-222': BigInteger;
+ '-221': BigInteger;
+ '-220': BigInteger;
+ '-219': BigInteger;
+ '-218': BigInteger;
+ '-217': BigInteger;
+ '-216': BigInteger;
+ '-215': BigInteger;
+ '-214': BigInteger;
+ '-213': BigInteger;
+ '-212': BigInteger;
+ '-211': BigInteger;
+ '-210': BigInteger;
+ '-209': BigInteger;
+ '-208': BigInteger;
+ '-207': BigInteger;
+ '-206': BigInteger;
+ '-205': BigInteger;
+ '-204': BigInteger;
+ '-203': BigInteger;
+ '-202': BigInteger;
+ '-201': BigInteger;
+ '-200': BigInteger;
+ '-199': BigInteger;
+ '-198': BigInteger;
+ '-197': BigInteger;
+ '-196': BigInteger;
+ '-195': BigInteger;
+ '-194': BigInteger;
+ '-193': BigInteger;
+ '-192': BigInteger;
+ '-191': BigInteger;
+ '-190': BigInteger;
+ '-189': BigInteger;
+ '-188': BigInteger;
+ '-187': BigInteger;
+ '-186': BigInteger;
+ '-185': BigInteger;
+ '-184': BigInteger;
+ '-183': BigInteger;
+ '-182': BigInteger;
+ '-181': BigInteger;
+ '-180': BigInteger;
+ '-179': BigInteger;
+ '-178': BigInteger;
+ '-177': BigInteger;
+ '-176': BigInteger;
+ '-175': BigInteger;
+ '-174': BigInteger;
+ '-173': BigInteger;
+ '-172': BigInteger;
+ '-171': BigInteger;
+ '-170': BigInteger;
+ '-169': BigInteger;
+ '-168': BigInteger;
+ '-167': BigInteger;
+ '-166': BigInteger;
+ '-165': BigInteger;
+ '-164': BigInteger;
+ '-163': BigInteger;
+ '-162': BigInteger;
+ '-161': BigInteger;
+ '-160': BigInteger;
+ '-159': BigInteger;
+ '-158': BigInteger;
+ '-157': BigInteger;
+ '-156': BigInteger;
+ '-155': BigInteger;
+ '-154': BigInteger;
+ '-153': BigInteger;
+ '-152': BigInteger;
+ '-151': BigInteger;
+ '-150': BigInteger;
+ '-149': BigInteger;
+ '-148': BigInteger;
+ '-147': BigInteger;
+ '-146': BigInteger;
+ '-145': BigInteger;
+ '-144': BigInteger;
+ '-143': BigInteger;
+ '-142': BigInteger;
+ '-141': BigInteger;
+ '-140': BigInteger;
+ '-139': BigInteger;
+ '-138': BigInteger;
+ '-137': BigInteger;
+ '-136': BigInteger;
+ '-135': BigInteger;
+ '-134': BigInteger;
+ '-133': BigInteger;
+ '-132': BigInteger;
+ '-131': BigInteger;
+ '-130': BigInteger;
+ '-129': BigInteger;
+ '-128': BigInteger;
+ '-127': BigInteger;
+ '-126': BigInteger;
+ '-125': BigInteger;
+ '-124': BigInteger;
+ '-123': BigInteger;
+ '-122': BigInteger;
+ '-121': BigInteger;
+ '-120': BigInteger;
+ '-119': BigInteger;
+ '-118': BigInteger;
+ '-117': BigInteger;
+ '-116': BigInteger;
+ '-115': BigInteger;
+ '-114': BigInteger;
+ '-113': BigInteger;
+ '-112': BigInteger;
+ '-111': BigInteger;
+ '-110': BigInteger;
+ '-109': BigInteger;
+ '-108': BigInteger;
+ '-107': BigInteger;
+ '-106': BigInteger;
+ '-105': BigInteger;
+ '-104': BigInteger;
+ '-103': BigInteger;
+ '-102': BigInteger;
+ '-101': BigInteger;
+ '-100': BigInteger;
+ '-99': BigInteger;
+ '-98': BigInteger;
+ '-97': BigInteger;
+ '-96': BigInteger;
+ '-95': BigInteger;
+ '-94': BigInteger;
+ '-93': BigInteger;
+ '-92': BigInteger;
+ '-91': BigInteger;
+ '-90': BigInteger;
+ '-89': BigInteger;
+ '-88': BigInteger;
+ '-87': BigInteger;
+ '-86': BigInteger;
+ '-85': BigInteger;
+ '-84': BigInteger;
+ '-83': BigInteger;
+ '-82': BigInteger;
+ '-81': BigInteger;
+ '-80': BigInteger;
+ '-79': BigInteger;
+ '-78': BigInteger;
+ '-77': BigInteger;
+ '-76': BigInteger;
+ '-75': BigInteger;
+ '-74': BigInteger;
+ '-73': BigInteger;
+ '-72': BigInteger;
+ '-71': BigInteger;
+ '-70': BigInteger;
+ '-69': BigInteger;
+ '-68': BigInteger;
+ '-67': BigInteger;
+ '-66': BigInteger;
+ '-65': BigInteger;
+ '-64': BigInteger;
+ '-63': BigInteger;
+ '-62': BigInteger;
+ '-61': BigInteger;
+ '-60': BigInteger;
+ '-59': BigInteger;
+ '-58': BigInteger;
+ '-57': BigInteger;
+ '-56': BigInteger;
+ '-55': BigInteger;
+ '-54': BigInteger;
+ '-53': BigInteger;
+ '-52': BigInteger;
+ '-51': BigInteger;
+ '-50': BigInteger;
+ '-49': BigInteger;
+ '-48': BigInteger;
+ '-47': BigInteger;
+ '-46': BigInteger;
+ '-45': BigInteger;
+ '-44': BigInteger;
+ '-43': BigInteger;
+ '-42': BigInteger;
+ '-41': BigInteger;
+ '-40': BigInteger;
+ '-39': BigInteger;
+ '-38': BigInteger;
+ '-37': BigInteger;
+ '-36': BigInteger;
+ '-35': BigInteger;
+ '-34': BigInteger;
+ '-33': BigInteger;
+ '-32': BigInteger;
+ '-31': BigInteger;
+ '-30': BigInteger;
+ '-29': BigInteger;
+ '-28': BigInteger;
+ '-27': BigInteger;
+ '-26': BigInteger;
+ '-25': BigInteger;
+ '-24': BigInteger;
+ '-23': BigInteger;
+ '-22': BigInteger;
+ '-21': BigInteger;
+ '-20': BigInteger;
+ '-19': BigInteger;
+ '-18': BigInteger;
+ '-17': BigInteger;
+ '-16': BigInteger;
+ '-15': BigInteger;
+ '-14': BigInteger;
+ '-13': BigInteger;
+ '-12': BigInteger;
+ '-11': BigInteger;
+ '-10': BigInteger;
+ '-9': BigInteger;
+ '-8': BigInteger;
+ '-7': BigInteger;
+ '-6': BigInteger;
+ '-5': BigInteger;
+ '-4': BigInteger;
+ '-3': BigInteger;
+ '-2': BigInteger;
+ '-1': BigInteger;
+ '0': BigInteger;
+ '1': BigInteger;
+ '2': BigInteger;
+ '3': BigInteger;
+ '4': BigInteger;
+ '5': BigInteger;
+ '6': BigInteger;
+ '7': BigInteger;
+ '8': BigInteger;
+ '9': BigInteger;
+ '10': BigInteger;
+ '11': BigInteger;
+ '12': BigInteger;
+ '13': BigInteger;
+ '14': BigInteger;
+ '15': BigInteger;
+ '16': BigInteger;
+ '17': BigInteger;
+ '18': BigInteger;
+ '19': BigInteger;
+ '20': BigInteger;
+ '21': BigInteger;
+ '22': BigInteger;
+ '23': BigInteger;
+ '24': BigInteger;
+ '25': BigInteger;
+ '26': BigInteger;
+ '27': BigInteger;
+ '28': BigInteger;
+ '29': BigInteger;
+ '30': BigInteger;
+ '31': BigInteger;
+ '32': BigInteger;
+ '33': BigInteger;
+ '34': BigInteger;
+ '35': BigInteger;
+ '36': BigInteger;
+ '37': BigInteger;
+ '38': BigInteger;
+ '39': BigInteger;
+ '40': BigInteger;
+ '41': BigInteger;
+ '42': BigInteger;
+ '43': BigInteger;
+ '44': BigInteger;
+ '45': BigInteger;
+ '46': BigInteger;
+ '47': BigInteger;
+ '48': BigInteger;
+ '49': BigInteger;
+ '50': BigInteger;
+ '51': BigInteger;
+ '52': BigInteger;
+ '53': BigInteger;
+ '54': BigInteger;
+ '55': BigInteger;
+ '56': BigInteger;
+ '57': BigInteger;
+ '58': BigInteger;
+ '59': BigInteger;
+ '60': BigInteger;
+ '61': BigInteger;
+ '62': BigInteger;
+ '63': BigInteger;
+ '64': BigInteger;
+ '65': BigInteger;
+ '66': BigInteger;
+ '67': BigInteger;
+ '68': BigInteger;
+ '69': BigInteger;
+ '70': BigInteger;
+ '71': BigInteger;
+ '72': BigInteger;
+ '73': BigInteger;
+ '74': BigInteger;
+ '75': BigInteger;
+ '76': BigInteger;
+ '77': BigInteger;
+ '78': BigInteger;
+ '79': BigInteger;
+ '80': BigInteger;
+ '81': BigInteger;
+ '82': BigInteger;
+ '83': BigInteger;
+ '84': BigInteger;
+ '85': BigInteger;
+ '86': BigInteger;
+ '87': BigInteger;
+ '88': BigInteger;
+ '89': BigInteger;
+ '90': BigInteger;
+ '91': BigInteger;
+ '92': BigInteger;
+ '93': BigInteger;
+ '94': BigInteger;
+ '95': BigInteger;
+ '96': BigInteger;
+ '97': BigInteger;
+ '98': BigInteger;
+ '99': BigInteger;
+ '100': BigInteger;
+ '101': BigInteger;
+ '102': BigInteger;
+ '103': BigInteger;
+ '104': BigInteger;
+ '105': BigInteger;
+ '106': BigInteger;
+ '107': BigInteger;
+ '108': BigInteger;
+ '109': BigInteger;
+ '110': BigInteger;
+ '111': BigInteger;
+ '112': BigInteger;
+ '113': BigInteger;
+ '114': BigInteger;
+ '115': BigInteger;
+ '116': BigInteger;
+ '117': BigInteger;
+ '118': BigInteger;
+ '119': BigInteger;
+ '120': BigInteger;
+ '121': BigInteger;
+ '122': BigInteger;
+ '123': BigInteger;
+ '124': BigInteger;
+ '125': BigInteger;
+ '126': BigInteger;
+ '127': BigInteger;
+ '128': BigInteger;
+ '129': BigInteger;
+ '130': BigInteger;
+ '131': BigInteger;
+ '132': BigInteger;
+ '133': BigInteger;
+ '134': BigInteger;
+ '135': BigInteger;
+ '136': BigInteger;
+ '137': BigInteger;
+ '138': BigInteger;
+ '139': BigInteger;
+ '140': BigInteger;
+ '141': BigInteger;
+ '142': BigInteger;
+ '143': BigInteger;
+ '144': BigInteger;
+ '145': BigInteger;
+ '146': BigInteger;
+ '147': BigInteger;
+ '148': BigInteger;
+ '149': BigInteger;
+ '150': BigInteger;
+ '151': BigInteger;
+ '152': BigInteger;
+ '153': BigInteger;
+ '154': BigInteger;
+ '155': BigInteger;
+ '156': BigInteger;
+ '157': BigInteger;
+ '158': BigInteger;
+ '159': BigInteger;
+ '160': BigInteger;
+ '161': BigInteger;
+ '162': BigInteger;
+ '163': BigInteger;
+ '164': BigInteger;
+ '165': BigInteger;
+ '166': BigInteger;
+ '167': BigInteger;
+ '168': BigInteger;
+ '169': BigInteger;
+ '170': BigInteger;
+ '171': BigInteger;
+ '172': BigInteger;
+ '173': BigInteger;
+ '174': BigInteger;
+ '175': BigInteger;
+ '176': BigInteger;
+ '177': BigInteger;
+ '178': BigInteger;
+ '179': BigInteger;
+ '180': BigInteger;
+ '181': BigInteger;
+ '182': BigInteger;
+ '183': BigInteger;
+ '184': BigInteger;
+ '185': BigInteger;
+ '186': BigInteger;
+ '187': BigInteger;
+ '188': BigInteger;
+ '189': BigInteger;
+ '190': BigInteger;
+ '191': BigInteger;
+ '192': BigInteger;
+ '193': BigInteger;
+ '194': BigInteger;
+ '195': BigInteger;
+ '196': BigInteger;
+ '197': BigInteger;
+ '198': BigInteger;
+ '199': BigInteger;
+ '200': BigInteger;
+ '201': BigInteger;
+ '202': BigInteger;
+ '203': BigInteger;
+ '204': BigInteger;
+ '205': BigInteger;
+ '206': BigInteger;
+ '207': BigInteger;
+ '208': BigInteger;
+ '209': BigInteger;
+ '210': BigInteger;
+ '211': BigInteger;
+ '212': BigInteger;
+ '213': BigInteger;
+ '214': BigInteger;
+ '215': BigInteger;
+ '216': BigInteger;
+ '217': BigInteger;
+ '218': BigInteger;
+ '219': BigInteger;
+ '220': BigInteger;
+ '221': BigInteger;
+ '222': BigInteger;
+ '223': BigInteger;
+ '224': BigInteger;
+ '225': BigInteger;
+ '226': BigInteger;
+ '227': BigInteger;
+ '228': BigInteger;
+ '229': BigInteger;
+ '230': BigInteger;
+ '231': BigInteger;
+ '232': BigInteger;
+ '233': BigInteger;
+ '234': BigInteger;
+ '235': BigInteger;
+ '236': BigInteger;
+ '237': BigInteger;
+ '238': BigInteger;
+ '239': BigInteger;
+ '240': BigInteger;
+ '241': BigInteger;
+ '242': BigInteger;
+ '243': BigInteger;
+ '244': BigInteger;
+ '245': BigInteger;
+ '246': BigInteger;
+ '247': BigInteger;
+ '248': BigInteger;
+ '249': BigInteger;
+ '250': BigInteger;
+ '251': BigInteger;
+ '252': BigInteger;
+ '253': BigInteger;
+ '254': BigInteger;
+ '255': BigInteger;
+ '256': BigInteger;
+ '257': BigInteger;
+ '258': BigInteger;
+ '259': BigInteger;
+ '260': BigInteger;
+ '261': BigInteger;
+ '262': BigInteger;
+ '263': BigInteger;
+ '264': BigInteger;
+ '265': BigInteger;
+ '266': BigInteger;
+ '267': BigInteger;
+ '268': BigInteger;
+ '269': BigInteger;
+ '270': BigInteger;
+ '271': BigInteger;
+ '272': BigInteger;
+ '273': BigInteger;
+ '274': BigInteger;
+ '275': BigInteger;
+ '276': BigInteger;
+ '277': BigInteger;
+ '278': BigInteger;
+ '279': BigInteger;
+ '280': BigInteger;
+ '281': BigInteger;
+ '282': BigInteger;
+ '283': BigInteger;
+ '284': BigInteger;
+ '285': BigInteger;
+ '286': BigInteger;
+ '287': BigInteger;
+ '288': BigInteger;
+ '289': BigInteger;
+ '290': BigInteger;
+ '291': BigInteger;
+ '292': BigInteger;
+ '293': BigInteger;
+ '294': BigInteger;
+ '295': BigInteger;
+ '296': BigInteger;
+ '297': BigInteger;
+ '298': BigInteger;
+ '299': BigInteger;
+ '300': BigInteger;
+ '301': BigInteger;
+ '302': BigInteger;
+ '303': BigInteger;
+ '304': BigInteger;
+ '305': BigInteger;
+ '306': BigInteger;
+ '307': BigInteger;
+ '308': BigInteger;
+ '309': BigInteger;
+ '310': BigInteger;
+ '311': BigInteger;
+ '312': BigInteger;
+ '313': BigInteger;
+ '314': BigInteger;
+ '315': BigInteger;
+ '316': BigInteger;
+ '317': BigInteger;
+ '318': BigInteger;
+ '319': BigInteger;
+ '320': BigInteger;
+ '321': BigInteger;
+ '322': BigInteger;
+ '323': BigInteger;
+ '324': BigInteger;
+ '325': BigInteger;
+ '326': BigInteger;
+ '327': BigInteger;
+ '328': BigInteger;
+ '329': BigInteger;
+ '330': BigInteger;
+ '331': BigInteger;
+ '332': BigInteger;
+ '333': BigInteger;
+ '334': BigInteger;
+ '335': BigInteger;
+ '336': BigInteger;
+ '337': BigInteger;
+ '338': BigInteger;
+ '339': BigInteger;
+ '340': BigInteger;
+ '341': BigInteger;
+ '342': BigInteger;
+ '343': BigInteger;
+ '344': BigInteger;
+ '345': BigInteger;
+ '346': BigInteger;
+ '347': BigInteger;
+ '348': BigInteger;
+ '349': BigInteger;
+ '350': BigInteger;
+ '351': BigInteger;
+ '352': BigInteger;
+ '353': BigInteger;
+ '354': BigInteger;
+ '355': BigInteger;
+ '356': BigInteger;
+ '357': BigInteger;
+ '358': BigInteger;
+ '359': BigInteger;
+ '360': BigInteger;
+ '361': BigInteger;
+ '362': BigInteger;
+ '363': BigInteger;
+ '364': BigInteger;
+ '365': BigInteger;
+ '366': BigInteger;
+ '367': BigInteger;
+ '368': BigInteger;
+ '369': BigInteger;
+ '370': BigInteger;
+ '371': BigInteger;
+ '372': BigInteger;
+ '373': BigInteger;
+ '374': BigInteger;
+ '375': BigInteger;
+ '376': BigInteger;
+ '377': BigInteger;
+ '378': BigInteger;
+ '379': BigInteger;
+ '380': BigInteger;
+ '381': BigInteger;
+ '382': BigInteger;
+ '383': BigInteger;
+ '384': BigInteger;
+ '385': BigInteger;
+ '386': BigInteger;
+ '387': BigInteger;
+ '388': BigInteger;
+ '389': BigInteger;
+ '390': BigInteger;
+ '391': BigInteger;
+ '392': BigInteger;
+ '393': BigInteger;
+ '394': BigInteger;
+ '395': BigInteger;
+ '396': BigInteger;
+ '397': BigInteger;
+ '398': BigInteger;
+ '399': BigInteger;
+ '400': BigInteger;
+ '401': BigInteger;
+ '402': BigInteger;
+ '403': BigInteger;
+ '404': BigInteger;
+ '405': BigInteger;
+ '406': BigInteger;
+ '407': BigInteger;
+ '408': BigInteger;
+ '409': BigInteger;
+ '410': BigInteger;
+ '411': BigInteger;
+ '412': BigInteger;
+ '413': BigInteger;
+ '414': BigInteger;
+ '415': BigInteger;
+ '416': BigInteger;
+ '417': BigInteger;
+ '418': BigInteger;
+ '419': BigInteger;
+ '420': BigInteger;
+ '421': BigInteger;
+ '422': BigInteger;
+ '423': BigInteger;
+ '424': BigInteger;
+ '425': BigInteger;
+ '426': BigInteger;
+ '427': BigInteger;
+ '428': BigInteger;
+ '429': BigInteger;
+ '430': BigInteger;
+ '431': BigInteger;
+ '432': BigInteger;
+ '433': BigInteger;
+ '434': BigInteger;
+ '435': BigInteger;
+ '436': BigInteger;
+ '437': BigInteger;
+ '438': BigInteger;
+ '439': BigInteger;
+ '440': BigInteger;
+ '441': BigInteger;
+ '442': BigInteger;
+ '443': BigInteger;
+ '444': BigInteger;
+ '445': BigInteger;
+ '446': BigInteger;
+ '447': BigInteger;
+ '448': BigInteger;
+ '449': BigInteger;
+ '450': BigInteger;
+ '451': BigInteger;
+ '452': BigInteger;
+ '453': BigInteger;
+ '454': BigInteger;
+ '455': BigInteger;
+ '456': BigInteger;
+ '457': BigInteger;
+ '458': BigInteger;
+ '459': BigInteger;
+ '460': BigInteger;
+ '461': BigInteger;
+ '462': BigInteger;
+ '463': BigInteger;
+ '464': BigInteger;
+ '465': BigInteger;
+ '466': BigInteger;
+ '467': BigInteger;
+ '468': BigInteger;
+ '469': BigInteger;
+ '470': BigInteger;
+ '471': BigInteger;
+ '472': BigInteger;
+ '473': BigInteger;
+ '474': BigInteger;
+ '475': BigInteger;
+ '476': BigInteger;
+ '477': BigInteger;
+ '478': BigInteger;
+ '479': BigInteger;
+ '480': BigInteger;
+ '481': BigInteger;
+ '482': BigInteger;
+ '483': BigInteger;
+ '484': BigInteger;
+ '485': BigInteger;
+ '486': BigInteger;
+ '487': BigInteger;
+ '488': BigInteger;
+ '489': BigInteger;
+ '490': BigInteger;
+ '491': BigInteger;
+ '492': BigInteger;
+ '493': BigInteger;
+ '494': BigInteger;
+ '495': BigInteger;
+ '496': BigInteger;
+ '497': BigInteger;
+ '498': BigInteger;
+ '499': BigInteger;
+ '500': BigInteger;
+ '501': BigInteger;
+ '502': BigInteger;
+ '503': BigInteger;
+ '504': BigInteger;
+ '505': BigInteger;
+ '506': BigInteger;
+ '507': BigInteger;
+ '508': BigInteger;
+ '509': BigInteger;
+ '510': BigInteger;
+ '511': BigInteger;
+ '512': BigInteger;
+ '513': BigInteger;
+ '514': BigInteger;
+ '515': BigInteger;
+ '516': BigInteger;
+ '517': BigInteger;
+ '518': BigInteger;
+ '519': BigInteger;
+ '520': BigInteger;
+ '521': BigInteger;
+ '522': BigInteger;
+ '523': BigInteger;
+ '524': BigInteger;
+ '525': BigInteger;
+ '526': BigInteger;
+ '527': BigInteger;
+ '528': BigInteger;
+ '529': BigInteger;
+ '530': BigInteger;
+ '531': BigInteger;
+ '532': BigInteger;
+ '533': BigInteger;
+ '534': BigInteger;
+ '535': BigInteger;
+ '536': BigInteger;
+ '537': BigInteger;
+ '538': BigInteger;
+ '539': BigInteger;
+ '540': BigInteger;
+ '541': BigInteger;
+ '542': BigInteger;
+ '543': BigInteger;
+ '544': BigInteger;
+ '545': BigInteger;
+ '546': BigInteger;
+ '547': BigInteger;
+ '548': BigInteger;
+ '549': BigInteger;
+ '550': BigInteger;
+ '551': BigInteger;
+ '552': BigInteger;
+ '553': BigInteger;
+ '554': BigInteger;
+ '555': BigInteger;
+ '556': BigInteger;
+ '557': BigInteger;
+ '558': BigInteger;
+ '559': BigInteger;
+ '560': BigInteger;
+ '561': BigInteger;
+ '562': BigInteger;
+ '563': BigInteger;
+ '564': BigInteger;
+ '565': BigInteger;
+ '566': BigInteger;
+ '567': BigInteger;
+ '568': BigInteger;
+ '569': BigInteger;
+ '570': BigInteger;
+ '571': BigInteger;
+ '572': BigInteger;
+ '573': BigInteger;
+ '574': BigInteger;
+ '575': BigInteger;
+ '576': BigInteger;
+ '577': BigInteger;
+ '578': BigInteger;
+ '579': BigInteger;
+ '580': BigInteger;
+ '581': BigInteger;
+ '582': BigInteger;
+ '583': BigInteger;
+ '584': BigInteger;
+ '585': BigInteger;
+ '586': BigInteger;
+ '587': BigInteger;
+ '588': BigInteger;
+ '589': BigInteger;
+ '590': BigInteger;
+ '591': BigInteger;
+ '592': BigInteger;
+ '593': BigInteger;
+ '594': BigInteger;
+ '595': BigInteger;
+ '596': BigInteger;
+ '597': BigInteger;
+ '598': BigInteger;
+ '599': BigInteger;
+ '600': BigInteger;
+ '601': BigInteger;
+ '602': BigInteger;
+ '603': BigInteger;
+ '604': BigInteger;
+ '605': BigInteger;
+ '606': BigInteger;
+ '607': BigInteger;
+ '608': BigInteger;
+ '609': BigInteger;
+ '610': BigInteger;
+ '611': BigInteger;
+ '612': BigInteger;
+ '613': BigInteger;
+ '614': BigInteger;
+ '615': BigInteger;
+ '616': BigInteger;
+ '617': BigInteger;
+ '618': BigInteger;
+ '619': BigInteger;
+ '620': BigInteger;
+ '621': BigInteger;
+ '622': BigInteger;
+ '623': BigInteger;
+ '624': BigInteger;
+ '625': BigInteger;
+ '626': BigInteger;
+ '627': BigInteger;
+ '628': BigInteger;
+ '629': BigInteger;
+ '630': BigInteger;
+ '631': BigInteger;
+ '632': BigInteger;
+ '633': BigInteger;
+ '634': BigInteger;
+ '635': BigInteger;
+ '636': BigInteger;
+ '637': BigInteger;
+ '638': BigInteger;
+ '639': BigInteger;
+ '640': BigInteger;
+ '641': BigInteger;
+ '642': BigInteger;
+ '643': BigInteger;
+ '644': BigInteger;
+ '645': BigInteger;
+ '646': BigInteger;
+ '647': BigInteger;
+ '648': BigInteger;
+ '649': BigInteger;
+ '650': BigInteger;
+ '651': BigInteger;
+ '652': BigInteger;
+ '653': BigInteger;
+ '654': BigInteger;
+ '655': BigInteger;
+ '656': BigInteger;
+ '657': BigInteger;
+ '658': BigInteger;
+ '659': BigInteger;
+ '660': BigInteger;
+ '661': BigInteger;
+ '662': BigInteger;
+ '663': BigInteger;
+ '664': BigInteger;
+ '665': BigInteger;
+ '666': BigInteger;
+ '667': BigInteger;
+ '668': BigInteger;
+ '669': BigInteger;
+ '670': BigInteger;
+ '671': BigInteger;
+ '672': BigInteger;
+ '673': BigInteger;
+ '674': BigInteger;
+ '675': BigInteger;
+ '676': BigInteger;
+ '677': BigInteger;
+ '678': BigInteger;
+ '679': BigInteger;
+ '680': BigInteger;
+ '681': BigInteger;
+ '682': BigInteger;
+ '683': BigInteger;
+ '684': BigInteger;
+ '685': BigInteger;
+ '686': BigInteger;
+ '687': BigInteger;
+ '688': BigInteger;
+ '689': BigInteger;
+ '690': BigInteger;
+ '691': BigInteger;
+ '692': BigInteger;
+ '693': BigInteger;
+ '694': BigInteger;
+ '695': BigInteger;
+ '696': BigInteger;
+ '697': BigInteger;
+ '698': BigInteger;
+ '699': BigInteger;
+ '700': BigInteger;
+ '701': BigInteger;
+ '702': BigInteger;
+ '703': BigInteger;
+ '704': BigInteger;
+ '705': BigInteger;
+ '706': BigInteger;
+ '707': BigInteger;
+ '708': BigInteger;
+ '709': BigInteger;
+ '710': BigInteger;
+ '711': BigInteger;
+ '712': BigInteger;
+ '713': BigInteger;
+ '714': BigInteger;
+ '715': BigInteger;
+ '716': BigInteger;
+ '717': BigInteger;
+ '718': BigInteger;
+ '719': BigInteger;
+ '720': BigInteger;
+ '721': BigInteger;
+ '722': BigInteger;
+ '723': BigInteger;
+ '724': BigInteger;
+ '725': BigInteger;
+ '726': BigInteger;
+ '727': BigInteger;
+ '728': BigInteger;
+ '729': BigInteger;
+ '730': BigInteger;
+ '731': BigInteger;
+ '732': BigInteger;
+ '733': BigInteger;
+ '734': BigInteger;
+ '735': BigInteger;
+ '736': BigInteger;
+ '737': BigInteger;
+ '738': BigInteger;
+ '739': BigInteger;
+ '740': BigInteger;
+ '741': BigInteger;
+ '742': BigInteger;
+ '743': BigInteger;
+ '744': BigInteger;
+ '745': BigInteger;
+ '746': BigInteger;
+ '747': BigInteger;
+ '748': BigInteger;
+ '749': BigInteger;
+ '750': BigInteger;
+ '751': BigInteger;
+ '752': BigInteger;
+ '753': BigInteger;
+ '754': BigInteger;
+ '755': BigInteger;
+ '756': BigInteger;
+ '757': BigInteger;
+ '758': BigInteger;
+ '759': BigInteger;
+ '760': BigInteger;
+ '761': BigInteger;
+ '762': BigInteger;
+ '763': BigInteger;
+ '764': BigInteger;
+ '765': BigInteger;
+ '766': BigInteger;
+ '767': BigInteger;
+ '768': BigInteger;
+ '769': BigInteger;
+ '770': BigInteger;
+ '771': BigInteger;
+ '772': BigInteger;
+ '773': BigInteger;
+ '774': BigInteger;
+ '775': BigInteger;
+ '776': BigInteger;
+ '777': BigInteger;
+ '778': BigInteger;
+ '779': BigInteger;
+ '780': BigInteger;
+ '781': BigInteger;
+ '782': BigInteger;
+ '783': BigInteger;
+ '784': BigInteger;
+ '785': BigInteger;
+ '786': BigInteger;
+ '787': BigInteger;
+ '788': BigInteger;
+ '789': BigInteger;
+ '790': BigInteger;
+ '791': BigInteger;
+ '792': BigInteger;
+ '793': BigInteger;
+ '794': BigInteger;
+ '795': BigInteger;
+ '796': BigInteger;
+ '797': BigInteger;
+ '798': BigInteger;
+ '799': BigInteger;
+ '800': BigInteger;
+ '801': BigInteger;
+ '802': BigInteger;
+ '803': BigInteger;
+ '804': BigInteger;
+ '805': BigInteger;
+ '806': BigInteger;
+ '807': BigInteger;
+ '808': BigInteger;
+ '809': BigInteger;
+ '810': BigInteger;
+ '811': BigInteger;
+ '812': BigInteger;
+ '813': BigInteger;
+ '814': BigInteger;
+ '815': BigInteger;
+ '816': BigInteger;
+ '817': BigInteger;
+ '818': BigInteger;
+ '819': BigInteger;
+ '820': BigInteger;
+ '821': BigInteger;
+ '822': BigInteger;
+ '823': BigInteger;
+ '824': BigInteger;
+ '825': BigInteger;
+ '826': BigInteger;
+ '827': BigInteger;
+ '828': BigInteger;
+ '829': BigInteger;
+ '830': BigInteger;
+ '831': BigInteger;
+ '832': BigInteger;
+ '833': BigInteger;
+ '834': BigInteger;
+ '835': BigInteger;
+ '836': BigInteger;
+ '837': BigInteger;
+ '838': BigInteger;
+ '839': BigInteger;
+ '840': BigInteger;
+ '841': BigInteger;
+ '842': BigInteger;
+ '843': BigInteger;
+ '844': BigInteger;
+ '845': BigInteger;
+ '846': BigInteger;
+ '847': BigInteger;
+ '848': BigInteger;
+ '849': BigInteger;
+ '850': BigInteger;
+ '851': BigInteger;
+ '852': BigInteger;
+ '853': BigInteger;
+ '854': BigInteger;
+ '855': BigInteger;
+ '856': BigInteger;
+ '857': BigInteger;
+ '858': BigInteger;
+ '859': BigInteger;
+ '860': BigInteger;
+ '861': BigInteger;
+ '862': BigInteger;
+ '863': BigInteger;
+ '864': BigInteger;
+ '865': BigInteger;
+ '866': BigInteger;
+ '867': BigInteger;
+ '868': BigInteger;
+ '869': BigInteger;
+ '870': BigInteger;
+ '871': BigInteger;
+ '872': BigInteger;
+ '873': BigInteger;
+ '874': BigInteger;
+ '875': BigInteger;
+ '876': BigInteger;
+ '877': BigInteger;
+ '878': BigInteger;
+ '879': BigInteger;
+ '880': BigInteger;
+ '881': BigInteger;
+ '882': BigInteger;
+ '883': BigInteger;
+ '884': BigInteger;
+ '885': BigInteger;
+ '886': BigInteger;
+ '887': BigInteger;
+ '888': BigInteger;
+ '889': BigInteger;
+ '890': BigInteger;
+ '891': BigInteger;
+ '892': BigInteger;
+ '893': BigInteger;
+ '894': BigInteger;
+ '895': BigInteger;
+ '896': BigInteger;
+ '897': BigInteger;
+ '898': BigInteger;
+ '899': BigInteger;
+ '900': BigInteger;
+ '901': BigInteger;
+ '902': BigInteger;
+ '903': BigInteger;
+ '904': BigInteger;
+ '905': BigInteger;
+ '906': BigInteger;
+ '907': BigInteger;
+ '908': BigInteger;
+ '909': BigInteger;
+ '910': BigInteger;
+ '911': BigInteger;
+ '912': BigInteger;
+ '913': BigInteger;
+ '914': BigInteger;
+ '915': BigInteger;
+ '916': BigInteger;
+ '917': BigInteger;
+ '918': BigInteger;
+ '919': BigInteger;
+ '920': BigInteger;
+ '921': BigInteger;
+ '922': BigInteger;
+ '923': BigInteger;
+ '924': BigInteger;
+ '925': BigInteger;
+ '926': BigInteger;
+ '927': BigInteger;
+ '928': BigInteger;
+ '929': BigInteger;
+ '930': BigInteger;
+ '931': BigInteger;
+ '932': BigInteger;
+ '933': BigInteger;
+ '934': BigInteger;
+ '935': BigInteger;
+ '936': BigInteger;
+ '937': BigInteger;
+ '938': BigInteger;
+ '939': BigInteger;
+ '940': BigInteger;
+ '941': BigInteger;
+ '942': BigInteger;
+ '943': BigInteger;
+ '944': BigInteger;
+ '945': BigInteger;
+ '946': BigInteger;
+ '947': BigInteger;
+ '948': BigInteger;
+ '949': BigInteger;
+ '950': BigInteger;
+ '951': BigInteger;
+ '952': BigInteger;
+ '953': BigInteger;
+ '954': BigInteger;
+ '955': BigInteger;
+ '956': BigInteger;
+ '957': BigInteger;
+ '958': BigInteger;
+ '959': BigInteger;
+ '960': BigInteger;
+ '961': BigInteger;
+ '962': BigInteger;
+ '963': BigInteger;
+ '964': BigInteger;
+ '965': BigInteger;
+ '966': BigInteger;
+ '967': BigInteger;
+ '968': BigInteger;
+ '969': BigInteger;
+ '970': BigInteger;
+ '971': BigInteger;
+ '972': BigInteger;
+ '973': BigInteger;
+ '974': BigInteger;
+ '975': BigInteger;
+ '976': BigInteger;
+ '977': BigInteger;
+ '978': BigInteger;
+ '979': BigInteger;
+ '980': BigInteger;
+ '981': BigInteger;
+ '982': BigInteger;
+ '983': BigInteger;
+ '984': BigInteger;
+ '985': BigInteger;
+ '986': BigInteger;
+ '987': BigInteger;
+ '988': BigInteger;
+ '989': BigInteger;
+ '990': BigInteger;
+ '991': BigInteger;
+ '992': BigInteger;
+ '993': BigInteger;
+ '994': BigInteger;
+ '995': BigInteger;
+ '996': BigInteger;
+ '997': BigInteger;
+ '998': BigInteger;
+ '999': BigInteger;
+ }
+
+ interface BaseArray {
+ value: number[],
+ isNegative: boolean
+ }
+}
diff --git a/temporary_modules/trezor-connect/node_modules/big-integer/BigInteger.js b/temporary_modules/trezor-connect/node_modules/big-integer/BigInteger.js
new file mode 100644
index 00000000..ecda792d
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/big-integer/BigInteger.js
@@ -0,0 +1,1453 @@
+var bigInt = (function (undefined) {
+ "use strict";
+
+ var BASE = 1e7,
+ LOG_BASE = 7,
+ MAX_INT = 9007199254740992,
+ MAX_INT_ARR = smallToArray(MAX_INT),
+ DEFAULT_ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz";
+
+ var supportsNativeBigInt = typeof BigInt === "function";
+
+ function Integer(v, radix, alphabet, caseSensitive) {
+ if (typeof v === "undefined") return Integer[0];
+ if (typeof radix !== "undefined") return +radix === 10 && !alphabet ? parseValue(v) : parseBase(v, radix, alphabet, caseSensitive);
+ return parseValue(v);
+ }
+
+ function BigInteger(value, sign) {
+ this.value = value;
+ this.sign = sign;
+ this.isSmall = false;
+ }
+ BigInteger.prototype = Object.create(Integer.prototype);
+
+ function SmallInteger(value) {
+ this.value = value;
+ this.sign = value < 0;
+ this.isSmall = true;
+ }
+ SmallInteger.prototype = Object.create(Integer.prototype);
+
+ function NativeBigInt(value) {
+ this.value = value;
+ }
+ NativeBigInt.prototype = Object.create(Integer.prototype);
+
+ function isPrecise(n) {
+ return -MAX_INT < n && n < MAX_INT;
+ }
+
+ function smallToArray(n) { // For performance reasons doesn't reference BASE, need to change this function if BASE changes
+ if (n < 1e7)
+ return [n];
+ if (n < 1e14)
+ return [n % 1e7, Math.floor(n / 1e7)];
+ return [n % 1e7, Math.floor(n / 1e7) % 1e7, Math.floor(n / 1e14)];
+ }
+
+ function arrayToSmall(arr) { // If BASE changes this function may need to change
+ trim(arr);
+ var length = arr.length;
+ if (length < 4 && compareAbs(arr, MAX_INT_ARR) < 0) {
+ switch (length) {
+ case 0: return 0;
+ case 1: return arr[0];
+ case 2: return arr[0] + arr[1] * BASE;
+ default: return arr[0] + (arr[1] + arr[2] * BASE) * BASE;
+ }
+ }
+ return arr;
+ }
+
+ function trim(v) {
+ var i = v.length;
+ while (v[--i] === 0);
+ v.length = i + 1;
+ }
+
+ function createArray(length) { // function shamelessly stolen from Yaffle's library https://github.com/Yaffle/BigInteger
+ var x = new Array(length);
+ var i = -1;
+ while (++i < length) {
+ x[i] = 0;
+ }
+ return x;
+ }
+
+ function truncate(n) {
+ if (n > 0) return Math.floor(n);
+ return Math.ceil(n);
+ }
+
+ function add(a, b) { // assumes a and b are arrays with a.length >= b.length
+ var l_a = a.length,
+ l_b = b.length,
+ r = new Array(l_a),
+ carry = 0,
+ base = BASE,
+ sum, i;
+ for (i = 0; i < l_b; i++) {
+ sum = a[i] + b[i] + carry;
+ carry = sum >= base ? 1 : 0;
+ r[i] = sum - carry * base;
+ }
+ while (i < l_a) {
+ sum = a[i] + carry;
+ carry = sum === base ? 1 : 0;
+ r[i++] = sum - carry * base;
+ }
+ if (carry > 0) r.push(carry);
+ return r;
+ }
+
+ function addAny(a, b) {
+ if (a.length >= b.length) return add(a, b);
+ return add(b, a);
+ }
+
+ function addSmall(a, carry) { // assumes a is array, carry is number with 0 <= carry < MAX_INT
+ var l = a.length,
+ r = new Array(l),
+ base = BASE,
+ sum, i;
+ for (i = 0; i < l; i++) {
+ sum = a[i] - base + carry;
+ carry = Math.floor(sum / base);
+ r[i] = sum - carry * base;
+ carry += 1;
+ }
+ while (carry > 0) {
+ r[i++] = carry % base;
+ carry = Math.floor(carry / base);
+ }
+ return r;
+ }
+
+ BigInteger.prototype.add = function (v) {
+ var n = parseValue(v);
+ if (this.sign !== n.sign) {
+ return this.subtract(n.negate());
+ }
+ var a = this.value, b = n.value;
+ if (n.isSmall) {
+ return new BigInteger(addSmall(a, Math.abs(b)), this.sign);
+ }
+ return new BigInteger(addAny(a, b), this.sign);
+ };
+ BigInteger.prototype.plus = BigInteger.prototype.add;
+
+ SmallInteger.prototype.add = function (v) {
+ var n = parseValue(v);
+ var a = this.value;
+ if (a < 0 !== n.sign) {
+ return this.subtract(n.negate());
+ }
+ var b = n.value;
+ if (n.isSmall) {
+ if (isPrecise(a + b)) return new SmallInteger(a + b);
+ b = smallToArray(Math.abs(b));
+ }
+ return new BigInteger(addSmall(b, Math.abs(a)), a < 0);
+ };
+ SmallInteger.prototype.plus = SmallInteger.prototype.add;
+
+ NativeBigInt.prototype.add = function (v) {
+ return new NativeBigInt(this.value + parseValue(v).value);
+ }
+ NativeBigInt.prototype.plus = NativeBigInt.prototype.add;
+
+ function subtract(a, b) { // assumes a and b are arrays with a >= b
+ var a_l = a.length,
+ b_l = b.length,
+ r = new Array(a_l),
+ borrow = 0,
+ base = BASE,
+ i, difference;
+ for (i = 0; i < b_l; i++) {
+ difference = a[i] - borrow - b[i];
+ if (difference < 0) {
+ difference += base;
+ borrow = 1;
+ } else borrow = 0;
+ r[i] = difference;
+ }
+ for (i = b_l; i < a_l; i++) {
+ difference = a[i] - borrow;
+ if (difference < 0) difference += base;
+ else {
+ r[i++] = difference;
+ break;
+ }
+ r[i] = difference;
+ }
+ for (; i < a_l; i++) {
+ r[i] = a[i];
+ }
+ trim(r);
+ return r;
+ }
+
+ function subtractAny(a, b, sign) {
+ var value;
+ if (compareAbs(a, b) >= 0) {
+ value = subtract(a, b);
+ } else {
+ value = subtract(b, a);
+ sign = !sign;
+ }
+ value = arrayToSmall(value);
+ if (typeof value === "number") {
+ if (sign) value = -value;
+ return new SmallInteger(value);
+ }
+ return new BigInteger(value, sign);
+ }
+
+ function subtractSmall(a, b, sign) { // assumes a is array, b is number with 0 <= b < MAX_INT
+ var l = a.length,
+ r = new Array(l),
+ carry = -b,
+ base = BASE,
+ i, difference;
+ for (i = 0; i < l; i++) {
+ difference = a[i] + carry;
+ carry = Math.floor(difference / base);
+ difference %= base;
+ r[i] = difference < 0 ? difference + base : difference;
+ }
+ r = arrayToSmall(r);
+ if (typeof r === "number") {
+ if (sign) r = -r;
+ return new SmallInteger(r);
+ } return new BigInteger(r, sign);
+ }
+
+ BigInteger.prototype.subtract = function (v) {
+ var n = parseValue(v);
+ if (this.sign !== n.sign) {
+ return this.add(n.negate());
+ }
+ var a = this.value, b = n.value;
+ if (n.isSmall)
+ return subtractSmall(a, Math.abs(b), this.sign);
+ return subtractAny(a, b, this.sign);
+ };
+ BigInteger.prototype.minus = BigInteger.prototype.subtract;
+
+ SmallInteger.prototype.subtract = function (v) {
+ var n = parseValue(v);
+ var a = this.value;
+ if (a < 0 !== n.sign) {
+ return this.add(n.negate());
+ }
+ var b = n.value;
+ if (n.isSmall) {
+ return new SmallInteger(a - b);
+ }
+ return subtractSmall(b, Math.abs(a), a >= 0);
+ };
+ SmallInteger.prototype.minus = SmallInteger.prototype.subtract;
+
+ NativeBigInt.prototype.subtract = function (v) {
+ return new NativeBigInt(this.value - parseValue(v).value);
+ }
+ NativeBigInt.prototype.minus = NativeBigInt.prototype.subtract;
+
+ BigInteger.prototype.negate = function () {
+ return new BigInteger(this.value, !this.sign);
+ };
+ SmallInteger.prototype.negate = function () {
+ var sign = this.sign;
+ var small = new SmallInteger(-this.value);
+ small.sign = !sign;
+ return small;
+ };
+ NativeBigInt.prototype.negate = function () {
+ return new NativeBigInt(-this.value);
+ }
+
+ BigInteger.prototype.abs = function () {
+ return new BigInteger(this.value, false);
+ };
+ SmallInteger.prototype.abs = function () {
+ return new SmallInteger(Math.abs(this.value));
+ };
+ NativeBigInt.prototype.abs = function () {
+ return new NativeBigInt(this.value >= 0 ? this.value : -this.value);
+ }
+
+
+ function multiplyLong(a, b) {
+ var a_l = a.length,
+ b_l = b.length,
+ l = a_l + b_l,
+ r = createArray(l),
+ base = BASE,
+ product, carry, i, a_i, b_j;
+ for (i = 0; i < a_l; ++i) {
+ a_i = a[i];
+ for (var j = 0; j < b_l; ++j) {
+ b_j = b[j];
+ product = a_i * b_j + r[i + j];
+ carry = Math.floor(product / base);
+ r[i + j] = product - carry * base;
+ r[i + j + 1] += carry;
+ }
+ }
+ trim(r);
+ return r;
+ }
+
+ function multiplySmall(a, b) { // assumes a is array, b is number with |b| < BASE
+ var l = a.length,
+ r = new Array(l),
+ base = BASE,
+ carry = 0,
+ product, i;
+ for (i = 0; i < l; i++) {
+ product = a[i] * b + carry;
+ carry = Math.floor(product / base);
+ r[i] = product - carry * base;
+ }
+ while (carry > 0) {
+ r[i++] = carry % base;
+ carry = Math.floor(carry / base);
+ }
+ return r;
+ }
+
+ function shiftLeft(x, n) {
+ var r = [];
+ while (n-- > 0) r.push(0);
+ return r.concat(x);
+ }
+
+ function multiplyKaratsuba(x, y) {
+ var n = Math.max(x.length, y.length);
+
+ if (n <= 30) return multiplyLong(x, y);
+ n = Math.ceil(n / 2);
+
+ var b = x.slice(n),
+ a = x.slice(0, n),
+ d = y.slice(n),
+ c = y.slice(0, n);
+
+ var ac = multiplyKaratsuba(a, c),
+ bd = multiplyKaratsuba(b, d),
+ abcd = multiplyKaratsuba(addAny(a, b), addAny(c, d));
+
+ var product = addAny(addAny(ac, shiftLeft(subtract(subtract(abcd, ac), bd), n)), shiftLeft(bd, 2 * n));
+ trim(product);
+ return product;
+ }
+
+ // The following function is derived from a surface fit of a graph plotting the performance difference
+ // between long multiplication and karatsuba multiplication versus the lengths of the two arrays.
+ function useKaratsuba(l1, l2) {
+ return -0.012 * l1 - 0.012 * l2 + 0.000015 * l1 * l2 > 0;
+ }
+
+ BigInteger.prototype.multiply = function (v) {
+ var n = parseValue(v),
+ a = this.value, b = n.value,
+ sign = this.sign !== n.sign,
+ abs;
+ if (n.isSmall) {
+ if (b === 0) return Integer[0];
+ if (b === 1) return this;
+ if (b === -1) return this.negate();
+ abs = Math.abs(b);
+ if (abs < BASE) {
+ return new BigInteger(multiplySmall(a, abs), sign);
+ }
+ b = smallToArray(abs);
+ }
+ if (useKaratsuba(a.length, b.length)) // Karatsuba is only faster for certain array sizes
+ return new BigInteger(multiplyKaratsuba(a, b), sign);
+ return new BigInteger(multiplyLong(a, b), sign);
+ };
+
+ BigInteger.prototype.times = BigInteger.prototype.multiply;
+
+ function multiplySmallAndArray(a, b, sign) { // a >= 0
+ if (a < BASE) {
+ return new BigInteger(multiplySmall(b, a), sign);
+ }
+ return new BigInteger(multiplyLong(b, smallToArray(a)), sign);
+ }
+ SmallInteger.prototype._multiplyBySmall = function (a) {
+ if (isPrecise(a.value * this.value)) {
+ return new SmallInteger(a.value * this.value);
+ }
+ return multiplySmallAndArray(Math.abs(a.value), smallToArray(Math.abs(this.value)), this.sign !== a.sign);
+ };
+ BigInteger.prototype._multiplyBySmall = function (a) {
+ if (a.value === 0) return Integer[0];
+ if (a.value === 1) return this;
+ if (a.value === -1) return this.negate();
+ return multiplySmallAndArray(Math.abs(a.value), this.value, this.sign !== a.sign);
+ };
+ SmallInteger.prototype.multiply = function (v) {
+ return parseValue(v)._multiplyBySmall(this);
+ };
+ SmallInteger.prototype.times = SmallInteger.prototype.multiply;
+
+ NativeBigInt.prototype.multiply = function (v) {
+ return new NativeBigInt(this.value * parseValue(v).value);
+ }
+ NativeBigInt.prototype.times = NativeBigInt.prototype.multiply;
+
+ function square(a) {
+ //console.assert(2 * BASE * BASE < MAX_INT);
+ var l = a.length,
+ r = createArray(l + l),
+ base = BASE,
+ product, carry, i, a_i, a_j;
+ for (i = 0; i < l; i++) {
+ a_i = a[i];
+ carry = 0 - a_i * a_i;
+ for (var j = i; j < l; j++) {
+ a_j = a[j];
+ product = 2 * (a_i * a_j) + r[i + j] + carry;
+ carry = Math.floor(product / base);
+ r[i + j] = product - carry * base;
+ }
+ r[i + l] = carry;
+ }
+ trim(r);
+ return r;
+ }
+
+ BigInteger.prototype.square = function () {
+ return new BigInteger(square(this.value), false);
+ };
+
+ SmallInteger.prototype.square = function () {
+ var value = this.value * this.value;
+ if (isPrecise(value)) return new SmallInteger(value);
+ return new BigInteger(square(smallToArray(Math.abs(this.value))), false);
+ };
+
+ NativeBigInt.prototype.square = function (v) {
+ return new NativeBigInt(this.value * this.value);
+ }
+
+ function divMod1(a, b) { // Left over from previous version. Performs faster than divMod2 on smaller input sizes.
+ var a_l = a.length,
+ b_l = b.length,
+ base = BASE,
+ result = createArray(b.length),
+ divisorMostSignificantDigit = b[b_l - 1],
+ // normalization
+ lambda = Math.ceil(base / (2 * divisorMostSignificantDigit)),
+ remainder = multiplySmall(a, lambda),
+ divisor = multiplySmall(b, lambda),
+ quotientDigit, shift, carry, borrow, i, l, q;
+ if (remainder.length <= a_l) remainder.push(0);
+ divisor.push(0);
+ divisorMostSignificantDigit = divisor[b_l - 1];
+ for (shift = a_l - b_l; shift >= 0; shift--) {
+ quotientDigit = base - 1;
+ if (remainder[shift + b_l] !== divisorMostSignificantDigit) {
+ quotientDigit = Math.floor((remainder[shift + b_l] * base + remainder[shift + b_l - 1]) / divisorMostSignificantDigit);
+ }
+ // quotientDigit <= base - 1
+ carry = 0;
+ borrow = 0;
+ l = divisor.length;
+ for (i = 0; i < l; i++) {
+ carry += quotientDigit * divisor[i];
+ q = Math.floor(carry / base);
+ borrow += remainder[shift + i] - (carry - q * base);
+ carry = q;
+ if (borrow < 0) {
+ remainder[shift + i] = borrow + base;
+ borrow = -1;
+ } else {
+ remainder[shift + i] = borrow;
+ borrow = 0;
+ }
+ }
+ while (borrow !== 0) {
+ quotientDigit -= 1;
+ carry = 0;
+ for (i = 0; i < l; i++) {
+ carry += remainder[shift + i] - base + divisor[i];
+ if (carry < 0) {
+ remainder[shift + i] = carry + base;
+ carry = 0;
+ } else {
+ remainder[shift + i] = carry;
+ carry = 1;
+ }
+ }
+ borrow += carry;
+ }
+ result[shift] = quotientDigit;
+ }
+ // denormalization
+ remainder = divModSmall(remainder, lambda)[0];
+ return [arrayToSmall(result), arrayToSmall(remainder)];
+ }
+
+ function divMod2(a, b) { // Implementation idea shamelessly stolen from Silent Matt's library http://silentmatt.com/biginteger/
+ // Performs faster than divMod1 on larger input sizes.
+ var a_l = a.length,
+ b_l = b.length,
+ result = [],
+ part = [],
+ base = BASE,
+ guess, xlen, highx, highy, check;
+ while (a_l) {
+ part.unshift(a[--a_l]);
+ trim(part);
+ if (compareAbs(part, b) < 0) {
+ result.push(0);
+ continue;
+ }
+ xlen = part.length;
+ highx = part[xlen - 1] * base + part[xlen - 2];
+ highy = b[b_l - 1] * base + b[b_l - 2];
+ if (xlen > b_l) {
+ highx = (highx + 1) * base;
+ }
+ guess = Math.ceil(highx / highy);
+ do {
+ check = multiplySmall(b, guess);
+ if (compareAbs(check, part) <= 0) break;
+ guess--;
+ } while (guess);
+ result.push(guess);
+ part = subtract(part, check);
+ }
+ result.reverse();
+ return [arrayToSmall(result), arrayToSmall(part)];
+ }
+
+ function divModSmall(value, lambda) {
+ var length = value.length,
+ quotient = createArray(length),
+ base = BASE,
+ i, q, remainder, divisor;
+ remainder = 0;
+ for (i = length - 1; i >= 0; --i) {
+ divisor = remainder * base + value[i];
+ q = truncate(divisor / lambda);
+ remainder = divisor - q * lambda;
+ quotient[i] = q | 0;
+ }
+ return [quotient, remainder | 0];
+ }
+
+ function divModAny(self, v) {
+ var value, n = parseValue(v);
+ if (supportsNativeBigInt) {
+ return [new NativeBigInt(self.value / n.value), new NativeBigInt(self.value % n.value)];
+ }
+ var a = self.value, b = n.value;
+ var quotient;
+ if (b === 0) throw new Error("Cannot divide by zero");
+ if (self.isSmall) {
+ if (n.isSmall) {
+ return [new SmallInteger(truncate(a / b)), new SmallInteger(a % b)];
+ }
+ return [Integer[0], self];
+ }
+ if (n.isSmall) {
+ if (b === 1) return [self, Integer[0]];
+ if (b == -1) return [self.negate(), Integer[0]];
+ var abs = Math.abs(b);
+ if (abs < BASE) {
+ value = divModSmall(a, abs);
+ quotient = arrayToSmall(value[0]);
+ var remainder = value[1];
+ if (self.sign) remainder = -remainder;
+ if (typeof quotient === "number") {
+ if (self.sign !== n.sign) quotient = -quotient;
+ return [new SmallInteger(quotient), new SmallInteger(remainder)];
+ }
+ return [new BigInteger(quotient, self.sign !== n.sign), new SmallInteger(remainder)];
+ }
+ b = smallToArray(abs);
+ }
+ var comparison = compareAbs(a, b);
+ if (comparison === -1) return [Integer[0], self];
+ if (comparison === 0) return [Integer[self.sign === n.sign ? 1 : -1], Integer[0]];
+
+ // divMod1 is faster on smaller input sizes
+ if (a.length + b.length <= 200)
+ value = divMod1(a, b);
+ else value = divMod2(a, b);
+
+ quotient = value[0];
+ var qSign = self.sign !== n.sign,
+ mod = value[1],
+ mSign = self.sign;
+ if (typeof quotient === "number") {
+ if (qSign) quotient = -quotient;
+ quotient = new SmallInteger(quotient);
+ } else quotient = new BigInteger(quotient, qSign);
+ if (typeof mod === "number") {
+ if (mSign) mod = -mod;
+ mod = new SmallInteger(mod);
+ } else mod = new BigInteger(mod, mSign);
+ return [quotient, mod];
+ }
+
+ BigInteger.prototype.divmod = function (v) {
+ var result = divModAny(this, v);
+ return {
+ quotient: result[0],
+ remainder: result[1]
+ };
+ };
+ NativeBigInt.prototype.divmod = SmallInteger.prototype.divmod = BigInteger.prototype.divmod;
+
+
+ BigInteger.prototype.divide = function (v) {
+ return divModAny(this, v)[0];
+ };
+ NativeBigInt.prototype.over = NativeBigInt.prototype.divide = function (v) {
+ return new NativeBigInt(this.value / parseValue(v).value);
+ };
+ SmallInteger.prototype.over = SmallInteger.prototype.divide = BigInteger.prototype.over = BigInteger.prototype.divide;
+
+ BigInteger.prototype.mod = function (v) {
+ return divModAny(this, v)[1];
+ };
+ NativeBigInt.prototype.mod = NativeBigInt.prototype.remainder = function (v) {
+ return new NativeBigInt(this.value % parseValue(v).value);
+ };
+ SmallInteger.prototype.remainder = SmallInteger.prototype.mod = BigInteger.prototype.remainder = BigInteger.prototype.mod;
+
+ BigInteger.prototype.pow = function (v) {
+ var n = parseValue(v),
+ a = this.value,
+ b = n.value,
+ value, x, y;
+ if (b === 0) return Integer[1];
+ if (a === 0) return Integer[0];
+ if (a === 1) return Integer[1];
+ if (a === -1) return n.isEven() ? Integer[1] : Integer[-1];
+ if (n.sign) {
+ return Integer[0];
+ }
+ if (!n.isSmall) throw new Error("The exponent " + n.toString() + " is too large.");
+ if (this.isSmall) {
+ if (isPrecise(value = Math.pow(a, b)))
+ return new SmallInteger(truncate(value));
+ }
+ x = this;
+ y = Integer[1];
+ while (true) {
+ if (b & 1 === 1) {
+ y = y.times(x);
+ --b;
+ }
+ if (b === 0) break;
+ b /= 2;
+ x = x.square();
+ }
+ return y;
+ };
+ SmallInteger.prototype.pow = BigInteger.prototype.pow;
+
+ NativeBigInt.prototype.pow = function (v) {
+ var n = parseValue(v);
+ var a = this.value, b = n.value;
+ var _0 = BigInt(0), _1 = BigInt(1), _2 = BigInt(2);
+ if (b === _0) return Integer[1];
+ if (a === _0) return Integer[0];
+ if (a === _1) return Integer[1];
+ if (a === BigInt(-1)) return n.isEven() ? Integer[1] : Integer[-1];
+ if (n.isNegative()) return new NativeBigInt(_0);
+ var x = this;
+ var y = Integer[1];
+ while (true) {
+ if ((b & _1) === _1) {
+ y = y.times(x);
+ --b;
+ }
+ if (b === _0) break;
+ b /= _2;
+ x = x.square();
+ }
+ return y;
+ }
+
+ BigInteger.prototype.modPow = function (exp, mod) {
+ exp = parseValue(exp);
+ mod = parseValue(mod);
+ if (mod.isZero()) throw new Error("Cannot take modPow with modulus 0");
+ var r = Integer[1],
+ base = this.mod(mod);
+ if (exp.isNegative()) {
+ exp = exp.multiply(Integer[-1]);
+ base = base.modInv(mod);
+ }
+ while (exp.isPositive()) {
+ if (base.isZero()) return Integer[0];
+ if (exp.isOdd()) r = r.multiply(base).mod(mod);
+ exp = exp.divide(2);
+ base = base.square().mod(mod);
+ }
+ return r;
+ };
+ NativeBigInt.prototype.modPow = SmallInteger.prototype.modPow = BigInteger.prototype.modPow;
+
+ function compareAbs(a, b) {
+ if (a.length !== b.length) {
+ return a.length > b.length ? 1 : -1;
+ }
+ for (var i = a.length - 1; i >= 0; i--) {
+ if (a[i] !== b[i]) return a[i] > b[i] ? 1 : -1;
+ }
+ return 0;
+ }
+
+ BigInteger.prototype.compareAbs = function (v) {
+ var n = parseValue(v),
+ a = this.value,
+ b = n.value;
+ if (n.isSmall) return 1;
+ return compareAbs(a, b);
+ };
+ SmallInteger.prototype.compareAbs = function (v) {
+ var n = parseValue(v),
+ a = Math.abs(this.value),
+ b = n.value;
+ if (n.isSmall) {
+ b = Math.abs(b);
+ return a === b ? 0 : a > b ? 1 : -1;
+ }
+ return -1;
+ };
+ NativeBigInt.prototype.compareAbs = function (v) {
+ var a = this.value;
+ var b = parseValue(v).value;
+ a = a >= 0 ? a : -a;
+ b = b >= 0 ? b : -b;
+ return a === b ? 0 : a > b ? 1 : -1;
+ }
+
+ BigInteger.prototype.compare = function (v) {
+ // See discussion about comparison with Infinity:
+ // https://github.com/peterolson/BigInteger.js/issues/61
+ if (v === Infinity) {
+ return -1;
+ }
+ if (v === -Infinity) {
+ return 1;
+ }
+
+ var n = parseValue(v),
+ a = this.value,
+ b = n.value;
+ if (this.sign !== n.sign) {
+ return n.sign ? 1 : -1;
+ }
+ if (n.isSmall) {
+ return this.sign ? -1 : 1;
+ }
+ return compareAbs(a, b) * (this.sign ? -1 : 1);
+ };
+ BigInteger.prototype.compareTo = BigInteger.prototype.compare;
+
+ SmallInteger.prototype.compare = function (v) {
+ if (v === Infinity) {
+ return -1;
+ }
+ if (v === -Infinity) {
+ return 1;
+ }
+
+ var n = parseValue(v),
+ a = this.value,
+ b = n.value;
+ if (n.isSmall) {
+ return a == b ? 0 : a > b ? 1 : -1;
+ }
+ if (a < 0 !== n.sign) {
+ return a < 0 ? -1 : 1;
+ }
+ return a < 0 ? 1 : -1;
+ };
+ SmallInteger.prototype.compareTo = SmallInteger.prototype.compare;
+
+ NativeBigInt.prototype.compare = function (v) {
+ if (v === Infinity) {
+ return -1;
+ }
+ if (v === -Infinity) {
+ return 1;
+ }
+ var a = this.value;
+ var b = parseValue(v).value;
+ return a === b ? 0 : a > b ? 1 : -1;
+ }
+ NativeBigInt.prototype.compareTo = NativeBigInt.prototype.compare;
+
+ BigInteger.prototype.equals = function (v) {
+ return this.compare(v) === 0;
+ };
+ NativeBigInt.prototype.eq = NativeBigInt.prototype.equals = SmallInteger.prototype.eq = SmallInteger.prototype.equals = BigInteger.prototype.eq = BigInteger.prototype.equals;
+
+ BigInteger.prototype.notEquals = function (v) {
+ return this.compare(v) !== 0;
+ };
+ NativeBigInt.prototype.neq = NativeBigInt.prototype.notEquals = SmallInteger.prototype.neq = SmallInteger.prototype.notEquals = BigInteger.prototype.neq = BigInteger.prototype.notEquals;
+
+ BigInteger.prototype.greater = function (v) {
+ return this.compare(v) > 0;
+ };
+ NativeBigInt.prototype.gt = NativeBigInt.prototype.greater = SmallInteger.prototype.gt = SmallInteger.prototype.greater = BigInteger.prototype.gt = BigInteger.prototype.greater;
+
+ BigInteger.prototype.lesser = function (v) {
+ return this.compare(v) < 0;
+ };
+ NativeBigInt.prototype.lt = NativeBigInt.prototype.lesser = SmallInteger.prototype.lt = SmallInteger.prototype.lesser = BigInteger.prototype.lt = BigInteger.prototype.lesser;
+
+ BigInteger.prototype.greaterOrEquals = function (v) {
+ return this.compare(v) >= 0;
+ };
+ NativeBigInt.prototype.geq = NativeBigInt.prototype.greaterOrEquals = SmallInteger.prototype.geq = SmallInteger.prototype.greaterOrEquals = BigInteger.prototype.geq = BigInteger.prototype.greaterOrEquals;
+
+ BigInteger.prototype.lesserOrEquals = function (v) {
+ return this.compare(v) <= 0;
+ };
+ NativeBigInt.prototype.leq = NativeBigInt.prototype.lesserOrEquals = SmallInteger.prototype.leq = SmallInteger.prototype.lesserOrEquals = BigInteger.prototype.leq = BigInteger.prototype.lesserOrEquals;
+
+ BigInteger.prototype.isEven = function () {
+ return (this.value[0] & 1) === 0;
+ };
+ SmallInteger.prototype.isEven = function () {
+ return (this.value & 1) === 0;
+ };
+ NativeBigInt.prototype.isEven = function () {
+ return (this.value & BigInt(1)) === BigInt(0);
+ }
+
+ BigInteger.prototype.isOdd = function () {
+ return (this.value[0] & 1) === 1;
+ };
+ SmallInteger.prototype.isOdd = function () {
+ return (this.value & 1) === 1;
+ };
+ NativeBigInt.prototype.isOdd = function () {
+ return (this.value & BigInt(1)) === BigInt(1);
+ }
+
+ BigInteger.prototype.isPositive = function () {
+ return !this.sign;
+ };
+ SmallInteger.prototype.isPositive = function () {
+ return this.value > 0;
+ };
+ NativeBigInt.prototype.isPositive = SmallInteger.prototype.isPositive;
+
+ BigInteger.prototype.isNegative = function () {
+ return this.sign;
+ };
+ SmallInteger.prototype.isNegative = function () {
+ return this.value < 0;
+ };
+ NativeBigInt.prototype.isNegative = SmallInteger.prototype.isNegative;
+
+ BigInteger.prototype.isUnit = function () {
+ return false;
+ };
+ SmallInteger.prototype.isUnit = function () {
+ return Math.abs(this.value) === 1;
+ };
+ NativeBigInt.prototype.isUnit = function () {
+ return this.abs().value === BigInt(1);
+ }
+
+ BigInteger.prototype.isZero = function () {
+ return false;
+ };
+ SmallInteger.prototype.isZero = function () {
+ return this.value === 0;
+ };
+ NativeBigInt.prototype.isZero = function () {
+ return this.value === BigInt(0);
+ }
+
+ BigInteger.prototype.isDivisibleBy = function (v) {
+ var n = parseValue(v);
+ if (n.isZero()) return false;
+ if (n.isUnit()) return true;
+ if (n.compareAbs(2) === 0) return this.isEven();
+ return this.mod(n).isZero();
+ };
+ NativeBigInt.prototype.isDivisibleBy = SmallInteger.prototype.isDivisibleBy = BigInteger.prototype.isDivisibleBy;
+
+ function isBasicPrime(v) {
+ var n = v.abs();
+ if (n.isUnit()) return false;
+ if (n.equals(2) || n.equals(3) || n.equals(5)) return true;
+ if (n.isEven() || n.isDivisibleBy(3) || n.isDivisibleBy(5)) return false;
+ if (n.lesser(49)) return true;
+ // we don't know if it's prime: let the other functions figure it out
+ }
+
+ function millerRabinTest(n, a) {
+ var nPrev = n.prev(),
+ b = nPrev,
+ r = 0,
+ d, t, i, x;
+ while (b.isEven()) b = b.divide(2), r++;
+ next: for (i = 0; i < a.length; i++) {
+ if (n.lesser(a[i])) continue;
+ x = bigInt(a[i]).modPow(b, n);
+ if (x.isUnit() || x.equals(nPrev)) continue;
+ for (d = r - 1; d != 0; d--) {
+ x = x.square().mod(n);
+ if (x.isUnit()) return false;
+ if (x.equals(nPrev)) continue next;
+ }
+ return false;
+ }
+ return true;
+ }
+
+ // Set "strict" to true to force GRH-supported lower bound of 2*log(N)^2
+ BigInteger.prototype.isPrime = function (strict) {
+ var isPrime = isBasicPrime(this);
+ if (isPrime !== undefined) return isPrime;
+ var n = this.abs();
+ var bits = n.bitLength();
+ if (bits <= 64)
+ return millerRabinTest(n, [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]);
+ var logN = Math.log(2) * bits.toJSNumber();
+ var t = Math.ceil((strict === true) ? (2 * Math.pow(logN, 2)) : logN);
+ for (var a = [], i = 0; i < t; i++) {
+ a.push(bigInt(i + 2));
+ }
+ return millerRabinTest(n, a);
+ };
+ NativeBigInt.prototype.isPrime = SmallInteger.prototype.isPrime = BigInteger.prototype.isPrime;
+
+ BigInteger.prototype.isProbablePrime = function (iterations, rng) {
+ var isPrime = isBasicPrime(this);
+ if (isPrime !== undefined) return isPrime;
+ var n = this.abs();
+ var t = iterations === undefined ? 5 : iterations;
+ for (var a = [], i = 0; i < t; i++) {
+ a.push(bigInt.randBetween(2, n.minus(2), rng));
+ }
+ return millerRabinTest(n, a);
+ };
+ NativeBigInt.prototype.isProbablePrime = SmallInteger.prototype.isProbablePrime = BigInteger.prototype.isProbablePrime;
+
+ BigInteger.prototype.modInv = function (n) {
+ var t = bigInt.zero, newT = bigInt.one, r = parseValue(n), newR = this.abs(), q, lastT, lastR;
+ while (!newR.isZero()) {
+ q = r.divide(newR);
+ lastT = t;
+ lastR = r;
+ t = newT;
+ r = newR;
+ newT = lastT.subtract(q.multiply(newT));
+ newR = lastR.subtract(q.multiply(newR));
+ }
+ if (!r.isUnit()) throw new Error(this.toString() + " and " + n.toString() + " are not co-prime");
+ if (t.compare(0) === -1) {
+ t = t.add(n);
+ }
+ if (this.isNegative()) {
+ return t.negate();
+ }
+ return t;
+ };
+
+ NativeBigInt.prototype.modInv = SmallInteger.prototype.modInv = BigInteger.prototype.modInv;
+
+ BigInteger.prototype.next = function () {
+ var value = this.value;
+ if (this.sign) {
+ return subtractSmall(value, 1, this.sign);
+ }
+ return new BigInteger(addSmall(value, 1), this.sign);
+ };
+ SmallInteger.prototype.next = function () {
+ var value = this.value;
+ if (value + 1 < MAX_INT) return new SmallInteger(value + 1);
+ return new BigInteger(MAX_INT_ARR, false);
+ };
+ NativeBigInt.prototype.next = function () {
+ return new NativeBigInt(this.value + BigInt(1));
+ }
+
+ BigInteger.prototype.prev = function () {
+ var value = this.value;
+ if (this.sign) {
+ return new BigInteger(addSmall(value, 1), true);
+ }
+ return subtractSmall(value, 1, this.sign);
+ };
+ SmallInteger.prototype.prev = function () {
+ var value = this.value;
+ if (value - 1 > -MAX_INT) return new SmallInteger(value - 1);
+ return new BigInteger(MAX_INT_ARR, true);
+ };
+ NativeBigInt.prototype.prev = function () {
+ return new NativeBigInt(this.value - BigInt(1));
+ }
+
+ var powersOfTwo = [1];
+ while (2 * powersOfTwo[powersOfTwo.length - 1] <= BASE) powersOfTwo.push(2 * powersOfTwo[powersOfTwo.length - 1]);
+ var powers2Length = powersOfTwo.length, highestPower2 = powersOfTwo[powers2Length - 1];
+
+ function shift_isSmall(n) {
+ return Math.abs(n) <= BASE;
+ }
+
+ BigInteger.prototype.shiftLeft = function (v) {
+ var n = parseValue(v).toJSNumber();
+ if (!shift_isSmall(n)) {
+ throw new Error(String(n) + " is too large for shifting.");
+ }
+ if (n < 0) return this.shiftRight(-n);
+ var result = this;
+ if (result.isZero()) return result;
+ while (n >= powers2Length) {
+ result = result.multiply(highestPower2);
+ n -= powers2Length - 1;
+ }
+ return result.multiply(powersOfTwo[n]);
+ };
+ NativeBigInt.prototype.shiftLeft = SmallInteger.prototype.shiftLeft = BigInteger.prototype.shiftLeft;
+
+ BigInteger.prototype.shiftRight = function (v) {
+ var remQuo;
+ var n = parseValue(v).toJSNumber();
+ if (!shift_isSmall(n)) {
+ throw new Error(String(n) + " is too large for shifting.");
+ }
+ if (n < 0) return this.shiftLeft(-n);
+ var result = this;
+ while (n >= powers2Length) {
+ if (result.isZero() || (result.isNegative() && result.isUnit())) return result;
+ remQuo = divModAny(result, highestPower2);
+ result = remQuo[1].isNegative() ? remQuo[0].prev() : remQuo[0];
+ n -= powers2Length - 1;
+ }
+ remQuo = divModAny(result, powersOfTwo[n]);
+ return remQuo[1].isNegative() ? remQuo[0].prev() : remQuo[0];
+ };
+ NativeBigInt.prototype.shiftRight = SmallInteger.prototype.shiftRight = BigInteger.prototype.shiftRight;
+
+ function bitwise(x, y, fn) {
+ y = parseValue(y);
+ var xSign = x.isNegative(), ySign = y.isNegative();
+ var xRem = xSign ? x.not() : x,
+ yRem = ySign ? y.not() : y;
+ var xDigit = 0, yDigit = 0;
+ var xDivMod = null, yDivMod = null;
+ var result = [];
+ while (!xRem.isZero() || !yRem.isZero()) {
+ xDivMod = divModAny(xRem, highestPower2);
+ xDigit = xDivMod[1].toJSNumber();
+ if (xSign) {
+ xDigit = highestPower2 - 1 - xDigit; // two's complement for negative numbers
+ }
+
+ yDivMod = divModAny(yRem, highestPower2);
+ yDigit = yDivMod[1].toJSNumber();
+ if (ySign) {
+ yDigit = highestPower2 - 1 - yDigit; // two's complement for negative numbers
+ }
+
+ xRem = xDivMod[0];
+ yRem = yDivMod[0];
+ result.push(fn(xDigit, yDigit));
+ }
+ var sum = fn(xSign ? 1 : 0, ySign ? 1 : 0) !== 0 ? bigInt(-1) : bigInt(0);
+ for (var i = result.length - 1; i >= 0; i -= 1) {
+ sum = sum.multiply(highestPower2).add(bigInt(result[i]));
+ }
+ return sum;
+ }
+
+ BigInteger.prototype.not = function () {
+ return this.negate().prev();
+ };
+ NativeBigInt.prototype.not = SmallInteger.prototype.not = BigInteger.prototype.not;
+
+ BigInteger.prototype.and = function (n) {
+ return bitwise(this, n, function (a, b) { return a & b; });
+ };
+ NativeBigInt.prototype.and = SmallInteger.prototype.and = BigInteger.prototype.and;
+
+ BigInteger.prototype.or = function (n) {
+ return bitwise(this, n, function (a, b) { return a | b; });
+ };
+ NativeBigInt.prototype.or = SmallInteger.prototype.or = BigInteger.prototype.or;
+
+ BigInteger.prototype.xor = function (n) {
+ return bitwise(this, n, function (a, b) { return a ^ b; });
+ };
+ NativeBigInt.prototype.xor = SmallInteger.prototype.xor = BigInteger.prototype.xor;
+
+ var LOBMASK_I = 1 << 30, LOBMASK_BI = (BASE & -BASE) * (BASE & -BASE) | LOBMASK_I;
+ function roughLOB(n) { // get lowestOneBit (rough)
+ // SmallInteger: return Min(lowestOneBit(n), 1 << 30)
+ // BigInteger: return Min(lowestOneBit(n), 1 << 14) [BASE=1e7]
+ var v = n.value,
+ x = typeof v === "number" ? v | LOBMASK_I :
+ typeof v === "bigint" ? v | BigInt(LOBMASK_I) :
+ v[0] + v[1] * BASE | LOBMASK_BI;
+ return x & -x;
+ }
+
+ function integerLogarithm(value, base) {
+ if (base.compareTo(value) <= 0) {
+ var tmp = integerLogarithm(value, base.square(base));
+ var p = tmp.p;
+ var e = tmp.e;
+ var t = p.multiply(base);
+ return t.compareTo(value) <= 0 ? { p: t, e: e * 2 + 1 } : { p: p, e: e * 2 };
+ }
+ return { p: bigInt(1), e: 0 };
+ }
+
+ BigInteger.prototype.bitLength = function () {
+ var n = this;
+ if (n.compareTo(bigInt(0)) < 0) {
+ n = n.negate().subtract(bigInt(1));
+ }
+ if (n.compareTo(bigInt(0)) === 0) {
+ return bigInt(0);
+ }
+ return bigInt(integerLogarithm(n, bigInt(2)).e).add(bigInt(1));
+ }
+ NativeBigInt.prototype.bitLength = SmallInteger.prototype.bitLength = BigInteger.prototype.bitLength;
+
+ function max(a, b) {
+ a = parseValue(a);
+ b = parseValue(b);
+ return a.greater(b) ? a : b;
+ }
+ function min(a, b) {
+ a = parseValue(a);
+ b = parseValue(b);
+ return a.lesser(b) ? a : b;
+ }
+ function gcd(a, b) {
+ a = parseValue(a).abs();
+ b = parseValue(b).abs();
+ if (a.equals(b)) return a;
+ if (a.isZero()) return b;
+ if (b.isZero()) return a;
+ var c = Integer[1], d, t;
+ while (a.isEven() && b.isEven()) {
+ d = min(roughLOB(a), roughLOB(b));
+ a = a.divide(d);
+ b = b.divide(d);
+ c = c.multiply(d);
+ }
+ while (a.isEven()) {
+ a = a.divide(roughLOB(a));
+ }
+ do {
+ while (b.isEven()) {
+ b = b.divide(roughLOB(b));
+ }
+ if (a.greater(b)) {
+ t = b; b = a; a = t;
+ }
+ b = b.subtract(a);
+ } while (!b.isZero());
+ return c.isUnit() ? a : a.multiply(c);
+ }
+ function lcm(a, b) {
+ a = parseValue(a).abs();
+ b = parseValue(b).abs();
+ return a.divide(gcd(a, b)).multiply(b);
+ }
+ function randBetween(a, b, rng) {
+ a = parseValue(a);
+ b = parseValue(b);
+ var usedRNG = rng || Math.random;
+ var low = min(a, b), high = max(a, b);
+ var range = high.subtract(low).add(1);
+ if (range.isSmall) return low.add(Math.floor(usedRNG() * range));
+ var digits = toBase(range, BASE).value;
+ var result = [], restricted = true;
+ for (var i = 0; i < digits.length; i++) {
+ var top = restricted ? digits[i] + (i + 1 < digits.length ? digits[i + 1] / BASE : 0) : BASE;
+ var digit = truncate(usedRNG() * top);
+ result.push(digit);
+ if (digit < digits[i]) restricted = false;
+ }
+ return low.add(Integer.fromArray(result, BASE, false));
+ }
+
+ var parseBase = function (text, base, alphabet, caseSensitive) {
+ alphabet = alphabet || DEFAULT_ALPHABET;
+ text = String(text);
+ if (!caseSensitive) {
+ text = text.toLowerCase();
+ alphabet = alphabet.toLowerCase();
+ }
+ var length = text.length;
+ var i;
+ var absBase = Math.abs(base);
+ var alphabetValues = {};
+ for (i = 0; i < alphabet.length; i++) {
+ alphabetValues[alphabet[i]] = i;
+ }
+ for (i = 0; i < length; i++) {
+ var c = text[i];
+ if (c === "-") continue;
+ if (c in alphabetValues) {
+ if (alphabetValues[c] >= absBase) {
+ if (c === "1" && absBase === 1) continue;
+ throw new Error(c + " is not a valid digit in base " + base + ".");
+ }
+ }
+ }
+ base = parseValue(base);
+ var digits = [];
+ var isNegative = text[0] === "-";
+ for (i = isNegative ? 1 : 0; i < text.length; i++) {
+ var c = text[i];
+ if (c in alphabetValues) digits.push(parseValue(alphabetValues[c]));
+ else if (c === "<") {
+ var start = i;
+ do { i++; } while (text[i] !== ">" && i < text.length);
+ digits.push(parseValue(text.slice(start + 1, i)));
+ }
+ else throw new Error(c + " is not a valid character");
+ }
+ return parseBaseFromArray(digits, base, isNegative);
+ };
+
+ function parseBaseFromArray(digits, base, isNegative) {
+ var val = Integer[0], pow = Integer[1], i;
+ for (i = digits.length - 1; i >= 0; i--) {
+ val = val.add(digits[i].times(pow));
+ pow = pow.times(base);
+ }
+ return isNegative ? val.negate() : val;
+ }
+
+ function stringify(digit, alphabet) {
+ alphabet = alphabet || DEFAULT_ALPHABET;
+ if (digit < alphabet.length) {
+ return alphabet[digit];
+ }
+ return "<" + digit + ">";
+ }
+
+ function toBase(n, base) {
+ base = bigInt(base);
+ if (base.isZero()) {
+ if (n.isZero()) return { value: [0], isNegative: false };
+ throw new Error("Cannot convert nonzero numbers to base 0.");
+ }
+ if (base.equals(-1)) {
+ if (n.isZero()) return { value: [0], isNegative: false };
+ if (n.isNegative())
+ return {
+ value: [].concat.apply([], Array.apply(null, Array(-n.toJSNumber()))
+ .map(Array.prototype.valueOf, [1, 0])
+ ),
+ isNegative: false
+ };
+
+ var arr = Array.apply(null, Array(n.toJSNumber() - 1))
+ .map(Array.prototype.valueOf, [0, 1]);
+ arr.unshift([1]);
+ return {
+ value: [].concat.apply([], arr),
+ isNegative: false
+ };
+ }
+
+ var neg = false;
+ if (n.isNegative() && base.isPositive()) {
+ neg = true;
+ n = n.abs();
+ }
+ if (base.isUnit()) {
+ if (n.isZero()) return { value: [0], isNegative: false };
+
+ return {
+ value: Array.apply(null, Array(n.toJSNumber()))
+ .map(Number.prototype.valueOf, 1),
+ isNegative: neg
+ };
+ }
+ var out = [];
+ var left = n, divmod;
+ while (left.isNegative() || left.compareAbs(base) >= 0) {
+ divmod = left.divmod(base);
+ left = divmod.quotient;
+ var digit = divmod.remainder;
+ if (digit.isNegative()) {
+ digit = base.minus(digit).abs();
+ left = left.next();
+ }
+ out.push(digit.toJSNumber());
+ }
+ out.push(left.toJSNumber());
+ return { value: out.reverse(), isNegative: neg };
+ }
+
+ function toBaseString(n, base, alphabet) {
+ var arr = toBase(n, base);
+ return (arr.isNegative ? "-" : "") + arr.value.map(function (x) {
+ return stringify(x, alphabet);
+ }).join('');
+ }
+
+ BigInteger.prototype.toArray = function (radix) {
+ return toBase(this, radix);
+ };
+
+ SmallInteger.prototype.toArray = function (radix) {
+ return toBase(this, radix);
+ };
+
+ NativeBigInt.prototype.toArray = function (radix) {
+ return toBase(this, radix);
+ };
+
+ BigInteger.prototype.toString = function (radix, alphabet) {
+ if (radix === undefined) radix = 10;
+ if (radix !== 10) return toBaseString(this, radix, alphabet);
+ var v = this.value, l = v.length, str = String(v[--l]), zeros = "0000000", digit;
+ while (--l >= 0) {
+ digit = String(v[l]);
+ str += zeros.slice(digit.length) + digit;
+ }
+ var sign = this.sign ? "-" : "";
+ return sign + str;
+ };
+
+ SmallInteger.prototype.toString = function (radix, alphabet) {
+ if (radix === undefined) radix = 10;
+ if (radix != 10) return toBaseString(this, radix, alphabet);
+ return String(this.value);
+ };
+
+ NativeBigInt.prototype.toString = SmallInteger.prototype.toString;
+
+ NativeBigInt.prototype.toJSON = BigInteger.prototype.toJSON = SmallInteger.prototype.toJSON = function () { return this.toString(); }
+
+ BigInteger.prototype.valueOf = function () {
+ return parseInt(this.toString(), 10);
+ };
+ BigInteger.prototype.toJSNumber = BigInteger.prototype.valueOf;
+
+ SmallInteger.prototype.valueOf = function () {
+ return this.value;
+ };
+ SmallInteger.prototype.toJSNumber = SmallInteger.prototype.valueOf;
+ NativeBigInt.prototype.valueOf = NativeBigInt.prototype.toJSNumber = function () {
+ return parseInt(this.toString(), 10);
+ }
+
+ function parseStringValue(v) {
+ if (isPrecise(+v)) {
+ var x = +v;
+ if (x === truncate(x))
+ return supportsNativeBigInt ? new NativeBigInt(BigInt(x)) : new SmallInteger(x);
+ throw new Error("Invalid integer: " + v);
+ }
+ var sign = v[0] === "-";
+ if (sign) v = v.slice(1);
+ var split = v.split(/e/i);
+ if (split.length > 2) throw new Error("Invalid integer: " + split.join("e"));
+ if (split.length === 2) {
+ var exp = split[1];
+ if (exp[0] === "+") exp = exp.slice(1);
+ exp = +exp;
+ if (exp !== truncate(exp) || !isPrecise(exp)) throw new Error("Invalid integer: " + exp + " is not a valid exponent.");
+ var text = split[0];
+ var decimalPlace = text.indexOf(".");
+ if (decimalPlace >= 0) {
+ exp -= text.length - decimalPlace - 1;
+ text = text.slice(0, decimalPlace) + text.slice(decimalPlace + 1);
+ }
+ if (exp < 0) throw new Error("Cannot include negative exponent part for integers");
+ text += (new Array(exp + 1)).join("0");
+ v = text;
+ }
+ var isValid = /^([0-9][0-9]*)$/.test(v);
+ if (!isValid) throw new Error("Invalid integer: " + v);
+ if (supportsNativeBigInt) {
+ return new NativeBigInt(BigInt(sign ? "-" + v : v));
+ }
+ var r = [], max = v.length, l = LOG_BASE, min = max - l;
+ while (max > 0) {
+ r.push(+v.slice(min, max));
+ min -= l;
+ if (min < 0) min = 0;
+ max -= l;
+ }
+ trim(r);
+ return new BigInteger(r, sign);
+ }
+
+ function parseNumberValue(v) {
+ if (supportsNativeBigInt) {
+ return new NativeBigInt(BigInt(v));
+ }
+ if (isPrecise(v)) {
+ if (v !== truncate(v)) throw new Error(v + " is not an integer.");
+ return new SmallInteger(v);
+ }
+ return parseStringValue(v.toString());
+ }
+
+ function parseValue(v) {
+ if (typeof v === "number") {
+ return parseNumberValue(v);
+ }
+ if (typeof v === "string") {
+ return parseStringValue(v);
+ }
+ if (typeof v === "bigint") {
+ return new NativeBigInt(v);
+ }
+ return v;
+ }
+ // Pre-define numbers in range [-999,999]
+ for (var i = 0; i < 1000; i++) {
+ Integer[i] = parseValue(i);
+ if (i > 0) Integer[-i] = parseValue(-i);
+ }
+ // Backwards compatibility
+ Integer.one = Integer[1];
+ Integer.zero = Integer[0];
+ Integer.minusOne = Integer[-1];
+ Integer.max = max;
+ Integer.min = min;
+ Integer.gcd = gcd;
+ Integer.lcm = lcm;
+ Integer.isInstance = function (x) { return x instanceof BigInteger || x instanceof SmallInteger || x instanceof NativeBigInt; };
+ Integer.randBetween = randBetween;
+
+ Integer.fromArray = function (digits, base, isNegative) {
+ return parseBaseFromArray(digits.map(parseValue), parseValue(base || 10), isNegative);
+ };
+
+ return Integer;
+})();
+
+// Node.js check
+if (typeof module !== "undefined" && module.hasOwnProperty("exports")) {
+ module.exports = bigInt;
+}
+
+//amd check
+if (typeof define === "function" && define.amd) {
+ define( function () {
+ return bigInt;
+ });
+}
diff --git a/temporary_modules/trezor-connect/node_modules/big-integer/BigInteger.min.js b/temporary_modules/trezor-connect/node_modules/big-integer/BigInteger.min.js
new file mode 100644
index 00000000..09835af1
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/big-integer/BigInteger.min.js
@@ -0,0 +1 @@
+var bigInt=function(t){"use strict";var e=1e7,r=9007199254740992,o=f(r),n="0123456789abcdefghijklmnopqrstuvwxyz",i="function"==typeof BigInt;function u(t,e,r,o){return void 0===t?u[0]:void 0!==e&&(10!=+e||r)?_(t,e,r,o):K(t)}function p(t,e){this.value=t,this.sign=e,this.isSmall=!1}function a(t){this.value=t,this.sign=t<0,this.isSmall=!0}function s(t){this.value=t}function l(t){return-r0?Math.floor(t):Math.ceil(t)}function c(t,r){var o,n,i=t.length,u=r.length,p=new Array(i),a=0,s=e;for(n=0;n=s?1:0,p[n]=o-a*s;for(;n0&&p.push(a),p}function m(t,e){return t.length>=e.length?c(t,e):c(e,t)}function d(t,r){var o,n,i=t.length,u=new Array(i),p=e;for(n=0;n0;)u[n++]=r%p,r=Math.floor(r/p);return u}function b(t,r){var o,n,i=t.length,u=r.length,p=new Array(i),a=0,s=e;for(o=0;o0;)u[n++]=a%p,a=Math.floor(a/p);return u}function q(t,e){for(var r=[];e-- >0;)r.push(0);return r.concat(t)}function M(t,e){var r=Math.max(t.length,e.length);if(r<=30)return S(t,e);r=Math.ceil(r/2);var o=t.slice(r),n=t.slice(0,r),i=e.slice(r),u=e.slice(0,r),p=M(n,u),a=M(o,i),s=M(m(n,o),m(u,i)),l=m(m(p,q(b(b(s,p),a),r)),q(a,2*r));return h(l),l}function N(t,r,o){return new p(t=0;--r)n=(i=1e7*n+t[r])-(o=g(i/e))*e,p[r]=0|o;return[p,0|n]}function B(t,r){var o,n=K(r);if(i)return[new s(t.value/n.value),new s(t.value%n.value)];var l,c=t.value,m=n.value;if(0===m)throw new Error("Cannot divide by zero");if(t.isSmall)return n.isSmall?[new a(g(c/m)),new a(c%m)]:[u[0],t];if(n.isSmall){if(1===m)return[t,u[0]];if(-1==m)return[t.negate(),u[0]];var d=Math.abs(m);if(d=0;n--){for(o=h-1,d[n+f]!==c&&(o=Math.floor((d[n+f]*h+d[n+f-1])/c)),i=0,u=0,a=b.length,p=0;ps&&(i=(i+1)*y),o=Math.ceil(i/u);do{if(A(p=I(r,o),f)<=0)break;o--}while(o);l.push(o),f=b(f,p)}return l.reverse(),[v(l),v(f)]}(c,m),l=o[0];var q=t.sign!==n.sign,M=o[1],N=t.sign;return"number"==typeof l?(q&&(l=-l),l=new a(l)):l=new p(l,q),"number"==typeof M?(N&&(M=-M),M=new a(M)):M=new p(M,N),[l,M]}function A(t,e){if(t.length!==e.length)return t.length>e.length?1:-1;for(var r=t.length-1;r>=0;r--)if(t[r]!==e[r])return t[r]>e[r]?1:-1;return 0}function P(t){var e=t.abs();return!e.isUnit()&&(!!(e.equals(2)||e.equals(3)||e.equals(5))||!(e.isEven()||e.isDivisibleBy(3)||e.isDivisibleBy(5))&&(!!e.lesser(49)||void 0))}function Z(t,e){for(var r,o,n,i=t.prev(),u=i,p=0;u.isEven();)u=u.divide(2),p++;t:for(o=0;o=0?o=b(t,e):(o=b(e,t),r=!r),"number"==typeof(o=v(o))?(r&&(o=-o),new a(o)):new p(o,r)}(r,o,this.sign)},p.prototype.minus=p.prototype.subtract,a.prototype.subtract=function(t){var e=K(t),r=this.value;if(r<0!==e.sign)return this.add(e.negate());var o=e.value;return e.isSmall?new a(r-o):w(o,Math.abs(r),r>=0)},a.prototype.minus=a.prototype.subtract,s.prototype.subtract=function(t){return new s(this.value-K(t).value)},s.prototype.minus=s.prototype.subtract,p.prototype.negate=function(){return new p(this.value,!this.sign)},a.prototype.negate=function(){var t=this.sign,e=new a(-this.value);return e.sign=!t,e},s.prototype.negate=function(){return new s(-this.value)},p.prototype.abs=function(){return new p(this.value,!1)},a.prototype.abs=function(){return new a(Math.abs(this.value))},s.prototype.abs=function(){return new s(this.value>=0?this.value:-this.value)},p.prototype.multiply=function(t){var r,o,n,i=K(t),a=this.value,s=i.value,l=this.sign!==i.sign;if(i.isSmall){if(0===s)return u[0];if(1===s)return this;if(-1===s)return this.negate();if((r=Math.abs(s))0?M(a,s):S(a,s),l)},p.prototype.times=p.prototype.multiply,a.prototype._multiplyBySmall=function(t){return l(t.value*this.value)?new a(t.value*this.value):N(Math.abs(t.value),f(Math.abs(this.value)),this.sign!==t.sign)},p.prototype._multiplyBySmall=function(t){return 0===t.value?u[0]:1===t.value?this:-1===t.value?this.negate():N(Math.abs(t.value),this.value,this.sign!==t.sign)},a.prototype.multiply=function(t){return K(t)._multiplyBySmall(this)},a.prototype.times=a.prototype.multiply,s.prototype.multiply=function(t){return new s(this.value*K(t).value)},s.prototype.times=s.prototype.multiply,p.prototype.square=function(){return new p(E(this.value),!1)},a.prototype.square=function(){var t=this.value*this.value;return l(t)?new a(t):new p(E(f(Math.abs(this.value))),!1)},s.prototype.square=function(t){return new s(this.value*this.value)},p.prototype.divmod=function(t){var e=B(this,t);return{quotient:e[0],remainder:e[1]}},s.prototype.divmod=a.prototype.divmod=p.prototype.divmod,p.prototype.divide=function(t){return B(this,t)[0]},s.prototype.over=s.prototype.divide=function(t){return new s(this.value/K(t).value)},a.prototype.over=a.prototype.divide=p.prototype.over=p.prototype.divide,p.prototype.mod=function(t){return B(this,t)[1]},s.prototype.mod=s.prototype.remainder=function(t){return new s(this.value%K(t).value)},a.prototype.remainder=a.prototype.mod=p.prototype.remainder=p.prototype.mod,p.prototype.pow=function(t){var e,r,o,n=K(t),i=this.value,p=n.value;if(0===p)return u[1];if(0===i)return u[0];if(1===i)return u[1];if(-1===i)return n.isEven()?u[1]:u[-1];if(n.sign)return u[0];if(!n.isSmall)throw new Error("The exponent "+n.toString()+" is too large.");if(this.isSmall&&l(e=Math.pow(i,p)))return new a(g(e));for(r=this,o=u[1];!0&p&&(o=o.times(r),--p),0!==p;)p/=2,r=r.square();return o},a.prototype.pow=p.prototype.pow,s.prototype.pow=function(t){var e=K(t),r=this.value,o=e.value,n=BigInt(0),i=BigInt(1),p=BigInt(2);if(o===n)return u[1];if(r===n)return u[0];if(r===i)return u[1];if(r===BigInt(-1))return e.isEven()?u[1]:u[-1];if(e.isNegative())return new s(n);for(var a=this,l=u[1];(o&i)===i&&(l=l.times(a),--o),o!==n;)o/=p,a=a.square();return l},p.prototype.modPow=function(t,e){if(t=K(t),(e=K(e)).isZero())throw new Error("Cannot take modPow with modulus 0");var r=u[1],o=this.mod(e);for(t.isNegative()&&(t=t.multiply(u[-1]),o=o.modInv(e));t.isPositive();){if(o.isZero())return u[0];t.isOdd()&&(r=r.multiply(o).mod(e)),t=t.divide(2),o=o.square().mod(e)}return r},s.prototype.modPow=a.prototype.modPow=p.prototype.modPow,p.prototype.compareAbs=function(t){var e=K(t),r=this.value,o=e.value;return e.isSmall?1:A(r,o)},a.prototype.compareAbs=function(t){var e=K(t),r=Math.abs(this.value),o=e.value;return e.isSmall?r===(o=Math.abs(o))?0:r>o?1:-1:-1},s.prototype.compareAbs=function(t){var e=this.value,r=K(t).value;return(e=e>=0?e:-e)===(r=r>=0?r:-r)?0:e>r?1:-1},p.prototype.compare=function(t){if(t===1/0)return-1;if(t===-1/0)return 1;var e=K(t),r=this.value,o=e.value;return this.sign!==e.sign?e.sign?1:-1:e.isSmall?this.sign?-1:1:A(r,o)*(this.sign?-1:1)},p.prototype.compareTo=p.prototype.compare,a.prototype.compare=function(t){if(t===1/0)return-1;if(t===-1/0)return 1;var e=K(t),r=this.value,o=e.value;return e.isSmall?r==o?0:r>o?1:-1:r<0!==e.sign?r<0?-1:1:r<0?1:-1},a.prototype.compareTo=a.prototype.compare,s.prototype.compare=function(t){if(t===1/0)return-1;if(t===-1/0)return 1;var e=this.value,r=K(t).value;return e===r?0:e>r?1:-1},s.prototype.compareTo=s.prototype.compare,p.prototype.equals=function(t){return 0===this.compare(t)},s.prototype.eq=s.prototype.equals=a.prototype.eq=a.prototype.equals=p.prototype.eq=p.prototype.equals,p.prototype.notEquals=function(t){return 0!==this.compare(t)},s.prototype.neq=s.prototype.notEquals=a.prototype.neq=a.prototype.notEquals=p.prototype.neq=p.prototype.notEquals,p.prototype.greater=function(t){return this.compare(t)>0},s.prototype.gt=s.prototype.greater=a.prototype.gt=a.prototype.greater=p.prototype.gt=p.prototype.greater,p.prototype.lesser=function(t){return this.compare(t)<0},s.prototype.lt=s.prototype.lesser=a.prototype.lt=a.prototype.lesser=p.prototype.lt=p.prototype.lesser,p.prototype.greaterOrEquals=function(t){return this.compare(t)>=0},s.prototype.geq=s.prototype.greaterOrEquals=a.prototype.geq=a.prototype.greaterOrEquals=p.prototype.geq=p.prototype.greaterOrEquals,p.prototype.lesserOrEquals=function(t){return this.compare(t)<=0},s.prototype.leq=s.prototype.lesserOrEquals=a.prototype.leq=a.prototype.lesserOrEquals=p.prototype.leq=p.prototype.lesserOrEquals,p.prototype.isEven=function(){return 0==(1&this.value[0])},a.prototype.isEven=function(){return 0==(1&this.value)},s.prototype.isEven=function(){return(this.value&BigInt(1))===BigInt(0)},p.prototype.isOdd=function(){return 1==(1&this.value[0])},a.prototype.isOdd=function(){return 1==(1&this.value)},s.prototype.isOdd=function(){return(this.value&BigInt(1))===BigInt(1)},p.prototype.isPositive=function(){return!this.sign},a.prototype.isPositive=function(){return this.value>0},s.prototype.isPositive=a.prototype.isPositive,p.prototype.isNegative=function(){return this.sign},a.prototype.isNegative=function(){return this.value<0},s.prototype.isNegative=a.prototype.isNegative,p.prototype.isUnit=function(){return!1},a.prototype.isUnit=function(){return 1===Math.abs(this.value)},s.prototype.isUnit=function(){return this.abs().value===BigInt(1)},p.prototype.isZero=function(){return!1},a.prototype.isZero=function(){return 0===this.value},s.prototype.isZero=function(){return this.value===BigInt(0)},p.prototype.isDivisibleBy=function(t){var e=K(t);return!e.isZero()&&(!!e.isUnit()||(0===e.compareAbs(2)?this.isEven():this.mod(e).isZero()))},s.prototype.isDivisibleBy=a.prototype.isDivisibleBy=p.prototype.isDivisibleBy,p.prototype.isPrime=function(e){var r=P(this);if(r!==t)return r;var o=this.abs(),n=o.bitLength();if(n<=64)return Z(o,[2,3,5,7,11,13,17,19,23,29,31,37]);for(var i=Math.log(2)*n.toJSNumber(),u=Math.ceil(!0===e?2*Math.pow(i,2):i),p=[],a=0;a-r?new a(t-1):new p(o,!0)},s.prototype.prev=function(){return new s(this.value-BigInt(1))};for(var x=[1];2*x[x.length-1]<=e;)x.push(2*x[x.length-1]);var J=x.length,L=x[J-1];function U(t){return Math.abs(t)<=e}function T(t,e,r){e=K(e);for(var o=t.isNegative(),n=e.isNegative(),i=o?t.not():t,u=n?e.not():e,p=0,a=0,s=null,l=null,f=[];!i.isZero()||!u.isZero();)p=(s=B(i,L))[1].toJSNumber(),o&&(p=L-1-p),a=(l=B(u,L))[1].toJSNumber(),n&&(a=L-1-a),i=s[0],u=l[0],f.push(r(p,a));for(var v=0!==r(o?1:0,n?1:0)?bigInt(-1):bigInt(0),h=f.length-1;h>=0;h-=1)v=v.multiply(L).add(bigInt(f[h]));return v}p.prototype.shiftLeft=function(t){var e=K(t).toJSNumber();if(!U(e))throw new Error(String(e)+" is too large for shifting.");if(e<0)return this.shiftRight(-e);var r=this;if(r.isZero())return r;for(;e>=J;)r=r.multiply(L),e-=J-1;return r.multiply(x[e])},s.prototype.shiftLeft=a.prototype.shiftLeft=p.prototype.shiftLeft,p.prototype.shiftRight=function(t){var e,r=K(t).toJSNumber();if(!U(r))throw new Error(String(r)+" is too large for shifting.");if(r<0)return this.shiftLeft(-r);for(var o=this;r>=J;){if(o.isZero()||o.isNegative()&&o.isUnit())return o;o=(e=B(o,L))[1].isNegative()?e[0].prev():e[0],r-=J-1}return(e=B(o,x[r]))[1].isNegative()?e[0].prev():e[0]},s.prototype.shiftRight=a.prototype.shiftRight=p.prototype.shiftRight,p.prototype.not=function(){return this.negate().prev()},s.prototype.not=a.prototype.not=p.prototype.not,p.prototype.and=function(t){return T(this,t,(function(t,e){return t&e}))},s.prototype.and=a.prototype.and=p.prototype.and,p.prototype.or=function(t){return T(this,t,(function(t,e){return t|e}))},s.prototype.or=a.prototype.or=p.prototype.or,p.prototype.xor=function(t){return T(this,t,(function(t,e){return t^e}))},s.prototype.xor=a.prototype.xor=p.prototype.xor;var j=1<<30;function C(t){var r=t.value,o="number"==typeof r?r|j:"bigint"==typeof r?r|BigInt(j):r[0]+r[1]*e|1073758208;return o&-o}function D(t,e){if(e.compareTo(t)<=0){var r=D(t,e.square(e)),o=r.p,n=r.e,i=o.multiply(e);return i.compareTo(t)<=0?{p:i,e:2*n+1}:{p:o,e:2*n}}return{p:bigInt(1),e:0}}function z(t,e){return t=K(t),e=K(e),t.greater(e)?t:e}function R(t,e){return t=K(t),e=K(e),t.lesser(e)?t:e}function k(t,e){if(t=K(t).abs(),e=K(e).abs(),t.equals(e))return t;if(t.isZero())return e;if(e.isZero())return t;for(var r,o,n=u[1];t.isEven()&&e.isEven();)r=R(C(t),C(e)),t=t.divide(r),e=e.divide(r),n=n.multiply(r);for(;t.isEven();)t=t.divide(C(t));do{for(;e.isEven();)e=e.divide(C(e));t.greater(e)&&(o=e,e=t,t=o),e=e.subtract(t)}while(!e.isZero());return n.isUnit()?t:t.multiply(n)}p.prototype.bitLength=function(){var t=this;return t.compareTo(bigInt(0))<0&&(t=t.negate().subtract(bigInt(1))),0===t.compareTo(bigInt(0))?bigInt(0):bigInt(D(t,bigInt(2)).e).add(bigInt(1))},s.prototype.bitLength=a.prototype.bitLength=p.prototype.bitLength;var _=function(t,e,r,o){r=r||n,t=String(t),o||(t=t.toLowerCase(),r=r.toLowerCase());var i,u=t.length,p=Math.abs(e),a={};for(i=0;i=p)){if("1"===f&&1===p)continue;throw new Error(f+" is not a valid digit in base "+e+".")}}e=K(e);var s=[],l="-"===t[0];for(i=l?1:0;i"!==t[i]&&i=0;o--)n=n.add(t[o].times(i)),i=i.times(e);return r?n.negate():n}function F(t,e){if((e=bigInt(e)).isZero()){if(t.isZero())return{value:[0],isNegative:!1};throw new Error("Cannot convert nonzero numbers to base 0.")}if(e.equals(-1)){if(t.isZero())return{value:[0],isNegative:!1};if(t.isNegative())return{value:[].concat.apply([],Array.apply(null,Array(-t.toJSNumber())).map(Array.prototype.valueOf,[1,0])),isNegative:!1};var r=Array.apply(null,Array(t.toJSNumber()-1)).map(Array.prototype.valueOf,[0,1]);return r.unshift([1]),{value:[].concat.apply([],r),isNegative:!1}}var o=!1;if(t.isNegative()&&e.isPositive()&&(o=!0,t=t.abs()),e.isUnit())return t.isZero()?{value:[0],isNegative:!1}:{value:Array.apply(null,Array(t.toJSNumber())).map(Number.prototype.valueOf,1),isNegative:o};for(var n,i=[],u=t;u.isNegative()||u.compareAbs(e)>=0;){n=u.divmod(e),u=n.quotient;var p=n.remainder;p.isNegative()&&(p=e.minus(p).abs(),u=u.next()),i.push(p.toJSNumber())}return i.push(u.toJSNumber()),{value:i.reverse(),isNegative:o}}function G(t,e,r){var o=F(t,e);return(o.isNegative?"-":"")+o.value.map((function(t){return function(t,e){return t<(e=e||n).length?e[t]:"<"+t+">"}(t,r)})).join("")}function H(t){if(l(+t)){var e=+t;if(e===g(e))return i?new s(BigInt(e)):new a(e);throw new Error("Invalid integer: "+t)}var r="-"===t[0];r&&(t=t.slice(1));var o=t.split(/e/i);if(o.length>2)throw new Error("Invalid integer: "+o.join("e"));if(2===o.length){var n=o[1];if("+"===n[0]&&(n=n.slice(1)),(n=+n)!==g(n)||!l(n))throw new Error("Invalid integer: "+n+" is not a valid exponent.");var u=o[0],f=u.indexOf(".");if(f>=0&&(n-=u.length-f-1,u=u.slice(0,f)+u.slice(f+1)),n<0)throw new Error("Cannot include negative exponent part for integers");t=u+=new Array(n+1).join("0")}if(!/^([0-9][0-9]*)$/.test(t))throw new Error("Invalid integer: "+t);if(i)return new s(BigInt(r?"-"+t:t));for(var v=[],y=t.length,c=y-7;y>0;)v.push(+t.slice(c,y)),(c-=7)<0&&(c=0),y-=7;return h(v),new p(v,r)}function K(t){return"number"==typeof t?function(t){if(i)return new s(BigInt(t));if(l(t)){if(t!==g(t))throw new Error(t+" is not an integer.");return new a(t)}return H(t.toString())}(t):"string"==typeof t?H(t):"bigint"==typeof t?new s(t):t}p.prototype.toArray=function(t){return F(this,t)},a.prototype.toArray=function(t){return F(this,t)},s.prototype.toArray=function(t){return F(this,t)},p.prototype.toString=function(e,r){if(e===t&&(e=10),10!==e)return G(this,e,r);for(var o,n=this.value,i=n.length,u=String(n[--i]);--i>=0;)o=String(n[i]),u+="0000000".slice(o.length)+o;return(this.sign?"-":"")+u},a.prototype.toString=function(e,r){return e===t&&(e=10),10!=e?G(this,e,r):String(this.value)},s.prototype.toString=a.prototype.toString,s.prototype.toJSON=p.prototype.toJSON=a.prototype.toJSON=function(){return this.toString()},p.prototype.valueOf=function(){return parseInt(this.toString(),10)},p.prototype.toJSNumber=p.prototype.valueOf,a.prototype.valueOf=function(){return this.value},a.prototype.toJSNumber=a.prototype.valueOf,s.prototype.valueOf=s.prototype.toJSNumber=function(){return parseInt(this.toString(),10)};for(var Q=0;Q<1e3;Q++)u[Q]=K(Q),Q>0&&(u[-Q]=K(-Q));return u.one=u[1],u.zero=u[0],u.minusOne=u[-1],u.max=z,u.min=R,u.gcd=k,u.lcm=function(t,e){return t=K(t).abs(),e=K(e).abs(),t.divide(k(t,e)).multiply(e)},u.isInstance=function(t){return t instanceof p||t instanceof a||t instanceof s},u.randBetween=function(t,r,o){t=K(t),r=K(r);var n=o||Math.random,i=R(t,r),p=z(t,r).subtract(i).add(1);if(p.isSmall)return i.add(Math.floor(n()*p));for(var a=F(p,e).value,s=[],l=!0,f=0;f
diff --git a/temporary_modules/trezor-connect/node_modules/big-integer/README.md b/temporary_modules/trezor-connect/node_modules/big-integer/README.md
new file mode 100644
index 00000000..d72420fb
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/big-integer/README.md
@@ -0,0 +1,589 @@
+# BigInteger.js [![Build Status][travis-img]][travis-url] [![Coverage Status][coveralls-img]][coveralls-url] [![Monthly Downloads][downloads-img]][downloads-url]
+
+[travis-url]: https://travis-ci.org/peterolson/BigInteger.js
+[travis-img]: https://travis-ci.org/peterolson/BigInteger.js.svg?branch=master
+[coveralls-url]: https://coveralls.io/github/peterolson/BigInteger.js?branch=master
+[coveralls-img]: https://coveralls.io/repos/peterolson/BigInteger.js/badge.svg?branch=master&service=github
+[downloads-url]: https://www.npmjs.com/package/big-integer
+[downloads-img]: https://img.shields.io/npm/dm/big-integer.svg
+
+**BigInteger.js** is an arbitrary-length integer library for Javascript, allowing arithmetic operations on integers of unlimited size, notwithstanding memory and time limitations.
+
+**Update (December 2, 2018):** [`BigInt` is being added as a native feature of JavaScript](https://tc39.github.io/proposal-bigint/). This library now works as a polyfill: if the environment supports the native `BigInt`, this library acts as a thin wrapper over the native implementation.
+
+## Installation
+
+If you are using a browser, you can download [BigInteger.js from GitHub](http://peterolson.github.com/BigInteger.js/BigInteger.min.js) or just hotlink to it:
+
+
+
+If you are using node, you can install BigInteger with [npm](https://npmjs.org/).
+
+ npm install big-integer
+
+Then you can include it in your code:
+
+ var bigInt = require("big-integer");
+
+
+## Usage
+### `bigInt(number, [base], [alphabet], [caseSensitive])`
+
+You can create a bigInt by calling the `bigInt` function. You can pass in
+
+ - a string, which it will parse as an bigInt and throw an `"Invalid integer"` error if the parsing fails.
+ - a Javascript number, which it will parse as an bigInt and throw an `"Invalid integer"` error if the parsing fails.
+ - another bigInt.
+ - nothing, and it will return `bigInt.zero`.
+
+ If you provide a second parameter, then it will parse `number` as a number in base `base`. Note that `base` can be any bigInt (even negative or zero). The letters "a-z" and "A-Z" will be interpreted as the numbers 10 to 35. Higher digits can be specified in angle brackets (`<` and `>`). The default `base` is `10`.
+
+ You can specify a custom alphabet for base conversion with the third parameter. The default `alphabet` is `"0123456789abcdefghijklmnopqrstuvwxyz"`.
+
+ The fourth parameter specifies whether or not the number string should be case-sensitive, i.e. whether `a` and `A` should be treated as different digits. By default `caseSensitive` is `false`.
+
+Examples:
+
+ var zero = bigInt();
+ var ninetyThree = bigInt(93);
+ var largeNumber = bigInt("75643564363473453456342378564387956906736546456235345");
+ var googol = bigInt("1e100");
+ var bigNumber = bigInt(largeNumber);
+
+ var maximumByte = bigInt("FF", 16);
+ var fiftyFiveGoogol = bigInt("<55>0", googol);
+
+Note that Javascript numbers larger than `9007199254740992` and smaller than `-9007199254740992` are not precisely represented numbers and will not produce exact results. If you are dealing with numbers outside that range, it is better to pass in strings.
+
+### Method Chaining
+
+Note that bigInt operations return bigInts, which allows you to chain methods, for example:
+
+ var salary = bigInt(dollarsPerHour).times(hoursWorked).plus(randomBonuses)
+
+### Constants
+
+There are three named constants already stored that you do not have to construct with the `bigInt` function yourself:
+
+ - `bigInt.one`, equivalent to `bigInt(1)`
+ - `bigInt.zero`, equivalent to `bigInt(0)`
+ - `bigInt.minusOne`, equivalent to `bigInt(-1)`
+
+The numbers from -999 to 999 are also already prestored and can be accessed using `bigInt[index]`, for example:
+
+ - `bigInt[-999]`, equivalent to `bigInt(-999)`
+ - `bigInt[256]`, equivalent to `bigInt(256)`
+
+### Methods
+
+#### `abs()`
+
+Returns the absolute value of a bigInt.
+
+ - `bigInt(-45).abs()` => `45`
+ - `bigInt(45).abs()` => `45`
+
+#### `add(number)`
+
+Performs addition.
+
+ - `bigInt(5).add(7)` => `12`
+
+[View benchmarks for this method](http://peterolson.github.io/BigInteger.js/benchmark/#Addition)
+
+#### `and(number)`
+
+Performs the bitwise AND operation. The operands are treated as if they were represented using [two's complement representation](http://en.wikipedia.org/wiki/Two%27s_complement).
+
+ - `bigInt(6).and(3)` => `2`
+ - `bigInt(6).and(-3)` => `4`
+
+#### `bitLength()`
+
+Returns the number of digits required to represent a bigInt in binary.
+
+ - `bigInt(5)` => `3` (since 5 is `101` in binary, which is three digits long)
+
+#### `compare(number)`
+
+Performs a comparison between two numbers. If the numbers are equal, it returns `0`. If the first number is greater, it returns `1`. If the first number is lesser, it returns `-1`.
+
+ - `bigInt(5).compare(5)` => `0`
+ - `bigInt(5).compare(4)` => `1`
+ - `bigInt(4).compare(5)` => `-1`
+
+#### `compareAbs(number)`
+
+Performs a comparison between the absolute value of two numbers.
+
+ - `bigInt(5).compareAbs(-5)` => `0`
+ - `bigInt(5).compareAbs(4)` => `1`
+ - `bigInt(4).compareAbs(-5)` => `-1`
+
+#### `compareTo(number)`
+
+Alias for the `compare` method.
+
+#### `divide(number)`
+
+Performs integer division, disregarding the remainder.
+
+ - `bigInt(59).divide(5)` => `11`
+
+[View benchmarks for this method](http://peterolson.github.io/BigInteger.js/benchmark/#Division)
+
+#### `divmod(number)`
+
+Performs division and returns an object with two properties: `quotient` and `remainder`. The sign of the remainder will match the sign of the dividend.
+
+ - `bigInt(59).divmod(5)` => `{quotient: bigInt(11), remainder: bigInt(4) }`
+ - `bigInt(-5).divmod(2)` => `{quotient: bigInt(-2), remainder: bigInt(-1) }`
+
+[View benchmarks for this method](http://peterolson.github.io/BigInteger.js/benchmark/#Division)
+
+#### `eq(number)`
+
+Alias for the `equals` method.
+
+#### `equals(number)`
+
+Checks if two numbers are equal.
+
+ - `bigInt(5).equals(5)` => `true`
+ - `bigInt(4).equals(7)` => `false`
+
+#### `geq(number)`
+
+Alias for the `greaterOrEquals` method.
+
+
+#### `greater(number)`
+
+Checks if the first number is greater than the second.
+
+ - `bigInt(5).greater(6)` => `false`
+ - `bigInt(5).greater(5)` => `false`
+ - `bigInt(5).greater(4)` => `true`
+
+#### `greaterOrEquals(number)`
+
+Checks if the first number is greater than or equal to the second.
+
+ - `bigInt(5).greaterOrEquals(6)` => `false`
+ - `bigInt(5).greaterOrEquals(5)` => `true`
+ - `bigInt(5).greaterOrEquals(4)` => `true`
+
+#### `gt(number)`
+
+Alias for the `greater` method.
+
+#### `isDivisibleBy(number)`
+
+Returns `true` if the first number is divisible by the second number, `false` otherwise.
+
+ - `bigInt(999).isDivisibleBy(333)` => `true`
+ - `bigInt(99).isDivisibleBy(5)` => `false`
+
+#### `isEven()`
+
+Returns `true` if the number is even, `false` otherwise.
+
+ - `bigInt(6).isEven()` => `true`
+ - `bigInt(3).isEven()` => `false`
+
+#### `isNegative()`
+
+Returns `true` if the number is negative, `false` otherwise.
+Returns `false` for `0` and `-0`.
+
+ - `bigInt(-23).isNegative()` => `true`
+ - `bigInt(50).isNegative()` => `false`
+
+#### `isOdd()`
+
+Returns `true` if the number is odd, `false` otherwise.
+
+ - `bigInt(13).isOdd()` => `true`
+ - `bigInt(40).isOdd()` => `false`
+
+#### `isPositive()`
+
+Return `true` if the number is positive, `false` otherwise.
+Returns `false` for `0` and `-0`.
+
+ - `bigInt(54).isPositive()` => `true`
+ - `bigInt(-1).isPositive()` => `false`
+
+#### `isPrime(strict?)`
+
+Returns `true` if the number is prime, `false` otherwise.
+Set "strict" boolean to true to force GRH-supported lower bound of 2*log(N)^2.
+
+ - `bigInt(5).isPrime()` => `true`
+ - `bigInt(6).isPrime()` => `false`
+
+#### `isProbablePrime([iterations], [rng])`
+
+Returns `true` if the number is very likely to be prime, `false` otherwise.
+Supplying `iterations` is optional - it determines the number of iterations of the test (default: `5`). The more iterations, the lower chance of getting a false positive.
+This uses the [Miller Rabin test](https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test).
+
+ - `bigInt(5).isProbablePrime()` => `true`
+ - `bigInt(49).isProbablePrime()` => `false`
+ - `bigInt(1729).isProbablePrime()` => `false`
+
+Note that this function is not deterministic, since it relies on random sampling of factors, so the result for some numbers is not always the same - unless you pass a predictable random number generator as `rng`. The behavior and requirements are the same as with `randBetween`.
+
+ - `bigInt(1729).isProbablePrime(1, () => 0.1)` => `false`
+ - `bigInt(1729).isProbablePrime(1, () => 0.2)` => `true`
+
+If the number is composite then the Miller–Rabin primality test declares the number probably prime with a probability at most `4` to the power `−iterations`.
+If the number is prime, this function always returns `true`.
+
+#### `isUnit()`
+
+Returns `true` if the number is `1` or `-1`, `false` otherwise.
+
+ - `bigInt.one.isUnit()` => `true`
+ - `bigInt.minusOne.isUnit()` => `true`
+ - `bigInt(5).isUnit()` => `false`
+
+#### `isZero()`
+
+Return `true` if the number is `0` or `-0`, `false` otherwise.
+
+ - `bigInt.zero.isZero()` => `true`
+ - `bigInt("-0").isZero()` => `true`
+ - `bigInt(50).isZero()` => `false`
+
+#### `leq(number)`
+
+Alias for the `lesserOrEquals` method.
+
+#### `lesser(number)`
+
+Checks if the first number is lesser than the second.
+
+ - `bigInt(5).lesser(6)` => `true`
+ - `bigInt(5).lesser(5)` => `false`
+ - `bigInt(5).lesser(4)` => `false`
+
+#### `lesserOrEquals(number)`
+
+Checks if the first number is less than or equal to the second.
+
+ - `bigInt(5).lesserOrEquals(6)` => `true`
+ - `bigInt(5).lesserOrEquals(5)` => `true`
+ - `bigInt(5).lesserOrEquals(4)` => `false`
+
+#### `lt(number)`
+
+Alias for the `lesser` method.
+
+#### `minus(number)`
+
+Alias for the `subtract` method.
+
+ - `bigInt(3).minus(5)` => `-2`
+
+[View benchmarks for this method](http://peterolson.github.io/BigInteger.js/benchmark/#Subtraction)
+
+#### `mod(number)`
+
+Performs division and returns the remainder, disregarding the quotient. The sign of the remainder will match the sign of the dividend.
+
+ - `bigInt(59).mod(5)` => `4`
+ - `bigInt(-5).mod(2)` => `-1`
+
+[View benchmarks for this method](http://peterolson.github.io/BigInteger.js/benchmark/#Division)
+
+#### `modInv(mod)`
+
+Finds the [multiplicative inverse](https://en.wikipedia.org/wiki/Modular_multiplicative_inverse) of the number modulo `mod`.
+
+ - `bigInt(3).modInv(11)` => `4`
+ - `bigInt(42).modInv(2017)` => `1969`
+
+#### `modPow(exp, mod)`
+
+Takes the number to the power `exp` modulo `mod`.
+
+ - `bigInt(10).modPow(3, 30)` => `10`
+
+#### `multiply(number)`
+
+Performs multiplication.
+
+ - `bigInt(111).multiply(111)` => `12321`
+
+[View benchmarks for this method](http://peterolson.github.io/BigInteger.js/benchmark/#Multiplication)
+
+#### `neq(number)`
+
+Alias for the `notEquals` method.
+
+#### `next()`
+
+Adds one to the number.
+
+ - `bigInt(6).next()` => `7`
+
+#### `not()`
+
+Performs the bitwise NOT operation. The operands are treated as if they were represented using [two's complement representation](http://en.wikipedia.org/wiki/Two%27s_complement).
+
+ - `bigInt(10).not()` => `-11`
+ - `bigInt(0).not()` => `-1`
+
+#### `notEquals(number)`
+
+Checks if two numbers are not equal.
+
+ - `bigInt(5).notEquals(5)` => `false`
+ - `bigInt(4).notEquals(7)` => `true`
+
+#### `or(number)`
+
+Performs the bitwise OR operation. The operands are treated as if they were represented using [two's complement representation](http://en.wikipedia.org/wiki/Two%27s_complement).
+
+ - `bigInt(13).or(10)` => `15`
+ - `bigInt(13).or(-8)` => `-3`
+
+#### `over(number)`
+
+Alias for the `divide` method.
+
+ - `bigInt(59).over(5)` => `11`
+
+[View benchmarks for this method](http://peterolson.github.io/BigInteger.js/benchmark/#Division)
+
+#### `plus(number)`
+
+Alias for the `add` method.
+
+ - `bigInt(5).plus(7)` => `12`
+
+[View benchmarks for this method](http://peterolson.github.io/BigInteger.js/benchmark/#Addition)
+
+#### `pow(number)`
+
+Performs exponentiation. If the exponent is less than `0`, `pow` returns `0`. `bigInt.zero.pow(0)` returns `1`.
+
+ - `bigInt(16).pow(16)` => `18446744073709551616`
+
+[View benchmarks for this method](http://peterolson.github.io/BigInteger.js/benchmark/#Exponentiation)
+
+#### `prev(number)`
+
+Subtracts one from the number.
+
+ - `bigInt(6).prev()` => `5`
+
+#### `remainder(number)`
+
+Alias for the `mod` method.
+
+[View benchmarks for this method](http://peterolson.github.io/BigInteger.js/benchmark/#Division)
+
+#### `shiftLeft(n)`
+
+Shifts the number left by `n` places in its binary representation. If a negative number is provided, it will shift right. Throws an error if `n` is outside of the range `[-9007199254740992, 9007199254740992]`.
+
+ - `bigInt(8).shiftLeft(2)` => `32`
+ - `bigInt(8).shiftLeft(-2)` => `2`
+
+#### `shiftRight(n)`
+
+Shifts the number right by `n` places in its binary representation. If a negative number is provided, it will shift left. Throws an error if `n` is outside of the range `[-9007199254740992, 9007199254740992]`.
+
+ - `bigInt(8).shiftRight(2)` => `2`
+ - `bigInt(8).shiftRight(-2)` => `32`
+
+#### `square()`
+
+Squares the number
+
+ - `bigInt(3).square()` => `9`
+
+[View benchmarks for this method](http://peterolson.github.io/BigInteger.js/benchmark/#Squaring)
+
+#### `subtract(number)`
+
+Performs subtraction.
+
+ - `bigInt(3).subtract(5)` => `-2`
+
+[View benchmarks for this method](http://peterolson.github.io/BigInteger.js/benchmark/#Subtraction)
+
+#### `times(number)`
+
+Alias for the `multiply` method.
+
+ - `bigInt(111).times(111)` => `12321`
+
+[View benchmarks for this method](http://peterolson.github.io/BigInteger.js/benchmark/#Multiplication)
+
+#### `toArray(radix)`
+
+Converts a bigInt into an object with the properties "value" and "isNegative." "Value" is an array of integers modulo the given radix. "isNegative" is a boolean that represents the sign of the result.
+
+ - `bigInt("1e9").toArray(10)` => {
+ value: [1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
+ isNegative: false
+ }
+ - `bigInt("1e9").toArray(16)` => {
+ value: [3, 11, 9, 10, 12, 10, 0, 0],
+ isNegative: false
+ }
+ - `bigInt(567890).toArray(100)` => {
+ value: [56, 78, 90],
+ isNegative: false
+ }
+
+Negative bases are supported.
+
+ - `bigInt(12345).toArray(-10)` => {
+ value: [2, 8, 4, 6, 5],
+ isNegative: false
+ }
+
+Base 1 and base -1 are also supported.
+
+ - `bigInt(-15).toArray(1)` => {
+ value: [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
+ isNegative: true
+ }
+ - `bigInt(-15).toArray(-1)` => {
+ value: [1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1,
+ 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0],
+ isNegative: false
+ }
+
+Base 0 is only allowed for the number zero.
+
+ - `bigInt(0).toArray(0)` => {
+ value: [0],
+ isNegative: false
+ }
+ - `bigInt(1).toArray(0)` => `Error: Cannot convert nonzero numbers to base 0.`
+
+#### `toJSNumber()`
+
+Converts a bigInt into a native Javascript number. Loses precision for numbers outside the range `[-9007199254740992, 9007199254740992]`.
+
+ - `bigInt("18446744073709551616").toJSNumber()` => `18446744073709552000`
+
+#### `xor(number)`
+
+Performs the bitwise XOR operation. The operands are treated as if they were represented using [two's complement representation](http://en.wikipedia.org/wiki/Two%27s_complement).
+
+ - `bigInt(12).xor(5)` => `9`
+ - `bigInt(12).xor(-5)` => `-9`
+
+### Static Methods
+
+#### `fromArray(digits, base = 10, isNegative?)`
+
+Constructs a bigInt from an array of digits in base `base`. The optional `isNegative` flag will make the number negative.
+
+ - `bigInt.fromArray([1, 2, 3, 4, 5], 10)` => `12345`
+ - `bigInt.fromArray([1, 0, 0], 2, true)` => `-4`
+
+#### `gcd(a, b)`
+
+Finds the greatest common denominator of `a` and `b`.
+
+ - `bigInt.gcd(42,56)` => `14`
+
+#### `isInstance(x)`
+
+Returns `true` if `x` is a BigInteger, `false` otherwise.
+
+ - `bigInt.isInstance(bigInt(14))` => `true`
+ - `bigInt.isInstance(14)` => `false`
+
+#### `lcm(a,b)`
+
+Finds the least common multiple of `a` and `b`.
+
+ - `bigInt.lcm(21, 6)` => `42`
+
+#### `max(a,b)`
+
+Returns the largest of `a` and `b`.
+
+ - `bigInt.max(77, 432)` => `432`
+
+#### `min(a,b)`
+
+Returns the smallest of `a` and `b`.
+
+ - `bigInt.min(77, 432)` => `77`
+
+#### `randBetween(min, max, [rng])`
+
+Returns a random number between `min` and `max`, optionally using `rng` to generate randomness.
+
+ - `bigInt.randBetween("-1e100", "1e100")` => (for example) `8494907165436643479673097939554427056789510374838494147955756275846226209006506706784609314471378745`
+
+`rng` should take no arguments and return a `number` between 0 and 1. It defaults to `Math.random`.
+
+ - `bigInt.randBetween("-1e100", "1e100", () => 0.5)` => (always) `50000005000000500000050000005000000500000050000005000000500000050000005000000500000050000005000000`
+
+
+### Override Methods
+
+#### `toString(radix = 10, [alphabet])`
+
+Converts a bigInt to a string. There is an optional radix parameter (which defaults to 10) that converts the number to the given radix. Digits in the range `10-35` will use the letters `a-z`.
+
+ - `bigInt("1e9").toString()` => `"1000000000"`
+ - `bigInt("1e9").toString(16)` => `"3b9aca00"`
+
+ You can use a custom base alphabet with the second parameter. The default `alphabet` is `"0123456789abcdefghijklmnopqrstuvwxyz"`.
+
+ - `bigInt("5").toString(2, "aA")` => `"AaA"`
+
+**Note that arithmetical operators will trigger the `valueOf` function rather than the `toString` function.** When converting a bigInteger to a string, you should use the `toString` method or the `String` function instead of adding the empty string.
+
+ - `bigInt("999999999999999999").toString()` => `"999999999999999999"`
+ - `String(bigInt("999999999999999999"))` => `"999999999999999999"`
+ - `bigInt("999999999999999999") + ""` => `1000000000000000000`
+
+Bases larger than 36 are supported. If a digit is greater than or equal to 36, it will be enclosed in angle brackets.
+
+ - `bigInt(567890).toString(100)` => `"<56><78><90>"`
+
+Negative bases are also supported.
+
+ - `bigInt(12345).toString(-10)` => `"28465"`
+
+Base 1 and base -1 are also supported.
+
+ - `bigInt(-15).toString(1)` => `"-111111111111111"`
+ - `bigInt(-15).toString(-1)` => `"101010101010101010101010101010"`
+
+Base 0 is only allowed for the number zero.
+
+ - `bigInt(0).toString(0)` => `0`
+ - `bigInt(1).toString(0)` => `Error: Cannot convert nonzero numbers to base 0.`
+
+[View benchmarks for this method](http://peterolson.github.io/BigInteger.js/benchmark/#toString)
+
+#### `valueOf()`
+
+Converts a bigInt to a native Javascript number. This override allows you to use native arithmetic operators without explicit conversion:
+
+ - `bigInt("100") + bigInt("200") === 300; //true`
+
+## Contributors
+
+To contribute, just fork the project, make some changes, and submit a pull request. Please verify that the unit tests pass before submitting.
+
+The unit tests are contained in the `spec/spec.js` file. You can run them locally by opening the `spec/SpecRunner.html` or file or running `npm test`. You can also [run the tests online from GitHub](http://peterolson.github.io/BigInteger.js/spec/SpecRunner.html).
+
+There are performance benchmarks that can be viewed from the `benchmarks/index.html` page. You can [run them online from GitHub](http://peterolson.github.io/BigInteger.js/benchmark/).
+
+## License
+
+This project is public domain. For more details, read about the [Unlicense](http://unlicense.org/).
diff --git a/temporary_modules/trezor-connect/node_modules/big-integer/bower.json b/temporary_modules/trezor-connect/node_modules/big-integer/bower.json
new file mode 100644
index 00000000..22dc58f5
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/big-integer/bower.json
@@ -0,0 +1,29 @@
+{
+ "name": "big-integer",
+ "description": "An arbitrary length integer library for Javascript",
+ "main": "./BigInteger.js",
+ "authors": [
+ "Peter Olson"
+ ],
+ "license": "Unlicense",
+ "keywords": [
+ "math",
+ "big",
+ "bignum",
+ "bigint",
+ "biginteger",
+ "integer",
+ "arbitrary",
+ "precision",
+ "arithmetic"
+ ],
+ "homepage": "https://github.com/peterolson/BigInteger.js",
+ "ignore": [
+ "**/.*",
+ "node_modules",
+ "bower_components",
+ "test",
+ "coverage",
+ "tests"
+ ]
+}
diff --git a/temporary_modules/trezor-connect/node_modules/big-integer/package.json b/temporary_modules/trezor-connect/node_modules/big-integer/package.json
new file mode 100644
index 00000000..a6eb2011
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/big-integer/package.json
@@ -0,0 +1,48 @@
+{
+ "name": "big-integer",
+ "version": "1.6.51",
+ "author": "Peter Olson ",
+ "description": "An arbitrary length integer library for Javascript",
+ "contributors": [],
+ "bin": {},
+ "scripts": {
+ "test": "tsc && karma start my.conf.js && node spec/tsDefinitions.js",
+ "minify": "uglifyjs BigInteger.js -o BigInteger.min.js"
+ },
+ "main": "./BigInteger",
+ "repository": {
+ "type": "git",
+ "url": "git@github.com:peterolson/BigInteger.js.git"
+ },
+ "keywords": [
+ "math",
+ "big",
+ "bignum",
+ "bigint",
+ "biginteger",
+ "integer",
+ "arbitrary",
+ "precision",
+ "arithmetic"
+ ],
+ "devDependencies": {
+ "@types/lodash": "^4.14.175",
+ "@types/node": "^7.10.2",
+ "coveralls": "^3.0.6",
+ "jasmine": "3.5.0",
+ "jasmine-core": "^3.5.0",
+ "karma": "^6.3.4",
+ "karma-cli": "^2.0.0",
+ "karma-coverage": "^2.0.3",
+ "karma-jasmine": "^4.0.1",
+ "karma-phantomjs-launcher": "^1.0.4",
+ "lodash": "^4.17.21",
+ "typescript": "^3.6.3",
+ "uglifyjs": "^2.4.10"
+ },
+ "license": "Unlicense",
+ "engines": {
+ "node": ">=0.6"
+ },
+ "typings": "./BigInteger.d.ts"
+}
diff --git a/temporary_modules/trezor-connect/node_modules/big-integer/tsconfig.json b/temporary_modules/trezor-connect/node_modules/big-integer/tsconfig.json
new file mode 100644
index 00000000..dae01d4f
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/big-integer/tsconfig.json
@@ -0,0 +1,26 @@
+{
+ "compilerOptions": {
+ "target": "esnext",
+ "module": "commonjs",
+ "lib": [
+ "es6"
+ ],
+ "noImplicitAny": true,
+ "noImplicitThis": true,
+ "strictNullChecks": false,
+ "baseUrl": "./",
+ "moduleResolution": "node",
+ "allowJs": true,
+ "typeRoots": [
+ "./"
+ ],
+ "types": [
+ "node"
+ ],
+ "forceConsistentCasingInFileNames": true
+ },
+ "files": [
+ "BigInteger.d.ts",
+ "spec/tsDefinitions.ts"
+ ]
+}
diff --git a/temporary_modules/trezor-connect/node_modules/bplist-parser/.editorconfig b/temporary_modules/trezor-connect/node_modules/bplist-parser/.editorconfig
new file mode 100644
index 00000000..c6812c16
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/bplist-parser/.editorconfig
@@ -0,0 +1,12 @@
+; EditorConfig file: https://EditorConfig.org
+; Install the "EditorConfig" plugin into your editor to use
+
+root = true
+
+[*]
+charset = utf-8
+end_of_line = lf
+insert_final_newline = true
+indent_style = space
+indent_size = 2
+trim_trailing_whitespace = true
diff --git a/temporary_modules/trezor-connect/node_modules/bplist-parser/.eslintignore b/temporary_modules/trezor-connect/node_modules/bplist-parser/.eslintignore
new file mode 100644
index 00000000..3c3629e6
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/bplist-parser/.eslintignore
@@ -0,0 +1 @@
+node_modules
diff --git a/temporary_modules/trezor-connect/node_modules/bplist-parser/.eslintrc.js b/temporary_modules/trezor-connect/node_modules/bplist-parser/.eslintrc.js
new file mode 100644
index 00000000..8ee3b33f
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/bplist-parser/.eslintrc.js
@@ -0,0 +1,295 @@
+module.exports = {
+ "env": {
+ "node": true,
+ "commonjs": true,
+ "es6": true
+ },
+ "extends": "eslint:recommended",
+ "globals": {
+ "Atomics": "readonly",
+ "SharedArrayBuffer": "readonly"
+ },
+ "parserOptions": {
+ "ecmaVersion": 2018
+ },
+ "rules": {
+ "accessor-pairs": "error",
+ "array-bracket-newline": "error",
+ "array-bracket-spacing": "off",
+ "array-callback-return": "error",
+ "array-element-newline": "off",
+ "arrow-body-style": "error",
+ "arrow-parens": "error",
+ "arrow-spacing": "error",
+ "block-scoped-var": "error",
+ "block-spacing": "error",
+ "brace-style": [
+ "error",
+ "1tbs"
+ ],
+ "callback-return": "off",
+ "camelcase": "off",
+ "capitalized-comments": "off",
+ "class-methods-use-this": "error",
+ "comma-dangle": "error",
+ "comma-spacing": [
+ "error",
+ {
+ "after": true,
+ "before": false
+ }
+ ],
+ "comma-style": "error",
+ "complexity": "error",
+ "computed-property-spacing": [
+ "error",
+ "never"
+ ],
+ "consistent-return": "off",
+ "consistent-this": "error",
+ "curly": "off",
+ "default-case": "error",
+ "dot-location": "error",
+ "dot-notation": "off",
+ "eol-last": "error",
+ "eqeqeq": "off",
+ "func-call-spacing": "error",
+ "func-name-matching": "error",
+ "func-names": "off",
+ "func-style": [
+ "error",
+ "declaration"
+ ],
+ "function-paren-newline": "error",
+ "generator-star-spacing": "error",
+ "global-require": "error",
+ "guard-for-in": "error",
+ "handle-callback-err": "error",
+ "id-blacklist": "error",
+ "id-length": "off",
+ "id-match": "error",
+ "implicit-arrow-linebreak": "error",
+ "indent": "off",
+ "indent-legacy": "off",
+ "init-declarations": "off",
+ "jsx-quotes": "error",
+ "key-spacing": "off",
+ "keyword-spacing": [
+ "error",
+ {
+ "after": true,
+ "before": true
+ }
+ ],
+ "line-comment-position": "off",
+ "linebreak-style": [
+ "error",
+ "unix"
+ ],
+ "lines-around-comment": "error",
+ "lines-around-directive": "error",
+ "lines-between-class-members": "error",
+ "max-classes-per-file": "error",
+ "max-depth": "error",
+ "max-len": "off",
+ "max-lines": "off",
+ "max-lines-per-function": "off",
+ "max-nested-callbacks": "error",
+ "max-params": "error",
+ "max-statements": "off",
+ "max-statements-per-line": "error",
+ "multiline-comment-style": [
+ "error",
+ "separate-lines"
+ ],
+ "multiline-ternary": "error",
+ "new-cap": "error",
+ "new-parens": "error",
+ "newline-after-var": "off",
+ "newline-before-return": "off",
+ "newline-per-chained-call": "error",
+ "no-alert": "error",
+ "no-array-constructor": "error",
+ "no-async-promise-executor": "error",
+ "no-await-in-loop": "error",
+ "no-bitwise": "off",
+ "no-buffer-constructor": "error",
+ "no-caller": "error",
+ "no-catch-shadow": "error",
+ "no-confusing-arrow": "error",
+ "no-continue": "error",
+ "no-div-regex": "error",
+ "no-duplicate-imports": "error",
+ "no-else-return": "error",
+ "no-empty-function": "error",
+ "no-eq-null": "error",
+ "no-eval": "error",
+ "no-extend-native": "error",
+ "no-extra-bind": "error",
+ "no-extra-label": "error",
+ "no-extra-parens": "off",
+ "no-floating-decimal": "error",
+ "no-implicit-coercion": "error",
+ "no-implicit-globals": "error",
+ "no-implied-eval": "error",
+ "no-inline-comments": "off",
+ "no-invalid-this": "error",
+ "no-iterator": "error",
+ "no-label-var": "error",
+ "no-labels": "error",
+ "no-lone-blocks": "error",
+ "no-lonely-if": "error",
+ "no-loop-func": "error",
+ "no-magic-numbers": "off",
+ "no-misleading-character-class": "error",
+ "no-mixed-operators": "off",
+ "no-mixed-requires": "error",
+ "no-multi-assign": "off",
+ "no-multi-spaces": [
+ "error",
+ {
+ "ignoreEOLComments": true
+ }
+ ],
+ "no-multi-str": "error",
+ "no-multiple-empty-lines": "error",
+ "no-native-reassign": "error",
+ "no-negated-condition": "error",
+ "no-negated-in-lhs": "error",
+ "no-nested-ternary": "error",
+ "no-new": "error",
+ "no-new-func": "error",
+ "no-new-object": "error",
+ "no-new-require": "error",
+ "no-new-wrappers": "error",
+ "no-octal-escape": "error",
+ "no-param-reassign": "off",
+ "no-path-concat": "error",
+ "no-plusplus": [
+ "error",
+ {
+ "allowForLoopAfterthoughts": true
+ }
+ ],
+ "no-process-env": "error",
+ "no-process-exit": "error",
+ "no-proto": "error",
+ "no-prototype-builtins": "error",
+ "no-restricted-globals": "error",
+ "no-restricted-imports": "error",
+ "no-restricted-modules": "error",
+ "no-restricted-properties": "error",
+ "no-restricted-syntax": "error",
+ "no-return-assign": "error",
+ "no-return-await": "error",
+ "no-script-url": "error",
+ "no-self-compare": "error",
+ "no-sequences": "error",
+ "no-shadow": "off",
+ "no-shadow-restricted-names": "error",
+ "no-spaced-func": "error",
+ "no-sync": "error",
+ "no-tabs": "error",
+ "no-template-curly-in-string": "error",
+ "no-ternary": "error",
+ "no-throw-literal": "error",
+ "no-trailing-spaces": "error",
+ "no-undef-init": "error",
+ "no-undefined": "error",
+ "no-underscore-dangle": "error",
+ "no-unmodified-loop-condition": "error",
+ "no-unneeded-ternary": "error",
+ "no-unused-expressions": "error",
+ "no-use-before-define": "off",
+ "no-useless-call": "error",
+ "no-useless-catch": "error",
+ "no-useless-computed-key": "error",
+ "no-useless-concat": "error",
+ "no-useless-constructor": "error",
+ "no-useless-rename": "error",
+ "no-useless-return": "error",
+ "no-var": "error",
+ "no-void": "error",
+ "no-warning-comments": "error",
+ "no-whitespace-before-property": "error",
+ "no-with": "error",
+ "nonblock-statement-body-position": "error",
+ "object-curly-newline": "error",
+ "object-curly-spacing": [
+ "error",
+ "never"
+ ],
+ "object-property-newline": "error",
+ "object-shorthand": "error",
+ "one-var": "off",
+ "one-var-declaration-per-line": "error",
+ "operator-assignment": [
+ "error",
+ "always"
+ ],
+ "operator-linebreak": "error",
+ "padded-blocks": "off",
+ "padding-line-between-statements": "error",
+ "prefer-arrow-callback": "off",
+ "prefer-const": "error",
+ "prefer-destructuring": "error",
+ "prefer-named-capture-group": "error",
+ "prefer-numeric-literals": "error",
+ "prefer-object-spread": "error",
+ "prefer-promise-reject-errors": "error",
+ "prefer-reflect": "error",
+ "prefer-rest-params": "error",
+ "prefer-spread": "error",
+ "prefer-template": "off",
+ "quote-props": "off",
+ "quotes": "off",
+ "radix": "error",
+ "require-atomic-updates": "error",
+ "require-await": "error",
+ "require-jsdoc": "off",
+ "require-unicode-regexp": "error",
+ "rest-spread-spacing": "error",
+ "semi": "error",
+ "semi-spacing": [
+ "error",
+ {
+ "after": true,
+ "before": false
+ }
+ ],
+ "semi-style": [
+ "error",
+ "last"
+ ],
+ "sort-imports": "error",
+ "sort-keys": "error",
+ "sort-vars": "error",
+ "space-before-blocks": "error",
+ "space-before-function-paren": "off",
+ "space-in-parens": [
+ "error",
+ "never"
+ ],
+ "space-infix-ops": "off",
+ "space-unary-ops": "error",
+ "spaced-comment": "off",
+ "strict": "error",
+ "switch-colon-spacing": "error",
+ "symbol-description": "error",
+ "template-curly-spacing": "error",
+ "template-tag-spacing": "error",
+ "unicode-bom": [
+ "error",
+ "never"
+ ],
+ "valid-jsdoc": "error",
+ "vars-on-top": "error",
+ "wrap-iife": "error",
+ "wrap-regex": "error",
+ "yield-star-spacing": "error",
+ "yoda": [
+ "error",
+ "never"
+ ]
+ }
+};
diff --git a/temporary_modules/trezor-connect/node_modules/bplist-parser/README.md b/temporary_modules/trezor-connect/node_modules/bplist-parser/README.md
new file mode 100644
index 00000000..eb540642
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/bplist-parser/README.md
@@ -0,0 +1,48 @@
+# bplist-parser
+
+Binary Mac OS X Plist (property list) parser.
+
+## Installation
+
+```bash
+$ npm install bplist-parser
+```
+
+## Quick Examples
+
+```javascript
+const bplist = require('bplist-parser');
+
+(async () => {
+
+ const obj = await bplist.parseFile('myPlist.bplist');
+
+ console.log(JSON.stringify(obj));
+
+})();
+```
+
+## License
+
+(The MIT License)
+
+Copyright (c) 2012 Near Infinity Corporation
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/temporary_modules/trezor-connect/node_modules/bplist-parser/bplistParser.d.ts b/temporary_modules/trezor-connect/node_modules/bplist-parser/bplistParser.d.ts
new file mode 100644
index 00000000..dd38a7e0
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/bplist-parser/bplistParser.d.ts
@@ -0,0 +1,6 @@
+declare namespace bPlistParser {
+ type CallbackFunction = (error: Error|null, result: [T]) => void
+ export function parseFile(fileNameOrBuffer: string|Buffer, callback?: CallbackFunction): Promise<[T]>
+}
+
+export = bPlistParser
diff --git a/temporary_modules/trezor-connect/node_modules/bplist-parser/bplistParser.js b/temporary_modules/trezor-connect/node_modules/bplist-parser/bplistParser.js
new file mode 100644
index 00000000..3956a290
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/bplist-parser/bplistParser.js
@@ -0,0 +1,366 @@
+/* eslint-disable no-console */
+
+'use strict';
+
+// adapted from https://github.com/3breadt/dd-plist
+
+const fs = require('fs');
+const bigInt = require('big-integer');
+const debug = false;
+
+exports.maxObjectSize = 100 * 1000 * 1000; // 100Meg
+exports.maxObjectCount = 32768;
+
+// EPOCH = new SimpleDateFormat("yyyy MM dd zzz").parse("2001 01 01 GMT").getTime();
+// ...but that's annoying in a static initializer because it can throw exceptions, ick.
+// So we just hardcode the correct value.
+const EPOCH = 978307200000;
+
+// UID object definition
+const UID = exports.UID = function(id) {
+ this.UID = id;
+};
+
+exports.parseFile = function (fileNameOrBuffer, callback) {
+ return new Promise(function (resolve, reject) {
+ function tryParseBuffer(buffer) {
+ let err = null;
+ let result;
+ try {
+ result = parseBuffer(buffer);
+ resolve(result);
+ } catch (ex) {
+ err = ex;
+ reject(err);
+ } finally {
+ if (callback) callback(err, result);
+ }
+ }
+
+ if (Buffer.isBuffer(fileNameOrBuffer)) {
+ return tryParseBuffer(fileNameOrBuffer);
+ }
+ fs.readFile(fileNameOrBuffer, function (err, data) {
+ if (err) {
+ reject(err);
+ return callback(err);
+ }
+ tryParseBuffer(data);
+ });
+ });
+};
+
+const parseBuffer = exports.parseBuffer = function (buffer) {
+ // check header
+ const header = buffer.slice(0, 'bplist'.length).toString('utf8');
+ if (header !== 'bplist') {
+ throw new Error("Invalid binary plist. Expected 'bplist' at offset 0.");
+ }
+
+ // Handle trailer, last 32 bytes of the file
+ const trailer = buffer.slice(buffer.length - 32, buffer.length);
+ // 6 null bytes (index 0 to 5)
+ const offsetSize = trailer.readUInt8(6);
+ if (debug) {
+ console.log("offsetSize: " + offsetSize);
+ }
+ const objectRefSize = trailer.readUInt8(7);
+ if (debug) {
+ console.log("objectRefSize: " + objectRefSize);
+ }
+ const numObjects = readUInt64BE(trailer, 8);
+ if (debug) {
+ console.log("numObjects: " + numObjects);
+ }
+ const topObject = readUInt64BE(trailer, 16);
+ if (debug) {
+ console.log("topObject: " + topObject);
+ }
+ const offsetTableOffset = readUInt64BE(trailer, 24);
+ if (debug) {
+ console.log("offsetTableOffset: " + offsetTableOffset);
+ }
+
+ if (numObjects > exports.maxObjectCount) {
+ throw new Error("maxObjectCount exceeded");
+ }
+
+ // Handle offset table
+ const offsetTable = [];
+
+ for (let i = 0; i < numObjects; i++) {
+ const offsetBytes = buffer.slice(offsetTableOffset + i * offsetSize, offsetTableOffset + (i + 1) * offsetSize);
+ offsetTable[i] = readUInt(offsetBytes, 0);
+ if (debug) {
+ console.log("Offset for Object #" + i + " is " + offsetTable[i] + " [" + offsetTable[i].toString(16) + "]");
+ }
+ }
+
+ // Parses an object inside the currently parsed binary property list.
+ // For the format specification check
+ //
+ // Apple's binary property list parser implementation.
+ function parseObject(tableOffset) {
+ const offset = offsetTable[tableOffset];
+ const type = buffer[offset];
+ const objType = (type & 0xF0) >> 4; //First 4 bits
+ const objInfo = (type & 0x0F); //Second 4 bits
+ switch (objType) {
+ case 0x0:
+ return parseSimple();
+ case 0x1:
+ return parseInteger();
+ case 0x8:
+ return parseUID();
+ case 0x2:
+ return parseReal();
+ case 0x3:
+ return parseDate();
+ case 0x4:
+ return parseData();
+ case 0x5: // ASCII
+ return parsePlistString();
+ case 0x6: // UTF-16
+ return parsePlistString(true);
+ case 0xA:
+ return parseArray();
+ case 0xD:
+ return parseDictionary();
+ default:
+ throw new Error("Unhandled type 0x" + objType.toString(16));
+ }
+
+ function parseSimple() {
+ //Simple
+ switch (objInfo) {
+ case 0x0: // null
+ return null;
+ case 0x8: // false
+ return false;
+ case 0x9: // true
+ return true;
+ case 0xF: // filler byte
+ return null;
+ default:
+ throw new Error("Unhandled simple type 0x" + objType.toString(16));
+ }
+ }
+
+ function bufferToHexString(buffer) {
+ let str = '';
+ let i;
+ for (i = 0; i < buffer.length; i++) {
+ if (buffer[i] != 0x00) {
+ break;
+ }
+ }
+ for (; i < buffer.length; i++) {
+ const part = '00' + buffer[i].toString(16);
+ str += part.substr(part.length - 2);
+ }
+ return str;
+ }
+
+ function parseInteger() {
+ const length = Math.pow(2, objInfo);
+ if (length < exports.maxObjectSize) {
+ const data = buffer.slice(offset + 1, offset + 1 + length);
+ if (length === 16) {
+ const str = bufferToHexString(data);
+ return bigInt(str, 16);
+ }
+ return data.reduce((acc, curr) => {
+ acc <<= 8;
+ acc |= curr & 255;
+ return acc;
+ });
+ } else {
+ throw new Error("Too little heap space available! Wanted to read " + length + " bytes, but only " + exports.maxObjectSize + " are available.");
+ }
+ }
+
+ function parseUID() {
+ const length = objInfo + 1;
+ if (length < exports.maxObjectSize) {
+ return new UID(readUInt(buffer.slice(offset + 1, offset + 1 + length)));
+ }
+ throw new Error("Too little heap space available! Wanted to read " + length + " bytes, but only " + exports.maxObjectSize + " are available.");
+ }
+
+ function parseReal() {
+ const length = Math.pow(2, objInfo);
+ if (length < exports.maxObjectSize) {
+ const realBuffer = buffer.slice(offset + 1, offset + 1 + length);
+ if (length === 4) {
+ return realBuffer.readFloatBE(0);
+ }
+ if (length === 8) {
+ return realBuffer.readDoubleBE(0);
+ }
+ } else {
+ throw new Error("Too little heap space available! Wanted to read " + length + " bytes, but only " + exports.maxObjectSize + " are available.");
+ }
+ }
+
+ function parseDate() {
+ if (objInfo != 0x3) {
+ console.error("Unknown date type :" + objInfo + ". Parsing anyway...");
+ }
+ const dateBuffer = buffer.slice(offset + 1, offset + 9);
+ return new Date(EPOCH + (1000 * dateBuffer.readDoubleBE(0)));
+ }
+
+ function parseData() {
+ let dataoffset = 1;
+ let length = objInfo;
+ if (objInfo == 0xF) {
+ const int_type = buffer[offset + 1];
+ const intType = (int_type & 0xF0) / 0x10;
+ if (intType != 0x1) {
+ console.error("0x4: UNEXPECTED LENGTH-INT TYPE! " + intType);
+ }
+ const intInfo = int_type & 0x0F;
+ const intLength = Math.pow(2, intInfo);
+ dataoffset = 2 + intLength;
+ if (intLength < 3) {
+ length = readUInt(buffer.slice(offset + 2, offset + 2 + intLength));
+ } else {
+ length = readUInt(buffer.slice(offset + 2, offset + 2 + intLength));
+ }
+ }
+ if (length < exports.maxObjectSize) {
+ return buffer.slice(offset + dataoffset, offset + dataoffset + length);
+ }
+ throw new Error("Too little heap space available! Wanted to read " + length + " bytes, but only " + exports.maxObjectSize + " are available.");
+ }
+
+ function parsePlistString (isUtf16) {
+ isUtf16 = isUtf16 || 0;
+ let enc = "utf8";
+ let length = objInfo;
+ let stroffset = 1;
+ if (objInfo == 0xF) {
+ const int_type = buffer[offset + 1];
+ const intType = (int_type & 0xF0) / 0x10;
+ if (intType != 0x1) {
+ console.error("UNEXPECTED LENGTH-INT TYPE! " + intType);
+ }
+ const intInfo = int_type & 0x0F;
+ const intLength = Math.pow(2, intInfo);
+ stroffset = 2 + intLength;
+ if (intLength < 3) {
+ length = readUInt(buffer.slice(offset + 2, offset + 2 + intLength));
+ } else {
+ length = readUInt(buffer.slice(offset + 2, offset + 2 + intLength));
+ }
+ }
+ // length is String length -> to get byte length multiply by 2, as 1 character takes 2 bytes in UTF-16
+ length *= (isUtf16 + 1);
+ if (length < exports.maxObjectSize) {
+ let plistString = Buffer.from(buffer.slice(offset + stroffset, offset + stroffset + length));
+ if (isUtf16) {
+ plistString = swapBytes(plistString);
+ enc = "ucs2";
+ }
+ return plistString.toString(enc);
+ }
+ throw new Error("Too little heap space available! Wanted to read " + length + " bytes, but only " + exports.maxObjectSize + " are available.");
+ }
+
+ function parseArray() {
+ let length = objInfo;
+ let arrayoffset = 1;
+ if (objInfo == 0xF) {
+ const int_type = buffer[offset + 1];
+ const intType = (int_type & 0xF0) / 0x10;
+ if (intType != 0x1) {
+ console.error("0xa: UNEXPECTED LENGTH-INT TYPE! " + intType);
+ }
+ const intInfo = int_type & 0x0F;
+ const intLength = Math.pow(2, intInfo);
+ arrayoffset = 2 + intLength;
+ if (intLength < 3) {
+ length = readUInt(buffer.slice(offset + 2, offset + 2 + intLength));
+ } else {
+ length = readUInt(buffer.slice(offset + 2, offset + 2 + intLength));
+ }
+ }
+ if (length * objectRefSize > exports.maxObjectSize) {
+ throw new Error("Too little heap space available!");
+ }
+ const array = [];
+ for (let i = 0; i < length; i++) {
+ const objRef = readUInt(buffer.slice(offset + arrayoffset + i * objectRefSize, offset + arrayoffset + (i + 1) * objectRefSize));
+ array[i] = parseObject(objRef);
+ }
+ return array;
+ }
+
+ function parseDictionary() {
+ let length = objInfo;
+ let dictoffset = 1;
+ if (objInfo == 0xF) {
+ const int_type = buffer[offset + 1];
+ const intType = (int_type & 0xF0) / 0x10;
+ if (intType != 0x1) {
+ console.error("0xD: UNEXPECTED LENGTH-INT TYPE! " + intType);
+ }
+ const intInfo = int_type & 0x0F;
+ const intLength = Math.pow(2, intInfo);
+ dictoffset = 2 + intLength;
+ if (intLength < 3) {
+ length = readUInt(buffer.slice(offset + 2, offset + 2 + intLength));
+ } else {
+ length = readUInt(buffer.slice(offset + 2, offset + 2 + intLength));
+ }
+ }
+ if (length * 2 * objectRefSize > exports.maxObjectSize) {
+ throw new Error("Too little heap space available!");
+ }
+ if (debug) {
+ console.log("Parsing dictionary #" + tableOffset);
+ }
+ const dict = {};
+ for (let i = 0; i < length; i++) {
+ const keyRef = readUInt(buffer.slice(offset + dictoffset + i * objectRefSize, offset + dictoffset + (i + 1) * objectRefSize));
+ const valRef = readUInt(buffer.slice(offset + dictoffset + (length * objectRefSize) + i * objectRefSize, offset + dictoffset + (length * objectRefSize) + (i + 1) * objectRefSize));
+ const key = parseObject(keyRef);
+ const val = parseObject(valRef);
+ if (debug) {
+ console.log(" DICT #" + tableOffset + ": Mapped " + key + " to " + val);
+ }
+ dict[key] = val;
+ }
+ return dict;
+ }
+ }
+
+ return [ parseObject(topObject) ];
+};
+
+function readUInt(buffer, start) {
+ start = start || 0;
+
+ let l = 0;
+ for (let i = start; i < buffer.length; i++) {
+ l <<= 8;
+ l |= buffer[i] & 0xFF;
+ }
+ return l;
+}
+
+// we're just going to toss the high order bits because javascript doesn't have 64-bit ints
+function readUInt64BE(buffer, start) {
+ const data = buffer.slice(start, start + 8);
+ return data.readUInt32BE(4, 8);
+}
+
+function swapBytes(buffer) {
+ const len = buffer.length;
+ for (let i = 0; i < len; i += 2) {
+ const a = buffer[i];
+ buffer[i] = buffer[i+1];
+ buffer[i+1] = a;
+ }
+ return buffer;
+}
diff --git a/temporary_modules/trezor-connect/node_modules/bplist-parser/package.json b/temporary_modules/trezor-connect/node_modules/bplist-parser/package.json
new file mode 100644
index 00000000..fd6bdd05
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/bplist-parser/package.json
@@ -0,0 +1,35 @@
+{
+ "name": "bplist-parser",
+ "version": "0.3.1",
+ "description": "Binary plist parser.",
+ "main": "bplistParser.js",
+ "scripts": {
+ "test": "mocha test"
+ },
+ "keywords": [
+ "bplist",
+ "plist",
+ "parser"
+ ],
+ "author": "Joe Ferner ",
+ "contributors": [
+ "Brett Zamir"
+ ],
+ "license": "MIT",
+ "devDependencies": {
+ "eslint": "6.5.x",
+ "mocha": "6.2.x"
+ },
+ "homepage": "https://github.com/nearinfinity/node-bplist-parser",
+ "bugs": "https://github.com/nearinfinity/node-bplist-parser/issues",
+ "engines": {
+ "node": ">= 5.10.0"
+ },
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/nearinfinity/node-bplist-parser.git"
+ },
+ "dependencies": {
+ "big-integer": "1.6.x"
+ }
+}
diff --git a/temporary_modules/trezor-connect/node_modules/buffer-crc32/LICENSE b/temporary_modules/trezor-connect/node_modules/buffer-crc32/LICENSE
new file mode 100644
index 00000000..4cef10eb
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/buffer-crc32/LICENSE
@@ -0,0 +1,19 @@
+The MIT License
+
+Copyright (c) 2013 Brian J. Brennan
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal in
+the Software without restriction, including without limitation the rights to use,
+copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
+Software, and to permit persons to whom the Software is furnished to do so,
+subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
+INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
+PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
+FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/temporary_modules/trezor-connect/node_modules/buffer-crc32/README.md b/temporary_modules/trezor-connect/node_modules/buffer-crc32/README.md
new file mode 100644
index 00000000..0d9d8b83
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/buffer-crc32/README.md
@@ -0,0 +1,47 @@
+# buffer-crc32
+
+[](http://travis-ci.org/brianloveswords/buffer-crc32)
+
+crc32 that works with binary data and fancy character sets, outputs
+buffer, signed or unsigned data and has tests.
+
+Derived from the sample CRC implementation in the PNG specification: http://www.w3.org/TR/PNG/#D-CRCAppendix
+
+# install
+```
+npm install buffer-crc32
+```
+
+# example
+```js
+var crc32 = require('buffer-crc32');
+// works with buffers
+var buf = Buffer([0x00, 0x73, 0x75, 0x70, 0x20, 0x62, 0x72, 0x6f, 0x00])
+crc32(buf) // ->
+
+// has convenience methods for getting signed or unsigned ints
+crc32.signed(buf) // -> -1805997238
+crc32.unsigned(buf) // -> 2488970058
+
+// will cast to buffer if given a string, so you can
+// directly use foreign characters safely
+crc32('自動販売機') // ->
+
+// and works in append mode too
+var partialCrc = crc32('hey');
+var partialCrc = crc32(' ', partialCrc);
+var partialCrc = crc32('sup', partialCrc);
+var partialCrc = crc32(' ', partialCrc);
+var finalCrc = crc32('bros', partialCrc); // ->
+```
+
+# tests
+This was tested against the output of zlib's crc32 method. You can run
+the tests with`npm test` (requires tap)
+
+# see also
+https://github.com/alexgorbatchev/node-crc, `crc.buffer.crc32` also
+supports buffer inputs and return unsigned ints (thanks @tjholowaychuk).
+
+# license
+MIT/X11
diff --git a/temporary_modules/trezor-connect/node_modules/buffer-crc32/index.js b/temporary_modules/trezor-connect/node_modules/buffer-crc32/index.js
new file mode 100644
index 00000000..6727dd39
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/buffer-crc32/index.js
@@ -0,0 +1,111 @@
+var Buffer = require('buffer').Buffer;
+
+var CRC_TABLE = [
+ 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419,
+ 0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4,
+ 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07,
+ 0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de,
+ 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856,
+ 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9,
+ 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4,
+ 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b,
+ 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3,
+ 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a,
+ 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599,
+ 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924,
+ 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190,
+ 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f,
+ 0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e,
+ 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01,
+ 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed,
+ 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950,
+ 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3,
+ 0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2,
+ 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a,
+ 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5,
+ 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010,
+ 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,
+ 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17,
+ 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6,
+ 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615,
+ 0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8,
+ 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344,
+ 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb,
+ 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a,
+ 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5,
+ 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1,
+ 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c,
+ 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef,
+ 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,
+ 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe,
+ 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31,
+ 0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c,
+ 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713,
+ 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b,
+ 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242,
+ 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1,
+ 0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c,
+ 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278,
+ 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7,
+ 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66,
+ 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
+ 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605,
+ 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8,
+ 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b,
+ 0x2d02ef8d
+];
+
+if (typeof Int32Array !== 'undefined') {
+ CRC_TABLE = new Int32Array(CRC_TABLE);
+}
+
+function ensureBuffer(input) {
+ if (Buffer.isBuffer(input)) {
+ return input;
+ }
+
+ var hasNewBufferAPI =
+ typeof Buffer.alloc === "function" &&
+ typeof Buffer.from === "function";
+
+ if (typeof input === "number") {
+ return hasNewBufferAPI ? Buffer.alloc(input) : new Buffer(input);
+ }
+ else if (typeof input === "string") {
+ return hasNewBufferAPI ? Buffer.from(input) : new Buffer(input);
+ }
+ else {
+ throw new Error("input must be buffer, number, or string, received " +
+ typeof input);
+ }
+}
+
+function bufferizeInt(num) {
+ var tmp = ensureBuffer(4);
+ tmp.writeInt32BE(num, 0);
+ return tmp;
+}
+
+function _crc32(buf, previous) {
+ buf = ensureBuffer(buf);
+ if (Buffer.isBuffer(previous)) {
+ previous = previous.readUInt32BE(0);
+ }
+ var crc = ~~previous ^ -1;
+ for (var n = 0; n < buf.length; n++) {
+ crc = CRC_TABLE[(crc ^ buf[n]) & 0xff] ^ (crc >>> 8);
+ }
+ return (crc ^ -1);
+}
+
+function crc32() {
+ return bufferizeInt(_crc32.apply(null, arguments));
+}
+crc32.signed = function () {
+ return _crc32.apply(null, arguments);
+};
+crc32.unsigned = function () {
+ return _crc32.apply(null, arguments) >>> 0;
+};
+
+module.exports = crc32;
diff --git a/temporary_modules/trezor-connect/node_modules/buffer-crc32/package.json b/temporary_modules/trezor-connect/node_modules/buffer-crc32/package.json
new file mode 100644
index 00000000..e896bec5
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/buffer-crc32/package.json
@@ -0,0 +1,39 @@
+{
+ "author": "Brian J. Brennan ",
+ "name": "buffer-crc32",
+ "description": "A pure javascript CRC32 algorithm that plays nice with binary data",
+ "version": "0.2.13",
+ "licenses": [
+ {
+ "type": "MIT",
+ "url": "https://github.com/brianloveswords/buffer-crc32/raw/master/LICENSE"
+ }
+ ],
+ "contributors": [
+ {
+ "name": "Vladimir Kuznetsov",
+ "github": "mistakster"
+ }
+ ],
+ "homepage": "https://github.com/brianloveswords/buffer-crc32",
+ "repository": {
+ "type": "git",
+ "url": "git://github.com/brianloveswords/buffer-crc32.git"
+ },
+ "main": "index.js",
+ "scripts": {
+ "test": "./node_modules/.bin/tap tests/*.test.js"
+ },
+ "dependencies": {},
+ "devDependencies": {
+ "tap": "~0.2.5"
+ },
+ "optionalDependencies": {},
+ "engines": {
+ "node": "*"
+ },
+ "license": "MIT",
+ "files": [
+ "index.js"
+ ]
+}
diff --git a/temporary_modules/trezor-connect/node_modules/chownr/LICENSE b/temporary_modules/trezor-connect/node_modules/chownr/LICENSE
new file mode 100644
index 00000000..19129e31
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/chownr/LICENSE
@@ -0,0 +1,15 @@
+The ISC License
+
+Copyright (c) Isaac Z. Schlueter and Contributors
+
+Permission to use, copy, modify, and/or distribute this software for any
+purpose with or without fee is hereby granted, provided that the above
+copyright notice and this permission notice appear in all copies.
+
+THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
+IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
diff --git a/temporary_modules/trezor-connect/node_modules/chownr/README.md b/temporary_modules/trezor-connect/node_modules/chownr/README.md
new file mode 100644
index 00000000..70e9a54a
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/chownr/README.md
@@ -0,0 +1,3 @@
+Like `chown -R`.
+
+Takes the same arguments as `fs.chown()`
diff --git a/temporary_modules/trezor-connect/node_modules/chownr/chownr.js b/temporary_modules/trezor-connect/node_modules/chownr/chownr.js
new file mode 100644
index 00000000..0d409321
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/chownr/chownr.js
@@ -0,0 +1,167 @@
+'use strict'
+const fs = require('fs')
+const path = require('path')
+
+/* istanbul ignore next */
+const LCHOWN = fs.lchown ? 'lchown' : 'chown'
+/* istanbul ignore next */
+const LCHOWNSYNC = fs.lchownSync ? 'lchownSync' : 'chownSync'
+
+/* istanbul ignore next */
+const needEISDIRHandled = fs.lchown &&
+ !process.version.match(/v1[1-9]+\./) &&
+ !process.version.match(/v10\.[6-9]/)
+
+const lchownSync = (path, uid, gid) => {
+ try {
+ return fs[LCHOWNSYNC](path, uid, gid)
+ } catch (er) {
+ if (er.code !== 'ENOENT')
+ throw er
+ }
+}
+
+/* istanbul ignore next */
+const chownSync = (path, uid, gid) => {
+ try {
+ return fs.chownSync(path, uid, gid)
+ } catch (er) {
+ if (er.code !== 'ENOENT')
+ throw er
+ }
+}
+
+/* istanbul ignore next */
+const handleEISDIR =
+ needEISDIRHandled ? (path, uid, gid, cb) => er => {
+ // Node prior to v10 had a very questionable implementation of
+ // fs.lchown, which would always try to call fs.open on a directory
+ // Fall back to fs.chown in those cases.
+ if (!er || er.code !== 'EISDIR')
+ cb(er)
+ else
+ fs.chown(path, uid, gid, cb)
+ }
+ : (_, __, ___, cb) => cb
+
+/* istanbul ignore next */
+const handleEISDirSync =
+ needEISDIRHandled ? (path, uid, gid) => {
+ try {
+ return lchownSync(path, uid, gid)
+ } catch (er) {
+ if (er.code !== 'EISDIR')
+ throw er
+ chownSync(path, uid, gid)
+ }
+ }
+ : (path, uid, gid) => lchownSync(path, uid, gid)
+
+// fs.readdir could only accept an options object as of node v6
+const nodeVersion = process.version
+let readdir = (path, options, cb) => fs.readdir(path, options, cb)
+let readdirSync = (path, options) => fs.readdirSync(path, options)
+/* istanbul ignore next */
+if (/^v4\./.test(nodeVersion))
+ readdir = (path, options, cb) => fs.readdir(path, cb)
+
+const chown = (cpath, uid, gid, cb) => {
+ fs[LCHOWN](cpath, uid, gid, handleEISDIR(cpath, uid, gid, er => {
+ // Skip ENOENT error
+ cb(er && er.code !== 'ENOENT' ? er : null)
+ }))
+}
+
+const chownrKid = (p, child, uid, gid, cb) => {
+ if (typeof child === 'string')
+ return fs.lstat(path.resolve(p, child), (er, stats) => {
+ // Skip ENOENT error
+ if (er)
+ return cb(er.code !== 'ENOENT' ? er : null)
+ stats.name = child
+ chownrKid(p, stats, uid, gid, cb)
+ })
+
+ if (child.isDirectory()) {
+ chownr(path.resolve(p, child.name), uid, gid, er => {
+ if (er)
+ return cb(er)
+ const cpath = path.resolve(p, child.name)
+ chown(cpath, uid, gid, cb)
+ })
+ } else {
+ const cpath = path.resolve(p, child.name)
+ chown(cpath, uid, gid, cb)
+ }
+}
+
+
+const chownr = (p, uid, gid, cb) => {
+ readdir(p, { withFileTypes: true }, (er, children) => {
+ // any error other than ENOTDIR or ENOTSUP means it's not readable,
+ // or doesn't exist. give up.
+ if (er) {
+ if (er.code === 'ENOENT')
+ return cb()
+ else if (er.code !== 'ENOTDIR' && er.code !== 'ENOTSUP')
+ return cb(er)
+ }
+ if (er || !children.length)
+ return chown(p, uid, gid, cb)
+
+ let len = children.length
+ let errState = null
+ const then = er => {
+ if (errState)
+ return
+ if (er)
+ return cb(errState = er)
+ if (-- len === 0)
+ return chown(p, uid, gid, cb)
+ }
+
+ children.forEach(child => chownrKid(p, child, uid, gid, then))
+ })
+}
+
+const chownrKidSync = (p, child, uid, gid) => {
+ if (typeof child === 'string') {
+ try {
+ const stats = fs.lstatSync(path.resolve(p, child))
+ stats.name = child
+ child = stats
+ } catch (er) {
+ if (er.code === 'ENOENT')
+ return
+ else
+ throw er
+ }
+ }
+
+ if (child.isDirectory())
+ chownrSync(path.resolve(p, child.name), uid, gid)
+
+ handleEISDirSync(path.resolve(p, child.name), uid, gid)
+}
+
+const chownrSync = (p, uid, gid) => {
+ let children
+ try {
+ children = readdirSync(p, { withFileTypes: true })
+ } catch (er) {
+ if (er.code === 'ENOENT')
+ return
+ else if (er.code === 'ENOTDIR' || er.code === 'ENOTSUP')
+ return handleEISDirSync(p, uid, gid)
+ else
+ throw er
+ }
+
+ if (children && children.length)
+ children.forEach(child => chownrKidSync(p, child, uid, gid))
+
+ return handleEISDirSync(p, uid, gid)
+}
+
+module.exports = chownr
+chownr.sync = chownrSync
diff --git a/temporary_modules/trezor-connect/node_modules/chownr/package.json b/temporary_modules/trezor-connect/node_modules/chownr/package.json
new file mode 100644
index 00000000..5b0214ca
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/chownr/package.json
@@ -0,0 +1,32 @@
+{
+ "author": "Isaac Z. Schlueter (http://blog.izs.me/)",
+ "name": "chownr",
+ "description": "like `chown -R`",
+ "version": "2.0.0",
+ "repository": {
+ "type": "git",
+ "url": "git://github.com/isaacs/chownr.git"
+ },
+ "main": "chownr.js",
+ "files": [
+ "chownr.js"
+ ],
+ "devDependencies": {
+ "mkdirp": "0.3",
+ "rimraf": "^2.7.1",
+ "tap": "^14.10.6"
+ },
+ "tap": {
+ "check-coverage": true
+ },
+ "scripts": {
+ "test": "tap",
+ "preversion": "npm test",
+ "postversion": "npm publish",
+ "prepublishOnly": "git push origin --follow-tags"
+ },
+ "license": "ISC",
+ "engines": {
+ "node": ">=10"
+ }
+}
diff --git a/temporary_modules/trezor-connect/node_modules/color-convert/CHANGELOG.md b/temporary_modules/trezor-connect/node_modules/color-convert/CHANGELOG.md
new file mode 100644
index 00000000..0a7bce4f
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/color-convert/CHANGELOG.md
@@ -0,0 +1,54 @@
+# 1.0.0 - 2016-01-07
+
+- Removed: unused speed test
+- Added: Automatic routing between previously unsupported conversions
+([#27](https://github.com/Qix-/color-convert/pull/27))
+- Removed: `xxx2xxx()` and `xxx2xxxRaw()` functions
+([#27](https://github.com/Qix-/color-convert/pull/27))
+- Removed: `convert()` class
+([#27](https://github.com/Qix-/color-convert/pull/27))
+- Changed: all functions to lookup dictionary
+([#27](https://github.com/Qix-/color-convert/pull/27))
+- Changed: `ansi` to `ansi256`
+([#27](https://github.com/Qix-/color-convert/pull/27))
+- Fixed: argument grouping for functions requiring only one argument
+([#27](https://github.com/Qix-/color-convert/pull/27))
+
+# 0.6.0 - 2015-07-23
+
+- Added: methods to handle
+[ANSI](https://en.wikipedia.org/wiki/ANSI_escape_code#Colors) 16/256 colors:
+ - rgb2ansi16
+ - rgb2ansi
+ - hsl2ansi16
+ - hsl2ansi
+ - hsv2ansi16
+ - hsv2ansi
+ - hwb2ansi16
+ - hwb2ansi
+ - cmyk2ansi16
+ - cmyk2ansi
+ - keyword2ansi16
+ - keyword2ansi
+ - ansi162rgb
+ - ansi162hsl
+ - ansi162hsv
+ - ansi162hwb
+ - ansi162cmyk
+ - ansi162keyword
+ - ansi2rgb
+ - ansi2hsl
+ - ansi2hsv
+ - ansi2hwb
+ - ansi2cmyk
+ - ansi2keyword
+([#18](https://github.com/harthur/color-convert/pull/18))
+
+# 0.5.3 - 2015-06-02
+
+- Fixed: hsl2hsv does not return `NaN` anymore when using `[0,0,0]`
+([#15](https://github.com/harthur/color-convert/issues/15))
+
+---
+
+Check out commit logs for older releases
diff --git a/temporary_modules/trezor-connect/node_modules/color-convert/LICENSE b/temporary_modules/trezor-connect/node_modules/color-convert/LICENSE
new file mode 100644
index 00000000..5b4c386f
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/color-convert/LICENSE
@@ -0,0 +1,21 @@
+Copyright (c) 2011-2016 Heather Arthur
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
diff --git a/temporary_modules/trezor-connect/node_modules/color-convert/README.md b/temporary_modules/trezor-connect/node_modules/color-convert/README.md
new file mode 100644
index 00000000..d4b08fc3
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/color-convert/README.md
@@ -0,0 +1,68 @@
+# color-convert
+
+[](https://travis-ci.org/Qix-/color-convert)
+
+Color-convert is a color conversion library for JavaScript and node.
+It converts all ways between `rgb`, `hsl`, `hsv`, `hwb`, `cmyk`, `ansi`, `ansi16`, `hex` strings, and CSS `keyword`s (will round to closest):
+
+```js
+var convert = require('color-convert');
+
+convert.rgb.hsl(140, 200, 100); // [96, 48, 59]
+convert.keyword.rgb('blue'); // [0, 0, 255]
+
+var rgbChannels = convert.rgb.channels; // 3
+var cmykChannels = convert.cmyk.channels; // 4
+var ansiChannels = convert.ansi16.channels; // 1
+```
+
+# Install
+
+```console
+$ npm install color-convert
+```
+
+# API
+
+Simply get the property of the _from_ and _to_ conversion that you're looking for.
+
+All functions have a rounded and unrounded variant. By default, return values are rounded. To get the unrounded (raw) results, simply tack on `.raw` to the function.
+
+All 'from' functions have a hidden property called `.channels` that indicates the number of channels the function expects (not including alpha).
+
+```js
+var convert = require('color-convert');
+
+// Hex to LAB
+convert.hex.lab('DEADBF'); // [ 76, 21, -2 ]
+convert.hex.lab.raw('DEADBF'); // [ 75.56213190997677, 20.653827952644754, -2.290532499330533 ]
+
+// RGB to CMYK
+convert.rgb.cmyk(167, 255, 4); // [ 35, 0, 98, 0 ]
+convert.rgb.cmyk.raw(167, 255, 4); // [ 34.509803921568626, 0, 98.43137254901961, 0 ]
+```
+
+### Arrays
+All functions that accept multiple arguments also support passing an array.
+
+Note that this does **not** apply to functions that convert from a color that only requires one value (e.g. `keyword`, `ansi256`, `hex`, etc.)
+
+```js
+var convert = require('color-convert');
+
+convert.rgb.hex(123, 45, 67); // '7B2D43'
+convert.rgb.hex([123, 45, 67]); // '7B2D43'
+```
+
+## Routing
+
+Conversions that don't have an _explicitly_ defined conversion (in [conversions.js](conversions.js)), but can be converted by means of sub-conversions (e.g. XYZ -> **RGB** -> CMYK), are automatically routed together. This allows just about any color model supported by `color-convert` to be converted to any other model, so long as a sub-conversion path exists. This is also true for conversions requiring more than one step in between (e.g. LCH -> **LAB** -> **XYZ** -> **RGB** -> Hex).
+
+Keep in mind that extensive conversions _may_ result in a loss of precision, and exist only to be complete. For a list of "direct" (single-step) conversions, see [conversions.js](conversions.js).
+
+# Contribute
+
+If there is a new model you would like to support, or want to add a direct conversion between two existing models, please send us a pull request.
+
+# License
+Copyright © 2011-2016, Heather Arthur and Josh Junon. Licensed under the [MIT License](LICENSE).
diff --git a/temporary_modules/trezor-connect/node_modules/color-convert/conversions.js b/temporary_modules/trezor-connect/node_modules/color-convert/conversions.js
new file mode 100644
index 00000000..2657f265
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/color-convert/conversions.js
@@ -0,0 +1,839 @@
+/* MIT license */
+/* eslint-disable no-mixed-operators */
+const cssKeywords = require('color-name');
+
+// NOTE: conversions should only return primitive values (i.e. arrays, or
+// values that give correct `typeof` results).
+// do not use box values types (i.e. Number(), String(), etc.)
+
+const reverseKeywords = {};
+for (const key of Object.keys(cssKeywords)) {
+ reverseKeywords[cssKeywords[key]] = key;
+}
+
+const convert = {
+ rgb: {channels: 3, labels: 'rgb'},
+ hsl: {channels: 3, labels: 'hsl'},
+ hsv: {channels: 3, labels: 'hsv'},
+ hwb: {channels: 3, labels: 'hwb'},
+ cmyk: {channels: 4, labels: 'cmyk'},
+ xyz: {channels: 3, labels: 'xyz'},
+ lab: {channels: 3, labels: 'lab'},
+ lch: {channels: 3, labels: 'lch'},
+ hex: {channels: 1, labels: ['hex']},
+ keyword: {channels: 1, labels: ['keyword']},
+ ansi16: {channels: 1, labels: ['ansi16']},
+ ansi256: {channels: 1, labels: ['ansi256']},
+ hcg: {channels: 3, labels: ['h', 'c', 'g']},
+ apple: {channels: 3, labels: ['r16', 'g16', 'b16']},
+ gray: {channels: 1, labels: ['gray']}
+};
+
+module.exports = convert;
+
+// Hide .channels and .labels properties
+for (const model of Object.keys(convert)) {
+ if (!('channels' in convert[model])) {
+ throw new Error('missing channels property: ' + model);
+ }
+
+ if (!('labels' in convert[model])) {
+ throw new Error('missing channel labels property: ' + model);
+ }
+
+ if (convert[model].labels.length !== convert[model].channels) {
+ throw new Error('channel and label counts mismatch: ' + model);
+ }
+
+ const {channels, labels} = convert[model];
+ delete convert[model].channels;
+ delete convert[model].labels;
+ Object.defineProperty(convert[model], 'channels', {value: channels});
+ Object.defineProperty(convert[model], 'labels', {value: labels});
+}
+
+convert.rgb.hsl = function (rgb) {
+ const r = rgb[0] / 255;
+ const g = rgb[1] / 255;
+ const b = rgb[2] / 255;
+ const min = Math.min(r, g, b);
+ const max = Math.max(r, g, b);
+ const delta = max - min;
+ let h;
+ let s;
+
+ if (max === min) {
+ h = 0;
+ } else if (r === max) {
+ h = (g - b) / delta;
+ } else if (g === max) {
+ h = 2 + (b - r) / delta;
+ } else if (b === max) {
+ h = 4 + (r - g) / delta;
+ }
+
+ h = Math.min(h * 60, 360);
+
+ if (h < 0) {
+ h += 360;
+ }
+
+ const l = (min + max) / 2;
+
+ if (max === min) {
+ s = 0;
+ } else if (l <= 0.5) {
+ s = delta / (max + min);
+ } else {
+ s = delta / (2 - max - min);
+ }
+
+ return [h, s * 100, l * 100];
+};
+
+convert.rgb.hsv = function (rgb) {
+ let rdif;
+ let gdif;
+ let bdif;
+ let h;
+ let s;
+
+ const r = rgb[0] / 255;
+ const g = rgb[1] / 255;
+ const b = rgb[2] / 255;
+ const v = Math.max(r, g, b);
+ const diff = v - Math.min(r, g, b);
+ const diffc = function (c) {
+ return (v - c) / 6 / diff + 1 / 2;
+ };
+
+ if (diff === 0) {
+ h = 0;
+ s = 0;
+ } else {
+ s = diff / v;
+ rdif = diffc(r);
+ gdif = diffc(g);
+ bdif = diffc(b);
+
+ if (r === v) {
+ h = bdif - gdif;
+ } else if (g === v) {
+ h = (1 / 3) + rdif - bdif;
+ } else if (b === v) {
+ h = (2 / 3) + gdif - rdif;
+ }
+
+ if (h < 0) {
+ h += 1;
+ } else if (h > 1) {
+ h -= 1;
+ }
+ }
+
+ return [
+ h * 360,
+ s * 100,
+ v * 100
+ ];
+};
+
+convert.rgb.hwb = function (rgb) {
+ const r = rgb[0];
+ const g = rgb[1];
+ let b = rgb[2];
+ const h = convert.rgb.hsl(rgb)[0];
+ const w = 1 / 255 * Math.min(r, Math.min(g, b));
+
+ b = 1 - 1 / 255 * Math.max(r, Math.max(g, b));
+
+ return [h, w * 100, b * 100];
+};
+
+convert.rgb.cmyk = function (rgb) {
+ const r = rgb[0] / 255;
+ const g = rgb[1] / 255;
+ const b = rgb[2] / 255;
+
+ const k = Math.min(1 - r, 1 - g, 1 - b);
+ const c = (1 - r - k) / (1 - k) || 0;
+ const m = (1 - g - k) / (1 - k) || 0;
+ const y = (1 - b - k) / (1 - k) || 0;
+
+ return [c * 100, m * 100, y * 100, k * 100];
+};
+
+function comparativeDistance(x, y) {
+ /*
+ See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance
+ */
+ return (
+ ((x[0] - y[0]) ** 2) +
+ ((x[1] - y[1]) ** 2) +
+ ((x[2] - y[2]) ** 2)
+ );
+}
+
+convert.rgb.keyword = function (rgb) {
+ const reversed = reverseKeywords[rgb];
+ if (reversed) {
+ return reversed;
+ }
+
+ let currentClosestDistance = Infinity;
+ let currentClosestKeyword;
+
+ for (const keyword of Object.keys(cssKeywords)) {
+ const value = cssKeywords[keyword];
+
+ // Compute comparative distance
+ const distance = comparativeDistance(rgb, value);
+
+ // Check if its less, if so set as closest
+ if (distance < currentClosestDistance) {
+ currentClosestDistance = distance;
+ currentClosestKeyword = keyword;
+ }
+ }
+
+ return currentClosestKeyword;
+};
+
+convert.keyword.rgb = function (keyword) {
+ return cssKeywords[keyword];
+};
+
+convert.rgb.xyz = function (rgb) {
+ let r = rgb[0] / 255;
+ let g = rgb[1] / 255;
+ let b = rgb[2] / 255;
+
+ // Assume sRGB
+ r = r > 0.04045 ? (((r + 0.055) / 1.055) ** 2.4) : (r / 12.92);
+ g = g > 0.04045 ? (((g + 0.055) / 1.055) ** 2.4) : (g / 12.92);
+ b = b > 0.04045 ? (((b + 0.055) / 1.055) ** 2.4) : (b / 12.92);
+
+ const x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805);
+ const y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722);
+ const z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505);
+
+ return [x * 100, y * 100, z * 100];
+};
+
+convert.rgb.lab = function (rgb) {
+ const xyz = convert.rgb.xyz(rgb);
+ let x = xyz[0];
+ let y = xyz[1];
+ let z = xyz[2];
+
+ x /= 95.047;
+ y /= 100;
+ z /= 108.883;
+
+ x = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116);
+ y = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116);
+ z = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116);
+
+ const l = (116 * y) - 16;
+ const a = 500 * (x - y);
+ const b = 200 * (y - z);
+
+ return [l, a, b];
+};
+
+convert.hsl.rgb = function (hsl) {
+ const h = hsl[0] / 360;
+ const s = hsl[1] / 100;
+ const l = hsl[2] / 100;
+ let t2;
+ let t3;
+ let val;
+
+ if (s === 0) {
+ val = l * 255;
+ return [val, val, val];
+ }
+
+ if (l < 0.5) {
+ t2 = l * (1 + s);
+ } else {
+ t2 = l + s - l * s;
+ }
+
+ const t1 = 2 * l - t2;
+
+ const rgb = [0, 0, 0];
+ for (let i = 0; i < 3; i++) {
+ t3 = h + 1 / 3 * -(i - 1);
+ if (t3 < 0) {
+ t3++;
+ }
+
+ if (t3 > 1) {
+ t3--;
+ }
+
+ if (6 * t3 < 1) {
+ val = t1 + (t2 - t1) * 6 * t3;
+ } else if (2 * t3 < 1) {
+ val = t2;
+ } else if (3 * t3 < 2) {
+ val = t1 + (t2 - t1) * (2 / 3 - t3) * 6;
+ } else {
+ val = t1;
+ }
+
+ rgb[i] = val * 255;
+ }
+
+ return rgb;
+};
+
+convert.hsl.hsv = function (hsl) {
+ const h = hsl[0];
+ let s = hsl[1] / 100;
+ let l = hsl[2] / 100;
+ let smin = s;
+ const lmin = Math.max(l, 0.01);
+
+ l *= 2;
+ s *= (l <= 1) ? l : 2 - l;
+ smin *= lmin <= 1 ? lmin : 2 - lmin;
+ const v = (l + s) / 2;
+ const sv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s);
+
+ return [h, sv * 100, v * 100];
+};
+
+convert.hsv.rgb = function (hsv) {
+ const h = hsv[0] / 60;
+ const s = hsv[1] / 100;
+ let v = hsv[2] / 100;
+ const hi = Math.floor(h) % 6;
+
+ const f = h - Math.floor(h);
+ const p = 255 * v * (1 - s);
+ const q = 255 * v * (1 - (s * f));
+ const t = 255 * v * (1 - (s * (1 - f)));
+ v *= 255;
+
+ switch (hi) {
+ case 0:
+ return [v, t, p];
+ case 1:
+ return [q, v, p];
+ case 2:
+ return [p, v, t];
+ case 3:
+ return [p, q, v];
+ case 4:
+ return [t, p, v];
+ case 5:
+ return [v, p, q];
+ }
+};
+
+convert.hsv.hsl = function (hsv) {
+ const h = hsv[0];
+ const s = hsv[1] / 100;
+ const v = hsv[2] / 100;
+ const vmin = Math.max(v, 0.01);
+ let sl;
+ let l;
+
+ l = (2 - s) * v;
+ const lmin = (2 - s) * vmin;
+ sl = s * vmin;
+ sl /= (lmin <= 1) ? lmin : 2 - lmin;
+ sl = sl || 0;
+ l /= 2;
+
+ return [h, sl * 100, l * 100];
+};
+
+// http://dev.w3.org/csswg/css-color/#hwb-to-rgb
+convert.hwb.rgb = function (hwb) {
+ const h = hwb[0] / 360;
+ let wh = hwb[1] / 100;
+ let bl = hwb[2] / 100;
+ const ratio = wh + bl;
+ let f;
+
+ // Wh + bl cant be > 1
+ if (ratio > 1) {
+ wh /= ratio;
+ bl /= ratio;
+ }
+
+ const i = Math.floor(6 * h);
+ const v = 1 - bl;
+ f = 6 * h - i;
+
+ if ((i & 0x01) !== 0) {
+ f = 1 - f;
+ }
+
+ const n = wh + f * (v - wh); // Linear interpolation
+
+ let r;
+ let g;
+ let b;
+ /* eslint-disable max-statements-per-line,no-multi-spaces */
+ switch (i) {
+ default:
+ case 6:
+ case 0: r = v; g = n; b = wh; break;
+ case 1: r = n; g = v; b = wh; break;
+ case 2: r = wh; g = v; b = n; break;
+ case 3: r = wh; g = n; b = v; break;
+ case 4: r = n; g = wh; b = v; break;
+ case 5: r = v; g = wh; b = n; break;
+ }
+ /* eslint-enable max-statements-per-line,no-multi-spaces */
+
+ return [r * 255, g * 255, b * 255];
+};
+
+convert.cmyk.rgb = function (cmyk) {
+ const c = cmyk[0] / 100;
+ const m = cmyk[1] / 100;
+ const y = cmyk[2] / 100;
+ const k = cmyk[3] / 100;
+
+ const r = 1 - Math.min(1, c * (1 - k) + k);
+ const g = 1 - Math.min(1, m * (1 - k) + k);
+ const b = 1 - Math.min(1, y * (1 - k) + k);
+
+ return [r * 255, g * 255, b * 255];
+};
+
+convert.xyz.rgb = function (xyz) {
+ const x = xyz[0] / 100;
+ const y = xyz[1] / 100;
+ const z = xyz[2] / 100;
+ let r;
+ let g;
+ let b;
+
+ r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986);
+ g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415);
+ b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570);
+
+ // Assume sRGB
+ r = r > 0.0031308
+ ? ((1.055 * (r ** (1.0 / 2.4))) - 0.055)
+ : r * 12.92;
+
+ g = g > 0.0031308
+ ? ((1.055 * (g ** (1.0 / 2.4))) - 0.055)
+ : g * 12.92;
+
+ b = b > 0.0031308
+ ? ((1.055 * (b ** (1.0 / 2.4))) - 0.055)
+ : b * 12.92;
+
+ r = Math.min(Math.max(0, r), 1);
+ g = Math.min(Math.max(0, g), 1);
+ b = Math.min(Math.max(0, b), 1);
+
+ return [r * 255, g * 255, b * 255];
+};
+
+convert.xyz.lab = function (xyz) {
+ let x = xyz[0];
+ let y = xyz[1];
+ let z = xyz[2];
+
+ x /= 95.047;
+ y /= 100;
+ z /= 108.883;
+
+ x = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116);
+ y = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116);
+ z = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116);
+
+ const l = (116 * y) - 16;
+ const a = 500 * (x - y);
+ const b = 200 * (y - z);
+
+ return [l, a, b];
+};
+
+convert.lab.xyz = function (lab) {
+ const l = lab[0];
+ const a = lab[1];
+ const b = lab[2];
+ let x;
+ let y;
+ let z;
+
+ y = (l + 16) / 116;
+ x = a / 500 + y;
+ z = y - b / 200;
+
+ const y2 = y ** 3;
+ const x2 = x ** 3;
+ const z2 = z ** 3;
+ y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787;
+ x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787;
+ z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787;
+
+ x *= 95.047;
+ y *= 100;
+ z *= 108.883;
+
+ return [x, y, z];
+};
+
+convert.lab.lch = function (lab) {
+ const l = lab[0];
+ const a = lab[1];
+ const b = lab[2];
+ let h;
+
+ const hr = Math.atan2(b, a);
+ h = hr * 360 / 2 / Math.PI;
+
+ if (h < 0) {
+ h += 360;
+ }
+
+ const c = Math.sqrt(a * a + b * b);
+
+ return [l, c, h];
+};
+
+convert.lch.lab = function (lch) {
+ const l = lch[0];
+ const c = lch[1];
+ const h = lch[2];
+
+ const hr = h / 360 * 2 * Math.PI;
+ const a = c * Math.cos(hr);
+ const b = c * Math.sin(hr);
+
+ return [l, a, b];
+};
+
+convert.rgb.ansi16 = function (args, saturation = null) {
+ const [r, g, b] = args;
+ let value = saturation === null ? convert.rgb.hsv(args)[2] : saturation; // Hsv -> ansi16 optimization
+
+ value = Math.round(value / 50);
+
+ if (value === 0) {
+ return 30;
+ }
+
+ let ansi = 30
+ + ((Math.round(b / 255) << 2)
+ | (Math.round(g / 255) << 1)
+ | Math.round(r / 255));
+
+ if (value === 2) {
+ ansi += 60;
+ }
+
+ return ansi;
+};
+
+convert.hsv.ansi16 = function (args) {
+ // Optimization here; we already know the value and don't need to get
+ // it converted for us.
+ return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]);
+};
+
+convert.rgb.ansi256 = function (args) {
+ const r = args[0];
+ const g = args[1];
+ const b = args[2];
+
+ // We use the extended greyscale palette here, with the exception of
+ // black and white. normal palette only has 4 greyscale shades.
+ if (r === g && g === b) {
+ if (r < 8) {
+ return 16;
+ }
+
+ if (r > 248) {
+ return 231;
+ }
+
+ return Math.round(((r - 8) / 247) * 24) + 232;
+ }
+
+ const ansi = 16
+ + (36 * Math.round(r / 255 * 5))
+ + (6 * Math.round(g / 255 * 5))
+ + Math.round(b / 255 * 5);
+
+ return ansi;
+};
+
+convert.ansi16.rgb = function (args) {
+ let color = args % 10;
+
+ // Handle greyscale
+ if (color === 0 || color === 7) {
+ if (args > 50) {
+ color += 3.5;
+ }
+
+ color = color / 10.5 * 255;
+
+ return [color, color, color];
+ }
+
+ const mult = (~~(args > 50) + 1) * 0.5;
+ const r = ((color & 1) * mult) * 255;
+ const g = (((color >> 1) & 1) * mult) * 255;
+ const b = (((color >> 2) & 1) * mult) * 255;
+
+ return [r, g, b];
+};
+
+convert.ansi256.rgb = function (args) {
+ // Handle greyscale
+ if (args >= 232) {
+ const c = (args - 232) * 10 + 8;
+ return [c, c, c];
+ }
+
+ args -= 16;
+
+ let rem;
+ const r = Math.floor(args / 36) / 5 * 255;
+ const g = Math.floor((rem = args % 36) / 6) / 5 * 255;
+ const b = (rem % 6) / 5 * 255;
+
+ return [r, g, b];
+};
+
+convert.rgb.hex = function (args) {
+ const integer = ((Math.round(args[0]) & 0xFF) << 16)
+ + ((Math.round(args[1]) & 0xFF) << 8)
+ + (Math.round(args[2]) & 0xFF);
+
+ const string = integer.toString(16).toUpperCase();
+ return '000000'.substring(string.length) + string;
+};
+
+convert.hex.rgb = function (args) {
+ const match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);
+ if (!match) {
+ return [0, 0, 0];
+ }
+
+ let colorString = match[0];
+
+ if (match[0].length === 3) {
+ colorString = colorString.split('').map(char => {
+ return char + char;
+ }).join('');
+ }
+
+ const integer = parseInt(colorString, 16);
+ const r = (integer >> 16) & 0xFF;
+ const g = (integer >> 8) & 0xFF;
+ const b = integer & 0xFF;
+
+ return [r, g, b];
+};
+
+convert.rgb.hcg = function (rgb) {
+ const r = rgb[0] / 255;
+ const g = rgb[1] / 255;
+ const b = rgb[2] / 255;
+ const max = Math.max(Math.max(r, g), b);
+ const min = Math.min(Math.min(r, g), b);
+ const chroma = (max - min);
+ let grayscale;
+ let hue;
+
+ if (chroma < 1) {
+ grayscale = min / (1 - chroma);
+ } else {
+ grayscale = 0;
+ }
+
+ if (chroma <= 0) {
+ hue = 0;
+ } else
+ if (max === r) {
+ hue = ((g - b) / chroma) % 6;
+ } else
+ if (max === g) {
+ hue = 2 + (b - r) / chroma;
+ } else {
+ hue = 4 + (r - g) / chroma;
+ }
+
+ hue /= 6;
+ hue %= 1;
+
+ return [hue * 360, chroma * 100, grayscale * 100];
+};
+
+convert.hsl.hcg = function (hsl) {
+ const s = hsl[1] / 100;
+ const l = hsl[2] / 100;
+
+ const c = l < 0.5 ? (2.0 * s * l) : (2.0 * s * (1.0 - l));
+
+ let f = 0;
+ if (c < 1.0) {
+ f = (l - 0.5 * c) / (1.0 - c);
+ }
+
+ return [hsl[0], c * 100, f * 100];
+};
+
+convert.hsv.hcg = function (hsv) {
+ const s = hsv[1] / 100;
+ const v = hsv[2] / 100;
+
+ const c = s * v;
+ let f = 0;
+
+ if (c < 1.0) {
+ f = (v - c) / (1 - c);
+ }
+
+ return [hsv[0], c * 100, f * 100];
+};
+
+convert.hcg.rgb = function (hcg) {
+ const h = hcg[0] / 360;
+ const c = hcg[1] / 100;
+ const g = hcg[2] / 100;
+
+ if (c === 0.0) {
+ return [g * 255, g * 255, g * 255];
+ }
+
+ const pure = [0, 0, 0];
+ const hi = (h % 1) * 6;
+ const v = hi % 1;
+ const w = 1 - v;
+ let mg = 0;
+
+ /* eslint-disable max-statements-per-line */
+ switch (Math.floor(hi)) {
+ case 0:
+ pure[0] = 1; pure[1] = v; pure[2] = 0; break;
+ case 1:
+ pure[0] = w; pure[1] = 1; pure[2] = 0; break;
+ case 2:
+ pure[0] = 0; pure[1] = 1; pure[2] = v; break;
+ case 3:
+ pure[0] = 0; pure[1] = w; pure[2] = 1; break;
+ case 4:
+ pure[0] = v; pure[1] = 0; pure[2] = 1; break;
+ default:
+ pure[0] = 1; pure[1] = 0; pure[2] = w;
+ }
+ /* eslint-enable max-statements-per-line */
+
+ mg = (1.0 - c) * g;
+
+ return [
+ (c * pure[0] + mg) * 255,
+ (c * pure[1] + mg) * 255,
+ (c * pure[2] + mg) * 255
+ ];
+};
+
+convert.hcg.hsv = function (hcg) {
+ const c = hcg[1] / 100;
+ const g = hcg[2] / 100;
+
+ const v = c + g * (1.0 - c);
+ let f = 0;
+
+ if (v > 0.0) {
+ f = c / v;
+ }
+
+ return [hcg[0], f * 100, v * 100];
+};
+
+convert.hcg.hsl = function (hcg) {
+ const c = hcg[1] / 100;
+ const g = hcg[2] / 100;
+
+ const l = g * (1.0 - c) + 0.5 * c;
+ let s = 0;
+
+ if (l > 0.0 && l < 0.5) {
+ s = c / (2 * l);
+ } else
+ if (l >= 0.5 && l < 1.0) {
+ s = c / (2 * (1 - l));
+ }
+
+ return [hcg[0], s * 100, l * 100];
+};
+
+convert.hcg.hwb = function (hcg) {
+ const c = hcg[1] / 100;
+ const g = hcg[2] / 100;
+ const v = c + g * (1.0 - c);
+ return [hcg[0], (v - c) * 100, (1 - v) * 100];
+};
+
+convert.hwb.hcg = function (hwb) {
+ const w = hwb[1] / 100;
+ const b = hwb[2] / 100;
+ const v = 1 - b;
+ const c = v - w;
+ let g = 0;
+
+ if (c < 1) {
+ g = (v - c) / (1 - c);
+ }
+
+ return [hwb[0], c * 100, g * 100];
+};
+
+convert.apple.rgb = function (apple) {
+ return [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255];
+};
+
+convert.rgb.apple = function (rgb) {
+ return [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535];
+};
+
+convert.gray.rgb = function (args) {
+ return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255];
+};
+
+convert.gray.hsl = function (args) {
+ return [0, 0, args[0]];
+};
+
+convert.gray.hsv = convert.gray.hsl;
+
+convert.gray.hwb = function (gray) {
+ return [0, 100, gray[0]];
+};
+
+convert.gray.cmyk = function (gray) {
+ return [0, 0, 0, gray[0]];
+};
+
+convert.gray.lab = function (gray) {
+ return [gray[0], 0, 0];
+};
+
+convert.gray.hex = function (gray) {
+ const val = Math.round(gray[0] / 100 * 255) & 0xFF;
+ const integer = (val << 16) + (val << 8) + val;
+
+ const string = integer.toString(16).toUpperCase();
+ return '000000'.substring(string.length) + string;
+};
+
+convert.rgb.gray = function (rgb) {
+ const val = (rgb[0] + rgb[1] + rgb[2]) / 3;
+ return [val / 255 * 100];
+};
diff --git a/temporary_modules/trezor-connect/node_modules/color-convert/index.js b/temporary_modules/trezor-connect/node_modules/color-convert/index.js
new file mode 100644
index 00000000..b648e573
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/color-convert/index.js
@@ -0,0 +1,81 @@
+const conversions = require('./conversions');
+const route = require('./route');
+
+const convert = {};
+
+const models = Object.keys(conversions);
+
+function wrapRaw(fn) {
+ const wrappedFn = function (...args) {
+ const arg0 = args[0];
+ if (arg0 === undefined || arg0 === null) {
+ return arg0;
+ }
+
+ if (arg0.length > 1) {
+ args = arg0;
+ }
+
+ return fn(args);
+ };
+
+ // Preserve .conversion property if there is one
+ if ('conversion' in fn) {
+ wrappedFn.conversion = fn.conversion;
+ }
+
+ return wrappedFn;
+}
+
+function wrapRounded(fn) {
+ const wrappedFn = function (...args) {
+ const arg0 = args[0];
+
+ if (arg0 === undefined || arg0 === null) {
+ return arg0;
+ }
+
+ if (arg0.length > 1) {
+ args = arg0;
+ }
+
+ const result = fn(args);
+
+ // We're assuming the result is an array here.
+ // see notice in conversions.js; don't use box types
+ // in conversion functions.
+ if (typeof result === 'object') {
+ for (let len = result.length, i = 0; i < len; i++) {
+ result[i] = Math.round(result[i]);
+ }
+ }
+
+ return result;
+ };
+
+ // Preserve .conversion property if there is one
+ if ('conversion' in fn) {
+ wrappedFn.conversion = fn.conversion;
+ }
+
+ return wrappedFn;
+}
+
+models.forEach(fromModel => {
+ convert[fromModel] = {};
+
+ Object.defineProperty(convert[fromModel], 'channels', {value: conversions[fromModel].channels});
+ Object.defineProperty(convert[fromModel], 'labels', {value: conversions[fromModel].labels});
+
+ const routes = route(fromModel);
+ const routeModels = Object.keys(routes);
+
+ routeModels.forEach(toModel => {
+ const fn = routes[toModel];
+
+ convert[fromModel][toModel] = wrapRounded(fn);
+ convert[fromModel][toModel].raw = wrapRaw(fn);
+ });
+});
+
+module.exports = convert;
diff --git a/temporary_modules/trezor-connect/node_modules/color-convert/package.json b/temporary_modules/trezor-connect/node_modules/color-convert/package.json
new file mode 100644
index 00000000..6e48000c
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/color-convert/package.json
@@ -0,0 +1,48 @@
+{
+ "name": "color-convert",
+ "description": "Plain color conversion functions",
+ "version": "2.0.1",
+ "author": "Heather Arthur ",
+ "license": "MIT",
+ "repository": "Qix-/color-convert",
+ "scripts": {
+ "pretest": "xo",
+ "test": "node test/basic.js"
+ },
+ "engines": {
+ "node": ">=7.0.0"
+ },
+ "keywords": [
+ "color",
+ "colour",
+ "convert",
+ "converter",
+ "conversion",
+ "rgb",
+ "hsl",
+ "hsv",
+ "hwb",
+ "cmyk",
+ "ansi",
+ "ansi16"
+ ],
+ "files": [
+ "index.js",
+ "conversions.js",
+ "route.js"
+ ],
+ "xo": {
+ "rules": {
+ "default-case": 0,
+ "no-inline-comments": 0,
+ "operator-linebreak": 0
+ }
+ },
+ "devDependencies": {
+ "chalk": "^2.4.2",
+ "xo": "^0.24.0"
+ },
+ "dependencies": {
+ "color-name": "~1.1.4"
+ }
+}
diff --git a/temporary_modules/trezor-connect/node_modules/color-convert/route.js b/temporary_modules/trezor-connect/node_modules/color-convert/route.js
new file mode 100644
index 00000000..1a08521b
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/color-convert/route.js
@@ -0,0 +1,97 @@
+const conversions = require('./conversions');
+
+/*
+ This function routes a model to all other models.
+
+ all functions that are routed have a property `.conversion` attached
+ to the returned synthetic function. This property is an array
+ of strings, each with the steps in between the 'from' and 'to'
+ color models (inclusive).
+
+ conversions that are not possible simply are not included.
+*/
+
+function buildGraph() {
+ const graph = {};
+ // https://jsperf.com/object-keys-vs-for-in-with-closure/3
+ const models = Object.keys(conversions);
+
+ for (let len = models.length, i = 0; i < len; i++) {
+ graph[models[i]] = {
+ // http://jsperf.com/1-vs-infinity
+ // micro-opt, but this is simple.
+ distance: -1,
+ parent: null
+ };
+ }
+
+ return graph;
+}
+
+// https://en.wikipedia.org/wiki/Breadth-first_search
+function deriveBFS(fromModel) {
+ const graph = buildGraph();
+ const queue = [fromModel]; // Unshift -> queue -> pop
+
+ graph[fromModel].distance = 0;
+
+ while (queue.length) {
+ const current = queue.pop();
+ const adjacents = Object.keys(conversions[current]);
+
+ for (let len = adjacents.length, i = 0; i < len; i++) {
+ const adjacent = adjacents[i];
+ const node = graph[adjacent];
+
+ if (node.distance === -1) {
+ node.distance = graph[current].distance + 1;
+ node.parent = current;
+ queue.unshift(adjacent);
+ }
+ }
+ }
+
+ return graph;
+}
+
+function link(from, to) {
+ return function (args) {
+ return to(from(args));
+ };
+}
+
+function wrapConversion(toModel, graph) {
+ const path = [graph[toModel].parent, toModel];
+ let fn = conversions[graph[toModel].parent][toModel];
+
+ let cur = graph[toModel].parent;
+ while (graph[cur].parent) {
+ path.unshift(graph[cur].parent);
+ fn = link(conversions[graph[cur].parent][cur], fn);
+ cur = graph[cur].parent;
+ }
+
+ fn.conversion = path;
+ return fn;
+}
+
+module.exports = function (fromModel) {
+ const graph = deriveBFS(fromModel);
+ const conversion = {};
+
+ const models = Object.keys(graph);
+ for (let len = models.length, i = 0; i < len; i++) {
+ const toModel = models[i];
+ const node = graph[toModel];
+
+ if (node.parent === null) {
+ // No possible conversion, or this node is the source model.
+ continue;
+ }
+
+ conversion[toModel] = wrapConversion(toModel, graph);
+ }
+
+ return conversion;
+};
+
diff --git a/temporary_modules/trezor-connect/node_modules/color-name/LICENSE b/temporary_modules/trezor-connect/node_modules/color-name/LICENSE
new file mode 100644
index 00000000..4d9802a8
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/color-name/LICENSE
@@ -0,0 +1,8 @@
+The MIT License (MIT)
+Copyright (c) 2015 Dmitry Ivanov
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
\ No newline at end of file
diff --git a/temporary_modules/trezor-connect/node_modules/color-name/README.md b/temporary_modules/trezor-connect/node_modules/color-name/README.md
new file mode 100644
index 00000000..3611a6b5
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/color-name/README.md
@@ -0,0 +1,11 @@
+A JSON with color names and its values. Based on http://dev.w3.org/csswg/css-color/#named-colors.
+
+[](https://nodei.co/npm/color-name/)
+
+
+```js
+var colors = require('color-name');
+colors.red //[255,0,0]
+```
+
+
diff --git a/temporary_modules/trezor-connect/node_modules/color-name/index.js b/temporary_modules/trezor-connect/node_modules/color-name/index.js
new file mode 100644
index 00000000..e42aa68a
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/color-name/index.js
@@ -0,0 +1,152 @@
+'use strict'
+
+module.exports = {
+ "aliceblue": [240, 248, 255],
+ "antiquewhite": [250, 235, 215],
+ "aqua": [0, 255, 255],
+ "aquamarine": [127, 255, 212],
+ "azure": [240, 255, 255],
+ "beige": [245, 245, 220],
+ "bisque": [255, 228, 196],
+ "black": [0, 0, 0],
+ "blanchedalmond": [255, 235, 205],
+ "blue": [0, 0, 255],
+ "blueviolet": [138, 43, 226],
+ "brown": [165, 42, 42],
+ "burlywood": [222, 184, 135],
+ "cadetblue": [95, 158, 160],
+ "chartreuse": [127, 255, 0],
+ "chocolate": [210, 105, 30],
+ "coral": [255, 127, 80],
+ "cornflowerblue": [100, 149, 237],
+ "cornsilk": [255, 248, 220],
+ "crimson": [220, 20, 60],
+ "cyan": [0, 255, 255],
+ "darkblue": [0, 0, 139],
+ "darkcyan": [0, 139, 139],
+ "darkgoldenrod": [184, 134, 11],
+ "darkgray": [169, 169, 169],
+ "darkgreen": [0, 100, 0],
+ "darkgrey": [169, 169, 169],
+ "darkkhaki": [189, 183, 107],
+ "darkmagenta": [139, 0, 139],
+ "darkolivegreen": [85, 107, 47],
+ "darkorange": [255, 140, 0],
+ "darkorchid": [153, 50, 204],
+ "darkred": [139, 0, 0],
+ "darksalmon": [233, 150, 122],
+ "darkseagreen": [143, 188, 143],
+ "darkslateblue": [72, 61, 139],
+ "darkslategray": [47, 79, 79],
+ "darkslategrey": [47, 79, 79],
+ "darkturquoise": [0, 206, 209],
+ "darkviolet": [148, 0, 211],
+ "deeppink": [255, 20, 147],
+ "deepskyblue": [0, 191, 255],
+ "dimgray": [105, 105, 105],
+ "dimgrey": [105, 105, 105],
+ "dodgerblue": [30, 144, 255],
+ "firebrick": [178, 34, 34],
+ "floralwhite": [255, 250, 240],
+ "forestgreen": [34, 139, 34],
+ "fuchsia": [255, 0, 255],
+ "gainsboro": [220, 220, 220],
+ "ghostwhite": [248, 248, 255],
+ "gold": [255, 215, 0],
+ "goldenrod": [218, 165, 32],
+ "gray": [128, 128, 128],
+ "green": [0, 128, 0],
+ "greenyellow": [173, 255, 47],
+ "grey": [128, 128, 128],
+ "honeydew": [240, 255, 240],
+ "hotpink": [255, 105, 180],
+ "indianred": [205, 92, 92],
+ "indigo": [75, 0, 130],
+ "ivory": [255, 255, 240],
+ "khaki": [240, 230, 140],
+ "lavender": [230, 230, 250],
+ "lavenderblush": [255, 240, 245],
+ "lawngreen": [124, 252, 0],
+ "lemonchiffon": [255, 250, 205],
+ "lightblue": [173, 216, 230],
+ "lightcoral": [240, 128, 128],
+ "lightcyan": [224, 255, 255],
+ "lightgoldenrodyellow": [250, 250, 210],
+ "lightgray": [211, 211, 211],
+ "lightgreen": [144, 238, 144],
+ "lightgrey": [211, 211, 211],
+ "lightpink": [255, 182, 193],
+ "lightsalmon": [255, 160, 122],
+ "lightseagreen": [32, 178, 170],
+ "lightskyblue": [135, 206, 250],
+ "lightslategray": [119, 136, 153],
+ "lightslategrey": [119, 136, 153],
+ "lightsteelblue": [176, 196, 222],
+ "lightyellow": [255, 255, 224],
+ "lime": [0, 255, 0],
+ "limegreen": [50, 205, 50],
+ "linen": [250, 240, 230],
+ "magenta": [255, 0, 255],
+ "maroon": [128, 0, 0],
+ "mediumaquamarine": [102, 205, 170],
+ "mediumblue": [0, 0, 205],
+ "mediumorchid": [186, 85, 211],
+ "mediumpurple": [147, 112, 219],
+ "mediumseagreen": [60, 179, 113],
+ "mediumslateblue": [123, 104, 238],
+ "mediumspringgreen": [0, 250, 154],
+ "mediumturquoise": [72, 209, 204],
+ "mediumvioletred": [199, 21, 133],
+ "midnightblue": [25, 25, 112],
+ "mintcream": [245, 255, 250],
+ "mistyrose": [255, 228, 225],
+ "moccasin": [255, 228, 181],
+ "navajowhite": [255, 222, 173],
+ "navy": [0, 0, 128],
+ "oldlace": [253, 245, 230],
+ "olive": [128, 128, 0],
+ "olivedrab": [107, 142, 35],
+ "orange": [255, 165, 0],
+ "orangered": [255, 69, 0],
+ "orchid": [218, 112, 214],
+ "palegoldenrod": [238, 232, 170],
+ "palegreen": [152, 251, 152],
+ "paleturquoise": [175, 238, 238],
+ "palevioletred": [219, 112, 147],
+ "papayawhip": [255, 239, 213],
+ "peachpuff": [255, 218, 185],
+ "peru": [205, 133, 63],
+ "pink": [255, 192, 203],
+ "plum": [221, 160, 221],
+ "powderblue": [176, 224, 230],
+ "purple": [128, 0, 128],
+ "rebeccapurple": [102, 51, 153],
+ "red": [255, 0, 0],
+ "rosybrown": [188, 143, 143],
+ "royalblue": [65, 105, 225],
+ "saddlebrown": [139, 69, 19],
+ "salmon": [250, 128, 114],
+ "sandybrown": [244, 164, 96],
+ "seagreen": [46, 139, 87],
+ "seashell": [255, 245, 238],
+ "sienna": [160, 82, 45],
+ "silver": [192, 192, 192],
+ "skyblue": [135, 206, 235],
+ "slateblue": [106, 90, 205],
+ "slategray": [112, 128, 144],
+ "slategrey": [112, 128, 144],
+ "snow": [255, 250, 250],
+ "springgreen": [0, 255, 127],
+ "steelblue": [70, 130, 180],
+ "tan": [210, 180, 140],
+ "teal": [0, 128, 128],
+ "thistle": [216, 191, 216],
+ "tomato": [255, 99, 71],
+ "turquoise": [64, 224, 208],
+ "violet": [238, 130, 238],
+ "wheat": [245, 222, 179],
+ "white": [255, 255, 255],
+ "whitesmoke": [245, 245, 245],
+ "yellow": [255, 255, 0],
+ "yellowgreen": [154, 205, 50]
+};
diff --git a/temporary_modules/trezor-connect/node_modules/color-name/package.json b/temporary_modules/trezor-connect/node_modules/color-name/package.json
new file mode 100644
index 00000000..7acc9028
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/color-name/package.json
@@ -0,0 +1,28 @@
+{
+ "name": "color-name",
+ "version": "1.1.4",
+ "description": "A list of color names and its values",
+ "main": "index.js",
+ "files": [
+ "index.js"
+ ],
+ "scripts": {
+ "test": "node test.js"
+ },
+ "repository": {
+ "type": "git",
+ "url": "git@github.com:colorjs/color-name.git"
+ },
+ "keywords": [
+ "color-name",
+ "color",
+ "color-keyword",
+ "keyword"
+ ],
+ "author": "DY ",
+ "license": "MIT",
+ "bugs": {
+ "url": "https://github.com/colorjs/color-name/issues"
+ },
+ "homepage": "https://github.com/colorjs/color-name"
+}
diff --git a/temporary_modules/trezor-connect/node_modules/commander/CHANGELOG.md b/temporary_modules/trezor-connect/node_modules/commander/CHANGELOG.md
new file mode 100644
index 00000000..9b8359bf
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/commander/CHANGELOG.md
@@ -0,0 +1,361 @@
+# Changelog
+
+All notable changes to this project will be documented in this file.
+
+The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
+and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html). (Format adopted after v3.0.0.)
+
+
+
+
+## [6.2.1] (2020-12-13)
+
+### Fixed
+
+- some tests failed if directory path included a space ([1390])
+
+## [6.2.0] (2020-10-25)
+
+### Added
+
+- added 'tsx' file extension for stand-alone executable subcommands ([#1368])
+- documented second parameter to `.description()` to describe command arguments ([#1353])
+- documentation of special cases with options taking varying numbers of option-arguments ([#1332])
+- documentation for terminology ([#1361])
+
+### Fixed
+
+- add missing TypeScript definition for `.addHelpCommand()' ([#1375])
+- removed blank line after "Arguments:" in help, to match "Options:" and "Commands:" ([#1360])
+
+### Changed
+
+- update dependencies
+
+## [6.1.0] (2020-08-28)
+
+### Added
+
+- include URL to relevant section of README for error for potential conflict between Command properties and option values ([#1306])
+- `.combineFlagAndOptionalValue(false)` to ease upgrade path from older versions of Commander ([#1326])
+- allow disabling the built-in help option using `.helpOption(false)` ([#1325])
+- allow just some arguments in `argumentDescription` to `.description()` ([#1323])
+
+### Changed
+
+- tidy async test and remove lint override ([#1312])
+
+### Fixed
+
+- executable subcommand launching when script path not known ([#1322])
+
+## [6.0.0] (2020-07-21)
+
+### Added
+
+- add support for variadic options ([#1250])
+- allow options to be added with just a short flag ([#1256])
+ - *Breaking* the option property has same case as flag. e.g. flag `-n` accessed as `opts().n` (previously uppercase)
+- *Breaking* throw an error if there might be a clash between option name and a Command property, with advice on how to resolve ([#1275])
+
+### Fixed
+
+- Options which contain -no- in the middle of the option flag should not be treated as negatable. ([#1301])
+
+## [6.0.0-0] (2020-06-20)
+
+(Released in 6.0.0)
+
+## [5.1.0] (2020-04-25)
+
+### Added
+
+- support for multiple command aliases, the first of which is shown in the auto-generated help ([#531], [#1236])
+- configuration support in `addCommand()` for `hidden` and `isDefault` ([#1232])
+
+### Fixed
+
+- omit masked help flags from the displayed help ([#645], [#1247])
+- remove old short help flag when change help flags using `helpOption` ([#1248])
+
+### Changed
+
+- remove use of `arguments` to improve auto-generated help in editors ([#1235])
+- rename `.command()` configuration `noHelp` to `hidden` (but not remove old support) ([#1232])
+- improvements to documentation
+- update dependencies
+- update tested versions of node
+- eliminate lint errors in TypeScript ([#1208])
+
+## [5.0.0] (2020-03-14)
+
+### Added
+
+* support for nested commands with action-handlers ([#1] [#764] [#1149])
+* `.addCommand()` for adding a separately configured command ([#764] [#1149])
+* allow a non-executable to be set as the default command ([#742] [#1149])
+* implicit help command when there are subcommands (previously only if executables) ([#1149])
+* customise implicit help command with `.addHelpCommand()` ([#1149])
+* display error message for unknown subcommand, by default ([#432] [#1088] [#1149])
+* display help for missing subcommand, by default ([#1088] [#1149])
+* combined short options as single argument may include boolean flags and value flag and value (e.g. `-a -b -p 80` can be written as `-abp80`) ([#1145])
+* `.parseOption()` includes short flag and long flag expansions ([#1145])
+* `.helpInformation()` returns help text as a string, previously a private routine ([#1169])
+* `.parse()` implicitly uses `process.argv` if arguments not specified ([#1172])
+* optionally specify where `.parse()` arguments "from", if not following node conventions ([#512] [#1172])
+* suggest help option along with unknown command error ([#1179])
+* TypeScript definition for `commands` property of `Command` ([#1184])
+* export `program` property ([#1195])
+* `createCommand` factory method to simplify subclassing ([#1191])
+
+### Fixed
+
+* preserve argument order in subcommands ([#508] [#962] [#1138])
+* do not emit `command:*` for executable subcommands ([#809] [#1149])
+* action handler called whether or not there are non-option arguments ([#1062] [#1149])
+* combining option short flag and value in single argument now works for subcommands ([#1145])
+* only add implicit help command when it will not conflict with other uses of argument ([#1153] [#1149])
+* implicit help command works with command aliases ([#948] [#1149])
+* options are validated whether or not there is an action handler ([#1149])
+
+### Changed
+
+* *Breaking* `.args` contains command arguments with just recognised options removed ([#1032] [#1138])
+* *Breaking* display error if required argument for command is missing ([#995] [#1149])
+* tighten TypeScript definition of custom option processing function passed to `.option()` ([#1119])
+* *Breaking* `.allowUnknownOption()` ([#802] [#1138])
+ * unknown options included in arguments passed to command action handler
+ * unknown options included in `.args`
+* only recognised option short flags and long flags are expanded (e.g. `-ab` or `--foo=bar`) ([#1145])
+* *Breaking* `.parseOptions()` ([#1138])
+ * `args` in returned result renamed `operands` and does not include anything after first unknown option
+ * `unknown` in returned result has arguments after first unknown option including operands, not just options and values
+* *Breaking* `.on('command:*', callback)` and other command events passed (changed) results from `.parseOptions`, i.e. operands and unknown ([#1138])
+* refactor Option from prototype to class ([#1133])
+* refactor Command from prototype to class ([#1159])
+* changes to error handling ([#1165])
+ * throw for author error, not just display message
+ * preflight for variadic error
+ * add tips to missing subcommand executable
+* TypeScript fluent return types changed to be more subclass friendly, return `this` rather than `Command` ([#1180])
+* `.parseAsync` returns `Promise` to be consistent with `.parse()` ([#1180])
+* update dependencies
+
+### Removed
+
+* removed EventEmitter from TypeScript definition for Command, eliminating implicit peer dependency on `@types/node` ([#1146])
+* removed private function `normalize` (the functionality has been integrated into `parseOptions`) ([#1145])
+* `parseExpectedArgs` is now private ([#1149])
+
+### Migration Tips
+
+If you use `.on('command:*')` or more complicated tests to detect an unrecognised subcommand, you may be able to delete the code and rely on the default behaviour.
+
+If you use `program.args` or more complicated tests to detect a missing subcommand, you may be able to delete the code and rely on the default behaviour.
+
+If you use `.command('*')` to add a default command, you may be be able to switch to `isDefault:true` with a named command.
+
+If you want to continue combining short options with optional values as though they were boolean flags, set `combineFlagAndOptionalValue(false)`
+to expand `-fb` to `-f -b` rather than `-f b`.
+
+## [5.0.0-4] (2020-03-03)
+
+(Released in 5.0.0)
+
+## [5.0.0-3] (2020-02-20)
+
+(Released in 5.0.0)
+
+## [5.0.0-2] (2020-02-10)
+
+(Released in 5.0.0)
+
+## [5.0.0-1] (2020-02-08)
+
+(Released in 5.0.0)
+
+## [5.0.0-0] (2020-02-02)
+
+(Released in 5.0.0)
+
+## [4.1.1] (2020-02-02)
+
+### Fixed
+
+* TypeScript definition for `.action()` should include Promise for async ([#1157])
+
+## [4.1.0] (2020-01-06)
+
+### Added
+
+* two routines to change how option values are handled, and eliminate name clashes with command properties ([#933] [#1102])
+ * see storeOptionsAsProperties and passCommandToAction in README
+* `.parseAsync` to use instead of `.parse` if supply async action handlers ([#806] [#1118])
+
+### Fixed
+
+* Remove trailing blanks from wrapped help text ([#1096])
+
+### Changed
+
+* update dependencies
+* extend security coverage for Commander 2.x to 2020-02-03
+* improvements to README
+* improvements to TypeScript definition documentation
+* move old versions out of main CHANGELOG
+* removed explicit use of `ts-node` in tests
+
+## [4.0.1] (2019-11-12)
+
+### Fixed
+
+* display help when requested, even if there are missing required options ([#1091])
+
+## [4.0.0] (2019-11-02)
+
+### Added
+
+* automatically wrap and indent help descriptions for options and commands ([#1051])
+* `.exitOverride()` allows override of calls to `process.exit` for additional error handling and to keep program running ([#1040])
+* support for declaring required options with `.requiredOptions()` ([#1071])
+* GitHub Actions support ([#1027])
+* translation links in README
+
+### Changed
+
+* dev: switch tests from Sinon+Should to Jest with major rewrite of tests ([#1035])
+* call default subcommand even when there are unknown options ([#1047])
+* *Breaking* Commander is only officially supported on Node 8 and above, and requires Node 6 ([#1053])
+
+### Fixed
+
+* *Breaking* keep command object out of program.args when action handler called ([#1048])
+ * also, action handler now passed array of unknown arguments
+* complain about unknown options when program argument supplied and action handler ([#1049])
+ * this changes parameters to `command:*` event to include unknown arguments
+* removed deprecated `customFds` option from call to `child_process.spawn` ([#1052])
+* rework TypeScript declarations to bring all types into imported namespace ([#1081])
+
+### Migration Tips
+
+#### Testing for no arguments
+
+If you were previously using code like:
+
+```js
+if (!program.args.length) ...
+```
+
+a partial replacement is:
+
+```js
+if (program.rawArgs.length < 3) ...
+```
+
+## [4.0.0-1] Prerelease (2019-10-08)
+
+(Released in 4.0.0)
+
+## [4.0.0-0] Prerelease (2019-10-01)
+
+(Released in 4.0.0)
+
+## Older versions
+
+* [3.x](./changelogs/CHANGELOG-3.md)
+* [2.x](./changelogs/CHANGELOG-2.md)
+* [1.x](./changelogs/CHANGELOG-1.md)
+* [0.x](./changelogs/CHANGELOG-0.md)
+
+[#1]: https://github.com/tj/commander.js/issues/1
+[#432]: https://github.com/tj/commander.js/issues/432
+[#508]: https://github.com/tj/commander.js/issues/508
+[#512]: https://github.com/tj/commander.js/issues/512
+[#531]: https://github.com/tj/commander.js/issues/531
+[#645]: https://github.com/tj/commander.js/issues/645
+[#742]: https://github.com/tj/commander.js/issues/742
+[#764]: https://github.com/tj/commander.js/issues/764
+[#802]: https://github.com/tj/commander.js/issues/802
+[#806]: https://github.com/tj/commander.js/issues/806
+[#809]: https://github.com/tj/commander.js/issues/809
+[#948]: https://github.com/tj/commander.js/issues/948
+[#962]: https://github.com/tj/commander.js/issues/962
+[#995]: https://github.com/tj/commander.js/issues/995
+[#1027]: https://github.com/tj/commander.js/pull/1027
+[#1032]: https://github.com/tj/commander.js/issues/1032
+[#1035]: https://github.com/tj/commander.js/pull/1035
+[#1040]: https://github.com/tj/commander.js/pull/1040
+[#1047]: https://github.com/tj/commander.js/pull/1047
+[#1048]: https://github.com/tj/commander.js/pull/1048
+[#1049]: https://github.com/tj/commander.js/pull/1049
+[#1051]: https://github.com/tj/commander.js/pull/1051
+[#1052]: https://github.com/tj/commander.js/pull/1052
+[#1053]: https://github.com/tj/commander.js/pull/1053
+[#1062]: https://github.com/tj/commander.js/pull/1062
+[#1071]: https://github.com/tj/commander.js/pull/1071
+[#1081]: https://github.com/tj/commander.js/pull/1081
+[#1088]: https://github.com/tj/commander.js/issues/1088
+[#1091]: https://github.com/tj/commander.js/pull/1091
+[#1096]: https://github.com/tj/commander.js/pull/1096
+[#1102]: https://github.com/tj/commander.js/pull/1102
+[#1118]: https://github.com/tj/commander.js/pull/1118
+[#1119]: https://github.com/tj/commander.js/pull/1119
+[#1133]: https://github.com/tj/commander.js/pull/1133
+[#1138]: https://github.com/tj/commander.js/pull/1138
+[#1145]: https://github.com/tj/commander.js/pull/1145
+[#1146]: https://github.com/tj/commander.js/pull/1146
+[#1149]: https://github.com/tj/commander.js/pull/1149
+[#1153]: https://github.com/tj/commander.js/issues/1153
+[#1157]: https://github.com/tj/commander.js/pull/1157
+[#1159]: https://github.com/tj/commander.js/pull/1159
+[#1165]: https://github.com/tj/commander.js/pull/1165
+[#1169]: https://github.com/tj/commander.js/pull/1169
+[#1172]: https://github.com/tj/commander.js/pull/1172
+[#1179]: https://github.com/tj/commander.js/pull/1179
+[#1180]: https://github.com/tj/commander.js/pull/1180
+[#1184]: https://github.com/tj/commander.js/pull/1184
+[#1191]: https://github.com/tj/commander.js/pull/1191
+[#1195]: https://github.com/tj/commander.js/pull/1195
+[#1208]: https://github.com/tj/commander.js/pull/1208
+[#1232]: https://github.com/tj/commander.js/pull/1232
+[#1235]: https://github.com/tj/commander.js/pull/1235
+[#1236]: https://github.com/tj/commander.js/pull/1236
+[#1247]: https://github.com/tj/commander.js/pull/1247
+[#1248]: https://github.com/tj/commander.js/pull/1248
+[#1250]: https://github.com/tj/commander.js/pull/1250
+[#1256]: https://github.com/tj/commander.js/pull/1256
+[#1275]: https://github.com/tj/commander.js/pull/1275
+[#1301]: https://github.com/tj/commander.js/issues/1301
+[#1306]: https://github.com/tj/commander.js/pull/1306
+[#1312]: https://github.com/tj/commander.js/pull/1312
+[#1322]: https://github.com/tj/commander.js/pull/1322
+[#1323]: https://github.com/tj/commander.js/pull/1323
+[#1325]: https://github.com/tj/commander.js/pull/1325
+[#1326]: https://github.com/tj/commander.js/pull/1326
+[#1332]: https://github.com/tj/commander.js/pull/1332
+[#1353]: https://github.com/tj/commander.js/pull/1353
+[#1360]: https://github.com/tj/commander.js/pull/1360
+[#1361]: https://github.com/tj/commander.js/pull/1361
+[#1368]: https://github.com/tj/commander.js/pull/1368
+[#1375]: https://github.com/tj/commander.js/pull/1375
+[#1390]: https://github.com/tj/commander.js/pull/1390
+
+[Unreleased]: https://github.com/tj/commander.js/compare/master...develop
+[6.2.1]: https://github.com/tj/commander.js/compare/v6.2.0..v6.2.1
+[6.2.0]: https://github.com/tj/commander.js/compare/v6.1.0..v6.2.0
+[6.1.0]: https://github.com/tj/commander.js/compare/v6.0.0..v6.1.0
+[6.0.0]: https://github.com/tj/commander.js/compare/v5.1.0..v6.0.0
+[6.0.0-0]: https://github.com/tj/commander.js/compare/v5.1.0..v6.0.0-0
+[5.1.0]: https://github.com/tj/commander.js/compare/v5.0.0..v5.1.0
+[5.0.0]: https://github.com/tj/commander.js/compare/v4.1.1..v5.0.0
+[5.0.0-4]: https://github.com/tj/commander.js/compare/v5.0.0-3..v5.0.0-4
+[5.0.0-3]: https://github.com/tj/commander.js/compare/v5.0.0-2..v5.0.0-3
+[5.0.0-2]: https://github.com/tj/commander.js/compare/v5.0.0-1..v5.0.0-2
+[5.0.0-1]: https://github.com/tj/commander.js/compare/v5.0.0-0..v5.0.0-1
+[5.0.0-0]: https://github.com/tj/commander.js/compare/v4.1.1..v5.0.0-0
+[4.1.1]: https://github.com/tj/commander.js/compare/v4.1.0..v4.1.1
+[4.1.0]: https://github.com/tj/commander.js/compare/v4.0.1..v4.1.0
+[4.0.1]: https://github.com/tj/commander.js/compare/v4.0.0..v4.0.1
+[4.0.0]: https://github.com/tj/commander.js/compare/v3.0.2..v4.0.0
+[4.0.0-1]: https://github.com/tj/commander.js/compare/v4.0.0-0..v4.0.0-1
+[4.0.0-0]: https://github.com/tj/commander.js/compare/v3.0.2...v4.0.0-0
diff --git a/temporary_modules/trezor-connect/node_modules/commander/LICENSE b/temporary_modules/trezor-connect/node_modules/commander/LICENSE
new file mode 100644
index 00000000..10f997ab
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/commander/LICENSE
@@ -0,0 +1,22 @@
+(The MIT License)
+
+Copyright (c) 2011 TJ Holowaychuk
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+'Software'), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/temporary_modules/trezor-connect/node_modules/commander/Readme.md b/temporary_modules/trezor-connect/node_modules/commander/Readme.md
new file mode 100644
index 00000000..45cd7553
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/commander/Readme.md
@@ -0,0 +1,791 @@
+# Commander.js
+
+[](http://travis-ci.org/tj/commander.js)
+[](https://www.npmjs.org/package/commander)
+[](https://npmcharts.com/compare/commander?minimal=true)
+[](https://packagephobia.now.sh/result?p=commander)
+
+The complete solution for [node.js](http://nodejs.org) command-line interfaces.
+
+Read this in other languages: English | [简体中文](./Readme_zh-CN.md)
+
+- [Commander.js](#commanderjs)
+ - [Installation](#installation)
+ - [Declaring _program_ variable](#declaring-program-variable)
+ - [Options](#options)
+ - [Common option types, boolean and value](#common-option-types-boolean-and-value)
+ - [Default option value](#default-option-value)
+ - [Other option types, negatable boolean and boolean|value](#other-option-types-negatable-boolean-and-booleanvalue)
+ - [Custom option processing](#custom-option-processing)
+ - [Required option](#required-option)
+ - [Variadic option](#variadic-option)
+ - [Version option](#version-option)
+ - [Commands](#commands)
+ - [Specify the argument syntax](#specify-the-argument-syntax)
+ - [Action handler (sub)commands](#action-handler-subcommands)
+ - [Stand-alone executable (sub)commands](#stand-alone-executable-subcommands)
+ - [Automated help](#automated-help)
+ - [Custom help](#custom-help)
+ - [.usage and .name](#usage-and-name)
+ - [.help(cb)](#helpcb)
+ - [.outputHelp(cb)](#outputhelpcb)
+ - [.helpInformation()](#helpinformation)
+ - [.helpOption(flags, description)](#helpoptionflags-description)
+ - [.addHelpCommand()](#addhelpcommand)
+ - [Custom event listeners](#custom-event-listeners)
+ - [Bits and pieces](#bits-and-pieces)
+ - [.parse() and .parseAsync()](#parse-and-parseasync)
+ - [Avoiding option name clashes](#avoiding-option-name-clashes)
+ - [TypeScript](#typescript)
+ - [createCommand()](#createcommand)
+ - [Import into ECMAScript Module](#import-into-ecmascript-module)
+ - [Node options such as `--harmony`](#node-options-such-as---harmony)
+ - [Debugging stand-alone executable subcommands](#debugging-stand-alone-executable-subcommands)
+ - [Override exit handling](#override-exit-handling)
+ - [Examples](#examples)
+ - [Support](#support)
+ - [Commander for enterprise](#commander-for-enterprise)
+
+For information about terms used in this document see: [terminology](./docs/terminology.md)
+
+## Installation
+
+```bash
+npm install commander
+```
+
+## Declaring _program_ variable
+
+Commander exports a global object which is convenient for quick programs.
+This is used in the examples in this README for brevity.
+
+```js
+const { program } = require('commander');
+program.version('0.0.1');
+```
+
+For larger programs which may use commander in multiple ways, including unit testing, it is better to create a local Command object to use.
+
+```js
+const { Command } = require('commander');
+const program = new Command();
+program.version('0.0.1');
+```
+
+## Options
+
+Options are defined with the `.option()` method, also serving as documentation for the options. Each option can have a short flag (single character) and a long name, separated by a comma or space or vertical bar ('|').
+
+The options can be accessed as properties on the Command object. Multi-word options such as "--template-engine" are camel-cased, becoming `program.templateEngine` etc. See also optional new behaviour to [avoid name clashes](#avoiding-option-name-clashes).
+
+Multiple short flags may optionally be combined in a single argument following the dash: boolean flags, followed by a single option taking a value (possibly followed by the value).
+For example `-a -b -p 80` may be written as `-ab -p80` or even `-abp80`.
+
+You can use `--` to indicate the end of the options, and any remaining arguments will be used without being interpreted.
+
+Options on the command line are not positional, and can be specified before or after other arguments.
+
+### Common option types, boolean and value
+
+The two most used option types are a boolean option, and an option which takes its value
+from the following argument (declared with angle brackets like `--expect `). Both are `undefined` unless specified on command line.
+
+Example file: [options-common.js](./examples/options-common.js)
+
+```js
+program
+ .option('-d, --debug', 'output extra debugging')
+ .option('-s, --small', 'small pizza size')
+ .option('-p, --pizza-type ', 'flavour of pizza');
+
+program.parse(process.argv);
+
+if (program.debug) console.log(program.opts());
+console.log('pizza details:');
+if (program.small) console.log('- small pizza size');
+if (program.pizzaType) console.log(`- ${program.pizzaType}`);
+```
+
+```bash
+$ pizza-options -d
+{ debug: true, small: undefined, pizzaType: undefined }
+pizza details:
+$ pizza-options -p
+error: option '-p, --pizza-type ' argument missing
+$ pizza-options -ds -p vegetarian
+{ debug: true, small: true, pizzaType: 'vegetarian' }
+pizza details:
+- small pizza size
+- vegetarian
+$ pizza-options --pizza-type=cheese
+pizza details:
+- cheese
+```
+
+`program.parse(arguments)` processes the arguments, leaving any args not consumed by the program options in the `program.args` array.
+
+### Default option value
+
+You can specify a default value for an option which takes a value.
+
+Example file: [options-defaults.js](./examples/options-defaults.js)
+
+```js
+program
+ .option('-c, --cheese ', 'add the specified type of cheese', 'blue');
+
+program.parse(process.argv);
+
+console.log(`cheese: ${program.cheese}`);
+```
+
+```bash
+$ pizza-options
+cheese: blue
+$ pizza-options --cheese stilton
+cheese: stilton
+```
+
+### Other option types, negatable boolean and boolean|value
+
+You can define a boolean option long name with a leading `no-` to set the option value to false when used.
+Defined alone this also makes the option true by default.
+
+If you define `--foo` first, adding `--no-foo` does not change the default value from what it would
+otherwise be. You can specify a default boolean value for a boolean option and it can be overridden on command line.
+
+Example file: [options-negatable.js](./examples/options-negatable.js)
+
+```js
+program
+ .option('--no-sauce', 'Remove sauce')
+ .option('--cheese ', 'cheese flavour', 'mozzarella')
+ .option('--no-cheese', 'plain with no cheese')
+ .parse(process.argv);
+
+const sauceStr = program.sauce ? 'sauce' : 'no sauce';
+const cheeseStr = (program.cheese === false) ? 'no cheese' : `${program.cheese} cheese`;
+console.log(`You ordered a pizza with ${sauceStr} and ${cheeseStr}`);
+```
+
+```bash
+$ pizza-options
+You ordered a pizza with sauce and mozzarella cheese
+$ pizza-options --sauce
+error: unknown option '--sauce'
+$ pizza-options --cheese=blue
+You ordered a pizza with sauce and blue cheese
+$ pizza-options --no-sauce --no-cheese
+You ordered a pizza with no sauce and no cheese
+```
+
+You can specify an option which may be used as a boolean option but may optionally take an option-argument
+(declared with square brackets like `--optional [value]`).
+
+Example file: [options-boolean-or-value.js](./examples/options-boolean-or-value.js)
+
+```js
+program
+ .option('-c, --cheese [type]', 'Add cheese with optional type');
+
+program.parse(process.argv);
+
+if (program.cheese === undefined) console.log('no cheese');
+else if (program.cheese === true) console.log('add cheese');
+else console.log(`add cheese type ${program.cheese}`);
+```
+
+```bash
+$ pizza-options
+no cheese
+$ pizza-options --cheese
+add cheese
+$ pizza-options --cheese mozzarella
+add cheese type mozzarella
+```
+
+For information about possible ambiguous cases, see [options taking varying arguments](./docs/options-taking-varying-arguments.md).
+
+### Custom option processing
+
+You may specify a function to do custom processing of option-arguments. The callback function receives two parameters,
+the user specified option-argument and the previous value for the option. It returns the new value for the option.
+
+This allows you to coerce the option-argument to the desired type, or accumulate values, or do entirely custom processing.
+
+You can optionally specify the default/starting value for the option after the function parameter.
+
+Example file: [options-custom-processing.js](./examples/options-custom-processing.js)
+
+```js
+function myParseInt(value, dummyPrevious) {
+ // parseInt takes a string and an optional radix
+ return parseInt(value);
+}
+
+function increaseVerbosity(dummyValue, previous) {
+ return previous + 1;
+}
+
+function collect(value, previous) {
+ return previous.concat([value]);
+}
+
+function commaSeparatedList(value, dummyPrevious) {
+ return value.split(',');
+}
+
+program
+ .option('-f, --float ', 'float argument', parseFloat)
+ .option('-i, --integer ', 'integer argument', myParseInt)
+ .option('-v, --verbose', 'verbosity that can be increased', increaseVerbosity, 0)
+ .option('-c, --collect ', 'repeatable value', collect, [])
+ .option('-l, --list ', 'comma separated list', commaSeparatedList)
+;
+
+program.parse(process.argv);
+
+if (program.float !== undefined) console.log(`float: ${program.float}`);
+if (program.integer !== undefined) console.log(`integer: ${program.integer}`);
+if (program.verbose > 0) console.log(`verbosity: ${program.verbose}`);
+if (program.collect.length > 0) console.log(program.collect);
+if (program.list !== undefined) console.log(program.list);
+```
+
+```bash
+$ custom -f 1e2
+float: 100
+$ custom --integer 2
+integer: 2
+$ custom -v -v -v
+verbose: 3
+$ custom -c a -c b -c c
+[ 'a', 'b', 'c' ]
+$ custom --list x,y,z
+[ 'x', 'y', 'z' ]
+```
+
+### Required option
+
+You may specify a required (mandatory) option using `.requiredOption`. The option must have a value after parsing, usually specified on the command line, or perhaps from a default value (say from environment). The method is otherwise the same as `.option` in format, taking flags and description, and optional default value or custom processing.
+
+Example file: [options-required.js](./examples/options-required.js)
+
+```js
+program
+ .requiredOption('-c, --cheese ', 'pizza must have cheese');
+
+program.parse(process.argv);
+```
+
+```bash
+$ pizza
+error: required option '-c, --cheese ' not specified
+```
+
+### Variadic option
+
+You may make an option variadic by appending `...` to the value placeholder when declaring the option. On the command line you
+can then specify multiple option-arguments, and the parsed option value will be an array. The extra arguments
+are read until the first argument starting with a dash. The special argument `--` stops option processing entirely. If a value
+is specified in the same argument as the option then no further values are read.
+
+Example file: [options-variadic.js](./examples/options-variadic.js)
+
+```js
+program
+ .option('-n, --number ', 'specify numbers')
+ .option('-l, --letter [letters...]', 'specify letters');
+
+program.parse();
+
+console.log('Options: ', program.opts());
+console.log('Remaining arguments: ', program.args);
+```
+
+```bash
+$ collect -n 1 2 3 --letter a b c
+Options: { number: [ '1', '2', '3' ], letter: [ 'a', 'b', 'c' ] }
+Remaining arguments: []
+$ collect --letter=A -n80 operand
+Options: { number: [ '80' ], letter: [ 'A' ] }
+Remaining arguments: [ 'operand' ]
+$ collect --letter -n 1 -n 2 3 -- operand
+Options: { number: [ '1', '2', '3' ], letter: true }
+Remaining arguments: [ 'operand' ]
+```
+
+For information about possible ambiguous cases, see [options taking varying arguments](./docs/options-taking-varying-arguments.md).
+
+### Version option
+
+The optional `version` method adds handling for displaying the command version. The default option flags are `-V` and `--version`, and when present the command prints the version number and exits.
+
+```js
+program.version('0.0.1');
+```
+
+```bash
+$ ./examples/pizza -V
+0.0.1
+```
+
+You may change the flags and description by passing additional parameters to the `version` method, using
+the same syntax for flags as the `option` method.
+
+```js
+program.version('0.0.1', '-v, --vers', 'output the current version');
+```
+
+## Commands
+
+You can specify (sub)commands using `.command()` or `.addCommand()`. There are two ways these can be implemented: using an action handler attached to the command, or as a stand-alone executable file (described in more detail later). The subcommands may be nested ([example](./examples/nestedCommands.js)).
+
+In the first parameter to `.command()` you specify the command name and any command-arguments. The arguments may be `` or `[optional]`, and the last argument may also be `variadic...`.
+
+You can use `.addCommand()` to add an already configured subcommand to the program.
+
+For example:
+
+```js
+// Command implemented using action handler (description is supplied separately to `.command`)
+// Returns new command for configuring.
+program
+ .command('clone [destination]')
+ .description('clone a repository into a newly created directory')
+ .action((source, destination) => {
+ console.log('clone command called');
+ });
+
+// Command implemented using stand-alone executable file (description is second parameter to `.command`)
+// Returns `this` for adding more commands.
+program
+ .command('start ', 'start named service')
+ .command('stop [service]', 'stop named service, or all if no name supplied');
+
+// Command prepared separately.
+// Returns `this` for adding more commands.
+program
+ .addCommand(build.makeBuildCommand());
+```
+
+Configuration options can be passed with the call to `.command()` and `.addCommand()`. Specifying `hidden: true` will
+remove the command from the generated help output. Specifying `isDefault: true` will run the subcommand if no other
+subcommand is specified ([example](./examples/defaultCommand.js)).
+
+### Specify the argument syntax
+
+You use `.arguments` to specify the expected command-arguments for the top-level command, and for subcommands they are usually
+included in the `.command` call. Angled brackets (e.g. ``) indicate required command-arguments.
+Square brackets (e.g. `[optional]`) indicate optional command-arguments.
+You can optionally describe the arguments in the help by supplying a hash as second parameter to `.description()`.
+
+Example file: [env](./examples/env)
+
+```js
+program
+ .version('0.1.0')
+ .arguments(' [env]')
+ .description('test command', {
+ cmd: 'command to run',
+ env: 'environment to run test in'
+ })
+ .action(function (cmd, env) {
+ console.log('command:', cmd);
+ console.log('environment:', env || 'no environment given');
+ });
+
+program.parse(process.argv);
+```
+
+ The last argument of a command can be variadic, and only the last argument. To make an argument variadic you
+ append `...` to the argument name. For example:
+
+```js
+const { program } = require('commander');
+
+program
+ .version('0.1.0')
+ .command('rmdir [otherDirs...]')
+ .action(function (dir, otherDirs) {
+ console.log('rmdir %s', dir);
+ if (otherDirs) {
+ otherDirs.forEach(function (oDir) {
+ console.log('rmdir %s', oDir);
+ });
+ }
+ });
+
+program.parse(process.argv);
+```
+
+The variadic argument is passed to the action handler as an array.
+
+### Action handler (sub)commands
+
+You can add options to a command that uses an action handler.
+The action handler gets passed a parameter for each argument you declared, and one additional argument which is the
+command object itself. This command argument has the values for the command-specific options added as properties.
+
+```js
+const { program } = require('commander');
+
+program
+ .command('rm ')
+ .option('-r, --recursive', 'Remove recursively')
+ .action(function (dir, cmdObj) {
+ console.log('remove ' + dir + (cmdObj.recursive ? ' recursively' : ''))
+ })
+
+program.parse(process.argv)
+```
+
+You may supply an `async` action handler, in which case you call `.parseAsync` rather than `.parse`.
+
+```js
+async function run() { /* code goes here */ }
+
+async function main() {
+ program
+ .command('run')
+ .action(run);
+ await program.parseAsync(process.argv);
+}
+```
+
+A command's options on the command line are validated when the command is used. Any unknown options will be reported as an error.
+
+### Stand-alone executable (sub)commands
+
+When `.command()` is invoked with a description argument, this tells Commander that you're going to use stand-alone executables for subcommands.
+Commander will search the executables in the directory of the entry script (like `./examples/pm`) with the name `program-subcommand`, like `pm-install`, `pm-search`.
+You can specify a custom name with the `executableFile` configuration option.
+
+You handle the options for an executable (sub)command in the executable, and don't declare them at the top-level.
+
+Example file: [pm](./examples/pm)
+
+```js
+program
+ .version('0.1.0')
+ .command('install [name]', 'install one or more packages')
+ .command('search [query]', 'search with optional query')
+ .command('update', 'update installed packages', { executableFile: 'myUpdateSubCommand' })
+ .command('list', 'list packages installed', { isDefault: true });
+
+program.parse(process.argv);
+```
+
+If the program is designed to be installed globally, make sure the executables have proper modes, like `755`.
+
+## Automated help
+
+The help information is auto-generated based on the information commander already knows about your program. The default
+help option is `-h,--help`.
+
+Example file: [pizza](./examples/pizza)
+
+```bash
+$ node ./examples/pizza --help
+Usage: pizza [options]
+
+An application for pizzas ordering
+
+Options:
+ -V, --version output the version number
+ -p, --peppers Add peppers
+ -c, --cheese Add the specified type of cheese (default: "marble")
+ -C, --no-cheese You do not want any cheese
+ -h, --help display help for command
+```
+
+A `help` command is added by default if your command has subcommands. It can be used alone, or with a subcommand name to show
+further help for the subcommand. These are effectively the same if the `shell` program has implicit help:
+
+```bash
+shell help
+shell --help
+
+shell help spawn
+shell spawn --help
+```
+
+### Custom help
+
+You can display extra information by listening for "--help".
+
+Example file: [custom-help](./examples/custom-help)
+
+```js
+program
+ .option('-f, --foo', 'enable some foo');
+
+// must be before .parse()
+program.on('--help', () => {
+ console.log('');
+ console.log('Example call:');
+ console.log(' $ custom-help --help');
+});
+```
+
+Yields the following help output:
+
+```Text
+Usage: custom-help [options]
+
+Options:
+ -f, --foo enable some foo
+ -h, --help display help for command
+
+Example call:
+ $ custom-help --help
+```
+
+### .usage and .name
+
+These allow you to customise the usage description in the first line of the help. The name is otherwise
+deduced from the (full) program arguments. Given:
+
+```js
+program
+ .name("my-command")
+ .usage("[global options] command")
+```
+
+The help will start with:
+
+```Text
+Usage: my-command [global options] command
+```
+
+### .help(cb)
+
+Output help information and exit immediately. Optional callback cb allows post-processing of help text before it is displayed.
+
+### .outputHelp(cb)
+
+Output help information without exiting.
+Optional callback cb allows post-processing of help text before it is displayed.
+
+### .helpInformation()
+
+Get the command help information as a string for processing or displaying yourself. (The text does not include the custom help
+from `--help` listeners.)
+
+### .helpOption(flags, description)
+
+Override the default help flags and description. Pass false to disable the built-in help option.
+
+```js
+program
+ .helpOption('-e, --HELP', 'read more information');
+```
+
+### .addHelpCommand()
+
+You can explicitly turn on or off the implicit help command with `.addHelpCommand()` and `.addHelpCommand(false)`.
+
+You can both turn on and customise the help command by supplying the name and description:
+
+```js
+program.addHelpCommand('assist [command]', 'show assistance');
+```
+
+## Custom event listeners
+
+You can execute custom actions by listening to command and option events.
+
+```js
+program.on('option:verbose', function () {
+ process.env.VERBOSE = this.verbose;
+});
+
+program.on('command:*', function (operands) {
+ console.error(`error: unknown command '${operands[0]}'`);
+ const availableCommands = program.commands.map(cmd => cmd.name());
+ mySuggestBestMatch(operands[0], availableCommands);
+ process.exitCode = 1;
+});
+```
+
+## Bits and pieces
+
+### .parse() and .parseAsync()
+
+The first argument to `.parse` is the array of strings to parse. You may omit the parameter to implicitly use `process.argv`.
+
+If the arguments follow different conventions than node you can pass a `from` option in the second parameter:
+
+- 'node': default, `argv[0]` is the application and `argv[1]` is the script being run, with user parameters after that
+- 'electron': `argv[1]` varies depending on whether the electron application is packaged
+- 'user': all of the arguments from the user
+
+For example:
+
+```js
+program.parse(process.argv); // Explicit, node conventions
+program.parse(); // Implicit, and auto-detect electron
+program.parse(['-f', 'filename'], { from: 'user' });
+```
+
+### Avoiding option name clashes
+
+The original and default behaviour is that the option values are stored
+as properties on the program, and the action handler is passed a
+command object with the options values stored as properties.
+This is very convenient to code, but the downside is possible clashes with
+existing properties of Command.
+
+There are two new routines to change the behaviour, and the default behaviour may change in the future:
+
+- `storeOptionsAsProperties`: whether to store option values as properties on command object, or store separately (specify false) and access using `.opts()`
+- `passCommandToAction`: whether to pass command to action handler,
+or just the options (specify false)
+
+Example file: [storeOptionsAsProperties-action.js](./examples/storeOptionsAsProperties-action.js)
+
+```js
+program
+ .storeOptionsAsProperties(false)
+ .passCommandToAction(false);
+
+program
+ .name('my-program-name')
+ .option('-n,--name ');
+
+program
+ .command('show')
+ .option('-a,--action ')
+ .action((options) => {
+ console.log(options.action);
+ });
+
+program.parse(process.argv);
+
+const programOptions = program.opts();
+console.log(programOptions.name);
+```
+
+### TypeScript
+
+The Commander package includes its TypeScript Definition file.
+
+If you use `ts-node` and stand-alone executable subcommands written as `.ts` files, you need to call your program through node to get the subcommands called correctly. e.g.
+
+```bash
+node -r ts-node/register pm.ts
+```
+
+### createCommand()
+
+This factory function creates a new command. It is exported and may be used instead of using `new`, like:
+
+```js
+const { createCommand } = require('commander');
+const program = createCommand();
+```
+
+`createCommand` is also a method of the Command object, and creates a new command rather than a subcommand. This gets used internally
+when creating subcommands using `.command()`, and you may override it to
+customise the new subcommand (examples using [subclass](./examples/custom-command-class.js) and [function](./examples/custom-command-function.js)).
+
+### Import into ECMAScript Module
+
+Commander is currently a CommonJS package, and the default export can be imported into an ES Module:
+
+```js
+// index.mjs
+import commander from 'commander';
+const program = commander.program;
+const newCommand = new commander.Command();
+```
+
+### Node options such as `--harmony`
+
+You can enable `--harmony` option in two ways:
+
+- Use `#! /usr/bin/env node --harmony` in the subcommands scripts. (Note Windows does not support this pattern.)
+- Use the `--harmony` option when call the command, like `node --harmony examples/pm publish`. The `--harmony` option will be preserved when spawning subcommand process.
+
+### Debugging stand-alone executable subcommands
+
+An executable subcommand is launched as a separate child process.
+
+If you are using the node inspector for [debugging](https://nodejs.org/en/docs/guides/debugging-getting-started/) executable subcommands using `node --inspect` et al,
+the inspector port is incremented by 1 for the spawned subcommand.
+
+If you are using VSCode to debug executable subcommands you need to set the `"autoAttachChildProcesses": true` flag in your launch.json configuration.
+
+### Override exit handling
+
+By default Commander calls `process.exit` when it detects errors, or after displaying the help or version. You can override
+this behaviour and optionally supply a callback. The default override throws a `CommanderError`.
+
+The override callback is passed a `CommanderError` with properties `exitCode` number, `code` string, and `message`. The default override behaviour is to throw the error, except for async handling of executable subcommand completion which carries on. The normal display of error messages or version or help
+is not affected by the override which is called after the display.
+
+```js
+program.exitOverride();
+
+try {
+ program.parse(process.argv);
+} catch (err) {
+ // custom processing...
+}
+```
+
+## Examples
+
+Example file: [deploy](./examples/deploy)
+
+```js
+const { program } = require('commander');
+
+program
+ .version('0.1.0')
+ .option('-C, --chdir ', 'change the working directory')
+ .option('-c, --config ', 'set config path. defaults to ./deploy.conf')
+ .option('-T, --no-tests', 'ignore test hook');
+
+program
+ .command('setup [env]')
+ .description('run setup commands for all envs')
+ .option("-s, --setup_mode [mode]", "Which setup mode to use")
+ .action(function(env, options){
+ const mode = options.setup_mode || "normal";
+ env = env || 'all';
+ console.log('setup for %s env(s) with %s mode', env, mode);
+ });
+
+program
+ .command('exec ')
+ .alias('ex')
+ .description('execute the given remote cmd')
+ .option("-e, --exec_mode ", "Which exec mode to use")
+ .action(function(cmd, options){
+ console.log('exec "%s" using %s mode', cmd, options.exec_mode);
+ }).on('--help', function() {
+ console.log('');
+ console.log('Examples:');
+ console.log('');
+ console.log(' $ deploy exec sequential');
+ console.log(' $ deploy exec async');
+ });
+
+program.parse(process.argv);
+```
+
+More Demos can be found in the [examples](https://github.com/tj/commander.js/tree/master/examples) directory.
+
+## Support
+
+The current version of Commander is fully supported on Long Term Support versions of Node, and is likely to work with Node 6 but not tested.
+(For versions of Node below Node 6, use Commander 3.x or 2.x.)
+
+The main forum for free and community support is the project [Issues](https://github.com/tj/commander.js/issues) on GitHub.
+
+### Commander for enterprise
+
+Available as part of the Tidelift Subscription
+
+The maintainers of Commander and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-commander?utm_source=npm-commander&utm_medium=referral&utm_campaign=enterprise&utm_term=repo)
diff --git a/temporary_modules/trezor-connect/node_modules/commander/index.js b/temporary_modules/trezor-connect/node_modules/commander/index.js
new file mode 100644
index 00000000..c85f7255
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/commander/index.js
@@ -0,0 +1,1881 @@
+/**
+ * Module dependencies.
+ */
+
+const EventEmitter = require('events').EventEmitter;
+const spawn = require('child_process').spawn;
+const path = require('path');
+const fs = require('fs');
+
+// @ts-check
+
+class Option {
+ /**
+ * Initialize a new `Option` with the given `flags` and `description`.
+ *
+ * @param {string} flags
+ * @param {string} description
+ * @api public
+ */
+
+ constructor(flags, description) {
+ this.flags = flags;
+ this.required = flags.includes('<'); // A value must be supplied when the option is specified.
+ this.optional = flags.includes('['); // A value is optional when the option is specified.
+ // variadic test ignores et al which might be used to describe custom splitting of single argument
+ this.variadic = /\w\.\.\.[>\]]$/.test(flags); // The option can take multiple values.
+ this.mandatory = false; // The option must have a value after parsing, which usually means it must be specified on command line.
+ const optionFlags = _parseOptionFlags(flags);
+ this.short = optionFlags.shortFlag;
+ this.long = optionFlags.longFlag;
+ this.negate = false;
+ if (this.long) {
+ this.negate = this.long.startsWith('--no-');
+ }
+ this.description = description || '';
+ this.defaultValue = undefined;
+ }
+
+ /**
+ * Return option name.
+ *
+ * @return {string}
+ * @api private
+ */
+
+ name() {
+ if (this.long) {
+ return this.long.replace(/^--/, '');
+ }
+ return this.short.replace(/^-/, '');
+ };
+
+ /**
+ * Return option name, in a camelcase format that can be used
+ * as a object attribute key.
+ *
+ * @return {string}
+ * @api private
+ */
+
+ attributeName() {
+ return camelcase(this.name().replace(/^no-/, ''));
+ };
+
+ /**
+ * Check if `arg` matches the short or long flag.
+ *
+ * @param {string} arg
+ * @return {boolean}
+ * @api private
+ */
+
+ is(arg) {
+ return this.short === arg || this.long === arg;
+ };
+}
+
+/**
+ * CommanderError class
+ * @class
+ */
+class CommanderError extends Error {
+ /**
+ * Constructs the CommanderError class
+ * @param {number} exitCode suggested exit code which could be used with process.exit
+ * @param {string} code an id string representing the error
+ * @param {string} message human-readable description of the error
+ * @constructor
+ */
+ constructor(exitCode, code, message) {
+ super(message);
+ // properly capture stack trace in Node.js
+ Error.captureStackTrace(this, this.constructor);
+ this.name = this.constructor.name;
+ this.code = code;
+ this.exitCode = exitCode;
+ this.nestedError = undefined;
+ }
+}
+
+class Command extends EventEmitter {
+ /**
+ * Initialize a new `Command`.
+ *
+ * @param {string} [name]
+ * @api public
+ */
+
+ constructor(name) {
+ super();
+ this.commands = [];
+ this.options = [];
+ this.parent = null;
+ this._allowUnknownOption = false;
+ this._args = [];
+ this.rawArgs = null;
+ this._scriptPath = null;
+ this._name = name || '';
+ this._optionValues = {};
+ this._storeOptionsAsProperties = true; // backwards compatible by default
+ this._storeOptionsAsPropertiesCalled = false;
+ this._passCommandToAction = true; // backwards compatible by default
+ this._actionResults = [];
+ this._actionHandler = null;
+ this._executableHandler = false;
+ this._executableFile = null; // custom name for executable
+ this._defaultCommandName = null;
+ this._exitCallback = null;
+ this._aliases = [];
+ this._combineFlagAndOptionalValue = true;
+
+ this._hidden = false;
+ this._hasHelpOption = true;
+ this._helpFlags = '-h, --help';
+ this._helpDescription = 'display help for command';
+ this._helpShortFlag = '-h';
+ this._helpLongFlag = '--help';
+ this._hasImplicitHelpCommand = undefined; // Deliberately undefined, not decided whether true or false
+ this._helpCommandName = 'help';
+ this._helpCommandnameAndArgs = 'help [command]';
+ this._helpCommandDescription = 'display help for command';
+ }
+
+ /**
+ * Define a command.
+ *
+ * There are two styles of command: pay attention to where to put the description.
+ *
+ * Examples:
+ *
+ * // Command implemented using action handler (description is supplied separately to `.command`)
+ * program
+ * .command('clone [destination]')
+ * .description('clone a repository into a newly created directory')
+ * .action((source, destination) => {
+ * console.log('clone command called');
+ * });
+ *
+ * // Command implemented using separate executable file (description is second parameter to `.command`)
+ * program
+ * .command('start ', 'start named service')
+ * .command('stop [service]', 'stop named service, or all if no name supplied');
+ *
+ * @param {string} nameAndArgs - command name and arguments, args are `` or `[optional]` and last may also be `variadic...`
+ * @param {Object|string} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
+ * @param {Object} [execOpts] - configuration options (for executable)
+ * @return {Command} returns new command for action handler, or `this` for executable command
+ * @api public
+ */
+
+ command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
+ let desc = actionOptsOrExecDesc;
+ let opts = execOpts;
+ if (typeof desc === 'object' && desc !== null) {
+ opts = desc;
+ desc = null;
+ }
+ opts = opts || {};
+ const args = nameAndArgs.split(/ +/);
+ const cmd = this.createCommand(args.shift());
+
+ if (desc) {
+ cmd.description(desc);
+ cmd._executableHandler = true;
+ }
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
+
+ cmd._hidden = !!(opts.noHelp || opts.hidden);
+ cmd._hasHelpOption = this._hasHelpOption;
+ cmd._helpFlags = this._helpFlags;
+ cmd._helpDescription = this._helpDescription;
+ cmd._helpShortFlag = this._helpShortFlag;
+ cmd._helpLongFlag = this._helpLongFlag;
+ cmd._helpCommandName = this._helpCommandName;
+ cmd._helpCommandnameAndArgs = this._helpCommandnameAndArgs;
+ cmd._helpCommandDescription = this._helpCommandDescription;
+ cmd._exitCallback = this._exitCallback;
+ cmd._storeOptionsAsProperties = this._storeOptionsAsProperties;
+ cmd._passCommandToAction = this._passCommandToAction;
+ cmd._combineFlagAndOptionalValue = this._combineFlagAndOptionalValue;
+
+ cmd._executableFile = opts.executableFile || null; // Custom name for executable file, set missing to null to match constructor
+ this.commands.push(cmd);
+ cmd._parseExpectedArgs(args);
+ cmd.parent = this;
+
+ if (desc) return this;
+ return cmd;
+ };
+
+ /**
+ * Factory routine to create a new unattached command.
+ *
+ * See .command() for creating an attached subcommand, which uses this routine to
+ * create the command. You can override createCommand to customise subcommands.
+ *
+ * @param {string} [name]
+ * @return {Command} new command
+ * @api public
+ */
+
+ createCommand(name) {
+ return new Command(name);
+ };
+
+ /**
+ * Add a prepared subcommand.
+ *
+ * See .command() for creating an attached subcommand which inherits settings from its parent.
+ *
+ * @param {Command} cmd - new subcommand
+ * @param {Object} [opts] - configuration options
+ * @return {Command} `this` command for chaining
+ * @api public
+ */
+
+ addCommand(cmd, opts) {
+ if (!cmd._name) throw new Error('Command passed to .addCommand() must have a name');
+
+ // To keep things simple, block automatic name generation for deeply nested executables.
+ // Fail fast and detect when adding rather than later when parsing.
+ function checkExplicitNames(commandArray) {
+ commandArray.forEach((cmd) => {
+ if (cmd._executableHandler && !cmd._executableFile) {
+ throw new Error(`Must specify executableFile for deeply nested executable: ${cmd.name()}`);
+ }
+ checkExplicitNames(cmd.commands);
+ });
+ }
+ checkExplicitNames(cmd.commands);
+
+ opts = opts || {};
+ if (opts.isDefault) this._defaultCommandName = cmd._name;
+ if (opts.noHelp || opts.hidden) cmd._hidden = true; // modifying passed command due to existing implementation
+
+ this.commands.push(cmd);
+ cmd.parent = this;
+ return this;
+ };
+
+ /**
+ * Define argument syntax for the command.
+ *
+ * @api public
+ */
+
+ arguments(desc) {
+ return this._parseExpectedArgs(desc.split(/ +/));
+ };
+
+ /**
+ * Override default decision whether to add implicit help command.
+ *
+ * addHelpCommand() // force on
+ * addHelpCommand(false); // force off
+ * addHelpCommand('help [cmd]', 'display help for [cmd]'); // force on with custom details
+ *
+ * @return {Command} `this` command for chaining
+ * @api public
+ */
+
+ addHelpCommand(enableOrNameAndArgs, description) {
+ if (enableOrNameAndArgs === false) {
+ this._hasImplicitHelpCommand = false;
+ } else {
+ this._hasImplicitHelpCommand = true;
+ if (typeof enableOrNameAndArgs === 'string') {
+ this._helpCommandName = enableOrNameAndArgs.split(' ')[0];
+ this._helpCommandnameAndArgs = enableOrNameAndArgs;
+ }
+ this._helpCommandDescription = description || this._helpCommandDescription;
+ }
+ return this;
+ };
+
+ /**
+ * @return {boolean}
+ * @api private
+ */
+
+ _lazyHasImplicitHelpCommand() {
+ if (this._hasImplicitHelpCommand === undefined) {
+ this._hasImplicitHelpCommand = this.commands.length && !this._actionHandler && !this._findCommand('help');
+ }
+ return this._hasImplicitHelpCommand;
+ };
+
+ /**
+ * Parse expected `args`.
+ *
+ * For example `["[type]"]` becomes `[{ required: false, name: 'type' }]`.
+ *
+ * @param {Array} args
+ * @return {Command} `this` command for chaining
+ * @api private
+ */
+
+ _parseExpectedArgs(args) {
+ if (!args.length) return;
+ args.forEach((arg) => {
+ const argDetails = {
+ required: false,
+ name: '',
+ variadic: false
+ };
+
+ switch (arg[0]) {
+ case '<':
+ argDetails.required = true;
+ argDetails.name = arg.slice(1, -1);
+ break;
+ case '[':
+ argDetails.name = arg.slice(1, -1);
+ break;
+ }
+
+ if (argDetails.name.length > 3 && argDetails.name.slice(-3) === '...') {
+ argDetails.variadic = true;
+ argDetails.name = argDetails.name.slice(0, -3);
+ }
+ if (argDetails.name) {
+ this._args.push(argDetails);
+ }
+ });
+ this._args.forEach((arg, i) => {
+ if (arg.variadic && i < this._args.length - 1) {
+ throw new Error(`only the last argument can be variadic '${arg.name}'`);
+ }
+ });
+ return this;
+ };
+
+ /**
+ * Register callback to use as replacement for calling process.exit.
+ *
+ * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
+ * @return {Command} `this` command for chaining
+ * @api public
+ */
+
+ exitOverride(fn) {
+ if (fn) {
+ this._exitCallback = fn;
+ } else {
+ this._exitCallback = (err) => {
+ if (err.code !== 'commander.executeSubCommandAsync') {
+ throw err;
+ } else {
+ // Async callback from spawn events, not useful to throw.
+ }
+ };
+ }
+ return this;
+ };
+
+ /**
+ * Call process.exit, and _exitCallback if defined.
+ *
+ * @param {number} exitCode exit code for using with process.exit
+ * @param {string} code an id string representing the error
+ * @param {string} message human-readable description of the error
+ * @return never
+ * @api private
+ */
+
+ _exit(exitCode, code, message) {
+ if (this._exitCallback) {
+ this._exitCallback(new CommanderError(exitCode, code, message));
+ // Expecting this line is not reached.
+ }
+ process.exit(exitCode);
+ };
+
+ /**
+ * Register callback `fn` for the command.
+ *
+ * Examples:
+ *
+ * program
+ * .command('help')
+ * .description('display verbose help')
+ * .action(function() {
+ * // output help here
+ * });
+ *
+ * @param {Function} fn
+ * @return {Command} `this` command for chaining
+ * @api public
+ */
+
+ action(fn) {
+ const listener = (args) => {
+ // The .action callback takes an extra parameter which is the command or options.
+ const expectedArgsCount = this._args.length;
+ const actionArgs = args.slice(0, expectedArgsCount);
+ if (this._passCommandToAction) {
+ actionArgs[expectedArgsCount] = this;
+ } else {
+ actionArgs[expectedArgsCount] = this.opts();
+ }
+ // Add the extra arguments so available too.
+ if (args.length > expectedArgsCount) {
+ actionArgs.push(args.slice(expectedArgsCount));
+ }
+
+ const actionResult = fn.apply(this, actionArgs);
+ // Remember result in case it is async. Assume parseAsync getting called on root.
+ let rootCommand = this;
+ while (rootCommand.parent) {
+ rootCommand = rootCommand.parent;
+ }
+ rootCommand._actionResults.push(actionResult);
+ };
+ this._actionHandler = listener;
+ return this;
+ };
+
+ /**
+ * Internal routine to check whether there is a clash storing option value with a Command property.
+ *
+ * @param {Option} option
+ * @api private
+ */
+
+ _checkForOptionNameClash(option) {
+ if (!this._storeOptionsAsProperties || this._storeOptionsAsPropertiesCalled) {
+ // Storing options safely, or user has been explicit and up to them.
+ return;
+ }
+ // User may override help, and hard to tell if worth warning.
+ if (option.name() === 'help') {
+ return;
+ }
+
+ const commandProperty = this._getOptionValue(option.attributeName());
+ if (commandProperty === undefined) {
+ // no clash
+ return;
+ }
+
+ let foundClash = true;
+ if (option.negate) {
+ // It is ok if define foo before --no-foo.
+ const positiveLongFlag = option.long.replace(/^--no-/, '--');
+ foundClash = !this._findOption(positiveLongFlag);
+ } else if (option.long) {
+ const negativeLongFlag = option.long.replace(/^--/, '--no-');
+ foundClash = !this._findOption(negativeLongFlag);
+ }
+
+ if (foundClash) {
+ throw new Error(`option '${option.name()}' clashes with existing property '${option.attributeName()}' on Command
+- call storeOptionsAsProperties(false) to store option values safely,
+- or call storeOptionsAsProperties(true) to suppress this check,
+- or change option name
+
+Read more on https://git.io/JJc0W`);
+ }
+ };
+
+ /**
+ * Internal implementation shared by .option() and .requiredOption()
+ *
+ * @param {Object} config
+ * @param {string} flags
+ * @param {string} description
+ * @param {Function|*} [fn] - custom option processing function or default value
+ * @param {*} [defaultValue]
+ * @return {Command} `this` command for chaining
+ * @api private
+ */
+
+ _optionEx(config, flags, description, fn, defaultValue) {
+ const option = new Option(flags, description);
+ const oname = option.name();
+ const name = option.attributeName();
+ option.mandatory = !!config.mandatory;
+
+ this._checkForOptionNameClash(option);
+
+ // default as 3rd arg
+ if (typeof fn !== 'function') {
+ if (fn instanceof RegExp) {
+ // This is a bit simplistic (especially no error messages), and probably better handled by caller using custom option processing.
+ // No longer documented in README, but still present for backwards compatibility.
+ const regex = fn;
+ fn = (val, def) => {
+ const m = regex.exec(val);
+ return m ? m[0] : def;
+ };
+ } else {
+ defaultValue = fn;
+ fn = null;
+ }
+ }
+
+ // preassign default value for --no-*, [optional], , or plain flag if boolean value
+ if (option.negate || option.optional || option.required || typeof defaultValue === 'boolean') {
+ // when --no-foo we make sure default is true, unless a --foo option is already defined
+ if (option.negate) {
+ const positiveLongFlag = option.long.replace(/^--no-/, '--');
+ defaultValue = this._findOption(positiveLongFlag) ? this._getOptionValue(name) : true;
+ }
+ // preassign only if we have a default
+ if (defaultValue !== undefined) {
+ this._setOptionValue(name, defaultValue);
+ option.defaultValue = defaultValue;
+ }
+ }
+
+ // register the option
+ this.options.push(option);
+
+ // when it's passed assign the value
+ // and conditionally invoke the callback
+ this.on('option:' + oname, (val) => {
+ const oldValue = this._getOptionValue(name);
+
+ // custom processing
+ if (val !== null && fn) {
+ val = fn(val, oldValue === undefined ? defaultValue : oldValue);
+ } else if (val !== null && option.variadic) {
+ if (oldValue === defaultValue || !Array.isArray(oldValue)) {
+ val = [val];
+ } else {
+ val = oldValue.concat(val);
+ }
+ }
+
+ // unassigned or boolean value
+ if (typeof oldValue === 'boolean' || typeof oldValue === 'undefined') {
+ // if no value, negate false, and we have a default, then use it!
+ if (val == null) {
+ this._setOptionValue(name, option.negate
+ ? false
+ : defaultValue || true);
+ } else {
+ this._setOptionValue(name, val);
+ }
+ } else if (val !== null) {
+ // reassign
+ this._setOptionValue(name, option.negate ? false : val);
+ }
+ });
+
+ return this;
+ };
+
+ /**
+ * Define option with `flags`, `description` and optional
+ * coercion `fn`.
+ *
+ * The `flags` string should contain both the short and long flags,
+ * separated by comma, a pipe or space. The following are all valid
+ * all will output this way when `--help` is used.
+ *
+ * "-p, --pepper"
+ * "-p|--pepper"
+ * "-p --pepper"
+ *
+ * Examples:
+ *
+ * // simple boolean defaulting to undefined
+ * program.option('-p, --pepper', 'add pepper');
+ *
+ * program.pepper
+ * // => undefined
+ *
+ * --pepper
+ * program.pepper
+ * // => true
+ *
+ * // simple boolean defaulting to true (unless non-negated option is also defined)
+ * program.option('-C, --no-cheese', 'remove cheese');
+ *
+ * program.cheese
+ * // => true
+ *
+ * --no-cheese
+ * program.cheese
+ * // => false
+ *
+ * // required argument
+ * program.option('-C, --chdir ', 'change the working directory');
+ *
+ * --chdir /tmp
+ * program.chdir
+ * // => "/tmp"
+ *
+ * // optional argument
+ * program.option('-c, --cheese [type]', 'add cheese [marble]');
+ *
+ * @param {string} flags
+ * @param {string} description
+ * @param {Function|*} [fn] - custom option processing function or default value
+ * @param {*} [defaultValue]
+ * @return {Command} `this` command for chaining
+ * @api public
+ */
+
+ option(flags, description, fn, defaultValue) {
+ return this._optionEx({}, flags, description, fn, defaultValue);
+ };
+
+ /**
+ * Add a required option which must have a value after parsing. This usually means
+ * the option must be specified on the command line. (Otherwise the same as .option().)
+ *
+ * The `flags` string should contain both the short and long flags, separated by comma, a pipe or space.
+ *
+ * @param {string} flags
+ * @param {string} description
+ * @param {Function|*} [fn] - custom option processing function or default value
+ * @param {*} [defaultValue]
+ * @return {Command} `this` command for chaining
+ * @api public
+ */
+
+ requiredOption(flags, description, fn, defaultValue) {
+ return this._optionEx({ mandatory: true }, flags, description, fn, defaultValue);
+ };
+
+ /**
+ * Alter parsing of short flags with optional values.
+ *
+ * Examples:
+ *
+ * // for `.option('-f,--flag [value]'):
+ * .combineFlagAndOptionalValue(true) // `-f80` is treated like `--flag=80`, this is the default behaviour
+ * .combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
+ *
+ * @param {Boolean} [arg] - if `true` or omitted, an optional value can be specified directly after the flag.
+ * @api public
+ */
+ combineFlagAndOptionalValue(arg) {
+ this._combineFlagAndOptionalValue = (arg === undefined) || arg;
+ return this;
+ };
+
+ /**
+ * Allow unknown options on the command line.
+ *
+ * @param {Boolean} [arg] - if `true` or omitted, no error will be thrown
+ * for unknown options.
+ * @api public
+ */
+ allowUnknownOption(arg) {
+ this._allowUnknownOption = (arg === undefined) || arg;
+ return this;
+ };
+
+ /**
+ * Whether to store option values as properties on command object,
+ * or store separately (specify false). In both cases the option values can be accessed using .opts().
+ *
+ * @param {boolean} value
+ * @return {Command} `this` command for chaining
+ * @api public
+ */
+
+ storeOptionsAsProperties(value) {
+ this._storeOptionsAsPropertiesCalled = true;
+ this._storeOptionsAsProperties = (value === undefined) || value;
+ if (this.options.length) {
+ throw new Error('call .storeOptionsAsProperties() before adding options');
+ }
+ return this;
+ };
+
+ /**
+ * Whether to pass command to action handler,
+ * or just the options (specify false).
+ *
+ * @param {boolean} value
+ * @return {Command} `this` command for chaining
+ * @api public
+ */
+
+ passCommandToAction(value) {
+ this._passCommandToAction = (value === undefined) || value;
+ return this;
+ };
+
+ /**
+ * Store option value
+ *
+ * @param {string} key
+ * @param {Object} value
+ * @api private
+ */
+
+ _setOptionValue(key, value) {
+ if (this._storeOptionsAsProperties) {
+ this[key] = value;
+ } else {
+ this._optionValues[key] = value;
+ }
+ };
+
+ /**
+ * Retrieve option value
+ *
+ * @param {string} key
+ * @return {Object} value
+ * @api private
+ */
+
+ _getOptionValue(key) {
+ if (this._storeOptionsAsProperties) {
+ return this[key];
+ }
+ return this._optionValues[key];
+ };
+
+ /**
+ * Parse `argv`, setting options and invoking commands when defined.
+ *
+ * The default expectation is that the arguments are from node and have the application as argv[0]
+ * and the script being run in argv[1], with user parameters after that.
+ *
+ * Examples:
+ *
+ * program.parse(process.argv);
+ * program.parse(); // implicitly use process.argv and auto-detect node vs electron conventions
+ * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
+ *
+ * @param {string[]} [argv] - optional, defaults to process.argv
+ * @param {Object} [parseOptions] - optionally specify style of options with from: node/user/electron
+ * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
+ * @return {Command} `this` command for chaining
+ * @api public
+ */
+
+ parse(argv, parseOptions) {
+ if (argv !== undefined && !Array.isArray(argv)) {
+ throw new Error('first parameter to parse must be array or undefined');
+ }
+ parseOptions = parseOptions || {};
+
+ // Default to using process.argv
+ if (argv === undefined) {
+ argv = process.argv;
+ // @ts-ignore
+ if (process.versions && process.versions.electron) {
+ parseOptions.from = 'electron';
+ }
+ }
+ this.rawArgs = argv.slice();
+
+ // make it a little easier for callers by supporting various argv conventions
+ let userArgs;
+ switch (parseOptions.from) {
+ case undefined:
+ case 'node':
+ this._scriptPath = argv[1];
+ userArgs = argv.slice(2);
+ break;
+ case 'electron':
+ // @ts-ignore
+ if (process.defaultApp) {
+ this._scriptPath = argv[1];
+ userArgs = argv.slice(2);
+ } else {
+ userArgs = argv.slice(1);
+ }
+ break;
+ case 'user':
+ userArgs = argv.slice(0);
+ break;
+ default:
+ throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`);
+ }
+ if (!this._scriptPath && process.mainModule) {
+ this._scriptPath = process.mainModule.filename;
+ }
+
+ // Guess name, used in usage in help.
+ this._name = this._name || (this._scriptPath && path.basename(this._scriptPath, path.extname(this._scriptPath)));
+
+ // Let's go!
+ this._parseCommand([], userArgs);
+
+ return this;
+ };
+
+ /**
+ * Parse `argv`, setting options and invoking commands when defined.
+ *
+ * Use parseAsync instead of parse if any of your action handlers are async. Returns a Promise.
+ *
+ * The default expectation is that the arguments are from node and have the application as argv[0]
+ * and the script being run in argv[1], with user parameters after that.
+ *
+ * Examples:
+ *
+ * program.parseAsync(process.argv);
+ * program.parseAsync(); // implicitly use process.argv and auto-detect node vs electron conventions
+ * program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
+ *
+ * @param {string[]} [argv]
+ * @param {Object} [parseOptions]
+ * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
+ * @return {Promise}
+ * @api public
+ */
+
+ parseAsync(argv, parseOptions) {
+ this.parse(argv, parseOptions);
+ return Promise.all(this._actionResults).then(() => this);
+ };
+
+ /**
+ * Execute a sub-command executable.
+ *
+ * @api private
+ */
+
+ _executeSubCommand(subcommand, args) {
+ args = args.slice();
+ let launchWithNode = false; // Use node for source targets so do not need to get permissions correct, and on Windows.
+ const sourceExt = ['.js', '.ts', '.tsx', '.mjs'];
+
+ // Not checking for help first. Unlikely to have mandatory and executable, and can't robustly test for help flags in external command.
+ this._checkForMissingMandatoryOptions();
+
+ // Want the entry script as the reference for command name and directory for searching for other files.
+ let scriptPath = this._scriptPath;
+ // Fallback in case not set, due to how Command created or called.
+ if (!scriptPath && process.mainModule) {
+ scriptPath = process.mainModule.filename;
+ }
+
+ let baseDir;
+ try {
+ const resolvedLink = fs.realpathSync(scriptPath);
+ baseDir = path.dirname(resolvedLink);
+ } catch (e) {
+ baseDir = '.'; // dummy, probably not going to find executable!
+ }
+
+ // name of the subcommand, like `pm-install`
+ let bin = path.basename(scriptPath, path.extname(scriptPath)) + '-' + subcommand._name;
+ if (subcommand._executableFile) {
+ bin = subcommand._executableFile;
+ }
+
+ const localBin = path.join(baseDir, bin);
+ if (fs.existsSync(localBin)) {
+ // prefer local `./` to bin in the $PATH
+ bin = localBin;
+ } else {
+ // Look for source files.
+ sourceExt.forEach((ext) => {
+ if (fs.existsSync(`${localBin}${ext}`)) {
+ bin = `${localBin}${ext}`;
+ }
+ });
+ }
+ launchWithNode = sourceExt.includes(path.extname(bin));
+
+ let proc;
+ if (process.platform !== 'win32') {
+ if (launchWithNode) {
+ args.unshift(bin);
+ // add executable arguments to spawn
+ args = incrementNodeInspectorPort(process.execArgv).concat(args);
+
+ proc = spawn(process.argv[0], args, { stdio: 'inherit' });
+ } else {
+ proc = spawn(bin, args, { stdio: 'inherit' });
+ }
+ } else {
+ args.unshift(bin);
+ // add executable arguments to spawn
+ args = incrementNodeInspectorPort(process.execArgv).concat(args);
+ proc = spawn(process.execPath, args, { stdio: 'inherit' });
+ }
+
+ const signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP'];
+ signals.forEach((signal) => {
+ // @ts-ignore
+ process.on(signal, () => {
+ if (proc.killed === false && proc.exitCode === null) {
+ proc.kill(signal);
+ }
+ });
+ });
+
+ // By default terminate process when spawned process terminates.
+ // Suppressing the exit if exitCallback defined is a bit messy and of limited use, but does allow process to stay running!
+ const exitCallback = this._exitCallback;
+ if (!exitCallback) {
+ proc.on('close', process.exit.bind(process));
+ } else {
+ proc.on('close', () => {
+ exitCallback(new CommanderError(process.exitCode || 0, 'commander.executeSubCommandAsync', '(close)'));
+ });
+ }
+ proc.on('error', (err) => {
+ // @ts-ignore
+ if (err.code === 'ENOENT') {
+ const executableMissing = `'${bin}' does not exist
+ - if '${subcommand._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
+ - if the default executable name is not suitable, use the executableFile option to supply a custom name`;
+ throw new Error(executableMissing);
+ // @ts-ignore
+ } else if (err.code === 'EACCES') {
+ throw new Error(`'${bin}' not executable`);
+ }
+ if (!exitCallback) {
+ process.exit(1);
+ } else {
+ const wrappedError = new CommanderError(1, 'commander.executeSubCommandAsync', '(error)');
+ wrappedError.nestedError = err;
+ exitCallback(wrappedError);
+ }
+ });
+
+ // Store the reference to the child process
+ this.runningCommand = proc;
+ };
+
+ /**
+ * @api private
+ */
+ _dispatchSubcommand(commandName, operands, unknown) {
+ const subCommand = this._findCommand(commandName);
+ if (!subCommand) this._helpAndError();
+
+ if (subCommand._executableHandler) {
+ this._executeSubCommand(subCommand, operands.concat(unknown));
+ } else {
+ subCommand._parseCommand(operands, unknown);
+ }
+ };
+
+ /**
+ * Process arguments in context of this command.
+ *
+ * @api private
+ */
+
+ _parseCommand(operands, unknown) {
+ const parsed = this.parseOptions(unknown);
+ operands = operands.concat(parsed.operands);
+ unknown = parsed.unknown;
+ this.args = operands.concat(unknown);
+
+ if (operands && this._findCommand(operands[0])) {
+ this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
+ } else if (this._lazyHasImplicitHelpCommand() && operands[0] === this._helpCommandName) {
+ if (operands.length === 1) {
+ this.help();
+ } else {
+ this._dispatchSubcommand(operands[1], [], [this._helpLongFlag]);
+ }
+ } else if (this._defaultCommandName) {
+ outputHelpIfRequested(this, unknown); // Run the help for default command from parent rather than passing to default command
+ this._dispatchSubcommand(this._defaultCommandName, operands, unknown);
+ } else {
+ if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
+ // probably missing subcommand and no handler, user needs help
+ this._helpAndError();
+ }
+
+ outputHelpIfRequested(this, parsed.unknown);
+ this._checkForMissingMandatoryOptions();
+ if (parsed.unknown.length > 0) {
+ this.unknownOption(parsed.unknown[0]);
+ }
+
+ if (this._actionHandler) {
+ const args = this.args.slice();
+ this._args.forEach((arg, i) => {
+ if (arg.required && args[i] == null) {
+ this.missingArgument(arg.name);
+ } else if (arg.variadic) {
+ args[i] = args.splice(i);
+ }
+ });
+
+ this._actionHandler(args);
+ this.emit('command:' + this.name(), operands, unknown);
+ } else if (operands.length) {
+ if (this._findCommand('*')) {
+ this._dispatchSubcommand('*', operands, unknown);
+ } else if (this.listenerCount('command:*')) {
+ this.emit('command:*', operands, unknown);
+ } else if (this.commands.length) {
+ this.unknownCommand();
+ }
+ } else if (this.commands.length) {
+ // This command has subcommands and nothing hooked up at this level, so display help.
+ this._helpAndError();
+ } else {
+ // fall through for caller to handle after calling .parse()
+ }
+ }
+ };
+
+ /**
+ * Find matching command.
+ *
+ * @api private
+ */
+ _findCommand(name) {
+ if (!name) return undefined;
+ return this.commands.find(cmd => cmd._name === name || cmd._aliases.includes(name));
+ };
+
+ /**
+ * Return an option matching `arg` if any.
+ *
+ * @param {string} arg
+ * @return {Option}
+ * @api private
+ */
+
+ _findOption(arg) {
+ return this.options.find(option => option.is(arg));
+ };
+
+ /**
+ * Display an error message if a mandatory option does not have a value.
+ * Lazy calling after checking for help flags from leaf subcommand.
+ *
+ * @api private
+ */
+
+ _checkForMissingMandatoryOptions() {
+ // Walk up hierarchy so can call in subcommand after checking for displaying help.
+ for (let cmd = this; cmd; cmd = cmd.parent) {
+ cmd.options.forEach((anOption) => {
+ if (anOption.mandatory && (cmd._getOptionValue(anOption.attributeName()) === undefined)) {
+ cmd.missingMandatoryOptionValue(anOption);
+ }
+ });
+ }
+ };
+
+ /**
+ * Parse options from `argv` removing known options,
+ * and return argv split into operands and unknown arguments.
+ *
+ * Examples:
+ *
+ * argv => operands, unknown
+ * --known kkk op => [op], []
+ * op --known kkk => [op], []
+ * sub --unknown uuu op => [sub], [--unknown uuu op]
+ * sub -- --unknown uuu op => [sub --unknown uuu op], []
+ *
+ * @param {String[]} argv
+ * @return {{operands: String[], unknown: String[]}}
+ * @api public
+ */
+
+ parseOptions(argv) {
+ const operands = []; // operands, not options or values
+ const unknown = []; // first unknown option and remaining unknown args
+ let dest = operands;
+ const args = argv.slice();
+
+ function maybeOption(arg) {
+ return arg.length > 1 && arg[0] === '-';
+ }
+
+ // parse options
+ let activeVariadicOption = null;
+ while (args.length) {
+ const arg = args.shift();
+
+ // literal
+ if (arg === '--') {
+ if (dest === unknown) dest.push(arg);
+ dest.push(...args);
+ break;
+ }
+
+ if (activeVariadicOption && !maybeOption(arg)) {
+ this.emit(`option:${activeVariadicOption.name()}`, arg);
+ continue;
+ }
+ activeVariadicOption = null;
+
+ if (maybeOption(arg)) {
+ const option = this._findOption(arg);
+ // recognised option, call listener to assign value with possible custom processing
+ if (option) {
+ if (option.required) {
+ const value = args.shift();
+ if (value === undefined) this.optionMissingArgument(option);
+ this.emit(`option:${option.name()}`, value);
+ } else if (option.optional) {
+ let value = null;
+ // historical behaviour is optional value is following arg unless an option
+ if (args.length > 0 && !maybeOption(args[0])) {
+ value = args.shift();
+ }
+ this.emit(`option:${option.name()}`, value);
+ } else { // boolean flag
+ this.emit(`option:${option.name()}`);
+ }
+ activeVariadicOption = option.variadic ? option : null;
+ continue;
+ }
+ }
+
+ // Look for combo options following single dash, eat first one if known.
+ if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') {
+ const option = this._findOption(`-${arg[1]}`);
+ if (option) {
+ if (option.required || (option.optional && this._combineFlagAndOptionalValue)) {
+ // option with value following in same argument
+ this.emit(`option:${option.name()}`, arg.slice(2));
+ } else {
+ // boolean option, emit and put back remainder of arg for further processing
+ this.emit(`option:${option.name()}`);
+ args.unshift(`-${arg.slice(2)}`);
+ }
+ continue;
+ }
+ }
+
+ // Look for known long flag with value, like --foo=bar
+ if (/^--[^=]+=/.test(arg)) {
+ const index = arg.indexOf('=');
+ const option = this._findOption(arg.slice(0, index));
+ if (option && (option.required || option.optional)) {
+ this.emit(`option:${option.name()}`, arg.slice(index + 1));
+ continue;
+ }
+ }
+
+ // looks like an option but unknown, unknowns from here
+ if (arg.length > 1 && arg[0] === '-') {
+ dest = unknown;
+ }
+
+ // add arg
+ dest.push(arg);
+ }
+
+ return { operands, unknown };
+ };
+
+ /**
+ * Return an object containing options as key-value pairs
+ *
+ * @return {Object}
+ * @api public
+ */
+ opts() {
+ if (this._storeOptionsAsProperties) {
+ // Preserve original behaviour so backwards compatible when still using properties
+ const result = {};
+ const len = this.options.length;
+
+ for (let i = 0; i < len; i++) {
+ const key = this.options[i].attributeName();
+ result[key] = key === this._versionOptionName ? this._version : this[key];
+ }
+ return result;
+ }
+
+ return this._optionValues;
+ };
+
+ /**
+ * Argument `name` is missing.
+ *
+ * @param {string} name
+ * @api private
+ */
+
+ missingArgument(name) {
+ const message = `error: missing required argument '${name}'`;
+ console.error(message);
+ this._exit(1, 'commander.missingArgument', message);
+ };
+
+ /**
+ * `Option` is missing an argument, but received `flag` or nothing.
+ *
+ * @param {Option} option
+ * @param {string} [flag]
+ * @api private
+ */
+
+ optionMissingArgument(option, flag) {
+ let message;
+ if (flag) {
+ message = `error: option '${option.flags}' argument missing, got '${flag}'`;
+ } else {
+ message = `error: option '${option.flags}' argument missing`;
+ }
+ console.error(message);
+ this._exit(1, 'commander.optionMissingArgument', message);
+ };
+
+ /**
+ * `Option` does not have a value, and is a mandatory option.
+ *
+ * @param {Option} option
+ * @api private
+ */
+
+ missingMandatoryOptionValue(option) {
+ const message = `error: required option '${option.flags}' not specified`;
+ console.error(message);
+ this._exit(1, 'commander.missingMandatoryOptionValue', message);
+ };
+
+ /**
+ * Unknown option `flag`.
+ *
+ * @param {string} flag
+ * @api private
+ */
+
+ unknownOption(flag) {
+ if (this._allowUnknownOption) return;
+ const message = `error: unknown option '${flag}'`;
+ console.error(message);
+ this._exit(1, 'commander.unknownOption', message);
+ };
+
+ /**
+ * Unknown command.
+ *
+ * @api private
+ */
+
+ unknownCommand() {
+ const partCommands = [this.name()];
+ for (let parentCmd = this.parent; parentCmd; parentCmd = parentCmd.parent) {
+ partCommands.unshift(parentCmd.name());
+ }
+ const fullCommand = partCommands.join(' ');
+ const message = `error: unknown command '${this.args[0]}'.` +
+ (this._hasHelpOption ? ` See '${fullCommand} ${this._helpLongFlag}'.` : '');
+ console.error(message);
+ this._exit(1, 'commander.unknownCommand', message);
+ };
+
+ /**
+ * Set the program version to `str`.
+ *
+ * This method auto-registers the "-V, --version" flag
+ * which will print the version number when passed.
+ *
+ * You can optionally supply the flags and description to override the defaults.
+ *
+ * @param {string} str
+ * @param {string} [flags]
+ * @param {string} [description]
+ * @return {this | string} `this` command for chaining, or version string if no arguments
+ * @api public
+ */
+
+ version(str, flags, description) {
+ if (str === undefined) return this._version;
+ this._version = str;
+ flags = flags || '-V, --version';
+ description = description || 'output the version number';
+ const versionOption = new Option(flags, description);
+ this._versionOptionName = versionOption.attributeName();
+ this.options.push(versionOption);
+ this.on('option:' + versionOption.name(), () => {
+ process.stdout.write(str + '\n');
+ this._exit(0, 'commander.version', str);
+ });
+ return this;
+ };
+
+ /**
+ * Set the description to `str`.
+ *
+ * @param {string} str
+ * @param {Object} [argsDescription]
+ * @return {string|Command}
+ * @api public
+ */
+
+ description(str, argsDescription) {
+ if (str === undefined && argsDescription === undefined) return this._description;
+ this._description = str;
+ this._argsDescription = argsDescription;
+ return this;
+ };
+
+ /**
+ * Set an alias for the command.
+ *
+ * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
+ *
+ * @param {string} [alias]
+ * @return {string|Command}
+ * @api public
+ */
+
+ alias(alias) {
+ if (alias === undefined) return this._aliases[0]; // just return first, for backwards compatibility
+
+ let command = this;
+ if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
+ // assume adding alias for last added executable subcommand, rather than this
+ command = this.commands[this.commands.length - 1];
+ }
+
+ if (alias === command._name) throw new Error('Command alias can\'t be the same as its name');
+
+ command._aliases.push(alias);
+ return this;
+ };
+
+ /**
+ * Set aliases for the command.
+ *
+ * Only the first alias is shown in the auto-generated help.
+ *
+ * @param {string[]} [aliases]
+ * @return {string[]|Command}
+ * @api public
+ */
+
+ aliases(aliases) {
+ // Getter for the array of aliases is the main reason for having aliases() in addition to alias().
+ if (aliases === undefined) return this._aliases;
+
+ aliases.forEach((alias) => this.alias(alias));
+ return this;
+ };
+
+ /**
+ * Set / get the command usage `str`.
+ *
+ * @param {string} [str]
+ * @return {String|Command}
+ * @api public
+ */
+
+ usage(str) {
+ if (str === undefined) {
+ if (this._usage) return this._usage;
+
+ const args = this._args.map((arg) => {
+ return humanReadableArgName(arg);
+ });
+ return [].concat(
+ (this.options.length || this._hasHelpOption ? '[options]' : []),
+ (this.commands.length ? '[command]' : []),
+ (this._args.length ? args : [])
+ ).join(' ');
+ }
+
+ this._usage = str;
+ return this;
+ };
+
+ /**
+ * Get or set the name of the command
+ *
+ * @param {string} [str]
+ * @return {String|Command}
+ * @api public
+ */
+
+ name(str) {
+ if (str === undefined) return this._name;
+ this._name = str;
+ return this;
+ };
+
+ /**
+ * Return prepared commands.
+ *
+ * @return {Array}
+ * @api private
+ */
+
+ prepareCommands() {
+ const commandDetails = this.commands.filter((cmd) => {
+ return !cmd._hidden;
+ }).map((cmd) => {
+ const args = cmd._args.map((arg) => {
+ return humanReadableArgName(arg);
+ }).join(' ');
+
+ return [
+ cmd._name +
+ (cmd._aliases[0] ? '|' + cmd._aliases[0] : '') +
+ (cmd.options.length ? ' [options]' : '') +
+ (args ? ' ' + args : ''),
+ cmd._description
+ ];
+ });
+
+ if (this._lazyHasImplicitHelpCommand()) {
+ commandDetails.push([this._helpCommandnameAndArgs, this._helpCommandDescription]);
+ }
+ return commandDetails;
+ };
+
+ /**
+ * Return the largest command length.
+ *
+ * @return {number}
+ * @api private
+ */
+
+ largestCommandLength() {
+ const commands = this.prepareCommands();
+ return commands.reduce((max, command) => {
+ return Math.max(max, command[0].length);
+ }, 0);
+ };
+
+ /**
+ * Return the largest option length.
+ *
+ * @return {number}
+ * @api private
+ */
+
+ largestOptionLength() {
+ const options = [].slice.call(this.options);
+ options.push({
+ flags: this._helpFlags
+ });
+
+ return options.reduce((max, option) => {
+ return Math.max(max, option.flags.length);
+ }, 0);
+ };
+
+ /**
+ * Return the largest arg length.
+ *
+ * @return {number}
+ * @api private
+ */
+
+ largestArgLength() {
+ return this._args.reduce((max, arg) => {
+ return Math.max(max, arg.name.length);
+ }, 0);
+ };
+
+ /**
+ * Return the pad width.
+ *
+ * @return {number}
+ * @api private
+ */
+
+ padWidth() {
+ let width = this.largestOptionLength();
+ if (this._argsDescription && this._args.length) {
+ if (this.largestArgLength() > width) {
+ width = this.largestArgLength();
+ }
+ }
+
+ if (this.commands && this.commands.length) {
+ if (this.largestCommandLength() > width) {
+ width = this.largestCommandLength();
+ }
+ }
+
+ return width;
+ };
+
+ /**
+ * Return help for options.
+ *
+ * @return {string}
+ * @api private
+ */
+
+ optionHelp() {
+ const width = this.padWidth();
+ const columns = process.stdout.columns || 80;
+ const descriptionWidth = columns - width - 4;
+ function padOptionDetails(flags, description) {
+ return pad(flags, width) + ' ' + optionalWrap(description, descriptionWidth, width + 2);
+ };
+
+ // Explicit options (including version)
+ const help = this.options.map((option) => {
+ const fullDesc = option.description +
+ ((!option.negate && option.defaultValue !== undefined) ? ' (default: ' + JSON.stringify(option.defaultValue) + ')' : '');
+ return padOptionDetails(option.flags, fullDesc);
+ });
+
+ // Implicit help
+ const showShortHelpFlag = this._hasHelpOption && this._helpShortFlag && !this._findOption(this._helpShortFlag);
+ const showLongHelpFlag = this._hasHelpOption && !this._findOption(this._helpLongFlag);
+ if (showShortHelpFlag || showLongHelpFlag) {
+ let helpFlags = this._helpFlags;
+ if (!showShortHelpFlag) {
+ helpFlags = this._helpLongFlag;
+ } else if (!showLongHelpFlag) {
+ helpFlags = this._helpShortFlag;
+ }
+ help.push(padOptionDetails(helpFlags, this._helpDescription));
+ }
+
+ return help.join('\n');
+ };
+
+ /**
+ * Return command help documentation.
+ *
+ * @return {string}
+ * @api private
+ */
+
+ commandHelp() {
+ if (!this.commands.length && !this._lazyHasImplicitHelpCommand()) return '';
+
+ const commands = this.prepareCommands();
+ const width = this.padWidth();
+
+ const columns = process.stdout.columns || 80;
+ const descriptionWidth = columns - width - 4;
+
+ return [
+ 'Commands:',
+ commands.map((cmd) => {
+ const desc = cmd[1] ? ' ' + cmd[1] : '';
+ return (desc ? pad(cmd[0], width) : cmd[0]) + optionalWrap(desc, descriptionWidth, width + 2);
+ }).join('\n').replace(/^/gm, ' '),
+ ''
+ ].join('\n');
+ };
+
+ /**
+ * Return program help documentation.
+ *
+ * @return {string}
+ * @api public
+ */
+
+ helpInformation() {
+ let desc = [];
+ if (this._description) {
+ desc = [
+ this._description,
+ ''
+ ];
+
+ const argsDescription = this._argsDescription;
+ if (argsDescription && this._args.length) {
+ const width = this.padWidth();
+ const columns = process.stdout.columns || 80;
+ const descriptionWidth = columns - width - 5;
+ desc.push('Arguments:');
+ this._args.forEach((arg) => {
+ desc.push(' ' + pad(arg.name, width) + ' ' + wrap(argsDescription[arg.name] || '', descriptionWidth, width + 4));
+ });
+ desc.push('');
+ }
+ }
+
+ let cmdName = this._name;
+ if (this._aliases[0]) {
+ cmdName = cmdName + '|' + this._aliases[0];
+ }
+ let parentCmdNames = '';
+ for (let parentCmd = this.parent; parentCmd; parentCmd = parentCmd.parent) {
+ parentCmdNames = parentCmd.name() + ' ' + parentCmdNames;
+ }
+ const usage = [
+ 'Usage: ' + parentCmdNames + cmdName + ' ' + this.usage(),
+ ''
+ ];
+
+ let cmds = [];
+ const commandHelp = this.commandHelp();
+ if (commandHelp) cmds = [commandHelp];
+
+ let options = [];
+ if (this._hasHelpOption || this.options.length > 0) {
+ options = [
+ 'Options:',
+ '' + this.optionHelp().replace(/^/gm, ' '),
+ ''
+ ];
+ }
+
+ return usage
+ .concat(desc)
+ .concat(options)
+ .concat(cmds)
+ .join('\n');
+ };
+
+ /**
+ * Output help information for this command.
+ *
+ * When listener(s) are available for the helpLongFlag
+ * those callbacks are invoked.
+ *
+ * @api public
+ */
+
+ outputHelp(cb) {
+ if (!cb) {
+ cb = (passthru) => {
+ return passthru;
+ };
+ }
+ const cbOutput = cb(this.helpInformation());
+ if (typeof cbOutput !== 'string' && !Buffer.isBuffer(cbOutput)) {
+ throw new Error('outputHelp callback must return a string or a Buffer');
+ }
+ process.stdout.write(cbOutput);
+ this.emit(this._helpLongFlag);
+ };
+
+ /**
+ * You can pass in flags and a description to override the help
+ * flags and help description for your command. Pass in false to
+ * disable the built-in help option.
+ *
+ * @param {string | boolean} [flags]
+ * @param {string} [description]
+ * @return {Command} `this` command for chaining
+ * @api public
+ */
+
+ helpOption(flags, description) {
+ if (typeof flags === 'boolean') {
+ this._hasHelpOption = flags;
+ return this;
+ }
+ this._helpFlags = flags || this._helpFlags;
+ this._helpDescription = description || this._helpDescription;
+
+ const helpFlags = _parseOptionFlags(this._helpFlags);
+ this._helpShortFlag = helpFlags.shortFlag;
+ this._helpLongFlag = helpFlags.longFlag;
+
+ return this;
+ };
+
+ /**
+ * Output help information and exit.
+ *
+ * @param {Function} [cb]
+ * @api public
+ */
+
+ help(cb) {
+ this.outputHelp(cb);
+ // exitCode: preserving original behaviour which was calling process.exit()
+ // message: do not have all displayed text available so only passing placeholder.
+ this._exit(process.exitCode || 0, 'commander.help', '(outputHelp)');
+ };
+
+ /**
+ * Output help information and exit. Display for error situations.
+ *
+ * @api private
+ */
+
+ _helpAndError() {
+ this.outputHelp();
+ // message: do not have all displayed text available so only passing placeholder.
+ this._exit(1, 'commander.help', '(outputHelp)');
+ };
+};
+
+/**
+ * Expose the root command.
+ */
+
+exports = module.exports = new Command();
+exports.program = exports; // More explicit access to global command.
+
+/**
+ * Expose classes
+ */
+
+exports.Command = Command;
+exports.Option = Option;
+exports.CommanderError = CommanderError;
+
+/**
+ * Camel-case the given `flag`
+ *
+ * @param {string} flag
+ * @return {string}
+ * @api private
+ */
+
+function camelcase(flag) {
+ return flag.split('-').reduce((str, word) => {
+ return str + word[0].toUpperCase() + word.slice(1);
+ });
+}
+
+/**
+ * Pad `str` to `width`.
+ *
+ * @param {string} str
+ * @param {number} width
+ * @return {string}
+ * @api private
+ */
+
+function pad(str, width) {
+ const len = Math.max(0, width - str.length);
+ return str + Array(len + 1).join(' ');
+}
+
+/**
+ * Wraps the given string with line breaks at the specified width while breaking
+ * words and indenting every but the first line on the left.
+ *
+ * @param {string} str
+ * @param {number} width
+ * @param {number} indent
+ * @return {string}
+ * @api private
+ */
+function wrap(str, width, indent) {
+ const regex = new RegExp('.{1,' + (width - 1) + '}([\\s\u200B]|$)|[^\\s\u200B]+?([\\s\u200B]|$)', 'g');
+ const lines = str.match(regex) || [];
+ return lines.map((line, i) => {
+ if (line.slice(-1) === '\n') {
+ line = line.slice(0, line.length - 1);
+ }
+ return ((i > 0 && indent) ? Array(indent + 1).join(' ') : '') + line.trimRight();
+ }).join('\n');
+}
+
+/**
+ * Optionally wrap the given str to a max width of width characters per line
+ * while indenting with indent spaces. Do not wrap if insufficient width or
+ * string is manually formatted.
+ *
+ * @param {string} str
+ * @param {number} width
+ * @param {number} indent
+ * @return {string}
+ * @api private
+ */
+function optionalWrap(str, width, indent) {
+ // Detect manually wrapped and indented strings by searching for line breaks
+ // followed by multiple spaces/tabs.
+ if (str.match(/[\n]\s+/)) return str;
+ // Do not wrap to narrow columns (or can end up with a word per line).
+ const minWidth = 40;
+ if (width < minWidth) return str;
+
+ return wrap(str, width, indent);
+}
+
+/**
+ * Output help information if help flags specified
+ *
+ * @param {Command} cmd - command to output help for
+ * @param {Array} args - array of options to search for help flags
+ * @api private
+ */
+
+function outputHelpIfRequested(cmd, args) {
+ const helpOption = cmd._hasHelpOption && args.find(arg => arg === cmd._helpLongFlag || arg === cmd._helpShortFlag);
+ if (helpOption) {
+ cmd.outputHelp();
+ // (Do not have all displayed text available so only passing placeholder.)
+ cmd._exit(0, 'commander.helpDisplayed', '(outputHelp)');
+ }
+}
+
+/**
+ * Takes an argument and returns its human readable equivalent for help usage.
+ *
+ * @param {Object} arg
+ * @return {string}
+ * @api private
+ */
+
+function humanReadableArgName(arg) {
+ const nameOutput = arg.name + (arg.variadic === true ? '...' : '');
+
+ return arg.required
+ ? '<' + nameOutput + '>'
+ : '[' + nameOutput + ']';
+}
+
+/**
+ * Parse the short and long flag out of something like '-m,--mixed '
+ *
+ * @api private
+ */
+
+function _parseOptionFlags(flags) {
+ let shortFlag;
+ let longFlag;
+ // Use original very loose parsing to maintain backwards compatibility for now,
+ // which allowed for example unintended `-sw, --short-word` [sic].
+ const flagParts = flags.split(/[ |,]+/);
+ if (flagParts.length > 1 && !/^[[<]/.test(flagParts[1])) shortFlag = flagParts.shift();
+ longFlag = flagParts.shift();
+ // Add support for lone short flag without significantly changing parsing!
+ if (!shortFlag && /^-[^-]$/.test(longFlag)) {
+ shortFlag = longFlag;
+ longFlag = undefined;
+ }
+ return { shortFlag, longFlag };
+}
+
+/**
+ * Scan arguments and increment port number for inspect calls (to avoid conflicts when spawning new command).
+ *
+ * @param {string[]} args - array of arguments from node.execArgv
+ * @returns {string[]}
+ * @api private
+ */
+
+function incrementNodeInspectorPort(args) {
+ // Testing for these options:
+ // --inspect[=[host:]port]
+ // --inspect-brk[=[host:]port]
+ // --inspect-port=[host:]port
+ return args.map((arg) => {
+ if (!arg.startsWith('--inspect')) {
+ return arg;
+ }
+ let debugOption;
+ let debugHost = '127.0.0.1';
+ let debugPort = '9229';
+ let match;
+ if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
+ // e.g. --inspect
+ debugOption = match[1];
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
+ debugOption = match[1];
+ if (/^\d+$/.test(match[3])) {
+ // e.g. --inspect=1234
+ debugPort = match[3];
+ } else {
+ // e.g. --inspect=localhost
+ debugHost = match[3];
+ }
+ } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
+ // e.g. --inspect=localhost:1234
+ debugOption = match[1];
+ debugHost = match[3];
+ debugPort = match[4];
+ }
+
+ if (debugOption && debugPort !== '0') {
+ return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
+ }
+ return arg;
+ });
+}
diff --git a/temporary_modules/trezor-connect/node_modules/commander/package.json b/temporary_modules/trezor-connect/node_modules/commander/package.json
new file mode 100644
index 00000000..69a67b90
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/commander/package.json
@@ -0,0 +1,51 @@
+{
+ "name": "commander",
+ "version": "6.2.1",
+ "description": "the complete solution for node.js command-line programs",
+ "keywords": [
+ "commander",
+ "command",
+ "option",
+ "parser",
+ "cli",
+ "argument",
+ "args",
+ "argv"
+ ],
+ "author": "TJ Holowaychuk ",
+ "license": "MIT",
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/tj/commander.js.git"
+ },
+ "scripts": {
+ "lint": "eslint index.js \"tests/**/*.js\"",
+ "typescript-lint": "eslint typings/*.ts",
+ "test": "jest && npm run test-typings",
+ "test-typings": "tsc -p tsconfig.json"
+ },
+ "main": "index",
+ "files": [
+ "index.js",
+ "typings/index.d.ts"
+ ],
+ "dependencies": {},
+ "devDependencies": {
+ "@types/jest": "^26.0.15",
+ "@types/node": "^14.14.2",
+ "@typescript-eslint/eslint-plugin": "^4.5.0",
+ "eslint": "^7.11.0",
+ "eslint-config-standard-with-typescript": "^19.0.1",
+ "eslint-plugin-jest": "^24.1.0",
+ "jest": "^26.6.0",
+ "standard": "^15.0.0",
+ "typescript": "^4.0.3"
+ },
+ "typings": "typings/index.d.ts",
+ "jest": {
+ "collectCoverage": true
+ },
+ "engines": {
+ "node": ">= 6"
+ }
+}
diff --git a/temporary_modules/trezor-connect/node_modules/commander/typings/index.d.ts b/temporary_modules/trezor-connect/node_modules/commander/typings/index.d.ts
new file mode 100644
index 00000000..479446d3
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/commander/typings/index.d.ts
@@ -0,0 +1,410 @@
+// Type definitions for commander
+// Original definitions by: Alan Agius , Marcelo Dezem , vvakame , Jules Randolph
+
+declare namespace commander {
+
+ interface CommanderError extends Error {
+ code: string;
+ exitCode: number;
+ message: string;
+ nestedError?: string;
+ }
+ type CommanderErrorConstructor = new (exitCode: number, code: string, message: string) => CommanderError;
+
+ interface Option {
+ flags: string;
+ required: boolean; // A value must be supplied when the option is specified.
+ optional: boolean; // A value is optional when the option is specified.
+ mandatory: boolean; // The option must have a value after parsing, which usually means it must be specified on command line.
+ bool: boolean;
+ short?: string;
+ long: string;
+ description: string;
+ }
+ type OptionConstructor = new (flags: string, description?: string) => Option;
+
+ interface ParseOptions {
+ from: 'node' | 'electron' | 'user';
+ }
+
+ interface Command {
+ [key: string]: any; // options as properties
+
+ args: string[];
+
+ commands: Command[];
+
+ /**
+ * Set the program version to `str`.
+ *
+ * This method auto-registers the "-V, --version" flag
+ * which will print the version number when passed.
+ *
+ * You can optionally supply the flags and description to override the defaults.
+ */
+ version(str: string, flags?: string, description?: string): this;
+
+ /**
+ * Define a command, implemented using an action handler.
+ *
+ * @remarks
+ * The command description is supplied using `.description`, not as a parameter to `.command`.
+ *
+ * @example
+ * ```ts
+ * program
+ * .command('clone [destination]')
+ * .description('clone a repository into a newly created directory')
+ * .action((source, destination) => {
+ * console.log('clone command called');
+ * });
+ * ```
+ *
+ * @param nameAndArgs - command name and arguments, args are `` or `[optional]` and last may also be `variadic...`
+ * @param opts - configuration options
+ * @returns new command
+ */
+ command(nameAndArgs: string, opts?: CommandOptions): ReturnType;
+ /**
+ * Define a command, implemented in a separate executable file.
+ *
+ * @remarks
+ * The command description is supplied as the second parameter to `.command`.
+ *
+ * @example
+ * ```ts
+ * program
+ * .command('start ', 'start named service')
+ * .command('stop [service]', 'stop named service, or all if no name supplied');
+ * ```
+ *
+ * @param nameAndArgs - command name and arguments, args are `` or `[optional]` and last may also be `variadic...`
+ * @param description - description of executable command
+ * @param opts - configuration options
+ * @returns `this` command for chaining
+ */
+ command(nameAndArgs: string, description: string, opts?: commander.ExecutableCommandOptions): this;
+
+ /**
+ * Factory routine to create a new unattached command.
+ *
+ * See .command() for creating an attached subcommand, which uses this routine to
+ * create the command. You can override createCommand to customise subcommands.
+ */
+ createCommand(name?: string): Command;
+
+ /**
+ * Add a prepared subcommand.
+ *
+ * See .command() for creating an attached subcommand which inherits settings from its parent.
+ *
+ * @returns `this` command for chaining
+ */
+ addCommand(cmd: Command, opts?: CommandOptions): this;
+
+ /**
+ * Define argument syntax for command.
+ *
+ * @returns `this` command for chaining
+ */
+ arguments(desc: string): this;
+
+ /**
+ * Override default decision whether to add implicit help command.
+ *
+ * addHelpCommand() // force on
+ * addHelpCommand(false); // force off
+ * addHelpCommand('help [cmd]', 'display help for [cmd]'); // force on with custom details
+ *
+ * @returns `this` command for chaining
+ */
+ addHelpCommand(enableOrNameAndArgs?: string | boolean, description?: string): this;
+
+ /**
+ * Register callback to use as replacement for calling process.exit.
+ */
+ exitOverride(callback?: (err: CommanderError) => never|void): this;
+
+ /**
+ * Register callback `fn` for the command.
+ *
+ * @example
+ * program
+ * .command('help')
+ * .description('display verbose help')
+ * .action(function() {
+ * // output help here
+ * });
+ *
+ * @returns `this` command for chaining
+ */
+ action(fn: (...args: any[]) => void | Promise): this;
+
+ /**
+ * Define option with `flags`, `description` and optional
+ * coercion `fn`.
+ *
+ * The `flags` string should contain both the short and long flags,
+ * separated by comma, a pipe or space. The following are all valid
+ * all will output this way when `--help` is used.
+ *
+ * "-p, --pepper"
+ * "-p|--pepper"
+ * "-p --pepper"
+ *
+ * @example
+ * // simple boolean defaulting to false
+ * program.option('-p, --pepper', 'add pepper');
+ *
+ * --pepper
+ * program.pepper
+ * // => Boolean
+ *
+ * // simple boolean defaulting to true
+ * program.option('-C, --no-cheese', 'remove cheese');
+ *
+ * program.cheese
+ * // => true
+ *
+ * --no-cheese
+ * program.cheese
+ * // => false
+ *
+ * // required argument
+ * program.option('-C, --chdir ', 'change the working directory');
+ *
+ * --chdir /tmp
+ * program.chdir
+ * // => "/tmp"
+ *
+ * // optional argument
+ * program.option('-c, --cheese [type]', 'add cheese [marble]');
+ *
+ * @returns `this` command for chaining
+ */
+ option(flags: string, description?: string, defaultValue?: string | boolean): this;
+ option(flags: string, description: string, regexp: RegExp, defaultValue?: string | boolean): this;
+ option(flags: string, description: string, fn: (value: string, previous: T) => T, defaultValue?: T): this;
+
+ /**
+ * Define a required option, which must have a value after parsing. This usually means
+ * the option must be specified on the command line. (Otherwise the same as .option().)
+ *
+ * The `flags` string should contain both the short and long flags, separated by comma, a pipe or space.
+ */
+ requiredOption(flags: string, description?: string, defaultValue?: string | boolean): this;
+ requiredOption(flags: string, description: string, regexp: RegExp, defaultValue?: string | boolean): this;
+ requiredOption(flags: string, description: string, fn: (value: string, previous: T) => T, defaultValue?: T): this;
+
+ /**
+ * Whether to store option values as properties on command object,
+ * or store separately (specify false). In both cases the option values can be accessed using .opts().
+ *
+ * @returns `this` command for chaining
+ */
+ storeOptionsAsProperties(value?: boolean): this;
+
+ /**
+ * Whether to pass command to action handler,
+ * or just the options (specify false).
+ *
+ * @returns `this` command for chaining
+ */
+ passCommandToAction(value?: boolean): this;
+
+ /**
+ * Alter parsing of short flags with optional values.
+ *
+ * @example
+ * // for `.option('-f,--flag [value]'):
+ * .combineFlagAndOptionalValue(true) // `-f80` is treated like `--flag=80`, this is the default behaviour
+ * .combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
+ *
+ * @returns `this` command for chaining
+ */
+ combineFlagAndOptionalValue(arg?: boolean): this;
+
+ /**
+ * Allow unknown options on the command line.
+ *
+ * @param [arg] if `true` or omitted, no error will be thrown for unknown options.
+ * @returns `this` command for chaining
+ */
+ allowUnknownOption(arg?: boolean): this;
+
+ /**
+ * Parse `argv`, setting options and invoking commands when defined.
+ *
+ * The default expectation is that the arguments are from node and have the application as argv[0]
+ * and the script being run in argv[1], with user parameters after that.
+ *
+ * Examples:
+ *
+ * program.parse(process.argv);
+ * program.parse(); // implicitly use process.argv and auto-detect node vs electron conventions
+ * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
+ *
+ * @returns `this` command for chaining
+ */
+ parse(argv?: string[], options?: ParseOptions): this;
+
+ /**
+ * Parse `argv`, setting options and invoking commands when defined.
+ *
+ * Use parseAsync instead of parse if any of your action handlers are async. Returns a Promise.
+ *
+ * The default expectation is that the arguments are from node and have the application as argv[0]
+ * and the script being run in argv[1], with user parameters after that.
+ *
+ * Examples:
+ *
+ * program.parseAsync(process.argv);
+ * program.parseAsync(); // implicitly use process.argv and auto-detect node vs electron conventions
+ * program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
+ *
+ * @returns Promise
+ */
+ parseAsync(argv?: string[], options?: ParseOptions): Promise;
+
+ /**
+ * Parse options from `argv` removing known options,
+ * and return argv split into operands and unknown arguments.
+ *
+ * @example
+ * argv => operands, unknown
+ * --known kkk op => [op], []
+ * op --known kkk => [op], []
+ * sub --unknown uuu op => [sub], [--unknown uuu op]
+ * sub -- --unknown uuu op => [sub --unknown uuu op], []
+ */
+ parseOptions(argv: string[]): commander.ParseOptionsResult;
+
+ /**
+ * Return an object containing options as key-value pairs
+ */
+ opts(): { [key: string]: any };
+
+ /**
+ * Set the description.
+ *
+ * @returns `this` command for chaining
+ */
+ description(str: string, argsDescription?: {[argName: string]: string}): this;
+ /**
+ * Get the description.
+ */
+ description(): string;
+
+ /**
+ * Set an alias for the command.
+ *
+ * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
+ *
+ * @returns `this` command for chaining
+ */
+ alias(alias: string): this;
+ /**
+ * Get alias for the command.
+ */
+ alias(): string;
+
+ /**
+ * Set aliases for the command.
+ *
+ * Only the first alias is shown in the auto-generated help.
+ *
+ * @returns `this` command for chaining
+ */
+ aliases(aliases: string[]): this;
+ /**
+ * Get aliases for the command.
+ */
+ aliases(): string[];
+
+ /**
+ * Set the command usage.
+ *
+ * @returns `this` command for chaining
+ */
+ usage(str: string): this;
+ /**
+ * Get the command usage.
+ */
+ usage(): string;
+
+ /**
+ * Set the name of the command.
+ *
+ * @returns `this` command for chaining
+ */
+ name(str: string): this;
+ /**
+ * Get the name of the command.
+ */
+ name(): string;
+
+ /**
+ * Output help information for this command.
+ *
+ * When listener(s) are available for the helpLongFlag
+ * those callbacks are invoked.
+ */
+ outputHelp(cb?: (str: string) => string): void;
+
+ /**
+ * Return command help documentation.
+ */
+ helpInformation(): string;
+
+ /**
+ * You can pass in flags and a description to override the help
+ * flags and help description for your command. Pass in false
+ * to disable the built-in help option.
+ */
+ helpOption(flags?: string | boolean, description?: string): this;
+
+ /**
+ * Output help information and exit.
+ */
+ help(cb?: (str: string) => string): never;
+
+ /**
+ * Add a listener (callback) for when events occur. (Implemented using EventEmitter.)
+ *
+ * @example
+ * program
+ * .on('--help', () -> {
+ * console.log('See web site for more information.');
+ * });
+ */
+ on(event: string | symbol, listener: (...args: any[]) => void): this;
+ }
+ type CommandConstructor = new (name?: string) => Command;
+
+ interface CommandOptions {
+ noHelp?: boolean; // old name for hidden
+ hidden?: boolean;
+ isDefault?: boolean;
+ }
+ interface ExecutableCommandOptions extends CommandOptions {
+ executableFile?: string;
+ }
+
+ interface ParseOptionsResult {
+ operands: string[];
+ unknown: string[];
+ }
+
+ interface CommanderStatic extends Command {
+ program: Command;
+ Command: CommandConstructor;
+ Option: OptionConstructor;
+ CommanderError: CommanderErrorConstructor;
+ }
+
+}
+
+// Declaring namespace AND global
+// eslint-disable-next-line @typescript-eslint/no-redeclare
+declare const commander: commander.CommanderStatic;
+export = commander;
diff --git a/temporary_modules/trezor-connect/node_modules/cross-spawn/CHANGELOG.md b/temporary_modules/trezor-connect/node_modules/cross-spawn/CHANGELOG.md
new file mode 100644
index 00000000..d07c9e5c
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/cross-spawn/CHANGELOG.md
@@ -0,0 +1,130 @@
+# Changelog
+
+All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
+
+### [7.0.3](https://github.com/moxystudio/node-cross-spawn/compare/v7.0.2...v7.0.3) (2020-05-25)
+
+
+### Bug Fixes
+
+* detect path key based on correct environment ([#133](https://github.com/moxystudio/node-cross-spawn/issues/133)) ([159e7e9](https://github.com/moxystudio/node-cross-spawn/commit/159e7e9785e57451cba034ae51719f97135074ae))
+
+### [7.0.2](https://github.com/moxystudio/node-cross-spawn/compare/v7.0.1...v7.0.2) (2020-04-04)
+
+
+### Bug Fixes
+
+* fix worker threads in Node >=11.10.0 ([#132](https://github.com/moxystudio/node-cross-spawn/issues/132)) ([6c5b4f0](https://github.com/moxystudio/node-cross-spawn/commit/6c5b4f015814a6c4f6b33230dfd1a860aedc0aaf))
+
+### [7.0.1](https://github.com/moxystudio/node-cross-spawn/compare/v7.0.0...v7.0.1) (2019-10-07)
+
+
+### Bug Fixes
+
+* **core:** support worker threads ([#127](https://github.com/moxystudio/node-cross-spawn/issues/127)) ([cfd49c9](https://github.com/moxystudio/node-cross-spawn/commit/cfd49c9))
+
+## [7.0.0](https://github.com/moxystudio/node-cross-spawn/compare/v6.0.5...v7.0.0) (2019-09-03)
+
+
+### ⚠ BREAKING CHANGES
+
+* drop support for Node.js < 8
+
+* drop support for versions below Node.js 8 ([#125](https://github.com/moxystudio/node-cross-spawn/issues/125)) ([16feb53](https://github.com/moxystudio/node-cross-spawn/commit/16feb53))
+
+
+## [6.0.5](https://github.com/moxystudio/node-cross-spawn/compare/v6.0.4...v6.0.5) (2018-03-02)
+
+
+### Bug Fixes
+
+* avoid using deprecated Buffer constructor ([#94](https://github.com/moxystudio/node-cross-spawn/issues/94)) ([d5770df](https://github.com/moxystudio/node-cross-spawn/commit/d5770df)), closes [/nodejs.org/api/deprecations.html#deprecations_dep0005](https://github.com//nodejs.org/api/deprecations.html/issues/deprecations_dep0005)
+
+
+
+
+## [6.0.4](https://github.com/moxystudio/node-cross-spawn/compare/v6.0.3...v6.0.4) (2018-01-31)
+
+
+### Bug Fixes
+
+* fix paths being incorrectly normalized on unix ([06ee3c6](https://github.com/moxystudio/node-cross-spawn/commit/06ee3c6)), closes [#90](https://github.com/moxystudio/node-cross-spawn/issues/90)
+
+
+
+
+## [6.0.3](https://github.com/moxystudio/node-cross-spawn/compare/v6.0.2...v6.0.3) (2018-01-23)
+
+
+
+
+## [6.0.2](https://github.com/moxystudio/node-cross-spawn/compare/v6.0.1...v6.0.2) (2018-01-23)
+
+
+
+
+## [6.0.1](https://github.com/moxystudio/node-cross-spawn/compare/v6.0.0...v6.0.1) (2018-01-23)
+
+
+
+
+# [6.0.0](https://github.com/moxystudio/node-cross-spawn/compare/5.1.0...6.0.0) (2018-01-23)
+
+
+### Bug Fixes
+
+* fix certain arguments not being correctly escaped or causing batch syntax error ([900cf10](https://github.com/moxystudio/node-cross-spawn/commit/900cf10)), closes [#82](https://github.com/moxystudio/node-cross-spawn/issues/82) [#51](https://github.com/moxystudio/node-cross-spawn/issues/51)
+* fix commands as posix relatixe paths not working correctly, e.g.: `./my-command` ([900cf10](https://github.com/moxystudio/node-cross-spawn/commit/900cf10))
+* fix `options` argument being mutated ([900cf10](https://github.com/moxystudio/node-cross-spawn/commit/900cf10))
+* fix commands resolution when PATH was actually Path ([900cf10](https://github.com/moxystudio/node-cross-spawn/commit/900cf10))
+
+
+### Features
+
+* improve compliance with node's ENOENT errors ([900cf10](https://github.com/moxystudio/node-cross-spawn/commit/900cf10))
+* improve detection of node's shell option support ([900cf10](https://github.com/moxystudio/node-cross-spawn/commit/900cf10))
+
+
+### Chores
+
+* upgrade tooling
+* upgrate project to es6 (node v4)
+
+
+### BREAKING CHANGES
+
+* remove support for older nodejs versions, only `node >= 4` is supported
+
+
+
+## [5.1.0](https://github.com/moxystudio/node-cross-spawn/compare/5.0.1...5.1.0) (2017-02-26)
+
+
+### Bug Fixes
+
+* fix `options.shell` support for NodeJS [v4.8](https://github.com/nodejs/node/blob/master/doc/changelogs/CHANGELOG_V4.md#4.8.0)
+
+
+
+## [5.0.1](https://github.com/moxystudio/node-cross-spawn/compare/5.0.0...5.0.1) (2016-11-04)
+
+
+### Bug Fixes
+
+* fix `options.shell` support for NodeJS v7
+
+
+
+# [5.0.0](https://github.com/moxystudio/node-cross-spawn/compare/4.0.2...5.0.0) (2016-10-30)
+
+
+## Features
+
+* add support for `options.shell`
+* improve parsing of shebangs by using [`shebang-command`](https://github.com/kevva/shebang-command) module
+
+
+## Chores
+
+* refactor some code to make it more clear
+* update README caveats
diff --git a/temporary_modules/trezor-connect/node_modules/cross-spawn/LICENSE b/temporary_modules/trezor-connect/node_modules/cross-spawn/LICENSE
new file mode 100644
index 00000000..8407b9a3
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/cross-spawn/LICENSE
@@ -0,0 +1,21 @@
+The MIT License (MIT)
+
+Copyright (c) 2018 Made With MOXY Lda
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
diff --git a/temporary_modules/trezor-connect/node_modules/cross-spawn/README.md b/temporary_modules/trezor-connect/node_modules/cross-spawn/README.md
new file mode 100644
index 00000000..c4a4da84
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/cross-spawn/README.md
@@ -0,0 +1,96 @@
+# cross-spawn
+
+[![NPM version][npm-image]][npm-url] [![Downloads][downloads-image]][npm-url] [![Build Status][travis-image]][travis-url] [![Build status][appveyor-image]][appveyor-url] [![Coverage Status][codecov-image]][codecov-url] [![Dependency status][david-dm-image]][david-dm-url] [![Dev Dependency status][david-dm-dev-image]][david-dm-dev-url]
+
+[npm-url]:https://npmjs.org/package/cross-spawn
+[downloads-image]:https://img.shields.io/npm/dm/cross-spawn.svg
+[npm-image]:https://img.shields.io/npm/v/cross-spawn.svg
+[travis-url]:https://travis-ci.org/moxystudio/node-cross-spawn
+[travis-image]:https://img.shields.io/travis/moxystudio/node-cross-spawn/master.svg
+[appveyor-url]:https://ci.appveyor.com/project/satazor/node-cross-spawn
+[appveyor-image]:https://img.shields.io/appveyor/ci/satazor/node-cross-spawn/master.svg
+[codecov-url]:https://codecov.io/gh/moxystudio/node-cross-spawn
+[codecov-image]:https://img.shields.io/codecov/c/github/moxystudio/node-cross-spawn/master.svg
+[david-dm-url]:https://david-dm.org/moxystudio/node-cross-spawn
+[david-dm-image]:https://img.shields.io/david/moxystudio/node-cross-spawn.svg
+[david-dm-dev-url]:https://david-dm.org/moxystudio/node-cross-spawn?type=dev
+[david-dm-dev-image]:https://img.shields.io/david/dev/moxystudio/node-cross-spawn.svg
+
+A cross platform solution to node's spawn and spawnSync.
+
+
+## Installation
+
+Node.js version 8 and up:
+`$ npm install cross-spawn`
+
+Node.js version 7 and under:
+`$ npm install cross-spawn@6`
+
+## Why
+
+Node has issues when using spawn on Windows:
+
+- It ignores [PATHEXT](https://github.com/joyent/node/issues/2318)
+- It does not support [shebangs](https://en.wikipedia.org/wiki/Shebang_(Unix))
+- Has problems running commands with [spaces](https://github.com/nodejs/node/issues/7367)
+- Has problems running commands with posix relative paths (e.g.: `./my-folder/my-executable`)
+- Has an [issue](https://github.com/moxystudio/node-cross-spawn/issues/82) with command shims (files in `node_modules/.bin/`), where arguments with quotes and parenthesis would result in [invalid syntax error](https://github.com/moxystudio/node-cross-spawn/blob/e77b8f22a416db46b6196767bcd35601d7e11d54/test/index.test.js#L149)
+- No `options.shell` support on node `` where `` must not contain any arguments.
+If you would like to have the shebang support improved, feel free to contribute via a pull-request.
+
+Remember to always test your code on Windows!
+
+
+## Tests
+
+`$ npm test`
+`$ npm test -- --watch` during development
+
+
+## License
+
+Released under the [MIT License](https://www.opensource.org/licenses/mit-license.php).
diff --git a/temporary_modules/trezor-connect/node_modules/cross-spawn/index.js b/temporary_modules/trezor-connect/node_modules/cross-spawn/index.js
new file mode 100644
index 00000000..5509742c
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/cross-spawn/index.js
@@ -0,0 +1,39 @@
+'use strict';
+
+const cp = require('child_process');
+const parse = require('./lib/parse');
+const enoent = require('./lib/enoent');
+
+function spawn(command, args, options) {
+ // Parse the arguments
+ const parsed = parse(command, args, options);
+
+ // Spawn the child process
+ const spawned = cp.spawn(parsed.command, parsed.args, parsed.options);
+
+ // Hook into child process "exit" event to emit an error if the command
+ // does not exists, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16
+ enoent.hookChildProcess(spawned, parsed);
+
+ return spawned;
+}
+
+function spawnSync(command, args, options) {
+ // Parse the arguments
+ const parsed = parse(command, args, options);
+
+ // Spawn the child process
+ const result = cp.spawnSync(parsed.command, parsed.args, parsed.options);
+
+ // Analyze if the command does not exist, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16
+ result.error = result.error || enoent.verifyENOENTSync(result.status, parsed);
+
+ return result;
+}
+
+module.exports = spawn;
+module.exports.spawn = spawn;
+module.exports.sync = spawnSync;
+
+module.exports._parse = parse;
+module.exports._enoent = enoent;
diff --git a/temporary_modules/trezor-connect/node_modules/cross-spawn/lib/enoent.js b/temporary_modules/trezor-connect/node_modules/cross-spawn/lib/enoent.js
new file mode 100644
index 00000000..14df9b62
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/cross-spawn/lib/enoent.js
@@ -0,0 +1,59 @@
+'use strict';
+
+const isWin = process.platform === 'win32';
+
+function notFoundError(original, syscall) {
+ return Object.assign(new Error(`${syscall} ${original.command} ENOENT`), {
+ code: 'ENOENT',
+ errno: 'ENOENT',
+ syscall: `${syscall} ${original.command}`,
+ path: original.command,
+ spawnargs: original.args,
+ });
+}
+
+function hookChildProcess(cp, parsed) {
+ if (!isWin) {
+ return;
+ }
+
+ const originalEmit = cp.emit;
+
+ cp.emit = function (name, arg1) {
+ // If emitting "exit" event and exit code is 1, we need to check if
+ // the command exists and emit an "error" instead
+ // See https://github.com/IndigoUnited/node-cross-spawn/issues/16
+ if (name === 'exit') {
+ const err = verifyENOENT(arg1, parsed, 'spawn');
+
+ if (err) {
+ return originalEmit.call(cp, 'error', err);
+ }
+ }
+
+ return originalEmit.apply(cp, arguments); // eslint-disable-line prefer-rest-params
+ };
+}
+
+function verifyENOENT(status, parsed) {
+ if (isWin && status === 1 && !parsed.file) {
+ return notFoundError(parsed.original, 'spawn');
+ }
+
+ return null;
+}
+
+function verifyENOENTSync(status, parsed) {
+ if (isWin && status === 1 && !parsed.file) {
+ return notFoundError(parsed.original, 'spawnSync');
+ }
+
+ return null;
+}
+
+module.exports = {
+ hookChildProcess,
+ verifyENOENT,
+ verifyENOENTSync,
+ notFoundError,
+};
diff --git a/temporary_modules/trezor-connect/node_modules/cross-spawn/lib/parse.js b/temporary_modules/trezor-connect/node_modules/cross-spawn/lib/parse.js
new file mode 100644
index 00000000..0129d747
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/cross-spawn/lib/parse.js
@@ -0,0 +1,91 @@
+'use strict';
+
+const path = require('path');
+const resolveCommand = require('./util/resolveCommand');
+const escape = require('./util/escape');
+const readShebang = require('./util/readShebang');
+
+const isWin = process.platform === 'win32';
+const isExecutableRegExp = /\.(?:com|exe)$/i;
+const isCmdShimRegExp = /node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;
+
+function detectShebang(parsed) {
+ parsed.file = resolveCommand(parsed);
+
+ const shebang = parsed.file && readShebang(parsed.file);
+
+ if (shebang) {
+ parsed.args.unshift(parsed.file);
+ parsed.command = shebang;
+
+ return resolveCommand(parsed);
+ }
+
+ return parsed.file;
+}
+
+function parseNonShell(parsed) {
+ if (!isWin) {
+ return parsed;
+ }
+
+ // Detect & add support for shebangs
+ const commandFile = detectShebang(parsed);
+
+ // We don't need a shell if the command filename is an executable
+ const needsShell = !isExecutableRegExp.test(commandFile);
+
+ // If a shell is required, use cmd.exe and take care of escaping everything correctly
+ // Note that `forceShell` is an hidden option used only in tests
+ if (parsed.options.forceShell || needsShell) {
+ // Need to double escape meta chars if the command is a cmd-shim located in `node_modules/.bin/`
+ // The cmd-shim simply calls execute the package bin file with NodeJS, proxying any argument
+ // Because the escape of metachars with ^ gets interpreted when the cmd.exe is first called,
+ // we need to double escape them
+ const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile);
+
+ // Normalize posix paths into OS compatible paths (e.g.: foo/bar -> foo\bar)
+ // This is necessary otherwise it will always fail with ENOENT in those cases
+ parsed.command = path.normalize(parsed.command);
+
+ // Escape command & arguments
+ parsed.command = escape.command(parsed.command);
+ parsed.args = parsed.args.map((arg) => escape.argument(arg, needsDoubleEscapeMetaChars));
+
+ const shellCommand = [parsed.command].concat(parsed.args).join(' ');
+
+ parsed.args = ['/d', '/s', '/c', `"${shellCommand}"`];
+ parsed.command = process.env.comspec || 'cmd.exe';
+ parsed.options.windowsVerbatimArguments = true; // Tell node's spawn that the arguments are already escaped
+ }
+
+ return parsed;
+}
+
+function parse(command, args, options) {
+ // Normalize arguments, similar to nodejs
+ if (args && !Array.isArray(args)) {
+ options = args;
+ args = null;
+ }
+
+ args = args ? args.slice(0) : []; // Clone array to avoid changing the original
+ options = Object.assign({}, options); // Clone object to avoid changing the original
+
+ // Build our parsed object
+ const parsed = {
+ command,
+ args,
+ options,
+ file: undefined,
+ original: {
+ command,
+ args,
+ },
+ };
+
+ // Delegate further parsing to shell or non-shell
+ return options.shell ? parsed : parseNonShell(parsed);
+}
+
+module.exports = parse;
diff --git a/temporary_modules/trezor-connect/node_modules/cross-spawn/lib/util/escape.js b/temporary_modules/trezor-connect/node_modules/cross-spawn/lib/util/escape.js
new file mode 100644
index 00000000..b0bb84c3
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/cross-spawn/lib/util/escape.js
@@ -0,0 +1,45 @@
+'use strict';
+
+// See http://www.robvanderwoude.com/escapechars.php
+const metaCharsRegExp = /([()\][%!^"`<>&|;, *?])/g;
+
+function escapeCommand(arg) {
+ // Escape meta chars
+ arg = arg.replace(metaCharsRegExp, '^$1');
+
+ return arg;
+}
+
+function escapeArgument(arg, doubleEscapeMetaChars) {
+ // Convert to string
+ arg = `${arg}`;
+
+ // Algorithm below is based on https://qntm.org/cmd
+
+ // Sequence of backslashes followed by a double quote:
+ // double up all the backslashes and escape the double quote
+ arg = arg.replace(/(\\*)"/g, '$1$1\\"');
+
+ // Sequence of backslashes followed by the end of the string
+ // (which will become a double quote later):
+ // double up all the backslashes
+ arg = arg.replace(/(\\*)$/, '$1$1');
+
+ // All other backslashes occur literally
+
+ // Quote the whole thing:
+ arg = `"${arg}"`;
+
+ // Escape meta chars
+ arg = arg.replace(metaCharsRegExp, '^$1');
+
+ // Double escape meta chars if necessary
+ if (doubleEscapeMetaChars) {
+ arg = arg.replace(metaCharsRegExp, '^$1');
+ }
+
+ return arg;
+}
+
+module.exports.command = escapeCommand;
+module.exports.argument = escapeArgument;
diff --git a/temporary_modules/trezor-connect/node_modules/cross-spawn/lib/util/readShebang.js b/temporary_modules/trezor-connect/node_modules/cross-spawn/lib/util/readShebang.js
new file mode 100644
index 00000000..5e83733f
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/cross-spawn/lib/util/readShebang.js
@@ -0,0 +1,23 @@
+'use strict';
+
+const fs = require('fs');
+const shebangCommand = require('shebang-command');
+
+function readShebang(command) {
+ // Read the first 150 bytes from the file
+ const size = 150;
+ const buffer = Buffer.alloc(size);
+
+ let fd;
+
+ try {
+ fd = fs.openSync(command, 'r');
+ fs.readSync(fd, buffer, 0, size, 0);
+ fs.closeSync(fd);
+ } catch (e) { /* Empty */ }
+
+ // Attempt to extract shebang (null is returned if not a shebang)
+ return shebangCommand(buffer.toString());
+}
+
+module.exports = readShebang;
diff --git a/temporary_modules/trezor-connect/node_modules/cross-spawn/lib/util/resolveCommand.js b/temporary_modules/trezor-connect/node_modules/cross-spawn/lib/util/resolveCommand.js
new file mode 100644
index 00000000..79724550
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/cross-spawn/lib/util/resolveCommand.js
@@ -0,0 +1,52 @@
+'use strict';
+
+const path = require('path');
+const which = require('which');
+const getPathKey = require('path-key');
+
+function resolveCommandAttempt(parsed, withoutPathExt) {
+ const env = parsed.options.env || process.env;
+ const cwd = process.cwd();
+ const hasCustomCwd = parsed.options.cwd != null;
+ // Worker threads do not have process.chdir()
+ const shouldSwitchCwd = hasCustomCwd && process.chdir !== undefined && !process.chdir.disabled;
+
+ // If a custom `cwd` was specified, we need to change the process cwd
+ // because `which` will do stat calls but does not support a custom cwd
+ if (shouldSwitchCwd) {
+ try {
+ process.chdir(parsed.options.cwd);
+ } catch (err) {
+ /* Empty */
+ }
+ }
+
+ let resolved;
+
+ try {
+ resolved = which.sync(parsed.command, {
+ path: env[getPathKey({ env })],
+ pathExt: withoutPathExt ? path.delimiter : undefined,
+ });
+ } catch (e) {
+ /* Empty */
+ } finally {
+ if (shouldSwitchCwd) {
+ process.chdir(cwd);
+ }
+ }
+
+ // If we successfully resolved, ensure that an absolute path is returned
+ // Note that when a custom `cwd` was used, we need to resolve to an absolute path based on it
+ if (resolved) {
+ resolved = path.resolve(hasCustomCwd ? parsed.options.cwd : '', resolved);
+ }
+
+ return resolved;
+}
+
+function resolveCommand(parsed) {
+ return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true);
+}
+
+module.exports = resolveCommand;
diff --git a/temporary_modules/trezor-connect/node_modules/cross-spawn/package.json b/temporary_modules/trezor-connect/node_modules/cross-spawn/package.json
new file mode 100644
index 00000000..232ff97e
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/cross-spawn/package.json
@@ -0,0 +1,73 @@
+{
+ "name": "cross-spawn",
+ "version": "7.0.3",
+ "description": "Cross platform child_process#spawn and child_process#spawnSync",
+ "keywords": [
+ "spawn",
+ "spawnSync",
+ "windows",
+ "cross-platform",
+ "path-ext",
+ "shebang",
+ "cmd",
+ "execute"
+ ],
+ "author": "André Cruz ",
+ "homepage": "https://github.com/moxystudio/node-cross-spawn",
+ "repository": {
+ "type": "git",
+ "url": "git@github.com:moxystudio/node-cross-spawn.git"
+ },
+ "license": "MIT",
+ "main": "index.js",
+ "files": [
+ "lib"
+ ],
+ "scripts": {
+ "lint": "eslint .",
+ "test": "jest --env node --coverage",
+ "prerelease": "npm t && npm run lint",
+ "release": "standard-version",
+ "postrelease": "git push --follow-tags origin HEAD && npm publish"
+ },
+ "husky": {
+ "hooks": {
+ "commit-msg": "commitlint -E HUSKY_GIT_PARAMS",
+ "pre-commit": "lint-staged"
+ }
+ },
+ "lint-staged": {
+ "*.js": [
+ "eslint --fix",
+ "git add"
+ ]
+ },
+ "commitlint": {
+ "extends": [
+ "@commitlint/config-conventional"
+ ]
+ },
+ "dependencies": {
+ "path-key": "^3.1.0",
+ "shebang-command": "^2.0.0",
+ "which": "^2.0.1"
+ },
+ "devDependencies": {
+ "@commitlint/cli": "^8.1.0",
+ "@commitlint/config-conventional": "^8.1.0",
+ "babel-core": "^6.26.3",
+ "babel-jest": "^24.9.0",
+ "babel-preset-moxy": "^3.1.0",
+ "eslint": "^5.16.0",
+ "eslint-config-moxy": "^7.1.0",
+ "husky": "^3.0.5",
+ "jest": "^24.9.0",
+ "lint-staged": "^9.2.5",
+ "mkdirp": "^0.5.1",
+ "rimraf": "^3.0.0",
+ "standard-version": "^7.0.0"
+ },
+ "engines": {
+ "node": ">= 8"
+ }
+}
diff --git a/temporary_modules/trezor-connect/node_modules/debug/LICENSE b/temporary_modules/trezor-connect/node_modules/debug/LICENSE
new file mode 100644
index 00000000..1a9820e2
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/debug/LICENSE
@@ -0,0 +1,20 @@
+(The MIT License)
+
+Copyright (c) 2014-2017 TJ Holowaychuk
+Copyright (c) 2018-2021 Josh Junon
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software
+and associated documentation files (the 'Software'), to deal in the Software without restriction,
+including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
+and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
+subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial
+portions of the Software.
+
+THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
+LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
diff --git a/temporary_modules/trezor-connect/node_modules/debug/README.md b/temporary_modules/trezor-connect/node_modules/debug/README.md
new file mode 100644
index 00000000..e9c3e047
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/debug/README.md
@@ -0,0 +1,481 @@
+# debug
+[](https://travis-ci.org/debug-js/debug) [](https://coveralls.io/github/debug-js/debug?branch=master) [](https://visionmedia-community-slackin.now.sh/) [](#backers)
+[](#sponsors)
+
+
+
+A tiny JavaScript debugging utility modelled after Node.js core's debugging
+technique. Works in Node.js and web browsers.
+
+## Installation
+
+```bash
+$ npm install debug
+```
+
+## Usage
+
+`debug` exposes a function; simply pass this function the name of your module, and it will return a decorated version of `console.error` for you to pass debug statements to. This will allow you to toggle the debug output for different parts of your module as well as the module as a whole.
+
+Example [_app.js_](./examples/node/app.js):
+
+```js
+var debug = require('debug')('http')
+ , http = require('http')
+ , name = 'My App';
+
+// fake app
+
+debug('booting %o', name);
+
+http.createServer(function(req, res){
+ debug(req.method + ' ' + req.url);
+ res.end('hello\n');
+}).listen(3000, function(){
+ debug('listening');
+});
+
+// fake worker of some kind
+
+require('./worker');
+```
+
+Example [_worker.js_](./examples/node/worker.js):
+
+```js
+var a = require('debug')('worker:a')
+ , b = require('debug')('worker:b');
+
+function work() {
+ a('doing lots of uninteresting work');
+ setTimeout(work, Math.random() * 1000);
+}
+
+work();
+
+function workb() {
+ b('doing some work');
+ setTimeout(workb, Math.random() * 2000);
+}
+
+workb();
+```
+
+The `DEBUG` environment variable is then used to enable these based on space or
+comma-delimited names.
+
+Here are some examples:
+
+
+
+
+
+#### Windows command prompt notes
+
+##### CMD
+
+On Windows the environment variable is set using the `set` command.
+
+```cmd
+set DEBUG=*,-not_this
+```
+
+Example:
+
+```cmd
+set DEBUG=* & node app.js
+```
+
+##### PowerShell (VS Code default)
+
+PowerShell uses different syntax to set environment variables.
+
+```cmd
+$env:DEBUG = "*,-not_this"
+```
+
+Example:
+
+```cmd
+$env:DEBUG='app';node app.js
+```
+
+Then, run the program to be debugged as usual.
+
+npm script example:
+```js
+ "windowsDebug": "@powershell -Command $env:DEBUG='*';node app.js",
+```
+
+## Namespace Colors
+
+Every debug instance has a color generated for it based on its namespace name.
+This helps when visually parsing the debug output to identify which debug instance
+a debug line belongs to.
+
+#### Node.js
+
+In Node.js, colors are enabled when stderr is a TTY. You also _should_ install
+the [`supports-color`](https://npmjs.org/supports-color) module alongside debug,
+otherwise debug will only use a small handful of basic colors.
+
+
+
+#### Web Browser
+
+Colors are also enabled on "Web Inspectors" that understand the `%c` formatting
+option. These are WebKit web inspectors, Firefox ([since version
+31](https://hacks.mozilla.org/2014/05/editable-box-model-multiple-selection-sublime-text-keys-much-more-firefox-developer-tools-episode-31/))
+and the Firebug plugin for Firefox (any version).
+
+
+
+
+## Millisecond diff
+
+When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the "+NNNms" will show you how much time was spent between calls.
+
+
+
+When stdout is not a TTY, `Date#toISOString()` is used, making it more useful for logging the debug information as shown below:
+
+
+
+
+## Conventions
+
+If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use ":" to separate features. For example "bodyParser" from Connect would then be "connect:bodyParser". If you append a "*" to the end of your name, it will always be enabled regardless of the setting of the DEBUG environment variable. You can then use it for normal output as well as debug output.
+
+## Wildcards
+
+The `*` character may be used as a wildcard. Suppose for example your library has
+debuggers named "connect:bodyParser", "connect:compress", "connect:session",
+instead of listing all three with
+`DEBUG=connect:bodyParser,connect:compress,connect:session`, you may simply do
+`DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`.
+
+You can also exclude specific debuggers by prefixing them with a "-" character.
+For example, `DEBUG=*,-connect:*` would include all debuggers except those
+starting with "connect:".
+
+## Environment Variables
+
+When running through Node.js, you can set a few environment variables that will
+change the behavior of the debug logging:
+
+| Name | Purpose |
+|-----------|-------------------------------------------------|
+| `DEBUG` | Enables/disables specific debugging namespaces. |
+| `DEBUG_HIDE_DATE` | Hide date from debug output (non-TTY). |
+| `DEBUG_COLORS`| Whether or not to use colors in the debug output. |
+| `DEBUG_DEPTH` | Object inspection depth. |
+| `DEBUG_SHOW_HIDDEN` | Shows hidden properties on inspected objects. |
+
+
+__Note:__ The environment variables beginning with `DEBUG_` end up being
+converted into an Options object that gets used with `%o`/`%O` formatters.
+See the Node.js documentation for
+[`util.inspect()`](https://nodejs.org/api/util.html#util_util_inspect_object_options)
+for the complete list.
+
+## Formatters
+
+Debug uses [printf-style](https://wikipedia.org/wiki/Printf_format_string) formatting.
+Below are the officially supported formatters:
+
+| Formatter | Representation |
+|-----------|----------------|
+| `%O` | Pretty-print an Object on multiple lines. |
+| `%o` | Pretty-print an Object all on a single line. |
+| `%s` | String. |
+| `%d` | Number (both integer and float). |
+| `%j` | JSON. Replaced with the string '[Circular]' if the argument contains circular references. |
+| `%%` | Single percent sign ('%'). This does not consume an argument. |
+
+
+### Custom formatters
+
+You can add custom formatters by extending the `debug.formatters` object.
+For example, if you wanted to add support for rendering a Buffer as hex with
+`%h`, you could do something like:
+
+```js
+const createDebug = require('debug')
+createDebug.formatters.h = (v) => {
+ return v.toString('hex')
+}
+
+// …elsewhere
+const debug = createDebug('foo')
+debug('this is hex: %h', new Buffer('hello world'))
+// foo this is hex: 68656c6c6f20776f726c6421 +0ms
+```
+
+
+## Browser Support
+
+You can build a browser-ready script using [browserify](https://github.com/substack/node-browserify),
+or just use the [browserify-as-a-service](https://wzrd.in/) [build](https://wzrd.in/standalone/debug@latest),
+if you don't want to build it yourself.
+
+Debug's enable state is currently persisted by `localStorage`.
+Consider the situation shown below where you have `worker:a` and `worker:b`,
+and wish to debug both. You can enable this using `localStorage.debug`:
+
+```js
+localStorage.debug = 'worker:*'
+```
+
+And then refresh the page.
+
+```js
+a = debug('worker:a');
+b = debug('worker:b');
+
+setInterval(function(){
+ a('doing some work');
+}, 1000);
+
+setInterval(function(){
+ b('doing some work');
+}, 1200);
+```
+
+In Chromium-based web browsers (e.g. Brave, Chrome, and Electron), the JavaScript console will—by default—only show messages logged by `debug` if the "Verbose" log level is _enabled_.
+
+
+
+## Output streams
+
+ By default `debug` will log to stderr, however this can be configured per-namespace by overriding the `log` method:
+
+Example [_stdout.js_](./examples/node/stdout.js):
+
+```js
+var debug = require('debug');
+var error = debug('app:error');
+
+// by default stderr is used
+error('goes to stderr!');
+
+var log = debug('app:log');
+// set this namespace to log via console.log
+log.log = console.log.bind(console); // don't forget to bind to console!
+log('goes to stdout');
+error('still goes to stderr!');
+
+// set all output to go via console.info
+// overrides all per-namespace log settings
+debug.log = console.info.bind(console);
+error('now goes to stdout via console.info');
+log('still goes to stdout, but via console.info now');
+```
+
+## Extend
+You can simply extend debugger
+```js
+const log = require('debug')('auth');
+
+//creates new debug instance with extended namespace
+const logSign = log.extend('sign');
+const logLogin = log.extend('login');
+
+log('hello'); // auth hello
+logSign('hello'); //auth:sign hello
+logLogin('hello'); //auth:login hello
+```
+
+## Set dynamically
+
+You can also enable debug dynamically by calling the `enable()` method :
+
+```js
+let debug = require('debug');
+
+console.log(1, debug.enabled('test'));
+
+debug.enable('test');
+console.log(2, debug.enabled('test'));
+
+debug.disable();
+console.log(3, debug.enabled('test'));
+
+```
+
+print :
+```
+1 false
+2 true
+3 false
+```
+
+Usage :
+`enable(namespaces)`
+`namespaces` can include modes separated by a colon and wildcards.
+
+Note that calling `enable()` completely overrides previously set DEBUG variable :
+
+```
+$ DEBUG=foo node -e 'var dbg = require("debug"); dbg.enable("bar"); console.log(dbg.enabled("foo"))'
+=> false
+```
+
+`disable()`
+
+Will disable all namespaces. The functions returns the namespaces currently
+enabled (and skipped). This can be useful if you want to disable debugging
+temporarily without knowing what was enabled to begin with.
+
+For example:
+
+```js
+let debug = require('debug');
+debug.enable('foo:*,-foo:bar');
+let namespaces = debug.disable();
+debug.enable(namespaces);
+```
+
+Note: There is no guarantee that the string will be identical to the initial
+enable string, but semantically they will be identical.
+
+## Checking whether a debug target is enabled
+
+After you've created a debug instance, you can determine whether or not it is
+enabled by checking the `enabled` property:
+
+```javascript
+const debug = require('debug')('http');
+
+if (debug.enabled) {
+ // do stuff...
+}
+```
+
+You can also manually toggle this property to force the debug instance to be
+enabled or disabled.
+
+## Usage in child processes
+
+Due to the way `debug` detects if the output is a TTY or not, colors are not shown in child processes when `stderr` is piped. A solution is to pass the `DEBUG_COLORS=1` environment variable to the child process.
+For example:
+
+```javascript
+worker = fork(WORKER_WRAP_PATH, [workerPath], {
+ stdio: [
+ /* stdin: */ 0,
+ /* stdout: */ 'pipe',
+ /* stderr: */ 'pipe',
+ 'ipc',
+ ],
+ env: Object.assign({}, process.env, {
+ DEBUG_COLORS: 1 // without this settings, colors won't be shown
+ }),
+});
+
+worker.stderr.pipe(process.stderr, { end: false });
+```
+
+
+## Authors
+
+ - TJ Holowaychuk
+ - Nathan Rajlich
+ - Andrew Rhyne
+ - Josh Junon
+
+## Backers
+
+Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/debug#backer)]
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+## Sponsors
+
+Become a sponsor and get your logo on our README on Github with a link to your site. [[Become a sponsor](https://opencollective.com/debug#sponsor)]
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+## License
+
+(The MIT License)
+
+Copyright (c) 2014-2017 TJ Holowaychuk <tj@vision-media.ca>
+Copyright (c) 2018-2021 Josh Junon
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+'Software'), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/temporary_modules/trezor-connect/node_modules/debug/package.json b/temporary_modules/trezor-connect/node_modules/debug/package.json
new file mode 100644
index 00000000..3bcdc242
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/debug/package.json
@@ -0,0 +1,59 @@
+{
+ "name": "debug",
+ "version": "4.3.4",
+ "repository": {
+ "type": "git",
+ "url": "git://github.com/debug-js/debug.git"
+ },
+ "description": "Lightweight debugging utility for Node.js and the browser",
+ "keywords": [
+ "debug",
+ "log",
+ "debugger"
+ ],
+ "files": [
+ "src",
+ "LICENSE",
+ "README.md"
+ ],
+ "author": "Josh Junon ",
+ "contributors": [
+ "TJ Holowaychuk ",
+ "Nathan Rajlich (http://n8.io)",
+ "Andrew Rhyne "
+ ],
+ "license": "MIT",
+ "scripts": {
+ "lint": "xo",
+ "test": "npm run test:node && npm run test:browser && npm run lint",
+ "test:node": "istanbul cover _mocha -- test.js",
+ "test:browser": "karma start --single-run",
+ "test:coverage": "cat ./coverage/lcov.info | coveralls"
+ },
+ "dependencies": {
+ "ms": "2.1.2"
+ },
+ "devDependencies": {
+ "brfs": "^2.0.1",
+ "browserify": "^16.2.3",
+ "coveralls": "^3.0.2",
+ "istanbul": "^0.4.5",
+ "karma": "^3.1.4",
+ "karma-browserify": "^6.0.0",
+ "karma-chrome-launcher": "^2.2.0",
+ "karma-mocha": "^1.3.0",
+ "mocha": "^5.2.0",
+ "mocha-lcov-reporter": "^1.2.0",
+ "xo": "^0.23.0"
+ },
+ "peerDependenciesMeta": {
+ "supports-color": {
+ "optional": true
+ }
+ },
+ "main": "./src/index.js",
+ "browser": "./src/browser.js",
+ "engines": {
+ "node": ">=6.0"
+ }
+}
diff --git a/temporary_modules/trezor-connect/node_modules/debug/src/browser.js b/temporary_modules/trezor-connect/node_modules/debug/src/browser.js
new file mode 100644
index 00000000..cd0fc35d
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/debug/src/browser.js
@@ -0,0 +1,269 @@
+/* eslint-env browser */
+
+/**
+ * This is the web browser implementation of `debug()`.
+ */
+
+exports.formatArgs = formatArgs;
+exports.save = save;
+exports.load = load;
+exports.useColors = useColors;
+exports.storage = localstorage();
+exports.destroy = (() => {
+ let warned = false;
+
+ return () => {
+ if (!warned) {
+ warned = true;
+ console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
+ }
+ };
+})();
+
+/**
+ * Colors.
+ */
+
+exports.colors = [
+ '#0000CC',
+ '#0000FF',
+ '#0033CC',
+ '#0033FF',
+ '#0066CC',
+ '#0066FF',
+ '#0099CC',
+ '#0099FF',
+ '#00CC00',
+ '#00CC33',
+ '#00CC66',
+ '#00CC99',
+ '#00CCCC',
+ '#00CCFF',
+ '#3300CC',
+ '#3300FF',
+ '#3333CC',
+ '#3333FF',
+ '#3366CC',
+ '#3366FF',
+ '#3399CC',
+ '#3399FF',
+ '#33CC00',
+ '#33CC33',
+ '#33CC66',
+ '#33CC99',
+ '#33CCCC',
+ '#33CCFF',
+ '#6600CC',
+ '#6600FF',
+ '#6633CC',
+ '#6633FF',
+ '#66CC00',
+ '#66CC33',
+ '#9900CC',
+ '#9900FF',
+ '#9933CC',
+ '#9933FF',
+ '#99CC00',
+ '#99CC33',
+ '#CC0000',
+ '#CC0033',
+ '#CC0066',
+ '#CC0099',
+ '#CC00CC',
+ '#CC00FF',
+ '#CC3300',
+ '#CC3333',
+ '#CC3366',
+ '#CC3399',
+ '#CC33CC',
+ '#CC33FF',
+ '#CC6600',
+ '#CC6633',
+ '#CC9900',
+ '#CC9933',
+ '#CCCC00',
+ '#CCCC33',
+ '#FF0000',
+ '#FF0033',
+ '#FF0066',
+ '#FF0099',
+ '#FF00CC',
+ '#FF00FF',
+ '#FF3300',
+ '#FF3333',
+ '#FF3366',
+ '#FF3399',
+ '#FF33CC',
+ '#FF33FF',
+ '#FF6600',
+ '#FF6633',
+ '#FF9900',
+ '#FF9933',
+ '#FFCC00',
+ '#FFCC33'
+];
+
+/**
+ * Currently only WebKit-based Web Inspectors, Firefox >= v31,
+ * and the Firebug extension (any Firefox version) are known
+ * to support "%c" CSS customizations.
+ *
+ * TODO: add a `localStorage` variable to explicitly enable/disable colors
+ */
+
+// eslint-disable-next-line complexity
+function useColors() {
+ // NB: In an Electron preload script, document will be defined but not fully
+ // initialized. Since we know we're in Chrome, we'll just detect this case
+ // explicitly
+ if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {
+ return true;
+ }
+
+ // Internet Explorer and Edge do not support colors.
+ if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
+ return false;
+ }
+
+ // Is webkit? http://stackoverflow.com/a/16459606/376773
+ // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
+ return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
+ // Is firebug? http://stackoverflow.com/a/398120/376773
+ (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
+ // Is firefox >= v31?
+ // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
+ (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||
+ // Double check webkit in userAgent just in case we are in a worker
+ (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
+}
+
+/**
+ * Colorize log arguments if enabled.
+ *
+ * @api public
+ */
+
+function formatArgs(args) {
+ args[0] = (this.useColors ? '%c' : '') +
+ this.namespace +
+ (this.useColors ? ' %c' : ' ') +
+ args[0] +
+ (this.useColors ? '%c ' : ' ') +
+ '+' + module.exports.humanize(this.diff);
+
+ if (!this.useColors) {
+ return;
+ }
+
+ const c = 'color: ' + this.color;
+ args.splice(1, 0, c, 'color: inherit');
+
+ // The final "%c" is somewhat tricky, because there could be other
+ // arguments passed either before or after the %c, so we need to
+ // figure out the correct index to insert the CSS into
+ let index = 0;
+ let lastC = 0;
+ args[0].replace(/%[a-zA-Z%]/g, match => {
+ if (match === '%%') {
+ return;
+ }
+ index++;
+ if (match === '%c') {
+ // We only are interested in the *last* %c
+ // (the user may have provided their own)
+ lastC = index;
+ }
+ });
+
+ args.splice(lastC, 0, c);
+}
+
+/**
+ * Invokes `console.debug()` when available.
+ * No-op when `console.debug` is not a "function".
+ * If `console.debug` is not available, falls back
+ * to `console.log`.
+ *
+ * @api public
+ */
+exports.log = console.debug || console.log || (() => {});
+
+/**
+ * Save `namespaces`.
+ *
+ * @param {String} namespaces
+ * @api private
+ */
+function save(namespaces) {
+ try {
+ if (namespaces) {
+ exports.storage.setItem('debug', namespaces);
+ } else {
+ exports.storage.removeItem('debug');
+ }
+ } catch (error) {
+ // Swallow
+ // XXX (@Qix-) should we be logging these?
+ }
+}
+
+/**
+ * Load `namespaces`.
+ *
+ * @return {String} returns the previously persisted debug modes
+ * @api private
+ */
+function load() {
+ let r;
+ try {
+ r = exports.storage.getItem('debug');
+ } catch (error) {
+ // Swallow
+ // XXX (@Qix-) should we be logging these?
+ }
+
+ // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
+ if (!r && typeof process !== 'undefined' && 'env' in process) {
+ r = process.env.DEBUG;
+ }
+
+ return r;
+}
+
+/**
+ * Localstorage attempts to return the localstorage.
+ *
+ * This is necessary because safari throws
+ * when a user disables cookies/localstorage
+ * and you attempt to access it.
+ *
+ * @return {LocalStorage}
+ * @api private
+ */
+
+function localstorage() {
+ try {
+ // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context
+ // The Browser also has localStorage in the global context.
+ return localStorage;
+ } catch (error) {
+ // Swallow
+ // XXX (@Qix-) should we be logging these?
+ }
+}
+
+module.exports = require('./common')(exports);
+
+const {formatters} = module.exports;
+
+/**
+ * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
+ */
+
+formatters.j = function (v) {
+ try {
+ return JSON.stringify(v);
+ } catch (error) {
+ return '[UnexpectedJSONParseError]: ' + error.message;
+ }
+};
diff --git a/temporary_modules/trezor-connect/node_modules/debug/src/common.js b/temporary_modules/trezor-connect/node_modules/debug/src/common.js
new file mode 100644
index 00000000..e3291b20
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/debug/src/common.js
@@ -0,0 +1,274 @@
+
+/**
+ * This is the common logic for both the Node.js and web browser
+ * implementations of `debug()`.
+ */
+
+function setup(env) {
+ createDebug.debug = createDebug;
+ createDebug.default = createDebug;
+ createDebug.coerce = coerce;
+ createDebug.disable = disable;
+ createDebug.enable = enable;
+ createDebug.enabled = enabled;
+ createDebug.humanize = require('ms');
+ createDebug.destroy = destroy;
+
+ Object.keys(env).forEach(key => {
+ createDebug[key] = env[key];
+ });
+
+ /**
+ * The currently active debug mode names, and names to skip.
+ */
+
+ createDebug.names = [];
+ createDebug.skips = [];
+
+ /**
+ * Map of special "%n" handling functions, for the debug "format" argument.
+ *
+ * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
+ */
+ createDebug.formatters = {};
+
+ /**
+ * Selects a color for a debug namespace
+ * @param {String} namespace The namespace string for the debug instance to be colored
+ * @return {Number|String} An ANSI color code for the given namespace
+ * @api private
+ */
+ function selectColor(namespace) {
+ let hash = 0;
+
+ for (let i = 0; i < namespace.length; i++) {
+ hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
+ hash |= 0; // Convert to 32bit integer
+ }
+
+ return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
+ }
+ createDebug.selectColor = selectColor;
+
+ /**
+ * Create a debugger with the given `namespace`.
+ *
+ * @param {String} namespace
+ * @return {Function}
+ * @api public
+ */
+ function createDebug(namespace) {
+ let prevTime;
+ let enableOverride = null;
+ let namespacesCache;
+ let enabledCache;
+
+ function debug(...args) {
+ // Disabled?
+ if (!debug.enabled) {
+ return;
+ }
+
+ const self = debug;
+
+ // Set `diff` timestamp
+ const curr = Number(new Date());
+ const ms = curr - (prevTime || curr);
+ self.diff = ms;
+ self.prev = prevTime;
+ self.curr = curr;
+ prevTime = curr;
+
+ args[0] = createDebug.coerce(args[0]);
+
+ if (typeof args[0] !== 'string') {
+ // Anything else let's inspect with %O
+ args.unshift('%O');
+ }
+
+ // Apply any `formatters` transformations
+ let index = 0;
+ args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {
+ // If we encounter an escaped % then don't increase the array index
+ if (match === '%%') {
+ return '%';
+ }
+ index++;
+ const formatter = createDebug.formatters[format];
+ if (typeof formatter === 'function') {
+ const val = args[index];
+ match = formatter.call(self, val);
+
+ // Now we need to remove `args[index]` since it's inlined in the `format`
+ args.splice(index, 1);
+ index--;
+ }
+ return match;
+ });
+
+ // Apply env-specific formatting (colors, etc.)
+ createDebug.formatArgs.call(self, args);
+
+ const logFn = self.log || createDebug.log;
+ logFn.apply(self, args);
+ }
+
+ debug.namespace = namespace;
+ debug.useColors = createDebug.useColors();
+ debug.color = createDebug.selectColor(namespace);
+ debug.extend = extend;
+ debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.
+
+ Object.defineProperty(debug, 'enabled', {
+ enumerable: true,
+ configurable: false,
+ get: () => {
+ if (enableOverride !== null) {
+ return enableOverride;
+ }
+ if (namespacesCache !== createDebug.namespaces) {
+ namespacesCache = createDebug.namespaces;
+ enabledCache = createDebug.enabled(namespace);
+ }
+
+ return enabledCache;
+ },
+ set: v => {
+ enableOverride = v;
+ }
+ });
+
+ // Env-specific initialization logic for debug instances
+ if (typeof createDebug.init === 'function') {
+ createDebug.init(debug);
+ }
+
+ return debug;
+ }
+
+ function extend(namespace, delimiter) {
+ const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
+ newDebug.log = this.log;
+ return newDebug;
+ }
+
+ /**
+ * Enables a debug mode by namespaces. This can include modes
+ * separated by a colon and wildcards.
+ *
+ * @param {String} namespaces
+ * @api public
+ */
+ function enable(namespaces) {
+ createDebug.save(namespaces);
+ createDebug.namespaces = namespaces;
+
+ createDebug.names = [];
+ createDebug.skips = [];
+
+ let i;
+ const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
+ const len = split.length;
+
+ for (i = 0; i < len; i++) {
+ if (!split[i]) {
+ // ignore empty strings
+ continue;
+ }
+
+ namespaces = split[i].replace(/\*/g, '.*?');
+
+ if (namespaces[0] === '-') {
+ createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$'));
+ } else {
+ createDebug.names.push(new RegExp('^' + namespaces + '$'));
+ }
+ }
+ }
+
+ /**
+ * Disable debug output.
+ *
+ * @return {String} namespaces
+ * @api public
+ */
+ function disable() {
+ const namespaces = [
+ ...createDebug.names.map(toNamespace),
+ ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)
+ ].join(',');
+ createDebug.enable('');
+ return namespaces;
+ }
+
+ /**
+ * Returns true if the given mode name is enabled, false otherwise.
+ *
+ * @param {String} name
+ * @return {Boolean}
+ * @api public
+ */
+ function enabled(name) {
+ if (name[name.length - 1] === '*') {
+ return true;
+ }
+
+ let i;
+ let len;
+
+ for (i = 0, len = createDebug.skips.length; i < len; i++) {
+ if (createDebug.skips[i].test(name)) {
+ return false;
+ }
+ }
+
+ for (i = 0, len = createDebug.names.length; i < len; i++) {
+ if (createDebug.names[i].test(name)) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ /**
+ * Convert regexp to namespace
+ *
+ * @param {RegExp} regxep
+ * @return {String} namespace
+ * @api private
+ */
+ function toNamespace(regexp) {
+ return regexp.toString()
+ .substring(2, regexp.toString().length - 2)
+ .replace(/\.\*\?$/, '*');
+ }
+
+ /**
+ * Coerce `val`.
+ *
+ * @param {Mixed} val
+ * @return {Mixed}
+ * @api private
+ */
+ function coerce(val) {
+ if (val instanceof Error) {
+ return val.stack || val.message;
+ }
+ return val;
+ }
+
+ /**
+ * XXX DO NOT USE. This is a temporary stub function.
+ * XXX It WILL be removed in the next major release.
+ */
+ function destroy() {
+ console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');
+ }
+
+ createDebug.enable(createDebug.load());
+
+ return createDebug;
+}
+
+module.exports = setup;
diff --git a/temporary_modules/trezor-connect/node_modules/debug/src/index.js b/temporary_modules/trezor-connect/node_modules/debug/src/index.js
new file mode 100644
index 00000000..bf4c57f2
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/debug/src/index.js
@@ -0,0 +1,10 @@
+/**
+ * Detect Electron renderer / nwjs process, which is node, but we should
+ * treat as a browser.
+ */
+
+if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) {
+ module.exports = require('./browser.js');
+} else {
+ module.exports = require('./node.js');
+}
diff --git a/temporary_modules/trezor-connect/node_modules/debug/src/node.js b/temporary_modules/trezor-connect/node_modules/debug/src/node.js
new file mode 100644
index 00000000..79bc085c
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/debug/src/node.js
@@ -0,0 +1,263 @@
+/**
+ * Module dependencies.
+ */
+
+const tty = require('tty');
+const util = require('util');
+
+/**
+ * This is the Node.js implementation of `debug()`.
+ */
+
+exports.init = init;
+exports.log = log;
+exports.formatArgs = formatArgs;
+exports.save = save;
+exports.load = load;
+exports.useColors = useColors;
+exports.destroy = util.deprecate(
+ () => {},
+ 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'
+);
+
+/**
+ * Colors.
+ */
+
+exports.colors = [6, 2, 3, 4, 5, 1];
+
+try {
+ // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json)
+ // eslint-disable-next-line import/no-extraneous-dependencies
+ const supportsColor = require('supports-color');
+
+ if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) {
+ exports.colors = [
+ 20,
+ 21,
+ 26,
+ 27,
+ 32,
+ 33,
+ 38,
+ 39,
+ 40,
+ 41,
+ 42,
+ 43,
+ 44,
+ 45,
+ 56,
+ 57,
+ 62,
+ 63,
+ 68,
+ 69,
+ 74,
+ 75,
+ 76,
+ 77,
+ 78,
+ 79,
+ 80,
+ 81,
+ 92,
+ 93,
+ 98,
+ 99,
+ 112,
+ 113,
+ 128,
+ 129,
+ 134,
+ 135,
+ 148,
+ 149,
+ 160,
+ 161,
+ 162,
+ 163,
+ 164,
+ 165,
+ 166,
+ 167,
+ 168,
+ 169,
+ 170,
+ 171,
+ 172,
+ 173,
+ 178,
+ 179,
+ 184,
+ 185,
+ 196,
+ 197,
+ 198,
+ 199,
+ 200,
+ 201,
+ 202,
+ 203,
+ 204,
+ 205,
+ 206,
+ 207,
+ 208,
+ 209,
+ 214,
+ 215,
+ 220,
+ 221
+ ];
+ }
+} catch (error) {
+ // Swallow - we only care if `supports-color` is available; it doesn't have to be.
+}
+
+/**
+ * Build up the default `inspectOpts` object from the environment variables.
+ *
+ * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js
+ */
+
+exports.inspectOpts = Object.keys(process.env).filter(key => {
+ return /^debug_/i.test(key);
+}).reduce((obj, key) => {
+ // Camel-case
+ const prop = key
+ .substring(6)
+ .toLowerCase()
+ .replace(/_([a-z])/g, (_, k) => {
+ return k.toUpperCase();
+ });
+
+ // Coerce string value into JS value
+ let val = process.env[key];
+ if (/^(yes|on|true|enabled)$/i.test(val)) {
+ val = true;
+ } else if (/^(no|off|false|disabled)$/i.test(val)) {
+ val = false;
+ } else if (val === 'null') {
+ val = null;
+ } else {
+ val = Number(val);
+ }
+
+ obj[prop] = val;
+ return obj;
+}, {});
+
+/**
+ * Is stdout a TTY? Colored output is enabled when `true`.
+ */
+
+function useColors() {
+ return 'colors' in exports.inspectOpts ?
+ Boolean(exports.inspectOpts.colors) :
+ tty.isatty(process.stderr.fd);
+}
+
+/**
+ * Adds ANSI color escape codes if enabled.
+ *
+ * @api public
+ */
+
+function formatArgs(args) {
+ const {namespace: name, useColors} = this;
+
+ if (useColors) {
+ const c = this.color;
+ const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c);
+ const prefix = ` ${colorCode};1m${name} \u001B[0m`;
+
+ args[0] = prefix + args[0].split('\n').join('\n' + prefix);
+ args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m');
+ } else {
+ args[0] = getDate() + name + ' ' + args[0];
+ }
+}
+
+function getDate() {
+ if (exports.inspectOpts.hideDate) {
+ return '';
+ }
+ return new Date().toISOString() + ' ';
+}
+
+/**
+ * Invokes `util.format()` with the specified arguments and writes to stderr.
+ */
+
+function log(...args) {
+ return process.stderr.write(util.format(...args) + '\n');
+}
+
+/**
+ * Save `namespaces`.
+ *
+ * @param {String} namespaces
+ * @api private
+ */
+function save(namespaces) {
+ if (namespaces) {
+ process.env.DEBUG = namespaces;
+ } else {
+ // If you set a process.env field to null or undefined, it gets cast to the
+ // string 'null' or 'undefined'. Just delete instead.
+ delete process.env.DEBUG;
+ }
+}
+
+/**
+ * Load `namespaces`.
+ *
+ * @return {String} returns the previously persisted debug modes
+ * @api private
+ */
+
+function load() {
+ return process.env.DEBUG;
+}
+
+/**
+ * Init logic for `debug` instances.
+ *
+ * Create a new `inspectOpts` object in case `useColors` is set
+ * differently for a particular `debug` instance.
+ */
+
+function init(debug) {
+ debug.inspectOpts = {};
+
+ const keys = Object.keys(exports.inspectOpts);
+ for (let i = 0; i < keys.length; i++) {
+ debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];
+ }
+}
+
+module.exports = require('./common')(exports);
+
+const {formatters} = module.exports;
+
+/**
+ * Map %o to `util.inspect()`, all on a single line.
+ */
+
+formatters.o = function (v) {
+ this.inspectOpts.colors = this.useColors;
+ return util.inspect(v, this.inspectOpts)
+ .split('\n')
+ .map(str => str.trim())
+ .join(' ');
+};
+
+/**
+ * Map %O to `util.inspect()`, allowing multiple lines if needed.
+ */
+
+formatters.O = function (v) {
+ this.inspectOpts.colors = this.useColors;
+ return util.inspect(v, this.inspectOpts);
+};
diff --git a/temporary_modules/trezor-connect/node_modules/elementtree/.npmignore b/temporary_modules/trezor-connect/node_modules/elementtree/.npmignore
new file mode 100644
index 00000000..3c3629e6
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/elementtree/.npmignore
@@ -0,0 +1 @@
+node_modules
diff --git a/temporary_modules/trezor-connect/node_modules/elementtree/.travis.yml b/temporary_modules/trezor-connect/node_modules/elementtree/.travis.yml
new file mode 100644
index 00000000..1ab26520
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/elementtree/.travis.yml
@@ -0,0 +1,14 @@
+language: node_js
+sudo: false
+
+node_js:
+ - "0.10"
+ - "0.11"
+ - "0.12"
+ - "iojs"
+
+script: make test
+
+notifications:
+ email:
+ - tomaz+travisci@tomaz.me
diff --git a/temporary_modules/trezor-connect/node_modules/elementtree/CHANGES.md b/temporary_modules/trezor-connect/node_modules/elementtree/CHANGES.md
new file mode 100644
index 00000000..08fdb1ff
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/elementtree/CHANGES.md
@@ -0,0 +1,39 @@
+elementtree v0.1.6 - 2014-02-06
+
+* Add support for CData elements. (#14)
+ [hermannpencole]
+
+elementtree v0.1.5 - 2012-11-14
+
+* Fix a bug in the find() and findtext() method which could manifest itself
+ under some conditions.
+ [metagriffin]
+
+elementtree v0.1.4 - 2012-10-15
+
+* Allow user to use namespaced attributes when using find* functions.
+ [Andrew Lunny]
+
+elementtree v0.1.3 - 2012-09-21
+
+* Improve the output of text content in the tags (strip unnecessary line break
+ characters).
+
+[Darryl Pogue]
+
+elementtree v0.1.2 - 2012-09-04
+
+ * Allow user to pass 'indent' option to ElementTree.write method. If this
+ option is specified (e.g. {'indent': 4}). XML will be pretty printed.
+ [Darryl Pogue, Tomaz Muraus]
+
+ * Bump sax dependency version.
+
+elementtree v0.1.1 - 2011-09-23
+
+ * Improve special character escaping.
+ [Ryan Phillips]
+
+elementtree v0.1.0 - 2011-09-05
+
+ * Initial release.
diff --git a/temporary_modules/trezor-connect/node_modules/elementtree/LICENSE.txt b/temporary_modules/trezor-connect/node_modules/elementtree/LICENSE.txt
new file mode 100644
index 00000000..6b0b1270
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/elementtree/LICENSE.txt
@@ -0,0 +1,203 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+
diff --git a/temporary_modules/trezor-connect/node_modules/elementtree/Makefile b/temporary_modules/trezor-connect/node_modules/elementtree/Makefile
new file mode 100644
index 00000000..ab7c4e0e
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/elementtree/Makefile
@@ -0,0 +1,21 @@
+TESTS := \
+ tests/test-simple.js
+
+
+
+PATH := ./node_modules/.bin:$(PATH)
+
+WHISKEY := $(shell bash -c 'PATH=$(PATH) type -p whiskey')
+
+default: test
+
+test:
+ NODE_PATH=`pwd`/lib/ ${WHISKEY} --scope-leaks --sequential --real-time --tests "${TESTS}"
+
+tap:
+ NODE_PATH=`pwd`/lib/ ${WHISKEY} --test-reporter tap --sequential --real-time --tests "${TESTS}"
+
+coverage:
+ NODE_PATH=`pwd`/lib/ ${WHISKEY} --sequential --coverage --coverage-reporter html --coverage-dir coverage_html --tests "${TESTS}"
+
+.PHONY: default test coverage tap scope
diff --git a/temporary_modules/trezor-connect/node_modules/elementtree/NOTICE b/temporary_modules/trezor-connect/node_modules/elementtree/NOTICE
new file mode 100644
index 00000000..28ad70aa
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/elementtree/NOTICE
@@ -0,0 +1,5 @@
+node-elementtree
+Copyright (c) 2011, Rackspace, Inc.
+
+The ElementTree toolkit is Copyright (c) 1999-2007 by Fredrik Lundh
+
diff --git a/temporary_modules/trezor-connect/node_modules/elementtree/README.md b/temporary_modules/trezor-connect/node_modules/elementtree/README.md
new file mode 100644
index 00000000..738420cc
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/elementtree/README.md
@@ -0,0 +1,141 @@
+node-elementtree
+====================
+
+node-elementtree is a [Node.js](http://nodejs.org) XML parser and serializer based upon the [Python ElementTree v1.3](http://effbot.org/zone/element-index.htm) module.
+
+Installation
+====================
+
+ $ npm install elementtree
+
+Using the library
+====================
+
+For the usage refer to the Python ElementTree library documentation - [http://effbot.org/zone/element-index.htm#usage](http://effbot.org/zone/element-index.htm#usage).
+
+Supported XPath expressions in `find`, `findall` and `findtext` methods are listed on [http://effbot.org/zone/element-xpath.htm](http://effbot.org/zone/element-xpath.htm).
+
+Example 1 – Creating An XML Document
+====================
+
+This example shows how to build a valid XML document that can be published to
+Atom Hopper. Atom Hopper is used internally as a bridge from products all the
+way to collecting revenue, called “Usage.” MaaS and other products send similar
+events to it every time user performs an action on a resource
+(e.g. creates,updates or deletes). Below is an example of leveraging the API
+to create a new XML document.
+
+```javascript
+var et = require('elementtree');
+var XML = et.XML;
+var ElementTree = et.ElementTree;
+var element = et.Element;
+var subElement = et.SubElement;
+
+var date, root, tenantId, serviceName, eventType, usageId, dataCenter, region,
+checks, resourceId, category, startTime, resourceName, etree, xml;
+
+date = new Date();
+
+root = element('entry');
+root.set('xmlns', 'http://www.w3.org/2005/Atom');
+
+tenantId = subElement(root, 'TenantId');
+tenantId.text = '12345';
+
+serviceName = subElement(root, 'ServiceName');
+serviceName.text = 'MaaS';
+
+resourceId = subElement(root, 'ResourceID');
+resourceId.text = 'enAAAA';
+
+usageId = subElement(root, 'UsageID');
+usageId.text = '550e8400-e29b-41d4-a716-446655440000';
+
+eventType = subElement(root, 'EventType');
+eventType.text = 'create';
+
+category = subElement(root, 'category');
+category.set('term', 'monitoring.entity.create');
+
+dataCenter = subElement(root, 'DataCenter');
+dataCenter.text = 'global';
+
+region = subElement(root, 'Region');
+region.text = 'global';
+
+startTime = subElement(root, 'StartTime');
+startTime.text = date;
+
+resourceName = subElement(root, 'ResourceName');
+resourceName.text = 'entity';
+
+etree = new ElementTree(root);
+xml = etree.write({'xml_declaration': false});
+console.log(xml);
+```
+
+As you can see, both et.Element and et.SubElement are factory methods which
+return a new instance of Element and SubElement class, respectively.
+When you create a new element (tag) you can use set method to set an attribute.
+To set the tag value, assign a value to the .text attribute.
+
+This example would output a document that looks like this:
+
+```xml
+
+ 12345
+ MaaS
+ enAAAA
+ 550e8400-e29b-41d4-a716-446655440000
+ create
+
+ global
+ global
+ Sun Apr 29 2012 16:37:32 GMT-0700 (PDT)
+ entity
+
+```
+
+Example 2 – Parsing An XML Document
+====================
+
+This example shows how to parse an XML document and use simple XPath selectors.
+For demonstration purposes, we will use the XML document located at
+https://gist.github.com/2554343.
+
+Behind the scenes, node-elementtree uses Isaac’s sax library for parsing XML,
+but the library has a concept of “parsers,” which means it’s pretty simple to
+add support for a different parser.
+
+```javascript
+var fs = require('fs');
+
+var et = require('elementtree');
+
+var XML = et.XML;
+var ElementTree = et.ElementTree;
+var element = et.Element;
+var subElement = et.SubElement;
+
+var data, etree;
+
+data = fs.readFileSync('document.xml').toString();
+etree = et.parse(data);
+
+console.log(etree.findall('./entry/TenantId').length); // 2
+console.log(etree.findtext('./entry/ServiceName')); // MaaS
+console.log(etree.findall('./entry/category')[0].get('term')); // monitoring.entity.create
+console.log(etree.findall('*/category/[@term="monitoring.entity.update"]').length); // 1
+```
+
+Build status
+====================
+
+[](http://travis-ci.org/racker/node-elementtree)
+
+
+License
+====================
+
+node-elementtree is distributed under the [Apache license](http://www.apache.org/licenses/LICENSE-2.0.html).
diff --git a/temporary_modules/trezor-connect/node_modules/elementtree/lib/constants.js b/temporary_modules/trezor-connect/node_modules/elementtree/lib/constants.js
new file mode 100644
index 00000000..b057fafe
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/elementtree/lib/constants.js
@@ -0,0 +1,20 @@
+/*
+ * Copyright 2011 Rackspace
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+var DEFAULT_PARSER = 'sax';
+
+exports.DEFAULT_PARSER = DEFAULT_PARSER;
diff --git a/temporary_modules/trezor-connect/node_modules/elementtree/lib/elementpath.js b/temporary_modules/trezor-connect/node_modules/elementtree/lib/elementpath.js
new file mode 100644
index 00000000..2e93f47e
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/elementtree/lib/elementpath.js
@@ -0,0 +1,343 @@
+/**
+ * Copyright 2011 Rackspace
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+var sprintf = require('./sprintf').sprintf;
+
+var utils = require('./utils');
+var SyntaxError = require('./errors').SyntaxError;
+
+var _cache = {};
+
+var RE = new RegExp(
+ "(" +
+ "'[^']*'|\"[^\"]*\"|" +
+ "::|" +
+ "//?|" +
+ "\\.\\.|" +
+ "\\(\\)|" +
+ "[/.*:\\[\\]\\(\\)@=])|" +
+ "((?:\\{[^}]+\\})?[^/\\[\\]\\(\\)@=\\s]+)|" +
+ "\\s+", 'g'
+);
+
+var xpath_tokenizer = utils.findall.bind(null, RE);
+
+function prepare_tag(next, token) {
+ var tag = token[0];
+
+ function select(context, result) {
+ var i, len, elem, rv = [];
+
+ for (i = 0, len = result.length; i < len; i++) {
+ elem = result[i];
+ elem._children.forEach(function(e) {
+ if (e.tag === tag) {
+ rv.push(e);
+ }
+ });
+ }
+
+ return rv;
+ }
+
+ return select;
+}
+
+function prepare_star(next, token) {
+ function select(context, result) {
+ var i, len, elem, rv = [];
+
+ for (i = 0, len = result.length; i < len; i++) {
+ elem = result[i];
+ elem._children.forEach(function(e) {
+ rv.push(e);
+ });
+ }
+
+ return rv;
+ }
+
+ return select;
+}
+
+function prepare_dot(next, token) {
+ function select(context, result) {
+ var i, len, elem, rv = [];
+
+ for (i = 0, len = result.length; i < len; i++) {
+ elem = result[i];
+ rv.push(elem);
+ }
+
+ return rv;
+ }
+
+ return select;
+}
+
+function prepare_iter(next, token) {
+ var tag;
+ token = next();
+
+ if (token[1] === '*') {
+ tag = '*';
+ }
+ else if (!token[1]) {
+ tag = token[0] || '';
+ }
+ else {
+ throw new SyntaxError(token);
+ }
+
+ function select(context, result) {
+ var i, len, elem, rv = [];
+
+ for (i = 0, len = result.length; i < len; i++) {
+ elem = result[i];
+ elem.iter(tag, function(e) {
+ if (e !== elem) {
+ rv.push(e);
+ }
+ });
+ }
+
+ return rv;
+ }
+
+ return select;
+}
+
+function prepare_dot_dot(next, token) {
+ function select(context, result) {
+ var i, len, elem, rv = [], parent_map = context.parent_map;
+
+ if (!parent_map) {
+ context.parent_map = parent_map = {};
+
+ context.root.iter(null, function(p) {
+ p._children.forEach(function(e) {
+ parent_map[e] = p;
+ });
+ });
+ }
+
+ for (i = 0, len = result.length; i < len; i++) {
+ elem = result[i];
+
+ if (parent_map.hasOwnProperty(elem)) {
+ rv.push(parent_map[elem]);
+ }
+ }
+
+ return rv;
+ }
+
+ return select;
+}
+
+
+function prepare_predicate(next, token) {
+ var tag, key, value, select;
+ token = next();
+
+ if (token[1] === '@') {
+ // attribute
+ token = next();
+
+ if (token[1]) {
+ throw new SyntaxError(token, 'Invalid attribute predicate');
+ }
+
+ key = token[0];
+ token = next();
+
+ if (token[1] === ']') {
+ select = function(context, result) {
+ var i, len, elem, rv = [];
+
+ for (i = 0, len = result.length; i < len; i++) {
+ elem = result[i];
+
+ if (elem.get(key)) {
+ rv.push(elem);
+ }
+ }
+
+ return rv;
+ };
+ }
+ else if (token[1] === '=') {
+ value = next()[1];
+
+ if (value[0] === '"' || value[value.length - 1] === '\'') {
+ value = value.slice(1, value.length - 1);
+ }
+ else {
+ throw new SyntaxError(token, 'Ivalid comparison target');
+ }
+
+ token = next();
+ select = function(context, result) {
+ var i, len, elem, rv = [];
+
+ for (i = 0, len = result.length; i < len; i++) {
+ elem = result[i];
+
+ if (elem.get(key) === value) {
+ rv.push(elem);
+ }
+ }
+
+ return rv;
+ };
+ }
+
+ if (token[1] !== ']') {
+ throw new SyntaxError(token, 'Invalid attribute predicate');
+ }
+ }
+ else if (!token[1]) {
+ tag = token[0] || '';
+ token = next();
+
+ if (token[1] !== ']') {
+ throw new SyntaxError(token, 'Invalid node predicate');
+ }
+
+ select = function(context, result) {
+ var i, len, elem, rv = [];
+
+ for (i = 0, len = result.length; i < len; i++) {
+ elem = result[i];
+
+ if (elem.find(tag)) {
+ rv.push(elem);
+ }
+ }
+
+ return rv;
+ };
+ }
+ else {
+ throw new SyntaxError(null, 'Invalid predicate');
+ }
+
+ return select;
+}
+
+
+
+var ops = {
+ "": prepare_tag,
+ "*": prepare_star,
+ ".": prepare_dot,
+ "..": prepare_dot_dot,
+ "//": prepare_iter,
+ "[": prepare_predicate,
+};
+
+function _SelectorContext(root) {
+ this.parent_map = null;
+ this.root = root;
+}
+
+function findall(elem, path) {
+ var selector, result, i, len, token, value, select, context;
+
+ if (_cache.hasOwnProperty(path)) {
+ selector = _cache[path];
+ }
+ else {
+ // TODO: Use smarter cache purging approach
+ if (Object.keys(_cache).length > 100) {
+ _cache = {};
+ }
+
+ if (path.charAt(0) === '/') {
+ throw new SyntaxError(null, 'Cannot use absolute path on element');
+ }
+
+ result = xpath_tokenizer(path);
+ selector = [];
+
+ function getToken() {
+ return result.shift();
+ }
+
+ token = getToken();
+ while (true) {
+ var c = token[1] || '';
+ value = ops[c](getToken, token);
+
+ if (!value) {
+ throw new SyntaxError(null, sprintf('Invalid path: %s', path));
+ }
+
+ selector.push(value);
+ token = getToken();
+
+ if (!token) {
+ break;
+ }
+ else if (token[1] === '/') {
+ token = getToken();
+ }
+
+ if (!token) {
+ break;
+ }
+ }
+
+ _cache[path] = selector;
+ }
+
+ // Execute slector pattern
+ result = [elem];
+ context = new _SelectorContext(elem);
+
+ for (i = 0, len = selector.length; i < len; i++) {
+ select = selector[i];
+ result = select(context, result);
+ }
+
+ return result || [];
+}
+
+function find(element, path) {
+ var resultElements = findall(element, path);
+
+ if (resultElements && resultElements.length > 0) {
+ return resultElements[0];
+ }
+
+ return null;
+}
+
+function findtext(element, path, defvalue) {
+ var resultElements = findall(element, path);
+
+ if (resultElements && resultElements.length > 0) {
+ return resultElements[0].text;
+ }
+
+ return defvalue;
+}
+
+
+exports.find = find;
+exports.findall = findall;
+exports.findtext = findtext;
diff --git a/temporary_modules/trezor-connect/node_modules/elementtree/lib/elementtree.js b/temporary_modules/trezor-connect/node_modules/elementtree/lib/elementtree.js
new file mode 100644
index 00000000..61d92769
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/elementtree/lib/elementtree.js
@@ -0,0 +1,611 @@
+/**
+ * Copyright 2011 Rackspace
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+var sprintf = require('./sprintf').sprintf;
+
+var utils = require('./utils');
+var ElementPath = require('./elementpath');
+var TreeBuilder = require('./treebuilder').TreeBuilder;
+var get_parser = require('./parser').get_parser;
+var constants = require('./constants');
+
+var element_ids = 0;
+
+function Element(tag, attrib)
+{
+ this._id = element_ids++;
+ this.tag = tag;
+ this.attrib = {};
+ this.text = null;
+ this.tail = null;
+ this._children = [];
+
+ if (attrib) {
+ this.attrib = utils.merge(this.attrib, attrib);
+ }
+}
+
+Element.prototype.toString = function()
+{
+ return sprintf("", this.tag, this._id);
+};
+
+Element.prototype.makeelement = function(tag, attrib)
+{
+ return new Element(tag, attrib);
+};
+
+Element.prototype.len = function()
+{
+ return this._children.length;
+};
+
+Element.prototype.getItem = function(index)
+{
+ return this._children[index];
+};
+
+Element.prototype.setItem = function(index, element)
+{
+ this._children[index] = element;
+};
+
+Element.prototype.delItem = function(index)
+{
+ this._children.splice(index, 1);
+};
+
+Element.prototype.getSlice = function(start, stop)
+{
+ return this._children.slice(start, stop);
+};
+
+Element.prototype.setSlice = function(start, stop, elements)
+{
+ var i;
+ var k = 0;
+ for (i = start; i < stop; i++, k++) {
+ this._children[i] = elements[k];
+ }
+};
+
+Element.prototype.delSlice = function(start, stop)
+{
+ this._children.splice(start, stop - start);
+};
+
+Element.prototype.append = function(element)
+{
+ this._children.push(element);
+};
+
+Element.prototype.extend = function(elements)
+{
+ this._children.concat(elements);
+};
+
+Element.prototype.insert = function(index, element)
+{
+ this._children[index] = element;
+};
+
+Element.prototype.remove = function(element)
+{
+ this._children = this._children.filter(function(e) {
+ /* TODO: is this the right way to do this? */
+ if (e._id === element._id) {
+ return false;
+ }
+ return true;
+ });
+};
+
+Element.prototype.getchildren = function() {
+ return this._children;
+};
+
+Element.prototype.find = function(path)
+{
+ return ElementPath.find(this, path);
+};
+
+Element.prototype.findtext = function(path, defvalue)
+{
+ return ElementPath.findtext(this, path, defvalue);
+};
+
+Element.prototype.findall = function(path, defvalue)
+{
+ return ElementPath.findall(this, path, defvalue);
+};
+
+Element.prototype.clear = function()
+{
+ this.attrib = {};
+ this._children = [];
+ this.text = null;
+ this.tail = null;
+};
+
+Element.prototype.get = function(key, defvalue)
+{
+ if (this.attrib[key] !== undefined) {
+ return this.attrib[key];
+ }
+ else {
+ return defvalue;
+ }
+};
+
+Element.prototype.set = function(key, value)
+{
+ this.attrib[key] = value;
+};
+
+Element.prototype.keys = function()
+{
+ return Object.keys(this.attrib);
+};
+
+Element.prototype.items = function()
+{
+ return utils.items(this.attrib);
+};
+
+/*
+ * In python this uses a generator, but in v8 we don't have em,
+ * so we use a callback instead.
+ **/
+Element.prototype.iter = function(tag, callback)
+{
+ var self = this;
+ var i, child;
+
+ if (tag === "*") {
+ tag = null;
+ }
+
+ if (tag === null || this.tag === tag) {
+ callback(self);
+ }
+
+ for (i = 0; i < this._children.length; i++) {
+ child = this._children[i];
+ child.iter(tag, function(e) {
+ callback(e);
+ });
+ }
+};
+
+Element.prototype.itertext = function(callback)
+{
+ this.iter(null, function(e) {
+ if (e.text) {
+ callback(e.text);
+ }
+
+ if (e.tail) {
+ callback(e.tail);
+ }
+ });
+};
+
+
+function SubElement(parent, tag, attrib) {
+ var element = parent.makeelement(tag, attrib);
+ parent.append(element);
+ return element;
+}
+
+function Comment(text) {
+ var element = new Element(Comment);
+ if (text) {
+ element.text = text;
+ }
+ return element;
+}
+
+function CData(text) {
+ var element = new Element(CData);
+ if (text) {
+ element.text = text;
+ }
+ return element;
+}
+
+function ProcessingInstruction(target, text)
+{
+ var element = new Element(ProcessingInstruction);
+ element.text = target;
+ if (text) {
+ element.text = element.text + " " + text;
+ }
+ return element;
+}
+
+function QName(text_or_uri, tag)
+{
+ if (tag) {
+ text_or_uri = sprintf("{%s}%s", text_or_uri, tag);
+ }
+ this.text = text_or_uri;
+}
+
+QName.prototype.toString = function() {
+ return this.text;
+};
+
+function ElementTree(element)
+{
+ this._root = element;
+}
+
+ElementTree.prototype.getroot = function() {
+ return this._root;
+};
+
+ElementTree.prototype._setroot = function(element) {
+ this._root = element;
+};
+
+ElementTree.prototype.parse = function(source, parser) {
+ if (!parser) {
+ parser = get_parser(constants.DEFAULT_PARSER);
+ parser = new parser.XMLParser(new TreeBuilder());
+ }
+
+ parser.feed(source);
+ this._root = parser.close();
+ return this._root;
+};
+
+ElementTree.prototype.iter = function(tag, callback) {
+ this._root.iter(tag, callback);
+};
+
+ElementTree.prototype.find = function(path) {
+ return this._root.find(path);
+};
+
+ElementTree.prototype.findtext = function(path, defvalue) {
+ return this._root.findtext(path, defvalue);
+};
+
+ElementTree.prototype.findall = function(path) {
+ return this._root.findall(path);
+};
+
+/**
+ * Unlike ElementTree, we don't write to a file, we return you a string.
+ */
+ElementTree.prototype.write = function(options) {
+ var sb = [];
+ options = utils.merge({
+ encoding: 'utf-8',
+ xml_declaration: null,
+ default_namespace: null,
+ method: 'xml'}, options);
+
+ if (options.xml_declaration !== false) {
+ sb.push("\n");
+ }
+
+ if (options.method === "text") {
+ _serialize_text(sb, self._root, encoding);
+ }
+ else {
+ var qnames, namespaces, indent, indent_string;
+ var x = _namespaces(this._root, options.encoding, options.default_namespace);
+ qnames = x[0];
+ namespaces = x[1];
+
+ if (options.hasOwnProperty('indent')) {
+ indent = 0;
+ indent_string = new Array(options.indent + 1).join(' ');
+ }
+ else {
+ indent = false;
+ }
+
+ if (options.method === "xml") {
+ _serialize_xml(function(data) {
+ sb.push(data);
+ }, this._root, options.encoding, qnames, namespaces, indent, indent_string);
+ }
+ else {
+ /* TODO: html */
+ throw new Error("unknown serialization method "+ options.method);
+ }
+ }
+
+ return sb.join("");
+};
+
+var _namespace_map = {
+ /* "well-known" namespace prefixes */
+ "http://www.w3.org/XML/1998/namespace": "xml",
+ "http://www.w3.org/1999/xhtml": "html",
+ "http://www.w3.org/1999/02/22-rdf-syntax-ns#": "rdf",
+ "http://schemas.xmlsoap.org/wsdl/": "wsdl",
+ /* xml schema */
+ "http://www.w3.org/2001/XMLSchema": "xs",
+ "http://www.w3.org/2001/XMLSchema-instance": "xsi",
+ /* dublic core */
+ "http://purl.org/dc/elements/1.1/": "dc",
+};
+
+function register_namespace(prefix, uri) {
+ if (/ns\d+$/.test(prefix)) {
+ throw new Error('Prefix format reserved for internal use');
+ }
+
+ if (_namespace_map.hasOwnProperty(uri) && _namespace_map[uri] === prefix) {
+ delete _namespace_map[uri];
+ }
+
+ _namespace_map[uri] = prefix;
+}
+
+
+function _escape(text, encoding, isAttribute, isText) {
+ if (text) {
+ text = text.toString();
+ text = text.replace(/&/g, '&');
+ text = text.replace(//g, '>');
+ if (!isText) {
+ text = text.replace(/\n/g, '
');
+ text = text.replace(/\r/g, '
');
+ }
+ if (isAttribute) {
+ text = text.replace(/"/g, '"');
+ }
+ }
+ return text;
+}
+
+/* TODO: benchmark single regex */
+function _escape_attrib(text, encoding) {
+ return _escape(text, encoding, true);
+}
+
+function _escape_cdata(text, encoding) {
+ return _escape(text, encoding, false);
+}
+
+function _escape_text(text, encoding) {
+ return _escape(text, encoding, false, true);
+}
+
+function _namespaces(elem, encoding, default_namespace) {
+ var qnames = {};
+ var namespaces = {};
+
+ if (default_namespace) {
+ namespaces[default_namespace] = "";
+ }
+
+ function encode(text) {
+ return text;
+ }
+
+ function add_qname(qname) {
+ if (qname[0] === "{") {
+ var tmp = qname.substring(1).split("}", 2);
+ var uri = tmp[0];
+ var tag = tmp[1];
+ var prefix = namespaces[uri];
+
+ if (prefix === undefined) {
+ prefix = _namespace_map[uri];
+ if (prefix === undefined) {
+ prefix = "ns" + Object.keys(namespaces).length;
+ }
+ if (prefix !== "xml") {
+ namespaces[uri] = prefix;
+ }
+ }
+
+ if (prefix) {
+ qnames[qname] = sprintf("%s:%s", prefix, tag);
+ }
+ else {
+ qnames[qname] = tag;
+ }
+ }
+ else {
+ if (default_namespace) {
+ throw new Error('cannot use non-qualified names with default_namespace option');
+ }
+
+ qnames[qname] = qname;
+ }
+ }
+
+
+ elem.iter(null, function(e) {
+ var i;
+ var tag = e.tag;
+ var text = e.text;
+ var items = e.items();
+
+ if (tag instanceof QName && qnames[tag.text] === undefined) {
+ add_qname(tag.text);
+ }
+ else if (typeof(tag) === "string") {
+ add_qname(tag);
+ }
+ else if (tag !== null && tag !== Comment && tag !== CData && tag !== ProcessingInstruction) {
+ throw new Error('Invalid tag type for serialization: '+ tag);
+ }
+
+ if (text instanceof QName && qnames[text.text] === undefined) {
+ add_qname(text.text);
+ }
+
+ items.forEach(function(item) {
+ var key = item[0],
+ value = item[1];
+ if (key instanceof QName) {
+ key = key.text;
+ }
+
+ if (qnames[key] === undefined) {
+ add_qname(key);
+ }
+
+ if (value instanceof QName && qnames[value.text] === undefined) {
+ add_qname(value.text);
+ }
+ });
+ });
+ return [qnames, namespaces];
+}
+
+function _serialize_xml(write, elem, encoding, qnames, namespaces, indent, indent_string) {
+ var tag = elem.tag;
+ var text = elem.text;
+ var items;
+ var i;
+
+ var newlines = indent || (indent === 0);
+ write(Array(indent + 1).join(indent_string));
+
+ if (tag === Comment) {
+ write(sprintf("", _escape_cdata(text, encoding)));
+ }
+ else if (tag === ProcessingInstruction) {
+ write(sprintf("%s?>", _escape_cdata(text, encoding)));
+ }
+ else if (tag === CData) {
+ text = text || '';
+ write(sprintf("", text));
+ }
+ else {
+ tag = qnames[tag];
+ if (tag === undefined) {
+ if (text) {
+ write(_escape_text(text, encoding));
+ }
+ elem.iter(function(e) {
+ _serialize_xml(write, e, encoding, qnames, null, newlines ? indent + 1 : false, indent_string);
+ });
+ }
+ else {
+ write("<" + tag);
+ items = elem.items();
+
+ if (items || namespaces) {
+ items.sort(); // lexical order
+
+ items.forEach(function(item) {
+ var k = item[0],
+ v = item[1];
+
+ if (k instanceof QName) {
+ k = k.text;
+ }
+
+ if (v instanceof QName) {
+ v = qnames[v.text];
+ }
+ else {
+ v = _escape_attrib(v, encoding);
+ }
+ write(sprintf(" %s=\"%s\"", qnames[k], v));
+ });
+
+ if (namespaces) {
+ items = utils.items(namespaces);
+ items.sort(function(a, b) { return a[1] < b[1]; });
+
+ items.forEach(function(item) {
+ var k = item[1],
+ v = item[0];
+
+ if (k) {
+ k = ':' + k;
+ }
+
+ write(sprintf(" xmlns%s=\"%s\"", k, _escape_attrib(v, encoding)));
+ });
+ }
+ }
+
+ if (text || elem.len()) {
+ if (text && text.toString().match(/^\s*$/)) {
+ text = null;
+ }
+
+ write(">");
+ if (!text && newlines) {
+ write("\n");
+ }
+
+ if (text) {
+ write(_escape_text(text, encoding));
+ }
+ elem._children.forEach(function(e) {
+ _serialize_xml(write, e, encoding, qnames, null, newlines ? indent + 1 : false, indent_string);
+ });
+
+ if (!text && indent) {
+ write(Array(indent + 1).join(indent_string));
+ }
+ write("" + tag + ">");
+ }
+ else {
+ write(" />");
+ }
+ }
+ }
+
+ if (newlines) {
+ write("\n");
+ }
+}
+
+function parse(source, parser) {
+ var tree = new ElementTree();
+ tree.parse(source, parser);
+ return tree;
+}
+
+function tostring(element, options) {
+ return new ElementTree(element).write(options);
+}
+
+exports.PI = ProcessingInstruction;
+exports.Comment = Comment;
+exports.CData = CData;
+exports.ProcessingInstruction = ProcessingInstruction;
+exports.SubElement = SubElement;
+exports.QName = QName;
+exports.ElementTree = ElementTree;
+exports.ElementPath = ElementPath;
+exports.Element = function(tag, attrib) {
+ return new Element(tag, attrib);
+};
+
+exports.XML = function(data) {
+ var et = new ElementTree();
+ return et.parse(data);
+};
+
+exports.parse = parse;
+exports.register_namespace = register_namespace;
+exports.tostring = tostring;
diff --git a/temporary_modules/trezor-connect/node_modules/elementtree/lib/errors.js b/temporary_modules/trezor-connect/node_modules/elementtree/lib/errors.js
new file mode 100644
index 00000000..e8742be1
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/elementtree/lib/errors.js
@@ -0,0 +1,31 @@
+/**
+ * Copyright 2011 Rackspace
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+var util = require('util');
+
+var sprintf = require('./sprintf').sprintf;
+
+function SyntaxError(token, msg) {
+ msg = msg || sprintf('Syntax Error at token %s', token.toString());
+ this.token = token;
+ this.message = msg;
+ Error.call(this, msg);
+}
+
+util.inherits(SyntaxError, Error);
+
+exports.SyntaxError = SyntaxError;
diff --git a/temporary_modules/trezor-connect/node_modules/elementtree/lib/parser.js b/temporary_modules/trezor-connect/node_modules/elementtree/lib/parser.js
new file mode 100644
index 00000000..7307ee47
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/elementtree/lib/parser.js
@@ -0,0 +1,33 @@
+/*
+ * Copyright 2011 Rackspace
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+/* TODO: support node-expat C++ module optionally */
+
+var util = require('util');
+var parsers = require('./parsers/index');
+
+function get_parser(name) {
+ if (name === 'sax') {
+ return parsers.sax;
+ }
+ else {
+ throw new Error('Invalid parser: ' + name);
+ }
+}
+
+
+exports.get_parser = get_parser;
diff --git a/temporary_modules/trezor-connect/node_modules/elementtree/lib/parsers/index.js b/temporary_modules/trezor-connect/node_modules/elementtree/lib/parsers/index.js
new file mode 100644
index 00000000..5eac5c88
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/elementtree/lib/parsers/index.js
@@ -0,0 +1 @@
+exports.sax = require('./sax');
diff --git a/temporary_modules/trezor-connect/node_modules/elementtree/lib/parsers/sax.js b/temporary_modules/trezor-connect/node_modules/elementtree/lib/parsers/sax.js
new file mode 100644
index 00000000..69b0a59b
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/elementtree/lib/parsers/sax.js
@@ -0,0 +1,56 @@
+var util = require('util');
+
+var sax = require('sax');
+
+var TreeBuilder = require('./../treebuilder').TreeBuilder;
+
+function XMLParser(target) {
+ this.parser = sax.parser(true);
+
+ this.target = (target) ? target : new TreeBuilder();
+
+ this.parser.onopentag = this._handleOpenTag.bind(this);
+ this.parser.ontext = this._handleText.bind(this);
+ this.parser.oncdata = this._handleCdata.bind(this);
+ this.parser.ondoctype = this._handleDoctype.bind(this);
+ this.parser.oncomment = this._handleComment.bind(this);
+ this.parser.onclosetag = this._handleCloseTag.bind(this);
+ this.parser.onerror = this._handleError.bind(this);
+}
+
+XMLParser.prototype._handleOpenTag = function(tag) {
+ this.target.start(tag.name, tag.attributes);
+};
+
+XMLParser.prototype._handleText = function(text) {
+ this.target.data(text);
+};
+
+XMLParser.prototype._handleCdata = function(text) {
+ this.target.data(text);
+};
+
+XMLParser.prototype._handleDoctype = function(text) {
+};
+
+XMLParser.prototype._handleComment = function(comment) {
+};
+
+XMLParser.prototype._handleCloseTag = function(tag) {
+ this.target.end(tag);
+};
+
+XMLParser.prototype._handleError = function(err) {
+ throw err;
+};
+
+XMLParser.prototype.feed = function(chunk) {
+ this.parser.write(chunk);
+};
+
+XMLParser.prototype.close = function() {
+ this.parser.close();
+ return this.target.close();
+};
+
+exports.XMLParser = XMLParser;
diff --git a/temporary_modules/trezor-connect/node_modules/elementtree/lib/sprintf.js b/temporary_modules/trezor-connect/node_modules/elementtree/lib/sprintf.js
new file mode 100644
index 00000000..f802c1b4
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/elementtree/lib/sprintf.js
@@ -0,0 +1,86 @@
+/*
+ * Copyright 2011 Rackspace
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+var cache = {};
+
+
+// Do any others need escaping?
+var TO_ESCAPE = {
+ '\'': '\\\'',
+ '\n': '\\n'
+};
+
+
+function populate(formatter) {
+ var i, type,
+ key = formatter,
+ prev = 0,
+ arg = 1,
+ builder = 'return \'';
+
+ for (i = 0; i < formatter.length; i++) {
+ if (formatter[i] === '%') {
+ type = formatter[i + 1];
+
+ switch (type) {
+ case 's':
+ builder += formatter.slice(prev, i) + '\' + arguments[' + arg + '] + \'';
+ prev = i + 2;
+ arg++;
+ break;
+ case 'j':
+ builder += formatter.slice(prev, i) + '\' + JSON.stringify(arguments[' + arg + ']) + \'';
+ prev = i + 2;
+ arg++;
+ break;
+ case '%':
+ builder += formatter.slice(prev, i + 1);
+ prev = i + 2;
+ i++;
+ break;
+ }
+
+
+ } else if (TO_ESCAPE[formatter[i]]) {
+ builder += formatter.slice(prev, i) + TO_ESCAPE[formatter[i]];
+ prev = i + 1;
+ }
+ }
+
+ builder += formatter.slice(prev) + '\';';
+ cache[key] = new Function(builder);
+}
+
+
+/**
+ * A fast version of sprintf(), which currently only supports the %s and %j.
+ * This caches a formatting function for each format string that is used, so
+ * you should only use this sprintf() will be called many times with a single
+ * format string and a limited number of format strings will ever be used (in
+ * general this means that format strings should be string literals).
+ *
+ * @param {String} formatter A format string.
+ * @param {...String} var_args Values that will be formatted by %s and %j.
+ * @return {String} The formatted output.
+ */
+exports.sprintf = function(formatter, var_args) {
+ if (!cache[formatter]) {
+ populate(formatter);
+ }
+
+ return cache[formatter].apply(null, arguments);
+};
diff --git a/temporary_modules/trezor-connect/node_modules/elementtree/lib/treebuilder.js b/temporary_modules/trezor-connect/node_modules/elementtree/lib/treebuilder.js
new file mode 100644
index 00000000..393a98fa
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/elementtree/lib/treebuilder.js
@@ -0,0 +1,60 @@
+function TreeBuilder(element_factory) {
+ this._data = [];
+ this._elem = [];
+ this._last = null;
+ this._tail = null;
+ if (!element_factory) {
+ /* evil circular dep */
+ element_factory = require('./elementtree').Element;
+ }
+ this._factory = element_factory;
+}
+
+TreeBuilder.prototype.close = function() {
+ return this._last;
+};
+
+TreeBuilder.prototype._flush = function() {
+ if (this._data) {
+ if (this._last !== null) {
+ var text = this._data.join("");
+ if (this._tail) {
+ this._last.tail = text;
+ }
+ else {
+ this._last.text = text;
+ }
+ }
+ this._data = [];
+ }
+};
+
+TreeBuilder.prototype.data = function(data) {
+ this._data.push(data);
+};
+
+TreeBuilder.prototype.start = function(tag, attrs) {
+ this._flush();
+ var elem = this._factory(tag, attrs);
+ this._last = elem;
+
+ if (this._elem.length) {
+ this._elem[this._elem.length - 1].append(elem);
+ }
+
+ this._elem.push(elem);
+
+ this._tail = null;
+};
+
+TreeBuilder.prototype.end = function(tag) {
+ this._flush();
+ this._last = this._elem.pop();
+ if (this._last.tag !== tag) {
+ throw new Error("end tag mismatch");
+ }
+ this._tail = 1;
+ return this._last;
+};
+
+exports.TreeBuilder = TreeBuilder;
diff --git a/temporary_modules/trezor-connect/node_modules/elementtree/lib/utils.js b/temporary_modules/trezor-connect/node_modules/elementtree/lib/utils.js
new file mode 100644
index 00000000..b08a6706
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/elementtree/lib/utils.js
@@ -0,0 +1,72 @@
+/**
+ * Copyright 2011 Rackspace
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+/**
+ * @param {Object} hash.
+ * @param {Array} ignored.
+ */
+function items(hash, ignored) {
+ ignored = ignored || null;
+ var k, rv = [];
+
+ function is_ignored(key) {
+ if (!ignored || ignored.length === 0) {
+ return false;
+ }
+
+ return ignored.indexOf(key);
+ }
+
+ for (k in hash) {
+ if (hash.hasOwnProperty(k) && !(is_ignored(ignored))) {
+ rv.push([k, hash[k]]);
+ }
+ }
+
+ return rv;
+}
+
+
+function findall(re, str) {
+ var match, matches = [];
+
+ while ((match = re.exec(str))) {
+ matches.push(match);
+ }
+
+ return matches;
+}
+
+function merge(a, b) {
+ var c = {}, attrname;
+
+ for (attrname in a) {
+ if (a.hasOwnProperty(attrname)) {
+ c[attrname] = a[attrname];
+ }
+ }
+ for (attrname in b) {
+ if (b.hasOwnProperty(attrname)) {
+ c[attrname] = b[attrname];
+ }
+ }
+ return c;
+}
+
+exports.items = items;
+exports.findall = findall;
+exports.merge = merge;
diff --git a/temporary_modules/trezor-connect/node_modules/elementtree/package.json b/temporary_modules/trezor-connect/node_modules/elementtree/package.json
new file mode 100644
index 00000000..e7480e74
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/elementtree/package.json
@@ -0,0 +1,39 @@
+{
+ "author": "Rackspace US, Inc.",
+ "contributors": [
+ "Paul Querna ",
+ "Tomaz Muraus "
+ ],
+ "name": "elementtree",
+ "description": "XML Serialization and Parsing module based on Python's ElementTree.",
+ "version": "0.1.7",
+ "keywords": [
+ "xml",
+ "sax",
+ "parser",
+ "seralization",
+ "elementtree"
+ ],
+ "homepage": "https://github.com/racker/node-elementtree",
+ "repository": {
+ "type": "git",
+ "url": "git://github.com/racker/node-elementtree.git"
+ },
+ "main": "lib/elementtree.js",
+ "directories": {
+ "lib": "lib"
+ },
+ "scripts": {
+ "test": "make test"
+ },
+ "engines": {
+ "node": ">= 0.4.0"
+ },
+ "dependencies": {
+ "sax": "1.1.4"
+ },
+ "devDependencies": {
+ "whiskey": "0.8.x"
+ },
+ "license": "Apache-2.0"
+}
diff --git a/temporary_modules/trezor-connect/node_modules/elementtree/tests/data/bom-xml.xml b/temporary_modules/trezor-connect/node_modules/elementtree/tests/data/bom-xml.xml
new file mode 100644
index 00000000..122cce62
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/elementtree/tests/data/bom-xml.xml
@@ -0,0 +1,17 @@
+
+
+
+
+
diff --git a/temporary_modules/trezor-connect/node_modules/elementtree/tests/data/xml1.xml b/temporary_modules/trezor-connect/node_modules/elementtree/tests/data/xml1.xml
new file mode 100644
index 00000000..72c33aec
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/elementtree/tests/data/xml1.xml
@@ -0,0 +1,17 @@
+
+
+
+
+
diff --git a/temporary_modules/trezor-connect/node_modules/elementtree/tests/data/xml2.xml b/temporary_modules/trezor-connect/node_modules/elementtree/tests/data/xml2.xml
new file mode 100644
index 00000000..5f94bbd9
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/elementtree/tests/data/xml2.xml
@@ -0,0 +1,14 @@
+
+
diff --git a/temporary_modules/trezor-connect/node_modules/elementtree/tests/test-simple.js b/temporary_modules/trezor-connect/node_modules/elementtree/tests/test-simple.js
new file mode 100644
index 00000000..629a2086
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/elementtree/tests/test-simple.js
@@ -0,0 +1,348 @@
+/**
+ * Copyright 2011 Rackspace
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+var fs = require('fs');
+var path = require('path');
+
+var sprintf = require('./../lib/sprintf').sprintf;
+var et = require('elementtree');
+var XML = et.XML;
+var ElementTree = et.ElementTree;
+var Element = et.Element;
+var SubElement = et.SubElement;
+var SyntaxError = require('./../lib/errors').SyntaxError;
+
+function readFile(name) {
+ return fs.readFileSync(path.join(__dirname, '/data/', name), 'utf8');
+}
+
+exports['test_simplest'] = function(test, assert) {
+ /* Ported from */
+ var Element = et.Element;
+ var root = Element('root');
+ root.append(Element('one'));
+ root.append(Element('two'));
+ root.append(Element('three'));
+ assert.equal(3, root.len());
+ assert.equal('one', root.getItem(0).tag);
+ assert.equal('two', root.getItem(1).tag);
+ assert.equal('three', root.getItem(2).tag);
+ test.finish();
+};
+
+
+exports['test_attribute_values'] = function(test, assert) {
+ var XML = et.XML;
+ var root = XML('');
+ assert.equal('Alpha', root.attrib['alpha']);
+ assert.equal('Beta', root.attrib['beta']);
+ assert.equal('Gamma', root.attrib['gamma']);
+ test.finish();
+};
+
+
+exports['test_findall'] = function(test, assert) {
+ var XML = et.XML;
+ var root = XML('');
+
+ assert.equal(root.findall("c").length, 1);
+ assert.equal(root.findall(".//c").length, 2);
+ assert.equal(root.findall(".//b").length, 3);
+ assert.equal(root.findall(".//b")[0]._children.length, 1);
+ assert.equal(root.findall(".//b")[1]._children.length, 0);
+ assert.equal(root.findall(".//b")[2]._children.length, 0);
+ assert.deepEqual(root.findall('.//b')[0], root.getchildren()[0]);
+
+ test.finish();
+};
+
+exports['test_find'] = function(test, assert) {
+ var a = Element('a');
+ var b = SubElement(a, 'b');
+ var c = SubElement(a, 'c');
+
+ assert.deepEqual(a.find('./b/..'), a);
+ test.finish();
+};
+
+exports['test_elementtree_find_qname'] = function(test, assert) {
+ var tree = new et.ElementTree(XML(''));
+ assert.deepEqual(tree.find(new et.QName('c')), tree.getroot()._children[2]);
+ test.finish();
+};
+
+exports['test_attrib_ns_clear'] = function(test, assert) {
+ var attribNS = '{http://foo/bar}x';
+
+ var par = Element('par');
+ par.set(attribNS, 'a');
+ var child = SubElement(par, 'child');
+ child.set(attribNS, 'b');
+
+ assert.equal('a', par.get(attribNS));
+ assert.equal('b', child.get(attribNS));
+
+ par.clear();
+ assert.equal(null, par.get(attribNS));
+ assert.equal('b', child.get(attribNS));
+ test.finish();
+};
+
+exports['test_create_tree_and_parse_simple'] = function(test, assert) {
+ var i = 0;
+ var e = new Element('bar', {});
+ var expected = "\n" +
+ 'ponies';
+
+ SubElement(e, "blah", {a: 11});
+ SubElement(e, "blah", {a: 12});
+ var se = et.SubElement(e, "gag", {a: '13', b: 'abc'});
+ se.text = 'ponies';
+
+ se.itertext(function(text) {
+ assert.equal(text, 'ponies');
+ i++;
+ });
+
+ assert.equal(i, 1);
+ var etree = new ElementTree(e);
+ var xml = etree.write();
+ assert.equal(xml, expected);
+ test.finish();
+};
+
+exports['test_write_with_options'] = function(test, assert) {
+ var i = 0;
+ var e = new Element('bar', {});
+ var expected1 = "\n" +
+ '\n' +
+ ' \n' +
+ ' test\n' +
+ ' \n' +
+ ' \n' +
+ ' ponies\n' +
+ '\n';
+ var expected2 = "\n" +
+ '\n' +
+ ' \n' +
+ ' test\n' +
+ ' \n' +
+ ' \n' +
+ ' ponies\n' +
+ '\n';
+
+ var expected3 = "\n" +
+ '\n' +
+ ' \n' +
+ ' Hello World\n' +
+ ' \n' +
+ ' \n' +
+ ' \n' +
+ ' \n' +
+ ' \n' +
+ ' \n' +
+ ' \n' +
+ ' Test & Test & Test\n' +
+ ' \n' +
+ '\n';
+
+ var se1 = SubElement(e, "blah", {a: 11});
+ var se2 = SubElement(se1, "baz", {d: 11});
+ se2.text = 'test';
+ SubElement(e, "blah", {a: 12});
+ var se = et.SubElement(e, "gag", {a: '13', b: 'abc'});
+ se.text = 'ponies';
+
+ se.itertext(function(text) {
+ assert.equal(text, 'ponies');
+ i++;
+ });
+
+ assert.equal(i, 1);
+ var etree = new ElementTree(e);
+ var xml1 = etree.write({'indent': 4});
+ var xml2 = etree.write({'indent': 2});
+ assert.equal(xml1, expected1);
+ assert.equal(xml2, expected2);
+
+ var file = readFile('xml2.xml');
+ var etree2 = et.parse(file);
+ var xml3 = etree2.write({'indent': 4});
+ assert.equal(xml3, expected3);
+ test.finish();
+};
+
+exports['test_parse_and_find_2'] = function(test, assert) {
+ var data = readFile('xml1.xml');
+ var etree = et.parse(data);
+
+ assert.equal(etree.findall('./object').length, 2);
+ assert.equal(etree.findall('[@name]').length, 1);
+ assert.equal(etree.findall('[@name="test_container_1"]').length, 1);
+ assert.equal(etree.findall('[@name=\'test_container_1\']').length, 1);
+ assert.equal(etree.findall('./object')[0].findtext('name'), 'test_object_1');
+ assert.equal(etree.findtext('./object/name'), 'test_object_1');
+ assert.equal(etree.findall('.//bytes').length, 2);
+ assert.equal(etree.findall('*/bytes').length, 2);
+ assert.equal(etree.findall('*/foobar').length, 0);
+
+ test.finish();
+};
+
+exports['test_namespaced_attribute'] = function(test, assert) {
+ var data = readFile('xml1.xml');
+ var etree = et.parse(data);
+
+ assert.equal(etree.findall('*/bytes[@android:type="cool"]').length, 1);
+
+ test.finish();
+}
+
+exports['test_syntax_errors'] = function(test, assert) {
+ var expressions = [ './/@bar', '[@bar', '[@foo=bar]', '[@', '/bar' ];
+ var errCount = 0;
+ var data = readFile('xml1.xml');
+ var etree = et.parse(data);
+
+ expressions.forEach(function(expression) {
+ try {
+ etree.findall(expression);
+ }
+ catch (err) {
+ errCount++;
+ }
+ });
+
+ assert.equal(errCount, expressions.length);
+ test.finish();
+};
+
+exports['test_register_namespace'] = function(test, assert){
+ var prefix = 'TESTPREFIX';
+ var namespace = 'http://seriously.unknown/namespace/URI';
+ var errCount = 0;
+
+ var etree = Element(sprintf('{%s}test', namespace));
+ assert.equal(et.tostring(etree, { 'xml_declaration': false}),
+ sprintf('', namespace));
+
+ et.register_namespace(prefix, namespace);
+ var etree = Element(sprintf('{%s}test', namespace));
+ assert.equal(et.tostring(etree, { 'xml_declaration': false}),
+ sprintf('<%s:test xmlns:%s="%s" />', prefix, prefix, namespace));
+
+ try {
+ et.register_namespace('ns25', namespace);
+ }
+ catch (err) {
+ errCount++;
+ }
+
+ assert.equal(errCount, 1, 'Reserved prefix used, but exception was not thrown');
+ test.finish();
+};
+
+exports['test_tostring'] = function(test, assert) {
+ var a = Element('a');
+ var b = SubElement(a, 'b');
+ var c = SubElement(a, 'c');
+ c.text = 543;
+
+ assert.equal(et.tostring(a, { 'xml_declaration': false }), '543');
+ assert.equal(et.tostring(c, { 'xml_declaration': false }), '543');
+ test.finish();
+};
+
+exports['test_escape'] = function(test, assert) {
+ var a = Element('a');
+ var b = SubElement(a, 'b');
+ b.text = '&&&&<>"\n\r';
+
+ assert.equal(et.tostring(a, { 'xml_declaration': false }), '&&&&<>\"\n\r');
+ test.finish();
+};
+
+exports['test_find_null'] = function(test, assert) {
+ var root = Element('root');
+ var node = SubElement(root, 'node');
+ var leaf = SubElement(node, 'leaf');
+ leaf.text = 'ipsum';
+
+ assert.equal(root.find('node/leaf'), leaf);
+ assert.equal(root.find('no-such-node/leaf'), null);
+ test.finish();
+};
+
+exports['test_findtext_null'] = function(test, assert) {
+ var root = Element('root');
+ var node = SubElement(root, 'node');
+ var leaf = SubElement(node, 'leaf');
+ leaf.text = 'ipsum';
+
+ assert.equal(root.findtext('node/leaf'), 'ipsum');
+ assert.equal(root.findtext('no-such-node/leaf'), null);
+ test.finish();
+};
+
+exports['test_remove'] = function(test, assert) {
+ var root = Element('root');
+ var node1 = SubElement(root, 'node1');
+ var node2 = SubElement(root, 'node2');
+ var node3 = SubElement(root, 'node3');
+
+ assert.equal(root.len(), 3);
+
+ root.remove(node2);
+
+ assert.equal(root.len(), 2);
+ assert.equal(root.getItem(0).tag, 'node1')
+ assert.equal(root.getItem(1).tag, 'node3')
+
+ test.finish();
+};
+
+exports['test_cdata_write'] = function(test, assert) {
+ var root, etree, xml, values, value, i;
+
+ values = [
+ 'if(0>1) then true;',
+ 'ponies hello',
+ ''
+ ];
+
+ for (i = 0; i < values.length; i++) {
+ value = values[i];
+
+ root = Element('root');
+ root.append(et.CData(value));
+ etree = new ElementTree(root);
+ xml = etree.write({'xml_declaration': false});
+
+ assert.equal(xml, sprintf('', value));
+ }
+
+ test.finish();
+};
+
+exports['test_read_bom'] = function(test, assert) {
+ var file = readFile('bom-xml.xml');
+ var etree = et.parse(file);
+
+ // If parse finished, test was successful
+
+ test.finish();
+};
diff --git a/temporary_modules/trezor-connect/node_modules/emoji-regex/LICENSE-MIT.txt b/temporary_modules/trezor-connect/node_modules/emoji-regex/LICENSE-MIT.txt
new file mode 100644
index 00000000..a41e0a7e
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/emoji-regex/LICENSE-MIT.txt
@@ -0,0 +1,20 @@
+Copyright Mathias Bynens
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/temporary_modules/trezor-connect/node_modules/emoji-regex/README.md b/temporary_modules/trezor-connect/node_modules/emoji-regex/README.md
new file mode 100644
index 00000000..f10e1733
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/emoji-regex/README.md
@@ -0,0 +1,73 @@
+# emoji-regex [](https://travis-ci.org/mathiasbynens/emoji-regex)
+
+_emoji-regex_ offers a regular expression to match all emoji symbols (including textual representations of emoji) as per the Unicode Standard.
+
+This repository contains a script that generates this regular expression based on [the data from Unicode v12](https://github.com/mathiasbynens/unicode-12.0.0). Because of this, the regular expression can easily be updated whenever new emoji are added to the Unicode standard.
+
+## Installation
+
+Via [npm](https://www.npmjs.com/):
+
+```bash
+npm install emoji-regex
+```
+
+In [Node.js](https://nodejs.org/):
+
+```js
+const emojiRegex = require('emoji-regex');
+// Note: because the regular expression has the global flag set, this module
+// exports a function that returns the regex rather than exporting the regular
+// expression itself, to make it impossible to (accidentally) mutate the
+// original regular expression.
+
+const text = `
+\u{231A}: ⌚ default emoji presentation character (Emoji_Presentation)
+\u{2194}\u{FE0F}: ↔️ default text presentation character rendered as emoji
+\u{1F469}: 👩 emoji modifier base (Emoji_Modifier_Base)
+\u{1F469}\u{1F3FF}: 👩🏿 emoji modifier base followed by a modifier
+`;
+
+const regex = emojiRegex();
+let match;
+while (match = regex.exec(text)) {
+ const emoji = match[0];
+ console.log(`Matched sequence ${ emoji } — code points: ${ [...emoji].length }`);
+}
+```
+
+Console output:
+
+```
+Matched sequence ⌚ — code points: 1
+Matched sequence ⌚ — code points: 1
+Matched sequence ↔️ — code points: 2
+Matched sequence ↔️ — code points: 2
+Matched sequence 👩 — code points: 1
+Matched sequence 👩 — code points: 1
+Matched sequence 👩🏿 — code points: 2
+Matched sequence 👩🏿 — code points: 2
+```
+
+To match emoji in their textual representation as well (i.e. emoji that are not `Emoji_Presentation` symbols and that aren’t forced to render as emoji by a variation selector), `require` the other regex:
+
+```js
+const emojiRegex = require('emoji-regex/text.js');
+```
+
+Additionally, in environments which support ES2015 Unicode escapes, you may `require` ES2015-style versions of the regexes:
+
+```js
+const emojiRegex = require('emoji-regex/es2015/index.js');
+const emojiRegexText = require('emoji-regex/es2015/text.js');
+```
+
+## Author
+
+| [](https://twitter.com/mathias "Follow @mathias on Twitter") |
+|---|
+| [Mathias Bynens](https://mathiasbynens.be/) |
+
+## License
+
+_emoji-regex_ is available under the [MIT](https://mths.be/mit) license.
diff --git a/temporary_modules/trezor-connect/node_modules/emoji-regex/es2015/index.js b/temporary_modules/trezor-connect/node_modules/emoji-regex/es2015/index.js
new file mode 100644
index 00000000..b4cf3dcd
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/emoji-regex/es2015/index.js
@@ -0,0 +1,6 @@
+"use strict";
+
+module.exports = () => {
+ // https://mths.be/emoji
+ return /\u{1F3F4}\u{E0067}\u{E0062}(?:\u{E0065}\u{E006E}\u{E0067}|\u{E0073}\u{E0063}\u{E0074}|\u{E0077}\u{E006C}\u{E0073})\u{E007F}|\u{1F468}(?:\u{1F3FC}\u200D(?:\u{1F91D}\u200D\u{1F468}\u{1F3FB}|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FF}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FE}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FE}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FD}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FD}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}\u{1F3FC}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u200D(?:\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F468}|[\u{1F468}\u{1F469}]\u200D(?:\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}])|\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}]|[\u{1F468}\u{1F469}]\u200D[\u{1F466}\u{1F467}]|[\u2695\u2696\u2708]\uFE0F|[\u{1F466}\u{1F467}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|(?:\u{1F3FB}\u200D[\u2695\u2696\u2708]|\u{1F3FF}\u200D[\u2695\u2696\u2708]|\u{1F3FE}\u200D[\u2695\u2696\u2708]|\u{1F3FD}\u200D[\u2695\u2696\u2708]|\u{1F3FC}\u200D[\u2695\u2696\u2708])\uFE0F|\u{1F3FB}\u200D[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]|[\u{1F3FB}-\u{1F3FF}])|(?:\u{1F9D1}\u{1F3FB}\u200D\u{1F91D}\u200D\u{1F9D1}|\u{1F469}\u{1F3FC}\u200D\u{1F91D}\u200D\u{1F469})\u{1F3FB}|\u{1F9D1}(?:\u{1F3FF}\u200D\u{1F91D}\u200D\u{1F9D1}[\u{1F3FB}-\u{1F3FF}]|\u200D\u{1F91D}\u200D\u{1F9D1})|(?:\u{1F9D1}\u{1F3FE}\u200D\u{1F91D}\u200D\u{1F9D1}|\u{1F469}\u{1F3FF}\u200D\u{1F91D}\u200D[\u{1F468}\u{1F469}])[\u{1F3FB}-\u{1F3FE}]|(?:\u{1F9D1}\u{1F3FC}\u200D\u{1F91D}\u200D\u{1F9D1}|\u{1F469}\u{1F3FD}\u200D\u{1F91D}\u200D\u{1F469})[\u{1F3FB}\u{1F3FC}]|\u{1F469}(?:\u{1F3FE}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FD}\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FC}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}\u{1F3FD}-\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FB}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FC}-\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FD}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}\u{1F3FC}\u{1F3FE}\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u200D(?:\u2764\uFE0F\u200D(?:\u{1F48B}\u200D[\u{1F468}\u{1F469}]|[\u{1F468}\u{1F469}])|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FF}\u200D[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F469}\u200D\u{1F469}\u200D(?:\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}])|(?:\u{1F9D1}\u{1F3FD}\u200D\u{1F91D}\u200D\u{1F9D1}|\u{1F469}\u{1F3FE}\u200D\u{1F91D}\u200D\u{1F469})[\u{1F3FB}-\u{1F3FD}]|\u{1F469}\u200D\u{1F466}\u200D\u{1F466}|\u{1F469}\u200D\u{1F469}\u200D[\u{1F466}\u{1F467}]|(?:\u{1F441}\uFE0F\u200D\u{1F5E8}|\u{1F469}(?:\u{1F3FF}\u200D[\u2695\u2696\u2708]|\u{1F3FE}\u200D[\u2695\u2696\u2708]|\u{1F3FC}\u200D[\u2695\u2696\u2708]|\u{1F3FB}\u200D[\u2695\u2696\u2708]|\u{1F3FD}\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:[\u26F9\u{1F3CB}\u{1F3CC}\u{1F575}]\uFE0F|[\u{1F46F}\u{1F93C}\u{1F9DE}\u{1F9DF}])\u200D[\u2640\u2642]|[\u26F9\u{1F3CB}\u{1F3CC}\u{1F575}][\u{1F3FB}-\u{1F3FF}]\u200D[\u2640\u2642]|[\u{1F3C3}\u{1F3C4}\u{1F3CA}\u{1F46E}\u{1F471}\u{1F473}\u{1F477}\u{1F481}\u{1F482}\u{1F486}\u{1F487}\u{1F645}-\u{1F647}\u{1F64B}\u{1F64D}\u{1F64E}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F926}\u{1F937}-\u{1F939}\u{1F93D}\u{1F93E}\u{1F9B8}\u{1F9B9}\u{1F9CD}-\u{1F9CF}\u{1F9D6}-\u{1F9DD}](?:[\u{1F3FB}-\u{1F3FF}]\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\u{1F3F4}\u200D\u2620)\uFE0F|\u{1F469}\u200D\u{1F467}\u200D[\u{1F466}\u{1F467}]|\u{1F3F3}\uFE0F\u200D\u{1F308}|\u{1F415}\u200D\u{1F9BA}|\u{1F469}\u200D\u{1F466}|\u{1F469}\u200D\u{1F467}|\u{1F1FD}\u{1F1F0}|\u{1F1F4}\u{1F1F2}|\u{1F1F6}\u{1F1E6}|[#\*0-9]\uFE0F\u20E3|\u{1F1E7}[\u{1F1E6}\u{1F1E7}\u{1F1E9}-\u{1F1EF}\u{1F1F1}-\u{1F1F4}\u{1F1F6}-\u{1F1F9}\u{1F1FB}\u{1F1FC}\u{1F1FE}\u{1F1FF}]|\u{1F1F9}[\u{1F1E6}\u{1F1E8}\u{1F1E9}\u{1F1EB}-\u{1F1ED}\u{1F1EF}-\u{1F1F4}\u{1F1F7}\u{1F1F9}\u{1F1FB}\u{1F1FC}\u{1F1FF}]|\u{1F1EA}[\u{1F1E6}\u{1F1E8}\u{1F1EA}\u{1F1EC}\u{1F1ED}\u{1F1F7}-\u{1F1FA}]|\u{1F9D1}[\u{1F3FB}-\u{1F3FF}]|\u{1F1F7}[\u{1F1EA}\u{1F1F4}\u{1F1F8}\u{1F1FA}\u{1F1FC}]|\u{1F469}[\u{1F3FB}-\u{1F3FF}]|\u{1F1F2}[\u{1F1E6}\u{1F1E8}-\u{1F1ED}\u{1F1F0}-\u{1F1FF}]|\u{1F1E6}[\u{1F1E8}-\u{1F1EC}\u{1F1EE}\u{1F1F1}\u{1F1F2}\u{1F1F4}\u{1F1F6}-\u{1F1FA}\u{1F1FC}\u{1F1FD}\u{1F1FF}]|\u{1F1F0}[\u{1F1EA}\u{1F1EC}-\u{1F1EE}\u{1F1F2}\u{1F1F3}\u{1F1F5}\u{1F1F7}\u{1F1FC}\u{1F1FE}\u{1F1FF}]|\u{1F1ED}[\u{1F1F0}\u{1F1F2}\u{1F1F3}\u{1F1F7}\u{1F1F9}\u{1F1FA}]|\u{1F1E9}[\u{1F1EA}\u{1F1EC}\u{1F1EF}\u{1F1F0}\u{1F1F2}\u{1F1F4}\u{1F1FF}]|\u{1F1FE}[\u{1F1EA}\u{1F1F9}]|\u{1F1EC}[\u{1F1E6}\u{1F1E7}\u{1F1E9}-\u{1F1EE}\u{1F1F1}-\u{1F1F3}\u{1F1F5}-\u{1F1FA}\u{1F1FC}\u{1F1FE}]|\u{1F1F8}[\u{1F1E6}-\u{1F1EA}\u{1F1EC}-\u{1F1F4}\u{1F1F7}-\u{1F1F9}\u{1F1FB}\u{1F1FD}-\u{1F1FF}]|\u{1F1EB}[\u{1F1EE}-\u{1F1F0}\u{1F1F2}\u{1F1F4}\u{1F1F7}]|\u{1F1F5}[\u{1F1E6}\u{1F1EA}-\u{1F1ED}\u{1F1F0}-\u{1F1F3}\u{1F1F7}-\u{1F1F9}\u{1F1FC}\u{1F1FE}]|\u{1F1FB}[\u{1F1E6}\u{1F1E8}\u{1F1EA}\u{1F1EC}\u{1F1EE}\u{1F1F3}\u{1F1FA}]|\u{1F1F3}[\u{1F1E6}\u{1F1E8}\u{1F1EA}-\u{1F1EC}\u{1F1EE}\u{1F1F1}\u{1F1F4}\u{1F1F5}\u{1F1F7}\u{1F1FA}\u{1F1FF}]|\u{1F1E8}[\u{1F1E6}\u{1F1E8}\u{1F1E9}\u{1F1EB}-\u{1F1EE}\u{1F1F0}-\u{1F1F5}\u{1F1F7}\u{1F1FA}-\u{1F1FF}]|\u{1F1F1}[\u{1F1E6}-\u{1F1E8}\u{1F1EE}\u{1F1F0}\u{1F1F7}-\u{1F1FB}\u{1F1FE}]|\u{1F1FF}[\u{1F1E6}\u{1F1F2}\u{1F1FC}]|\u{1F1FC}[\u{1F1EB}\u{1F1F8}]|\u{1F1FA}[\u{1F1E6}\u{1F1EC}\u{1F1F2}\u{1F1F3}\u{1F1F8}\u{1F1FE}\u{1F1FF}]|\u{1F1EE}[\u{1F1E8}-\u{1F1EA}\u{1F1F1}-\u{1F1F4}\u{1F1F6}-\u{1F1F9}]|\u{1F1EF}[\u{1F1EA}\u{1F1F2}\u{1F1F4}\u{1F1F5}]|[\u{1F3C3}\u{1F3C4}\u{1F3CA}\u{1F46E}\u{1F471}\u{1F473}\u{1F477}\u{1F481}\u{1F482}\u{1F486}\u{1F487}\u{1F645}-\u{1F647}\u{1F64B}\u{1F64D}\u{1F64E}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F926}\u{1F937}-\u{1F939}\u{1F93D}\u{1F93E}\u{1F9B8}\u{1F9B9}\u{1F9CD}-\u{1F9CF}\u{1F9D6}-\u{1F9DD}][\u{1F3FB}-\u{1F3FF}]|[\u26F9\u{1F3CB}\u{1F3CC}\u{1F575}][\u{1F3FB}-\u{1F3FF}]|[\u261D\u270A-\u270D\u{1F385}\u{1F3C2}\u{1F3C7}\u{1F442}\u{1F443}\u{1F446}-\u{1F450}\u{1F466}\u{1F467}\u{1F46B}-\u{1F46D}\u{1F470}\u{1F472}\u{1F474}-\u{1F476}\u{1F478}\u{1F47C}\u{1F483}\u{1F485}\u{1F4AA}\u{1F574}\u{1F57A}\u{1F590}\u{1F595}\u{1F596}\u{1F64C}\u{1F64F}\u{1F6C0}\u{1F6CC}\u{1F90F}\u{1F918}-\u{1F91C}\u{1F91E}\u{1F91F}\u{1F930}-\u{1F936}\u{1F9B5}\u{1F9B6}\u{1F9BB}\u{1F9D2}-\u{1F9D5}][\u{1F3FB}-\u{1F3FF}]|[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55\u{1F004}\u{1F0CF}\u{1F18E}\u{1F191}-\u{1F19A}\u{1F1E6}-\u{1F1FF}\u{1F201}\u{1F21A}\u{1F22F}\u{1F232}-\u{1F236}\u{1F238}-\u{1F23A}\u{1F250}\u{1F251}\u{1F300}-\u{1F320}\u{1F32D}-\u{1F335}\u{1F337}-\u{1F37C}\u{1F37E}-\u{1F393}\u{1F3A0}-\u{1F3CA}\u{1F3CF}-\u{1F3D3}\u{1F3E0}-\u{1F3F0}\u{1F3F4}\u{1F3F8}-\u{1F43E}\u{1F440}\u{1F442}-\u{1F4FC}\u{1F4FF}-\u{1F53D}\u{1F54B}-\u{1F54E}\u{1F550}-\u{1F567}\u{1F57A}\u{1F595}\u{1F596}\u{1F5A4}\u{1F5FB}-\u{1F64F}\u{1F680}-\u{1F6C5}\u{1F6CC}\u{1F6D0}-\u{1F6D2}\u{1F6D5}\u{1F6EB}\u{1F6EC}\u{1F6F4}-\u{1F6FA}\u{1F7E0}-\u{1F7EB}\u{1F90D}-\u{1F93A}\u{1F93C}-\u{1F945}\u{1F947}-\u{1F971}\u{1F973}-\u{1F976}\u{1F97A}-\u{1F9A2}\u{1F9A5}-\u{1F9AA}\u{1F9AE}-\u{1F9CA}\u{1F9CD}-\u{1F9FF}\u{1FA70}-\u{1FA73}\u{1FA78}-\u{1FA7A}\u{1FA80}-\u{1FA82}\u{1FA90}-\u{1FA95}]|[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299\u{1F004}\u{1F0CF}\u{1F170}\u{1F171}\u{1F17E}\u{1F17F}\u{1F18E}\u{1F191}-\u{1F19A}\u{1F1E6}-\u{1F1FF}\u{1F201}\u{1F202}\u{1F21A}\u{1F22F}\u{1F232}-\u{1F23A}\u{1F250}\u{1F251}\u{1F300}-\u{1F321}\u{1F324}-\u{1F393}\u{1F396}\u{1F397}\u{1F399}-\u{1F39B}\u{1F39E}-\u{1F3F0}\u{1F3F3}-\u{1F3F5}\u{1F3F7}-\u{1F4FD}\u{1F4FF}-\u{1F53D}\u{1F549}-\u{1F54E}\u{1F550}-\u{1F567}\u{1F56F}\u{1F570}\u{1F573}-\u{1F57A}\u{1F587}\u{1F58A}-\u{1F58D}\u{1F590}\u{1F595}\u{1F596}\u{1F5A4}\u{1F5A5}\u{1F5A8}\u{1F5B1}\u{1F5B2}\u{1F5BC}\u{1F5C2}-\u{1F5C4}\u{1F5D1}-\u{1F5D3}\u{1F5DC}-\u{1F5DE}\u{1F5E1}\u{1F5E3}\u{1F5E8}\u{1F5EF}\u{1F5F3}\u{1F5FA}-\u{1F64F}\u{1F680}-\u{1F6C5}\u{1F6CB}-\u{1F6D2}\u{1F6D5}\u{1F6E0}-\u{1F6E5}\u{1F6E9}\u{1F6EB}\u{1F6EC}\u{1F6F0}\u{1F6F3}-\u{1F6FA}\u{1F7E0}-\u{1F7EB}\u{1F90D}-\u{1F93A}\u{1F93C}-\u{1F945}\u{1F947}-\u{1F971}\u{1F973}-\u{1F976}\u{1F97A}-\u{1F9A2}\u{1F9A5}-\u{1F9AA}\u{1F9AE}-\u{1F9CA}\u{1F9CD}-\u{1F9FF}\u{1FA70}-\u{1FA73}\u{1FA78}-\u{1FA7A}\u{1FA80}-\u{1FA82}\u{1FA90}-\u{1FA95}]\uFE0F|[\u261D\u26F9\u270A-\u270D\u{1F385}\u{1F3C2}-\u{1F3C4}\u{1F3C7}\u{1F3CA}-\u{1F3CC}\u{1F442}\u{1F443}\u{1F446}-\u{1F450}\u{1F466}-\u{1F478}\u{1F47C}\u{1F481}-\u{1F483}\u{1F485}-\u{1F487}\u{1F48F}\u{1F491}\u{1F4AA}\u{1F574}\u{1F575}\u{1F57A}\u{1F590}\u{1F595}\u{1F596}\u{1F645}-\u{1F647}\u{1F64B}-\u{1F64F}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F6C0}\u{1F6CC}\u{1F90F}\u{1F918}-\u{1F91F}\u{1F926}\u{1F930}-\u{1F939}\u{1F93C}-\u{1F93E}\u{1F9B5}\u{1F9B6}\u{1F9B8}\u{1F9B9}\u{1F9BB}\u{1F9CD}-\u{1F9CF}\u{1F9D1}-\u{1F9DD}]/gu;
+};
diff --git a/temporary_modules/trezor-connect/node_modules/emoji-regex/es2015/text.js b/temporary_modules/trezor-connect/node_modules/emoji-regex/es2015/text.js
new file mode 100644
index 00000000..780309df
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/emoji-regex/es2015/text.js
@@ -0,0 +1,6 @@
+"use strict";
+
+module.exports = () => {
+ // https://mths.be/emoji
+ return /\u{1F3F4}\u{E0067}\u{E0062}(?:\u{E0065}\u{E006E}\u{E0067}|\u{E0073}\u{E0063}\u{E0074}|\u{E0077}\u{E006C}\u{E0073})\u{E007F}|\u{1F468}(?:\u{1F3FC}\u200D(?:\u{1F91D}\u200D\u{1F468}\u{1F3FB}|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FF}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FE}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FE}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FD}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FD}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}\u{1F3FC}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u200D(?:\u2764\uFE0F\u200D(?:\u{1F48B}\u200D)?\u{1F468}|[\u{1F468}\u{1F469}]\u200D(?:\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}])|\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}]|[\u{1F468}\u{1F469}]\u200D[\u{1F466}\u{1F467}]|[\u2695\u2696\u2708]\uFE0F|[\u{1F466}\u{1F467}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|(?:\u{1F3FB}\u200D[\u2695\u2696\u2708]|\u{1F3FF}\u200D[\u2695\u2696\u2708]|\u{1F3FE}\u200D[\u2695\u2696\u2708]|\u{1F3FD}\u200D[\u2695\u2696\u2708]|\u{1F3FC}\u200D[\u2695\u2696\u2708])\uFE0F|\u{1F3FB}\u200D[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}]|[\u{1F3FB}-\u{1F3FF}])|(?:\u{1F9D1}\u{1F3FB}\u200D\u{1F91D}\u200D\u{1F9D1}|\u{1F469}\u{1F3FC}\u200D\u{1F91D}\u200D\u{1F469})\u{1F3FB}|\u{1F9D1}(?:\u{1F3FF}\u200D\u{1F91D}\u200D\u{1F9D1}[\u{1F3FB}-\u{1F3FF}]|\u200D\u{1F91D}\u200D\u{1F9D1})|(?:\u{1F9D1}\u{1F3FE}\u200D\u{1F91D}\u200D\u{1F9D1}|\u{1F469}\u{1F3FF}\u200D\u{1F91D}\u200D[\u{1F468}\u{1F469}])[\u{1F3FB}-\u{1F3FE}]|(?:\u{1F9D1}\u{1F3FC}\u200D\u{1F91D}\u200D\u{1F9D1}|\u{1F469}\u{1F3FD}\u200D\u{1F91D}\u200D\u{1F469})[\u{1F3FB}\u{1F3FC}]|\u{1F469}(?:\u{1F3FE}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}-\u{1F3FD}\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FC}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}\u{1F3FD}-\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FB}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FC}-\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FD}\u200D(?:\u{1F91D}\u200D\u{1F468}[\u{1F3FB}\u{1F3FC}\u{1F3FE}\u{1F3FF}]|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u200D(?:\u2764\uFE0F\u200D(?:\u{1F48B}\u200D[\u{1F468}\u{1F469}]|[\u{1F468}\u{1F469}])|[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F3FF}\u200D[\u{1F33E}\u{1F373}\u{1F393}\u{1F3A4}\u{1F3A8}\u{1F3EB}\u{1F3ED}\u{1F4BB}\u{1F4BC}\u{1F527}\u{1F52C}\u{1F680}\u{1F692}\u{1F9AF}-\u{1F9B3}\u{1F9BC}\u{1F9BD}])|\u{1F469}\u200D\u{1F469}\u200D(?:\u{1F466}\u200D\u{1F466}|\u{1F467}\u200D[\u{1F466}\u{1F467}])|(?:\u{1F9D1}\u{1F3FD}\u200D\u{1F91D}\u200D\u{1F9D1}|\u{1F469}\u{1F3FE}\u200D\u{1F91D}\u200D\u{1F469})[\u{1F3FB}-\u{1F3FD}]|\u{1F469}\u200D\u{1F466}\u200D\u{1F466}|\u{1F469}\u200D\u{1F469}\u200D[\u{1F466}\u{1F467}]|(?:\u{1F441}\uFE0F\u200D\u{1F5E8}|\u{1F469}(?:\u{1F3FF}\u200D[\u2695\u2696\u2708]|\u{1F3FE}\u200D[\u2695\u2696\u2708]|\u{1F3FC}\u200D[\u2695\u2696\u2708]|\u{1F3FB}\u200D[\u2695\u2696\u2708]|\u{1F3FD}\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:[\u26F9\u{1F3CB}\u{1F3CC}\u{1F575}]\uFE0F|[\u{1F46F}\u{1F93C}\u{1F9DE}\u{1F9DF}])\u200D[\u2640\u2642]|[\u26F9\u{1F3CB}\u{1F3CC}\u{1F575}][\u{1F3FB}-\u{1F3FF}]\u200D[\u2640\u2642]|[\u{1F3C3}\u{1F3C4}\u{1F3CA}\u{1F46E}\u{1F471}\u{1F473}\u{1F477}\u{1F481}\u{1F482}\u{1F486}\u{1F487}\u{1F645}-\u{1F647}\u{1F64B}\u{1F64D}\u{1F64E}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F926}\u{1F937}-\u{1F939}\u{1F93D}\u{1F93E}\u{1F9B8}\u{1F9B9}\u{1F9CD}-\u{1F9CF}\u{1F9D6}-\u{1F9DD}](?:[\u{1F3FB}-\u{1F3FF}]\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\u{1F3F4}\u200D\u2620)\uFE0F|\u{1F469}\u200D\u{1F467}\u200D[\u{1F466}\u{1F467}]|\u{1F3F3}\uFE0F\u200D\u{1F308}|\u{1F415}\u200D\u{1F9BA}|\u{1F469}\u200D\u{1F466}|\u{1F469}\u200D\u{1F467}|\u{1F1FD}\u{1F1F0}|\u{1F1F4}\u{1F1F2}|\u{1F1F6}\u{1F1E6}|[#\*0-9]\uFE0F\u20E3|\u{1F1E7}[\u{1F1E6}\u{1F1E7}\u{1F1E9}-\u{1F1EF}\u{1F1F1}-\u{1F1F4}\u{1F1F6}-\u{1F1F9}\u{1F1FB}\u{1F1FC}\u{1F1FE}\u{1F1FF}]|\u{1F1F9}[\u{1F1E6}\u{1F1E8}\u{1F1E9}\u{1F1EB}-\u{1F1ED}\u{1F1EF}-\u{1F1F4}\u{1F1F7}\u{1F1F9}\u{1F1FB}\u{1F1FC}\u{1F1FF}]|\u{1F1EA}[\u{1F1E6}\u{1F1E8}\u{1F1EA}\u{1F1EC}\u{1F1ED}\u{1F1F7}-\u{1F1FA}]|\u{1F9D1}[\u{1F3FB}-\u{1F3FF}]|\u{1F1F7}[\u{1F1EA}\u{1F1F4}\u{1F1F8}\u{1F1FA}\u{1F1FC}]|\u{1F469}[\u{1F3FB}-\u{1F3FF}]|\u{1F1F2}[\u{1F1E6}\u{1F1E8}-\u{1F1ED}\u{1F1F0}-\u{1F1FF}]|\u{1F1E6}[\u{1F1E8}-\u{1F1EC}\u{1F1EE}\u{1F1F1}\u{1F1F2}\u{1F1F4}\u{1F1F6}-\u{1F1FA}\u{1F1FC}\u{1F1FD}\u{1F1FF}]|\u{1F1F0}[\u{1F1EA}\u{1F1EC}-\u{1F1EE}\u{1F1F2}\u{1F1F3}\u{1F1F5}\u{1F1F7}\u{1F1FC}\u{1F1FE}\u{1F1FF}]|\u{1F1ED}[\u{1F1F0}\u{1F1F2}\u{1F1F3}\u{1F1F7}\u{1F1F9}\u{1F1FA}]|\u{1F1E9}[\u{1F1EA}\u{1F1EC}\u{1F1EF}\u{1F1F0}\u{1F1F2}\u{1F1F4}\u{1F1FF}]|\u{1F1FE}[\u{1F1EA}\u{1F1F9}]|\u{1F1EC}[\u{1F1E6}\u{1F1E7}\u{1F1E9}-\u{1F1EE}\u{1F1F1}-\u{1F1F3}\u{1F1F5}-\u{1F1FA}\u{1F1FC}\u{1F1FE}]|\u{1F1F8}[\u{1F1E6}-\u{1F1EA}\u{1F1EC}-\u{1F1F4}\u{1F1F7}-\u{1F1F9}\u{1F1FB}\u{1F1FD}-\u{1F1FF}]|\u{1F1EB}[\u{1F1EE}-\u{1F1F0}\u{1F1F2}\u{1F1F4}\u{1F1F7}]|\u{1F1F5}[\u{1F1E6}\u{1F1EA}-\u{1F1ED}\u{1F1F0}-\u{1F1F3}\u{1F1F7}-\u{1F1F9}\u{1F1FC}\u{1F1FE}]|\u{1F1FB}[\u{1F1E6}\u{1F1E8}\u{1F1EA}\u{1F1EC}\u{1F1EE}\u{1F1F3}\u{1F1FA}]|\u{1F1F3}[\u{1F1E6}\u{1F1E8}\u{1F1EA}-\u{1F1EC}\u{1F1EE}\u{1F1F1}\u{1F1F4}\u{1F1F5}\u{1F1F7}\u{1F1FA}\u{1F1FF}]|\u{1F1E8}[\u{1F1E6}\u{1F1E8}\u{1F1E9}\u{1F1EB}-\u{1F1EE}\u{1F1F0}-\u{1F1F5}\u{1F1F7}\u{1F1FA}-\u{1F1FF}]|\u{1F1F1}[\u{1F1E6}-\u{1F1E8}\u{1F1EE}\u{1F1F0}\u{1F1F7}-\u{1F1FB}\u{1F1FE}]|\u{1F1FF}[\u{1F1E6}\u{1F1F2}\u{1F1FC}]|\u{1F1FC}[\u{1F1EB}\u{1F1F8}]|\u{1F1FA}[\u{1F1E6}\u{1F1EC}\u{1F1F2}\u{1F1F3}\u{1F1F8}\u{1F1FE}\u{1F1FF}]|\u{1F1EE}[\u{1F1E8}-\u{1F1EA}\u{1F1F1}-\u{1F1F4}\u{1F1F6}-\u{1F1F9}]|\u{1F1EF}[\u{1F1EA}\u{1F1F2}\u{1F1F4}\u{1F1F5}]|[\u{1F3C3}\u{1F3C4}\u{1F3CA}\u{1F46E}\u{1F471}\u{1F473}\u{1F477}\u{1F481}\u{1F482}\u{1F486}\u{1F487}\u{1F645}-\u{1F647}\u{1F64B}\u{1F64D}\u{1F64E}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F926}\u{1F937}-\u{1F939}\u{1F93D}\u{1F93E}\u{1F9B8}\u{1F9B9}\u{1F9CD}-\u{1F9CF}\u{1F9D6}-\u{1F9DD}][\u{1F3FB}-\u{1F3FF}]|[\u26F9\u{1F3CB}\u{1F3CC}\u{1F575}][\u{1F3FB}-\u{1F3FF}]|[\u261D\u270A-\u270D\u{1F385}\u{1F3C2}\u{1F3C7}\u{1F442}\u{1F443}\u{1F446}-\u{1F450}\u{1F466}\u{1F467}\u{1F46B}-\u{1F46D}\u{1F470}\u{1F472}\u{1F474}-\u{1F476}\u{1F478}\u{1F47C}\u{1F483}\u{1F485}\u{1F4AA}\u{1F574}\u{1F57A}\u{1F590}\u{1F595}\u{1F596}\u{1F64C}\u{1F64F}\u{1F6C0}\u{1F6CC}\u{1F90F}\u{1F918}-\u{1F91C}\u{1F91E}\u{1F91F}\u{1F930}-\u{1F936}\u{1F9B5}\u{1F9B6}\u{1F9BB}\u{1F9D2}-\u{1F9D5}][\u{1F3FB}-\u{1F3FF}]|[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55\u{1F004}\u{1F0CF}\u{1F18E}\u{1F191}-\u{1F19A}\u{1F1E6}-\u{1F1FF}\u{1F201}\u{1F21A}\u{1F22F}\u{1F232}-\u{1F236}\u{1F238}-\u{1F23A}\u{1F250}\u{1F251}\u{1F300}-\u{1F320}\u{1F32D}-\u{1F335}\u{1F337}-\u{1F37C}\u{1F37E}-\u{1F393}\u{1F3A0}-\u{1F3CA}\u{1F3CF}-\u{1F3D3}\u{1F3E0}-\u{1F3F0}\u{1F3F4}\u{1F3F8}-\u{1F43E}\u{1F440}\u{1F442}-\u{1F4FC}\u{1F4FF}-\u{1F53D}\u{1F54B}-\u{1F54E}\u{1F550}-\u{1F567}\u{1F57A}\u{1F595}\u{1F596}\u{1F5A4}\u{1F5FB}-\u{1F64F}\u{1F680}-\u{1F6C5}\u{1F6CC}\u{1F6D0}-\u{1F6D2}\u{1F6D5}\u{1F6EB}\u{1F6EC}\u{1F6F4}-\u{1F6FA}\u{1F7E0}-\u{1F7EB}\u{1F90D}-\u{1F93A}\u{1F93C}-\u{1F945}\u{1F947}-\u{1F971}\u{1F973}-\u{1F976}\u{1F97A}-\u{1F9A2}\u{1F9A5}-\u{1F9AA}\u{1F9AE}-\u{1F9CA}\u{1F9CD}-\u{1F9FF}\u{1FA70}-\u{1FA73}\u{1FA78}-\u{1FA7A}\u{1FA80}-\u{1FA82}\u{1FA90}-\u{1FA95}]|[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299\u{1F004}\u{1F0CF}\u{1F170}\u{1F171}\u{1F17E}\u{1F17F}\u{1F18E}\u{1F191}-\u{1F19A}\u{1F1E6}-\u{1F1FF}\u{1F201}\u{1F202}\u{1F21A}\u{1F22F}\u{1F232}-\u{1F23A}\u{1F250}\u{1F251}\u{1F300}-\u{1F321}\u{1F324}-\u{1F393}\u{1F396}\u{1F397}\u{1F399}-\u{1F39B}\u{1F39E}-\u{1F3F0}\u{1F3F3}-\u{1F3F5}\u{1F3F7}-\u{1F4FD}\u{1F4FF}-\u{1F53D}\u{1F549}-\u{1F54E}\u{1F550}-\u{1F567}\u{1F56F}\u{1F570}\u{1F573}-\u{1F57A}\u{1F587}\u{1F58A}-\u{1F58D}\u{1F590}\u{1F595}\u{1F596}\u{1F5A4}\u{1F5A5}\u{1F5A8}\u{1F5B1}\u{1F5B2}\u{1F5BC}\u{1F5C2}-\u{1F5C4}\u{1F5D1}-\u{1F5D3}\u{1F5DC}-\u{1F5DE}\u{1F5E1}\u{1F5E3}\u{1F5E8}\u{1F5EF}\u{1F5F3}\u{1F5FA}-\u{1F64F}\u{1F680}-\u{1F6C5}\u{1F6CB}-\u{1F6D2}\u{1F6D5}\u{1F6E0}-\u{1F6E5}\u{1F6E9}\u{1F6EB}\u{1F6EC}\u{1F6F0}\u{1F6F3}-\u{1F6FA}\u{1F7E0}-\u{1F7EB}\u{1F90D}-\u{1F93A}\u{1F93C}-\u{1F945}\u{1F947}-\u{1F971}\u{1F973}-\u{1F976}\u{1F97A}-\u{1F9A2}\u{1F9A5}-\u{1F9AA}\u{1F9AE}-\u{1F9CA}\u{1F9CD}-\u{1F9FF}\u{1FA70}-\u{1FA73}\u{1FA78}-\u{1FA7A}\u{1FA80}-\u{1FA82}\u{1FA90}-\u{1FA95}]\uFE0F?|[\u261D\u26F9\u270A-\u270D\u{1F385}\u{1F3C2}-\u{1F3C4}\u{1F3C7}\u{1F3CA}-\u{1F3CC}\u{1F442}\u{1F443}\u{1F446}-\u{1F450}\u{1F466}-\u{1F478}\u{1F47C}\u{1F481}-\u{1F483}\u{1F485}-\u{1F487}\u{1F48F}\u{1F491}\u{1F4AA}\u{1F574}\u{1F575}\u{1F57A}\u{1F590}\u{1F595}\u{1F596}\u{1F645}-\u{1F647}\u{1F64B}-\u{1F64F}\u{1F6A3}\u{1F6B4}-\u{1F6B6}\u{1F6C0}\u{1F6CC}\u{1F90F}\u{1F918}-\u{1F91F}\u{1F926}\u{1F930}-\u{1F939}\u{1F93C}-\u{1F93E}\u{1F9B5}\u{1F9B6}\u{1F9B8}\u{1F9B9}\u{1F9BB}\u{1F9CD}-\u{1F9CF}\u{1F9D1}-\u{1F9DD}]/gu;
+};
diff --git a/temporary_modules/trezor-connect/node_modules/emoji-regex/index.d.ts b/temporary_modules/trezor-connect/node_modules/emoji-regex/index.d.ts
new file mode 100644
index 00000000..1955b470
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/emoji-regex/index.d.ts
@@ -0,0 +1,23 @@
+declare module 'emoji-regex' {
+ function emojiRegex(): RegExp;
+
+ export default emojiRegex;
+}
+
+declare module 'emoji-regex/text' {
+ function emojiRegex(): RegExp;
+
+ export default emojiRegex;
+}
+
+declare module 'emoji-regex/es2015' {
+ function emojiRegex(): RegExp;
+
+ export default emojiRegex;
+}
+
+declare module 'emoji-regex/es2015/text' {
+ function emojiRegex(): RegExp;
+
+ export default emojiRegex;
+}
diff --git a/temporary_modules/trezor-connect/node_modules/emoji-regex/index.js b/temporary_modules/trezor-connect/node_modules/emoji-regex/index.js
new file mode 100644
index 00000000..d993a3a9
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/emoji-regex/index.js
@@ -0,0 +1,6 @@
+"use strict";
+
+module.exports = function () {
+ // https://mths.be/emoji
+ return /\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F|\uD83D\uDC68(?:\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68\uD83C\uDFFB|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|[\u2695\u2696\u2708]\uFE0F|\uD83D[\uDC66\uDC67]|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708])\uFE0F|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C[\uDFFB-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)\uD83C\uDFFB|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB\uDFFC])|\uD83D\uDC69(?:\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB-\uDFFD])|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)\uFE0F|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\uD83C\uDFF4\u200D\u2620)\uFE0F|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF4\uD83C\uDDF2|\uD83C\uDDF6\uD83C\uDDE6|[#\*0-9]\uFE0F\u20E3|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270A-\u270D]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC70\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDCAA\uDD74\uDD7A\uDD90\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD36\uDDB5\uDDB6\uDDBB\uDDD2-\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5\uDEEB\uDEEC\uDEF4-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g;
+};
diff --git a/temporary_modules/trezor-connect/node_modules/emoji-regex/package.json b/temporary_modules/trezor-connect/node_modules/emoji-regex/package.json
new file mode 100644
index 00000000..6d323528
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/emoji-regex/package.json
@@ -0,0 +1,50 @@
+{
+ "name": "emoji-regex",
+ "version": "8.0.0",
+ "description": "A regular expression to match all Emoji-only symbols as per the Unicode Standard.",
+ "homepage": "https://mths.be/emoji-regex",
+ "main": "index.js",
+ "types": "index.d.ts",
+ "keywords": [
+ "unicode",
+ "regex",
+ "regexp",
+ "regular expressions",
+ "code points",
+ "symbols",
+ "characters",
+ "emoji"
+ ],
+ "license": "MIT",
+ "author": {
+ "name": "Mathias Bynens",
+ "url": "https://mathiasbynens.be/"
+ },
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/mathiasbynens/emoji-regex.git"
+ },
+ "bugs": "https://github.com/mathiasbynens/emoji-regex/issues",
+ "files": [
+ "LICENSE-MIT.txt",
+ "index.js",
+ "index.d.ts",
+ "text.js",
+ "es2015/index.js",
+ "es2015/text.js"
+ ],
+ "scripts": {
+ "build": "rm -rf -- es2015; babel src -d .; NODE_ENV=es2015 babel src -d ./es2015; node script/inject-sequences.js",
+ "test": "mocha",
+ "test:watch": "npm run test -- --watch"
+ },
+ "devDependencies": {
+ "@babel/cli": "^7.2.3",
+ "@babel/core": "^7.3.4",
+ "@babel/plugin-proposal-unicode-property-regex": "^7.2.0",
+ "@babel/preset-env": "^7.3.4",
+ "mocha": "^6.0.2",
+ "regexgen": "^1.3.0",
+ "unicode-12.0.0": "^0.7.9"
+ }
+}
diff --git a/temporary_modules/trezor-connect/node_modules/emoji-regex/text.js b/temporary_modules/trezor-connect/node_modules/emoji-regex/text.js
new file mode 100644
index 00000000..0a55ce2f
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/emoji-regex/text.js
@@ -0,0 +1,6 @@
+"use strict";
+
+module.exports = function () {
+ // https://mths.be/emoji
+ return /\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F|\uD83D\uDC68(?:\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68\uD83C\uDFFB|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|[\u2695\u2696\u2708]\uFE0F|\uD83D[\uDC66\uDC67]|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708])\uFE0F|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C[\uDFFB-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)\uD83C\uDFFB|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB\uDFFC])|\uD83D\uDC69(?:\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB-\uDFFD])|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)\uFE0F|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\uD83C\uDFF4\u200D\u2620)\uFE0F|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF4\uD83C\uDDF2|\uD83C\uDDF6\uD83C\uDDE6|[#\*0-9]\uFE0F\u20E3|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270A-\u270D]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC70\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDCAA\uDD74\uDD7A\uDD90\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD36\uDDB5\uDDB6\uDDBB\uDDD2-\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5\uDEEB\uDEEC\uDEF4-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])\uFE0F?|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g;
+};
diff --git a/temporary_modules/trezor-connect/node_modules/env-paths/index.d.ts b/temporary_modules/trezor-connect/node_modules/env-paths/index.d.ts
new file mode 100644
index 00000000..277ddc0a
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/env-paths/index.d.ts
@@ -0,0 +1,101 @@
+declare namespace envPaths {
+ export interface Options {
+ /**
+ __Don't use this option unless you really have to!__
+
+ Suffix appended to the project name to avoid name conflicts with native apps. Pass an empty string to disable it.
+
+ @default 'nodejs'
+ */
+ readonly suffix?: string;
+ }
+
+ export interface Paths {
+ /**
+ Directory for data files.
+
+ Example locations (with the default `nodejs` suffix):
+
+ - macOS: `~/Library/Application Support/MyApp-nodejs`
+ - Windows: `%LOCALAPPDATA%\MyApp-nodejs\Data` (for example, `C:\Users\USERNAME\AppData\Local\MyApp-nodejs\Data`)
+ - Linux: `~/.local/share/MyApp-nodejs` (or `$XDG_DATA_HOME/MyApp-nodejs`)
+ */
+ readonly data: string;
+
+ /**
+ Directory for data files.
+
+ Example locations (with the default `nodejs` suffix):
+
+ - macOS: `~/Library/Preferences/MyApp-nodejs`
+ - Windows: `%APPDATA%\MyApp-nodejs\Config` (for example, `C:\Users\USERNAME\AppData\Roaming\MyApp-nodejs\Config`)
+ - Linux: `~/.config/MyApp-nodejs` (or `$XDG_CONFIG_HOME/MyApp-nodejs`)
+ */
+ readonly config: string;
+
+ /**
+ Directory for non-essential data files.
+
+ Example locations (with the default `nodejs` suffix):
+
+ - macOS: `~/Library/Caches/MyApp-nodejs`
+ - Windows: `%LOCALAPPDATA%\MyApp-nodejs\Cache` (for example, `C:\Users\USERNAME\AppData\Local\MyApp-nodejs\Cache`)
+ - Linux: `~/.cache/MyApp-nodejs` (or `$XDG_CACHE_HOME/MyApp-nodejs`)
+ */
+ readonly cache: string;
+
+ /**
+ Directory for log files.
+
+ Example locations (with the default `nodejs` suffix):
+
+ - macOS: `~/Library/Logs/MyApp-nodejs`
+ - Windows: `%LOCALAPPDATA%\MyApp-nodejs\Log` (for example, `C:\Users\USERNAME\AppData\Local\MyApp-nodejs\Log`)
+ - Linux: `~/.local/state/MyApp-nodejs` (or `$XDG_STATE_HOME/MyApp-nodejs`)
+ */
+ readonly log: string;
+
+ /**
+ Directory for temporary files.
+
+ Example locations (with the default `nodejs` suffix):
+
+ - macOS: `/var/folders/jf/f2twvvvs5jl_m49tf034ffpw0000gn/T/MyApp-nodejs`
+ - Windows: `%LOCALAPPDATA%\Temp\MyApp-nodejs` (for example, `C:\Users\USERNAME\AppData\Local\Temp\MyApp-nodejs`)
+ - Linux: `/tmp/USERNAME/MyApp-nodejs`
+ */
+ readonly temp: string;
+ }
+}
+
+declare const envPaths: {
+ /**
+ Get paths for storing things like data, config, cache, etc.
+
+ Note: It only generates the path strings. It doesn't create the directories for you. You could use [`make-dir`](https://github.com/sindresorhus/make-dir) to create the directories.
+
+ @param name - Name of your project. Used to generate the paths.
+ @returns The paths to use for your project on current OS.
+
+ @example
+ ```
+ import envPaths = require('env-paths');
+
+ const paths = envPaths('MyApp');
+
+ paths.data;
+ //=> '/home/sindresorhus/.local/share/MyApp-nodejs'
+
+ paths.config
+ //=> '/home/sindresorhus/.config/MyApp-nodejs'
+ ```
+ */
+ (name: string, options?: envPaths.Options): envPaths.Paths;
+
+ // TODO: Remove this for the next major release, refactor the whole definition to:
+ // declare function envPaths(name: string, options?: envPaths.Options): envPaths.Paths;
+ // export = envPaths;
+ default: typeof envPaths;
+};
+
+export = envPaths;
diff --git a/temporary_modules/trezor-connect/node_modules/env-paths/index.js b/temporary_modules/trezor-connect/node_modules/env-paths/index.js
new file mode 100644
index 00000000..7e7b50ba
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/env-paths/index.js
@@ -0,0 +1,74 @@
+'use strict';
+const path = require('path');
+const os = require('os');
+
+const homedir = os.homedir();
+const tmpdir = os.tmpdir();
+const {env} = process;
+
+const macos = name => {
+ const library = path.join(homedir, 'Library');
+
+ return {
+ data: path.join(library, 'Application Support', name),
+ config: path.join(library, 'Preferences', name),
+ cache: path.join(library, 'Caches', name),
+ log: path.join(library, 'Logs', name),
+ temp: path.join(tmpdir, name)
+ };
+};
+
+const windows = name => {
+ const appData = env.APPDATA || path.join(homedir, 'AppData', 'Roaming');
+ const localAppData = env.LOCALAPPDATA || path.join(homedir, 'AppData', 'Local');
+
+ return {
+ // Data/config/cache/log are invented by me as Windows isn't opinionated about this
+ data: path.join(localAppData, name, 'Data'),
+ config: path.join(appData, name, 'Config'),
+ cache: path.join(localAppData, name, 'Cache'),
+ log: path.join(localAppData, name, 'Log'),
+ temp: path.join(tmpdir, name)
+ };
+};
+
+// https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html
+const linux = name => {
+ const username = path.basename(homedir);
+
+ return {
+ data: path.join(env.XDG_DATA_HOME || path.join(homedir, '.local', 'share'), name),
+ config: path.join(env.XDG_CONFIG_HOME || path.join(homedir, '.config'), name),
+ cache: path.join(env.XDG_CACHE_HOME || path.join(homedir, '.cache'), name),
+ // https://wiki.debian.org/XDGBaseDirectorySpecification#state
+ log: path.join(env.XDG_STATE_HOME || path.join(homedir, '.local', 'state'), name),
+ temp: path.join(tmpdir, username, name)
+ };
+};
+
+const envPaths = (name, options) => {
+ if (typeof name !== 'string') {
+ throw new TypeError(`Expected string, got ${typeof name}`);
+ }
+
+ options = Object.assign({suffix: 'nodejs'}, options);
+
+ if (options.suffix) {
+ // Add suffix to prevent possible conflict with native apps
+ name += `-${options.suffix}`;
+ }
+
+ if (process.platform === 'darwin') {
+ return macos(name);
+ }
+
+ if (process.platform === 'win32') {
+ return windows(name);
+ }
+
+ return linux(name);
+};
+
+module.exports = envPaths;
+// TODO: Remove this for the next major release
+module.exports.default = envPaths;
diff --git a/temporary_modules/trezor-connect/node_modules/env-paths/license b/temporary_modules/trezor-connect/node_modules/env-paths/license
new file mode 100644
index 00000000..e7af2f77
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/env-paths/license
@@ -0,0 +1,9 @@
+MIT License
+
+Copyright (c) Sindre Sorhus (sindresorhus.com)
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/temporary_modules/trezor-connect/node_modules/env-paths/package.json b/temporary_modules/trezor-connect/node_modules/env-paths/package.json
new file mode 100644
index 00000000..fae4ebcf
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/env-paths/package.json
@@ -0,0 +1,45 @@
+{
+ "name": "env-paths",
+ "version": "2.2.1",
+ "description": "Get paths for storing things like data, config, cache, etc",
+ "license": "MIT",
+ "repository": "sindresorhus/env-paths",
+ "author": {
+ "name": "Sindre Sorhus",
+ "email": "sindresorhus@gmail.com",
+ "url": "sindresorhus.com"
+ },
+ "engines": {
+ "node": ">=6"
+ },
+ "scripts": {
+ "test": "xo && ava && tsd"
+ },
+ "files": [
+ "index.js",
+ "index.d.ts"
+ ],
+ "keywords": [
+ "common",
+ "user",
+ "paths",
+ "env",
+ "environment",
+ "directory",
+ "dir",
+ "appdir",
+ "path",
+ "data",
+ "config",
+ "cache",
+ "logs",
+ "temp",
+ "linux",
+ "unix"
+ ],
+ "devDependencies": {
+ "ava": "^1.4.1",
+ "tsd": "^0.7.1",
+ "xo": "^0.24.0"
+ }
+}
diff --git a/temporary_modules/trezor-connect/node_modules/env-paths/readme.md b/temporary_modules/trezor-connect/node_modules/env-paths/readme.md
new file mode 100644
index 00000000..b66d571a
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/env-paths/readme.md
@@ -0,0 +1,115 @@
+# env-paths
+
+> Get paths for storing things like data, config, cache, etc
+
+Uses the correct OS-specific paths. Most developers get this wrong.
+
+
+## Install
+
+```
+$ npm install env-paths
+```
+
+
+## Usage
+
+```js
+const envPaths = require('env-paths');
+
+const paths = envPaths('MyApp');
+
+paths.data;
+//=> '/home/sindresorhus/.local/share/MyApp-nodejs'
+
+paths.config
+//=> '/home/sindresorhus/.config/MyApp-nodejs'
+```
+
+
+## API
+
+### paths = envPaths(name, options?)
+
+Note: It only generates the path strings. It doesn't create the directories for you. You could use [`make-dir`](https://github.com/sindresorhus/make-dir) to create the directories.
+
+#### name
+
+Type: `string`
+
+Name of your project. Used to generate the paths.
+
+#### options
+
+Type: `object`
+
+##### suffix
+
+Type: `string`
+Default: `'nodejs'`
+
+**Don't use this option unless you really have to!**
+Suffix appended to the project name to avoid name conflicts with native
+apps. Pass an empty string to disable it.
+
+### paths.data
+
+Directory for data files.
+
+Example locations (with the default `nodejs` [suffix](#suffix)):
+
+- macOS: `~/Library/Application Support/MyApp-nodejs`
+- Windows: `%LOCALAPPDATA%\MyApp-nodejs\Data` (for example, `C:\Users\USERNAME\AppData\Local\MyApp-nodejs\Data`)
+- Linux: `~/.local/share/MyApp-nodejs` (or `$XDG_DATA_HOME/MyApp-nodejs`)
+
+### paths.config
+
+Directory for config files.
+
+Example locations (with the default `nodejs` [suffix](#suffix)):
+
+- macOS: `~/Library/Preferences/MyApp-nodejs`
+- Windows: `%APPDATA%\MyApp-nodejs\Config` (for example, `C:\Users\USERNAME\AppData\Roaming\MyApp-nodejs\Config`)
+- Linux: `~/.config/MyApp-nodejs` (or `$XDG_CONFIG_HOME/MyApp-nodejs`)
+
+### paths.cache
+
+Directory for non-essential data files.
+
+Example locations (with the default `nodejs` [suffix](#suffix)):
+
+- macOS: `~/Library/Caches/MyApp-nodejs`
+- Windows: `%LOCALAPPDATA%\MyApp-nodejs\Cache` (for example, `C:\Users\USERNAME\AppData\Local\MyApp-nodejs\Cache`)
+- Linux: `~/.cache/MyApp-nodejs` (or `$XDG_CACHE_HOME/MyApp-nodejs`)
+
+### paths.log
+
+Directory for log files.
+
+Example locations (with the default `nodejs` [suffix](#suffix)):
+
+- macOS: `~/Library/Logs/MyApp-nodejs`
+- Windows: `%LOCALAPPDATA%\MyApp-nodejs\Log` (for example, `C:\Users\USERNAME\AppData\Local\MyApp-nodejs\Log`)
+- Linux: `~/.local/state/MyApp-nodejs` (or `$XDG_STATE_HOME/MyApp-nodejs`)
+
+### paths.temp
+
+Directory for temporary files.
+
+Example locations (with the default `nodejs` [suffix](#suffix)):
+
+- macOS: `/var/folders/jf/f2twvvvs5jl_m49tf034ffpw0000gn/T/MyApp-nodejs`
+- Windows: `%LOCALAPPDATA%\Temp\MyApp-nodejs` (for example, `C:\Users\USERNAME\AppData\Local\Temp\MyApp-nodejs`)
+- Linux: `/tmp/USERNAME/MyApp-nodejs`
+
+---
+
+
diff --git a/temporary_modules/trezor-connect/node_modules/events/.airtap.yml b/temporary_modules/trezor-connect/node_modules/events/.airtap.yml
new file mode 100644
index 00000000..c7a8a87d
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/events/.airtap.yml
@@ -0,0 +1,15 @@
+sauce_connect: true
+loopback: airtap.local
+browsers:
+ - name: chrome
+ version: latest
+ - name: firefox
+ version: latest
+ - name: safari
+ version: 9..latest
+ - name: iphone
+ version: latest
+ - name: ie
+ version: 9..latest
+ - name: microsoftedge
+ version: 13..latest
diff --git a/temporary_modules/trezor-connect/node_modules/events/.github/FUNDING.yml b/temporary_modules/trezor-connect/node_modules/events/.github/FUNDING.yml
new file mode 100644
index 00000000..8b8cb78b
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/events/.github/FUNDING.yml
@@ -0,0 +1,12 @@
+# These are supported funding model platforms
+
+github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
+patreon: # Replace with a single Patreon username
+open_collective: # Replace with a single Open Collective username
+ko_fi: # Replace with a single Ko-fi username
+tidelift: npm/events
+community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
+liberapay: # Replace with a single Liberapay username
+issuehunt: # Replace with a single IssueHunt username
+otechie: # Replace with a single Otechie username
+custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
diff --git a/temporary_modules/trezor-connect/node_modules/events/.travis.yml b/temporary_modules/trezor-connect/node_modules/events/.travis.yml
new file mode 100644
index 00000000..486dc3c4
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/events/.travis.yml
@@ -0,0 +1,18 @@
+dist: xenial
+os: linux
+language: node_js
+node_js:
+ - 'stable'
+ - 'lts/*'
+ - '0.12'
+script:
+ - npm test
+ - if [ "${TRAVIS_PULL_REQUEST}" = "false" ] && [ "${TRAVIS_NODE_VERSION}" = "stable" ]; then npm run test:browsers; fi
+addons:
+ sauce_connect: true
+ hosts:
+ - airtap.local
+env:
+ global:
+ - secure: XcBiD8yReflut9q7leKsigDZ0mI3qTKH+QrNVY8DaqlomJOZw8aOrVuX9Jz12l86ZJ41nbxmKnRNkFzcVr9mbP9YaeTb3DpeOBWmvaoSfud9Wnc16VfXtc1FCcwDhSVcSiM3UtnrmFU5cH+Dw1LPh5PbfylYOS/nJxUvG0FFLqI=
+ - secure: jNWtEbqhUdQ0xXDHvCYfUbKYeJCi6a7B4LsrcxYCyWWn4NIgncE5x2YbB+FSUUFVYfz0dsn5RKP1oHB99f0laUEo18HBNkrAS/rtyOdVzcpJjbQ6kgSILGjnJD/Ty1B57Rcz3iyev5Y7bLZ6Y1FbDnk/i9/l0faOGz8vTC3Vdkc=
diff --git a/temporary_modules/trezor-connect/node_modules/events/History.md b/temporary_modules/trezor-connect/node_modules/events/History.md
new file mode 100644
index 00000000..f48bf210
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/events/History.md
@@ -0,0 +1,118 @@
+# 3.3.0
+
+ - Support EventTarget emitters in `events.once` from Node.js 12.11.0.
+
+ Now you can use the `events.once` function with objects that implement the EventTarget interface. This interface is used widely in
+ the DOM and other web APIs.
+
+ ```js
+ var events = require('events');
+ var assert = require('assert');
+
+ async function connect() {
+ var ws = new WebSocket('wss://example.com');
+ await events.once(ws, 'open');
+ assert(ws.readyState === WebSocket.OPEN);
+ }
+
+ async function onClick() {
+ await events.once(document.body, 'click');
+ alert('you clicked the page!');
+ }
+ ```
+
+# 3.2.0
+
+ - Add `events.once` from Node.js 11.13.0.
+
+ To use this function, Promises must be supported in the environment. Use a polyfill like `es6-promise` if you support older browsers.
+
+# 3.1.0 (2020-01-08)
+
+`events` now matches the Node.js 11.12.0 API.
+
+ - pass through return value in wrapped `emitter.once()` listeners
+
+ Now, this works:
+ ```js
+ emitter.once('myevent', function () { return 1; });
+ var listener = emitter.rawListeners('myevent')[0]
+ assert(listener() === 1);
+ ```
+ Previously, `listener()` would return undefined regardless of the implementation.
+
+ Ported from https://github.com/nodejs/node/commit/acc506c2d2771dab8d7bba6d3452bc5180dff7cf
+
+ - Reduce code duplication in listener type check ([#67](https://github.com/Gozala/events/pull/67) by [@friederbluemle](https://github.com/friederbluemle)).
+ - Improve `emitter.once()` performance in some engines
+
+# 3.0.0 (2018-05-25)
+
+**This version drops support for IE8.** `events` no longer includes polyfills
+for ES5 features. If you need to support older environments, use an ES5 shim
+like [es5-shim](https://npmjs.com/package/es5-shim). Both the shim and sham
+versions of es5-shim are necessary.
+
+ - Update to events code from Node.js 10.x
+ - (semver major) Adds `off()` method
+ - Port more tests from Node.js
+ - Switch browser tests to airtap, making things more reliable
+
+# 2.1.0 (2018-05-25)
+
+ - add Emitter#rawListeners from Node.js v9.4
+
+# 2.0.0 (2018-02-02)
+
+ - Update to events code from node.js 8.x
+ - Adds `prependListener()` and `prependOnceListener()`
+ - Adds `eventNames()` method
+ - (semver major) Unwrap `once()` listeners in `listeners()`
+ - copy tests from node.js
+
+Note that this version doubles the gzipped size, jumping from 1.1KB to 2.1KB,
+due to new methods and runtime performance improvements. Be aware of that when
+upgrading.
+
+# 1.1.1 (2016-06-22)
+
+ - add more context to errors if they are not instanceof Error
+
+# 1.1.0 (2015-09-29)
+
+ - add Emitter#listerCount (to match node v4 api)
+
+# 1.0.2 (2014-08-28)
+
+ - remove un-reachable code
+ - update devDeps
+
+## 1.0.1 / 2014-05-11
+
+ - check for console.trace before using it
+
+## 1.0.0 / 2013-12-10
+
+ - Update to latest events code from node.js 0.10
+ - copy tests from node.js
+
+## 0.4.0 / 2011-07-03 ##
+
+ - Switching to graphquire@0.8.0
+
+## 0.3.0 / 2011-07-03 ##
+
+ - Switching to URL based module require.
+
+## 0.2.0 / 2011-06-10 ##
+
+ - Simplified package structure.
+ - Graphquire for dependency management.
+
+## 0.1.1 / 2011-05-16 ##
+
+ - Unhandled errors are logged via console.error
+
+## 0.1.0 / 2011-04-22 ##
+
+ - Initial release
diff --git a/temporary_modules/trezor-connect/node_modules/events/LICENSE b/temporary_modules/trezor-connect/node_modules/events/LICENSE
new file mode 100644
index 00000000..52ed3b0a
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/events/LICENSE
@@ -0,0 +1,22 @@
+MIT
+
+Copyright Joyent, Inc. and other Node contributors.
+
+Permission is hereby granted, free of charge, to any person obtaining a
+copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to permit
+persons to whom the Software is furnished to do so, subject to the
+following conditions:
+
+The above copyright notice and this permission notice shall be included
+in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
+NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
+USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/temporary_modules/trezor-connect/node_modules/events/Readme.md b/temporary_modules/trezor-connect/node_modules/events/Readme.md
new file mode 100644
index 00000000..80849c0b
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/events/Readme.md
@@ -0,0 +1,50 @@
+# events [](https://travis-ci.org/Gozala/events)
+
+> Node's event emitter for all engines.
+
+This implements the Node.js [`events`][node.js docs] module for environments that do not have it, like browsers.
+
+> `events` currently matches the **Node.js 11.13.0** API.
+
+Note that the `events` module uses ES5 features. If you need to support very old browsers like IE8, use a shim like [`es5-shim`](https://www.npmjs.com/package/es5-shim). You need both the shim and the sham versions of `es5-shim`.
+
+This module is maintained, but only by very few people. If you'd like to help, let us know in the [Maintainer Needed](https://github.com/Gozala/events/issues/43) issue!
+
+## Install
+
+You usually do not have to install `events` yourself! If your code runs in Node.js, `events` is built in. If your code runs in the browser, bundlers like [browserify](https://github.com/browserify/browserify) or [webpack](https://github.com/webpack/webpack) also include the `events` module.
+
+But if none of those apply, with npm do:
+
+```
+npm install events
+```
+
+## Usage
+
+```javascript
+var EventEmitter = require('events')
+
+var ee = new EventEmitter()
+ee.on('message', function (text) {
+ console.log(text)
+})
+ee.emit('message', 'hello world')
+```
+
+## API
+
+See the [Node.js EventEmitter docs][node.js docs]. `events` currently matches the Node.js 11.13.0 API.
+
+## Contributing
+
+PRs are very welcome! The main way to contribute to `events` is by porting features, bugfixes and tests from Node.js. Ideally, code contributions to this module are copy-pasted from Node.js and transpiled to ES5, rather than reimplemented from scratch. Matching the Node.js code as closely as possible makes maintenance simpler when new changes land in Node.js.
+This module intends to provide exactly the same API as Node.js, so features that are not available in the core `events` module will not be accepted. Feature requests should instead be directed at [nodejs/node](https://github.com/nodejs/node) and will be added to this module once they are implemented in Node.js.
+
+If there is a difference in behaviour between Node.js's `events` module and this module, please open an issue!
+
+## License
+
+[MIT](./LICENSE)
+
+[node.js docs]: https://nodejs.org/dist/v11.13.0/docs/api/events.html
diff --git a/temporary_modules/trezor-connect/node_modules/events/events.js b/temporary_modules/trezor-connect/node_modules/events/events.js
new file mode 100644
index 00000000..34b69a0b
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/events/events.js
@@ -0,0 +1,497 @@
+// Copyright Joyent, Inc. and other Node contributors.
+//
+// Permission is hereby granted, free of charge, to any person obtaining a
+// copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to permit
+// persons to whom the Software is furnished to do so, subject to the
+// following conditions:
+//
+// The above copyright notice and this permission notice shall be included
+// in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
+// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
+// USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+'use strict';
+
+var R = typeof Reflect === 'object' ? Reflect : null
+var ReflectApply = R && typeof R.apply === 'function'
+ ? R.apply
+ : function ReflectApply(target, receiver, args) {
+ return Function.prototype.apply.call(target, receiver, args);
+ }
+
+var ReflectOwnKeys
+if (R && typeof R.ownKeys === 'function') {
+ ReflectOwnKeys = R.ownKeys
+} else if (Object.getOwnPropertySymbols) {
+ ReflectOwnKeys = function ReflectOwnKeys(target) {
+ return Object.getOwnPropertyNames(target)
+ .concat(Object.getOwnPropertySymbols(target));
+ };
+} else {
+ ReflectOwnKeys = function ReflectOwnKeys(target) {
+ return Object.getOwnPropertyNames(target);
+ };
+}
+
+function ProcessEmitWarning(warning) {
+ if (console && console.warn) console.warn(warning);
+}
+
+var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) {
+ return value !== value;
+}
+
+function EventEmitter() {
+ EventEmitter.init.call(this);
+}
+module.exports = EventEmitter;
+module.exports.once = once;
+
+// Backwards-compat with node 0.10.x
+EventEmitter.EventEmitter = EventEmitter;
+
+EventEmitter.prototype._events = undefined;
+EventEmitter.prototype._eventsCount = 0;
+EventEmitter.prototype._maxListeners = undefined;
+
+// By default EventEmitters will print a warning if more than 10 listeners are
+// added to it. This is a useful default which helps finding memory leaks.
+var defaultMaxListeners = 10;
+
+function checkListener(listener) {
+ if (typeof listener !== 'function') {
+ throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener);
+ }
+}
+
+Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
+ enumerable: true,
+ get: function() {
+ return defaultMaxListeners;
+ },
+ set: function(arg) {
+ if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) {
+ throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.');
+ }
+ defaultMaxListeners = arg;
+ }
+});
+
+EventEmitter.init = function() {
+
+ if (this._events === undefined ||
+ this._events === Object.getPrototypeOf(this)._events) {
+ this._events = Object.create(null);
+ this._eventsCount = 0;
+ }
+
+ this._maxListeners = this._maxListeners || undefined;
+};
+
+// Obviously not all Emitters should be limited to 10. This function allows
+// that to be increased. Set to zero for unlimited.
+EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
+ if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) {
+ throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.');
+ }
+ this._maxListeners = n;
+ return this;
+};
+
+function _getMaxListeners(that) {
+ if (that._maxListeners === undefined)
+ return EventEmitter.defaultMaxListeners;
+ return that._maxListeners;
+}
+
+EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
+ return _getMaxListeners(this);
+};
+
+EventEmitter.prototype.emit = function emit(type) {
+ var args = [];
+ for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);
+ var doError = (type === 'error');
+
+ var events = this._events;
+ if (events !== undefined)
+ doError = (doError && events.error === undefined);
+ else if (!doError)
+ return false;
+
+ // If there is no 'error' event listener then throw.
+ if (doError) {
+ var er;
+ if (args.length > 0)
+ er = args[0];
+ if (er instanceof Error) {
+ // Note: The comments on the `throw` lines are intentional, they show
+ // up in Node's output if this results in an unhandled exception.
+ throw er; // Unhandled 'error' event
+ }
+ // At least give some kind of context to the user
+ var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : ''));
+ err.context = er;
+ throw err; // Unhandled 'error' event
+ }
+
+ var handler = events[type];
+
+ if (handler === undefined)
+ return false;
+
+ if (typeof handler === 'function') {
+ ReflectApply(handler, this, args);
+ } else {
+ var len = handler.length;
+ var listeners = arrayClone(handler, len);
+ for (var i = 0; i < len; ++i)
+ ReflectApply(listeners[i], this, args);
+ }
+
+ return true;
+};
+
+function _addListener(target, type, listener, prepend) {
+ var m;
+ var events;
+ var existing;
+
+ checkListener(listener);
+
+ events = target._events;
+ if (events === undefined) {
+ events = target._events = Object.create(null);
+ target._eventsCount = 0;
+ } else {
+ // To avoid recursion in the case that type === "newListener"! Before
+ // adding it to the listeners, first emit "newListener".
+ if (events.newListener !== undefined) {
+ target.emit('newListener', type,
+ listener.listener ? listener.listener : listener);
+
+ // Re-assign `events` because a newListener handler could have caused the
+ // this._events to be assigned to a new object
+ events = target._events;
+ }
+ existing = events[type];
+ }
+
+ if (existing === undefined) {
+ // Optimize the case of one listener. Don't need the extra array object.
+ existing = events[type] = listener;
+ ++target._eventsCount;
+ } else {
+ if (typeof existing === 'function') {
+ // Adding the second element, need to change to array.
+ existing = events[type] =
+ prepend ? [listener, existing] : [existing, listener];
+ // If we've already got an array, just append.
+ } else if (prepend) {
+ existing.unshift(listener);
+ } else {
+ existing.push(listener);
+ }
+
+ // Check for listener leak
+ m = _getMaxListeners(target);
+ if (m > 0 && existing.length > m && !existing.warned) {
+ existing.warned = true;
+ // No error code for this since it is a Warning
+ // eslint-disable-next-line no-restricted-syntax
+ var w = new Error('Possible EventEmitter memory leak detected. ' +
+ existing.length + ' ' + String(type) + ' listeners ' +
+ 'added. Use emitter.setMaxListeners() to ' +
+ 'increase limit');
+ w.name = 'MaxListenersExceededWarning';
+ w.emitter = target;
+ w.type = type;
+ w.count = existing.length;
+ ProcessEmitWarning(w);
+ }
+ }
+
+ return target;
+}
+
+EventEmitter.prototype.addListener = function addListener(type, listener) {
+ return _addListener(this, type, listener, false);
+};
+
+EventEmitter.prototype.on = EventEmitter.prototype.addListener;
+
+EventEmitter.prototype.prependListener =
+ function prependListener(type, listener) {
+ return _addListener(this, type, listener, true);
+ };
+
+function onceWrapper() {
+ if (!this.fired) {
+ this.target.removeListener(this.type, this.wrapFn);
+ this.fired = true;
+ if (arguments.length === 0)
+ return this.listener.call(this.target);
+ return this.listener.apply(this.target, arguments);
+ }
+}
+
+function _onceWrap(target, type, listener) {
+ var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
+ var wrapped = onceWrapper.bind(state);
+ wrapped.listener = listener;
+ state.wrapFn = wrapped;
+ return wrapped;
+}
+
+EventEmitter.prototype.once = function once(type, listener) {
+ checkListener(listener);
+ this.on(type, _onceWrap(this, type, listener));
+ return this;
+};
+
+EventEmitter.prototype.prependOnceListener =
+ function prependOnceListener(type, listener) {
+ checkListener(listener);
+ this.prependListener(type, _onceWrap(this, type, listener));
+ return this;
+ };
+
+// Emits a 'removeListener' event if and only if the listener was removed.
+EventEmitter.prototype.removeListener =
+ function removeListener(type, listener) {
+ var list, events, position, i, originalListener;
+
+ checkListener(listener);
+
+ events = this._events;
+ if (events === undefined)
+ return this;
+
+ list = events[type];
+ if (list === undefined)
+ return this;
+
+ if (list === listener || list.listener === listener) {
+ if (--this._eventsCount === 0)
+ this._events = Object.create(null);
+ else {
+ delete events[type];
+ if (events.removeListener)
+ this.emit('removeListener', type, list.listener || listener);
+ }
+ } else if (typeof list !== 'function') {
+ position = -1;
+
+ for (i = list.length - 1; i >= 0; i--) {
+ if (list[i] === listener || list[i].listener === listener) {
+ originalListener = list[i].listener;
+ position = i;
+ break;
+ }
+ }
+
+ if (position < 0)
+ return this;
+
+ if (position === 0)
+ list.shift();
+ else {
+ spliceOne(list, position);
+ }
+
+ if (list.length === 1)
+ events[type] = list[0];
+
+ if (events.removeListener !== undefined)
+ this.emit('removeListener', type, originalListener || listener);
+ }
+
+ return this;
+ };
+
+EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
+
+EventEmitter.prototype.removeAllListeners =
+ function removeAllListeners(type) {
+ var listeners, events, i;
+
+ events = this._events;
+ if (events === undefined)
+ return this;
+
+ // not listening for removeListener, no need to emit
+ if (events.removeListener === undefined) {
+ if (arguments.length === 0) {
+ this._events = Object.create(null);
+ this._eventsCount = 0;
+ } else if (events[type] !== undefined) {
+ if (--this._eventsCount === 0)
+ this._events = Object.create(null);
+ else
+ delete events[type];
+ }
+ return this;
+ }
+
+ // emit removeListener for all listeners on all events
+ if (arguments.length === 0) {
+ var keys = Object.keys(events);
+ var key;
+ for (i = 0; i < keys.length; ++i) {
+ key = keys[i];
+ if (key === 'removeListener') continue;
+ this.removeAllListeners(key);
+ }
+ this.removeAllListeners('removeListener');
+ this._events = Object.create(null);
+ this._eventsCount = 0;
+ return this;
+ }
+
+ listeners = events[type];
+
+ if (typeof listeners === 'function') {
+ this.removeListener(type, listeners);
+ } else if (listeners !== undefined) {
+ // LIFO order
+ for (i = listeners.length - 1; i >= 0; i--) {
+ this.removeListener(type, listeners[i]);
+ }
+ }
+
+ return this;
+ };
+
+function _listeners(target, type, unwrap) {
+ var events = target._events;
+
+ if (events === undefined)
+ return [];
+
+ var evlistener = events[type];
+ if (evlistener === undefined)
+ return [];
+
+ if (typeof evlistener === 'function')
+ return unwrap ? [evlistener.listener || evlistener] : [evlistener];
+
+ return unwrap ?
+ unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
+}
+
+EventEmitter.prototype.listeners = function listeners(type) {
+ return _listeners(this, type, true);
+};
+
+EventEmitter.prototype.rawListeners = function rawListeners(type) {
+ return _listeners(this, type, false);
+};
+
+EventEmitter.listenerCount = function(emitter, type) {
+ if (typeof emitter.listenerCount === 'function') {
+ return emitter.listenerCount(type);
+ } else {
+ return listenerCount.call(emitter, type);
+ }
+};
+
+EventEmitter.prototype.listenerCount = listenerCount;
+function listenerCount(type) {
+ var events = this._events;
+
+ if (events !== undefined) {
+ var evlistener = events[type];
+
+ if (typeof evlistener === 'function') {
+ return 1;
+ } else if (evlistener !== undefined) {
+ return evlistener.length;
+ }
+ }
+
+ return 0;
+}
+
+EventEmitter.prototype.eventNames = function eventNames() {
+ return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];
+};
+
+function arrayClone(arr, n) {
+ var copy = new Array(n);
+ for (var i = 0; i < n; ++i)
+ copy[i] = arr[i];
+ return copy;
+}
+
+function spliceOne(list, index) {
+ for (; index + 1 < list.length; index++)
+ list[index] = list[index + 1];
+ list.pop();
+}
+
+function unwrapListeners(arr) {
+ var ret = new Array(arr.length);
+ for (var i = 0; i < ret.length; ++i) {
+ ret[i] = arr[i].listener || arr[i];
+ }
+ return ret;
+}
+
+function once(emitter, name) {
+ return new Promise(function (resolve, reject) {
+ function errorListener(err) {
+ emitter.removeListener(name, resolver);
+ reject(err);
+ }
+
+ function resolver() {
+ if (typeof emitter.removeListener === 'function') {
+ emitter.removeListener('error', errorListener);
+ }
+ resolve([].slice.call(arguments));
+ };
+
+ eventTargetAgnosticAddListener(emitter, name, resolver, { once: true });
+ if (name !== 'error') {
+ addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true });
+ }
+ });
+}
+
+function addErrorHandlerIfEventEmitter(emitter, handler, flags) {
+ if (typeof emitter.on === 'function') {
+ eventTargetAgnosticAddListener(emitter, 'error', handler, flags);
+ }
+}
+
+function eventTargetAgnosticAddListener(emitter, name, listener, flags) {
+ if (typeof emitter.on === 'function') {
+ if (flags.once) {
+ emitter.once(name, listener);
+ } else {
+ emitter.on(name, listener);
+ }
+ } else if (typeof emitter.addEventListener === 'function') {
+ // EventTarget does not have `error` event semantics like Node
+ // EventEmitters, we do not listen for `error` events here.
+ emitter.addEventListener(name, function wrapListener(arg) {
+ // IE does not have builtin `{ once: true }` support so we
+ // have to do it manually.
+ if (flags.once) {
+ emitter.removeEventListener(name, wrapListener);
+ }
+ listener(arg);
+ });
+ } else {
+ throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter);
+ }
+}
diff --git a/temporary_modules/trezor-connect/node_modules/events/package.json b/temporary_modules/trezor-connect/node_modules/events/package.json
new file mode 100644
index 00000000..b9580d88
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/events/package.json
@@ -0,0 +1,37 @@
+{
+ "name": "events",
+ "version": "3.3.0",
+ "description": "Node's event emitter for all engines.",
+ "keywords": [
+ "events",
+ "eventEmitter",
+ "eventDispatcher",
+ "listeners"
+ ],
+ "author": "Irakli Gozalishvili (http://jeditoolkit.com)",
+ "repository": {
+ "type": "git",
+ "url": "git://github.com/Gozala/events.git",
+ "web": "https://github.com/Gozala/events"
+ },
+ "bugs": {
+ "url": "http://github.com/Gozala/events/issues/"
+ },
+ "main": "./events.js",
+ "engines": {
+ "node": ">=0.8.x"
+ },
+ "devDependencies": {
+ "airtap": "^1.0.0",
+ "functions-have-names": "^1.2.1",
+ "has": "^1.0.3",
+ "has-symbols": "^1.0.1",
+ "isarray": "^2.0.5",
+ "tape": "^5.0.0"
+ },
+ "scripts": {
+ "test": "node tests/index.js",
+ "test:browsers": "airtap -- tests/index.js"
+ },
+ "license": "MIT"
+}
diff --git a/temporary_modules/trezor-connect/node_modules/events/security.md b/temporary_modules/trezor-connect/node_modules/events/security.md
new file mode 100644
index 00000000..a14ace6a
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/events/security.md
@@ -0,0 +1,10 @@
+# Security Policy
+
+## Supported Versions
+Only the latest major version is supported at any given time.
+
+## Reporting a Vulnerability
+
+To report a security vulnerability, please use the
+[Tidelift security contact](https://tidelift.com/security).
+Tidelift will coordinate the fix and disclosure.
diff --git a/temporary_modules/trezor-connect/node_modules/events/tests/add-listeners.js b/temporary_modules/trezor-connect/node_modules/events/tests/add-listeners.js
new file mode 100644
index 00000000..9b578272
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/events/tests/add-listeners.js
@@ -0,0 +1,111 @@
+// Copyright Joyent, Inc. and other Node contributors.
+//
+// Permission is hereby granted, free of charge, to any person obtaining a
+// copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to permit
+// persons to whom the Software is furnished to do so, subject to the
+// following conditions:
+//
+// The above copyright notice and this permission notice shall be included
+// in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
+// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
+// USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+var common = require('./common');
+var assert = require('assert');
+var EventEmitter = require('../');
+
+{
+ var ee = new EventEmitter();
+ var events_new_listener_emitted = [];
+ var listeners_new_listener_emitted = [];
+
+ // Sanity check
+ assert.strictEqual(ee.addListener, ee.on);
+
+ ee.on('newListener', function(event, listener) {
+ // Don't track newListener listeners.
+ if (event === 'newListener')
+ return;
+
+ events_new_listener_emitted.push(event);
+ listeners_new_listener_emitted.push(listener);
+ });
+
+ var hello = common.mustCall(function(a, b) {
+ assert.strictEqual('a', a);
+ assert.strictEqual('b', b);
+ });
+
+ ee.once('newListener', function(name, listener) {
+ assert.strictEqual(name, 'hello');
+ assert.strictEqual(listener, hello);
+
+ var listeners = this.listeners('hello');
+ assert.ok(Array.isArray(listeners));
+ assert.strictEqual(listeners.length, 0);
+ });
+
+ ee.on('hello', hello);
+ ee.once('foo', assert.fail);
+
+ assert.ok(Array.isArray(events_new_listener_emitted));
+ assert.strictEqual(events_new_listener_emitted.length, 2);
+ assert.strictEqual(events_new_listener_emitted[0], 'hello');
+ assert.strictEqual(events_new_listener_emitted[1], 'foo');
+
+ assert.ok(Array.isArray(listeners_new_listener_emitted));
+ assert.strictEqual(listeners_new_listener_emitted.length, 2);
+ assert.strictEqual(listeners_new_listener_emitted[0], hello);
+ assert.strictEqual(listeners_new_listener_emitted[1], assert.fail);
+
+ ee.emit('hello', 'a', 'b');
+}
+
+// just make sure that this doesn't throw:
+{
+ var f = new EventEmitter();
+
+ f.setMaxListeners(0);
+}
+
+{
+ var listen1 = function() {};
+ var listen2 = function() {};
+ var ee = new EventEmitter();
+
+ ee.once('newListener', function() {
+ var listeners = ee.listeners('hello');
+ assert.ok(Array.isArray(listeners));
+ assert.strictEqual(listeners.length, 0);
+ ee.once('newListener', function() {
+ var listeners = ee.listeners('hello');
+ assert.ok(Array.isArray(listeners));
+ assert.strictEqual(listeners.length, 0);
+ });
+ ee.on('hello', listen2);
+ });
+ ee.on('hello', listen1);
+ // The order of listeners on an event is not always the order in which the
+ // listeners were added.
+ var listeners = ee.listeners('hello');
+ assert.ok(Array.isArray(listeners));
+ assert.strictEqual(listeners.length, 2);
+ assert.strictEqual(listeners[0], listen2);
+ assert.strictEqual(listeners[1], listen1);
+}
+
+// Verify that the listener must be a function
+assert.throws(function() {
+ var ee = new EventEmitter();
+
+ ee.on('foo', null);
+}, /^TypeError: The "listener" argument must be of type Function. Received type object$/);
diff --git a/temporary_modules/trezor-connect/node_modules/events/tests/check-listener-leaks.js b/temporary_modules/trezor-connect/node_modules/events/tests/check-listener-leaks.js
new file mode 100644
index 00000000..7fce48f3
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/events/tests/check-listener-leaks.js
@@ -0,0 +1,101 @@
+// Copyright Joyent, Inc. and other Node contributors.
+//
+// Permission is hereby granted, free of charge, to any person obtaining a
+// copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to permit
+// persons to whom the Software is furnished to do so, subject to the
+// following conditions:
+//
+// The above copyright notice and this permission notice shall be included
+// in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
+// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
+// USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+var common = require('./common');
+var assert = require('assert');
+var events = require('../');
+
+// Redirect warning output to tape.
+var consoleWarn = console.warn;
+console.warn = common.test.comment;
+
+common.test.on('end', function () {
+ console.warn = consoleWarn;
+});
+
+// default
+{
+ var e = new events.EventEmitter();
+
+ for (var i = 0; i < 10; i++) {
+ e.on('default', common.mustNotCall());
+ }
+ assert.ok(!e._events['default'].hasOwnProperty('warned'));
+ e.on('default', common.mustNotCall());
+ assert.ok(e._events['default'].warned);
+
+ // specific
+ e.setMaxListeners(5);
+ for (var i = 0; i < 5; i++) {
+ e.on('specific', common.mustNotCall());
+ }
+ assert.ok(!e._events['specific'].hasOwnProperty('warned'));
+ e.on('specific', common.mustNotCall());
+ assert.ok(e._events['specific'].warned);
+
+ // only one
+ e.setMaxListeners(1);
+ e.on('only one', common.mustNotCall());
+ assert.ok(!e._events['only one'].hasOwnProperty('warned'));
+ e.on('only one', common.mustNotCall());
+ assert.ok(e._events['only one'].hasOwnProperty('warned'));
+
+ // unlimited
+ e.setMaxListeners(0);
+ for (var i = 0; i < 1000; i++) {
+ e.on('unlimited', common.mustNotCall());
+ }
+ assert.ok(!e._events['unlimited'].hasOwnProperty('warned'));
+}
+
+// process-wide
+{
+ events.EventEmitter.defaultMaxListeners = 42;
+ var e = new events.EventEmitter();
+
+ for (var i = 0; i < 42; ++i) {
+ e.on('fortytwo', common.mustNotCall());
+ }
+ assert.ok(!e._events['fortytwo'].hasOwnProperty('warned'));
+ e.on('fortytwo', common.mustNotCall());
+ assert.ok(e._events['fortytwo'].hasOwnProperty('warned'));
+ delete e._events['fortytwo'].warned;
+
+ events.EventEmitter.defaultMaxListeners = 44;
+ e.on('fortytwo', common.mustNotCall());
+ assert.ok(!e._events['fortytwo'].hasOwnProperty('warned'));
+ e.on('fortytwo', common.mustNotCall());
+ assert.ok(e._events['fortytwo'].hasOwnProperty('warned'));
+}
+
+// but _maxListeners still has precedence over defaultMaxListeners
+{
+ events.EventEmitter.defaultMaxListeners = 42;
+ var e = new events.EventEmitter();
+ e.setMaxListeners(1);
+ e.on('uno', common.mustNotCall());
+ assert.ok(!e._events['uno'].hasOwnProperty('warned'));
+ e.on('uno', common.mustNotCall());
+ assert.ok(e._events['uno'].hasOwnProperty('warned'));
+
+ // chainable
+ assert.strictEqual(e, e.setMaxListeners(1));
+}
diff --git a/temporary_modules/trezor-connect/node_modules/events/tests/common.js b/temporary_modules/trezor-connect/node_modules/events/tests/common.js
new file mode 100644
index 00000000..49569b05
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/events/tests/common.js
@@ -0,0 +1,104 @@
+// Copyright Joyent, Inc. and other Node contributors.
+//
+// Permission is hereby granted, free of charge, to any person obtaining a
+// copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to permit
+// persons to whom the Software is furnished to do so, subject to the
+// following conditions:
+//
+// The above copyright notice and this permission notice shall be included
+// in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
+// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
+// USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+var test = require('tape');
+var assert = require('assert');
+
+var noop = function() {};
+
+var mustCallChecks = [];
+
+function runCallChecks(exitCode) {
+ if (exitCode !== 0) return;
+
+ var failed = filter(mustCallChecks, function(context) {
+ if ('minimum' in context) {
+ context.messageSegment = 'at least ' + context.minimum;
+ return context.actual < context.minimum;
+ } else {
+ context.messageSegment = 'exactly ' + context.exact;
+ return context.actual !== context.exact;
+ }
+ });
+
+ for (var i = 0; i < failed.length; i++) {
+ var context = failed[i];
+ console.log('Mismatched %s function calls. Expected %s, actual %d.',
+ context.name,
+ context.messageSegment,
+ context.actual);
+ // IE8 has no .stack
+ if (context.stack) console.log(context.stack.split('\n').slice(2).join('\n'));
+ }
+
+ assert.strictEqual(failed.length, 0);
+}
+
+exports.mustCall = function(fn, exact) {
+ return _mustCallInner(fn, exact, 'exact');
+};
+
+function _mustCallInner(fn, criteria, field) {
+ if (typeof criteria == 'undefined') criteria = 1;
+
+ if (typeof fn === 'number') {
+ criteria = fn;
+ fn = noop;
+ } else if (fn === undefined) {
+ fn = noop;
+ }
+
+ if (typeof criteria !== 'number')
+ throw new TypeError('Invalid ' + field + ' value: ' + criteria);
+
+ var context = {
+ actual: 0,
+ stack: (new Error()).stack,
+ name: fn.name || ''
+ };
+
+ context[field] = criteria;
+
+ // add the exit listener only once to avoid listener leak warnings
+ if (mustCallChecks.length === 0) test.onFinish(function() { runCallChecks(0); });
+
+ mustCallChecks.push(context);
+
+ return function() {
+ context.actual++;
+ return fn.apply(this, arguments);
+ };
+}
+
+exports.mustNotCall = function(msg) {
+ return function mustNotCall() {
+ assert.fail(msg || 'function should not have been called');
+ };
+};
+
+function filter(arr, fn) {
+ if (arr.filter) return arr.filter(fn);
+ var filtered = [];
+ for (var i = 0; i < arr.length; i++) {
+ if (fn(arr[i], i, arr)) filtered.push(arr[i]);
+ }
+ return filtered
+}
diff --git a/temporary_modules/trezor-connect/node_modules/events/tests/errors.js b/temporary_modules/trezor-connect/node_modules/events/tests/errors.js
new file mode 100644
index 00000000..a23df437
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/events/tests/errors.js
@@ -0,0 +1,13 @@
+'use strict';
+var assert = require('assert');
+var EventEmitter = require('../');
+
+var EE = new EventEmitter();
+
+assert.throws(function () {
+ EE.emit('error', 'Accepts a string');
+}, 'Error: Unhandled error. (Accepts a string)');
+
+assert.throws(function () {
+ EE.emit('error', { message: 'Error!' });
+}, 'Unhandled error. ([object Object])');
diff --git a/temporary_modules/trezor-connect/node_modules/events/tests/events-list.js b/temporary_modules/trezor-connect/node_modules/events/tests/events-list.js
new file mode 100644
index 00000000..08aa6217
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/events/tests/events-list.js
@@ -0,0 +1,28 @@
+'use strict';
+
+var EventEmitter = require('../');
+var assert = require('assert');
+
+var EE = new EventEmitter();
+var m = function() {};
+EE.on('foo', function() {});
+assert.equal(1, EE.eventNames().length);
+assert.equal('foo', EE.eventNames()[0]);
+EE.on('bar', m);
+assert.equal(2, EE.eventNames().length);
+assert.equal('foo', EE.eventNames()[0]);
+assert.equal('bar', EE.eventNames()[1]);
+EE.removeListener('bar', m);
+assert.equal(1, EE.eventNames().length);
+assert.equal('foo', EE.eventNames()[0]);
+
+if (typeof Symbol !== 'undefined') {
+ var s = Symbol('s');
+ EE.on(s, m);
+ assert.equal(2, EE.eventNames().length);
+ assert.equal('foo', EE.eventNames()[0]);
+ assert.equal(s, EE.eventNames()[1]);
+ EE.removeListener(s, m);
+ assert.equal(1, EE.eventNames().length);
+ assert.equal('foo', EE.eventNames()[0]);
+}
diff --git a/temporary_modules/trezor-connect/node_modules/events/tests/events-once.js b/temporary_modules/trezor-connect/node_modules/events/tests/events-once.js
new file mode 100644
index 00000000..dae86496
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/events/tests/events-once.js
@@ -0,0 +1,234 @@
+'use strict';
+
+var common = require('./common');
+var EventEmitter = require('../').EventEmitter;
+var once = require('../').once;
+var has = require('has');
+var assert = require('assert');
+
+function Event(type) {
+ this.type = type;
+}
+
+function EventTargetMock() {
+ this.events = {};
+
+ this.addEventListener = common.mustCall(this.addEventListener);
+ this.removeEventListener = common.mustCall(this.removeEventListener);
+}
+
+EventTargetMock.prototype.addEventListener = function addEventListener(name, listener, options) {
+ if (!(name in this.events)) {
+ this.events[name] = { listeners: [], options: options || {} }
+ }
+ this.events[name].listeners.push(listener);
+};
+
+EventTargetMock.prototype.removeEventListener = function removeEventListener(name, callback) {
+ if (!(name in this.events)) {
+ return;
+ }
+ var event = this.events[name];
+ var stack = event.listeners;
+
+ for (var i = 0, l = stack.length; i < l; i++) {
+ if (stack[i] === callback) {
+ stack.splice(i, 1);
+ if (stack.length === 0) {
+ delete this.events[name];
+ }
+ return;
+ }
+ }
+};
+
+EventTargetMock.prototype.dispatchEvent = function dispatchEvent(arg) {
+ if (!(arg.type in this.events)) {
+ return true;
+ }
+
+ var event = this.events[arg.type];
+ var stack = event.listeners.slice();
+
+ for (var i = 0, l = stack.length; i < l; i++) {
+ stack[i].call(null, arg);
+ if (event.options.once) {
+ this.removeEventListener(arg.type, stack[i]);
+ }
+ }
+ return !arg.defaultPrevented;
+};
+
+function onceAnEvent() {
+ var ee = new EventEmitter();
+
+ process.nextTick(function () {
+ ee.emit('myevent', 42);
+ });
+
+ return once(ee, 'myevent').then(function (args) {
+ var value = args[0]
+ assert.strictEqual(value, 42);
+ assert.strictEqual(ee.listenerCount('error'), 0);
+ assert.strictEqual(ee.listenerCount('myevent'), 0);
+ });
+}
+
+function onceAnEventWithTwoArgs() {
+ var ee = new EventEmitter();
+
+ process.nextTick(function () {
+ ee.emit('myevent', 42, 24);
+ });
+
+ return once(ee, 'myevent').then(function (value) {
+ assert.strictEqual(value.length, 2);
+ assert.strictEqual(value[0], 42);
+ assert.strictEqual(value[1], 24);
+ });
+}
+
+function catchesErrors() {
+ var ee = new EventEmitter();
+
+ var expected = new Error('kaboom');
+ var err;
+ process.nextTick(function () {
+ ee.emit('error', expected);
+ });
+
+ return once(ee, 'myevent').then(function () {
+ throw new Error('should reject')
+ }, function (err) {
+ assert.strictEqual(err, expected);
+ assert.strictEqual(ee.listenerCount('error'), 0);
+ assert.strictEqual(ee.listenerCount('myevent'), 0);
+ });
+}
+
+function stopListeningAfterCatchingError() {
+ var ee = new EventEmitter();
+
+ var expected = new Error('kaboom');
+ var err;
+ process.nextTick(function () {
+ ee.emit('error', expected);
+ ee.emit('myevent', 42, 24);
+ });
+
+ // process.on('multipleResolves', common.mustNotCall());
+
+ return once(ee, 'myevent').then(common.mustNotCall, function (err) {
+ // process.removeAllListeners('multipleResolves');
+ assert.strictEqual(err, expected);
+ assert.strictEqual(ee.listenerCount('error'), 0);
+ assert.strictEqual(ee.listenerCount('myevent'), 0);
+ });
+}
+
+function onceError() {
+ var ee = new EventEmitter();
+
+ var expected = new Error('kaboom');
+ process.nextTick(function () {
+ ee.emit('error', expected);
+ });
+
+ var promise = once(ee, 'error');
+ assert.strictEqual(ee.listenerCount('error'), 1);
+ return promise.then(function (args) {
+ var err = args[0]
+ assert.strictEqual(err, expected);
+ assert.strictEqual(ee.listenerCount('error'), 0);
+ assert.strictEqual(ee.listenerCount('myevent'), 0);
+ });
+}
+
+function onceWithEventTarget() {
+ var et = new EventTargetMock();
+ var event = new Event('myevent');
+ process.nextTick(function () {
+ et.dispatchEvent(event);
+ });
+ return once(et, 'myevent').then(function (args) {
+ var value = args[0];
+ assert.strictEqual(value, event);
+ assert.strictEqual(has(et.events, 'myevent'), false);
+ });
+}
+
+function onceWithEventTargetError() {
+ var et = new EventTargetMock();
+ var error = new Event('error');
+ process.nextTick(function () {
+ et.dispatchEvent(error);
+ });
+ return once(et, 'error').then(function (args) {
+ var err = args[0];
+ assert.strictEqual(err, error);
+ assert.strictEqual(has(et.events, 'error'), false);
+ });
+}
+
+function prioritizesEventEmitter() {
+ var ee = new EventEmitter();
+ ee.addEventListener = assert.fail;
+ ee.removeAllListeners = assert.fail;
+ process.nextTick(function () {
+ ee.emit('foo');
+ });
+ return once(ee, 'foo');
+}
+
+var allTests = [
+ onceAnEvent(),
+ onceAnEventWithTwoArgs(),
+ catchesErrors(),
+ stopListeningAfterCatchingError(),
+ onceError(),
+ onceWithEventTarget(),
+ onceWithEventTargetError(),
+ prioritizesEventEmitter()
+];
+
+var hasBrowserEventTarget = false;
+try {
+ hasBrowserEventTarget = typeof (new window.EventTarget().addEventListener) === 'function' &&
+ new window.Event('xyz').type === 'xyz';
+} catch (err) {}
+
+if (hasBrowserEventTarget) {
+ var onceWithBrowserEventTarget = function onceWithBrowserEventTarget() {
+ var et = new window.EventTarget();
+ var event = new window.Event('myevent');
+ process.nextTick(function () {
+ et.dispatchEvent(event);
+ });
+ return once(et, 'myevent').then(function (args) {
+ var value = args[0];
+ assert.strictEqual(value, event);
+ assert.strictEqual(has(et.events, 'myevent'), false);
+ });
+ }
+
+ var onceWithBrowserEventTargetError = function onceWithBrowserEventTargetError() {
+ var et = new window.EventTarget();
+ var error = new window.Event('error');
+ process.nextTick(function () {
+ et.dispatchEvent(error);
+ });
+ return once(et, 'error').then(function (args) {
+ var err = args[0];
+ assert.strictEqual(err, error);
+ assert.strictEqual(has(et.events, 'error'), false);
+ });
+ }
+
+ common.test.comment('Testing with browser built-in EventTarget');
+ allTests.push([
+ onceWithBrowserEventTarget(),
+ onceWithBrowserEventTargetError()
+ ]);
+}
+
+module.exports = Promise.all(allTests);
diff --git a/temporary_modules/trezor-connect/node_modules/events/tests/index.js b/temporary_modules/trezor-connect/node_modules/events/tests/index.js
new file mode 100644
index 00000000..2d739e67
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/events/tests/index.js
@@ -0,0 +1,64 @@
+var test = require('tape');
+var functionsHaveNames = require('functions-have-names');
+var hasSymbols = require('has-symbols');
+
+require('./legacy-compat');
+var common = require('./common');
+
+// we do this to easily wrap each file in a mocha test
+// and also have browserify be able to statically analyze this file
+var orig_require = require;
+var require = function(file) {
+ test(file, function(t) {
+ // Store the tape object so tests can access it.
+ t.on('end', function () { delete common.test; });
+ common.test = t;
+
+ try {
+ var exp = orig_require(file);
+ if (exp && exp.then) {
+ exp.then(function () { t.end(); }, t.fail);
+ return;
+ }
+ } catch (err) {
+ t.fail(err);
+ }
+ t.end();
+ });
+};
+
+require('./add-listeners.js');
+require('./check-listener-leaks.js');
+require('./errors.js');
+require('./events-list.js');
+if (typeof Promise === 'function') {
+ require('./events-once.js');
+} else {
+ // Promise support is not available.
+ test('./events-once.js', { skip: true }, function () {});
+}
+require('./listener-count.js');
+require('./listeners-side-effects.js');
+require('./listeners.js');
+require('./max-listeners.js');
+if (functionsHaveNames()) {
+ require('./method-names.js');
+} else {
+ // Function.name is not supported in IE
+ test('./method-names.js', { skip: true }, function () {});
+}
+require('./modify-in-emit.js');
+require('./num-args.js');
+require('./once.js');
+require('./prepend.js');
+require('./set-max-listeners-side-effects.js');
+require('./special-event-names.js');
+require('./subclass.js');
+if (hasSymbols()) {
+ require('./symbols.js');
+} else {
+ // Symbol is not available.
+ test('./symbols.js', { skip: true }, function () {});
+}
+require('./remove-all-listeners.js');
+require('./remove-listeners.js');
diff --git a/temporary_modules/trezor-connect/node_modules/events/tests/legacy-compat.js b/temporary_modules/trezor-connect/node_modules/events/tests/legacy-compat.js
new file mode 100644
index 00000000..a402be6e
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/events/tests/legacy-compat.js
@@ -0,0 +1,16 @@
+// sigh... life is hard
+if (!global.console) {
+ console = {}
+}
+
+var fns = ['log', 'error', 'trace'];
+for (var i=0 ; ifoo should not be emitted');
+}
+
+e.once('foo', remove);
+e.removeListener('foo', remove);
+e.emit('foo');
+
+e.once('e', common.mustCall(function() {
+ e.emit('e');
+}));
+
+e.once('e', common.mustCall());
+
+e.emit('e');
+
+// Verify that the listener must be a function
+assert.throws(function() {
+ var ee = new EventEmitter();
+
+ ee.once('foo', null);
+}, /^TypeError: The "listener" argument must be of type Function. Received type object$/);
+
+{
+ // once() has different code paths based on the number of arguments being
+ // emitted. Verify that all of the cases are covered.
+ var maxArgs = 4;
+
+ for (var i = 0; i <= maxArgs; ++i) {
+ var ee = new EventEmitter();
+ var args = ['foo'];
+
+ for (var j = 0; j < i; ++j)
+ args.push(j);
+
+ ee.once('foo', common.mustCall(function() {
+ var params = Array.prototype.slice.call(arguments);
+ var restArgs = args.slice(1);
+ assert.ok(Array.isArray(params));
+ assert.strictEqual(params.length, restArgs.length);
+ for (var index = 0; index < params.length; index++) {
+ var param = params[index];
+ assert.strictEqual(param, restArgs[index]);
+ }
+ }));
+
+ EventEmitter.prototype.emit.apply(ee, args);
+ }
+}
diff --git a/temporary_modules/trezor-connect/node_modules/events/tests/prepend.js b/temporary_modules/trezor-connect/node_modules/events/tests/prepend.js
new file mode 100644
index 00000000..79afde0b
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/events/tests/prepend.js
@@ -0,0 +1,31 @@
+'use strict';
+
+var common = require('./common');
+var EventEmitter = require('../');
+var assert = require('assert');
+
+var myEE = new EventEmitter();
+var m = 0;
+// This one comes last.
+myEE.on('foo', common.mustCall(function () {
+ assert.strictEqual(m, 2);
+}));
+
+// This one comes second.
+myEE.prependListener('foo', common.mustCall(function () {
+ assert.strictEqual(m++, 1);
+}));
+
+// This one comes first.
+myEE.prependOnceListener('foo',
+ common.mustCall(function () {
+ assert.strictEqual(m++, 0);
+ }));
+
+myEE.emit('foo');
+
+// Verify that the listener must be a function
+assert.throws(function () {
+ var ee = new EventEmitter();
+ ee.prependOnceListener('foo', null);
+}, 'TypeError: The "listener" argument must be of type Function. Received type object');
diff --git a/temporary_modules/trezor-connect/node_modules/events/tests/remove-all-listeners.js b/temporary_modules/trezor-connect/node_modules/events/tests/remove-all-listeners.js
new file mode 100644
index 00000000..622941cf
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/events/tests/remove-all-listeners.js
@@ -0,0 +1,133 @@
+// Copyright Joyent, Inc. and other Node contributors.
+//
+// Permission is hereby granted, free of charge, to any person obtaining a
+// copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to permit
+// persons to whom the Software is furnished to do so, subject to the
+// following conditions:
+//
+// The above copyright notice and this permission notice shall be included
+// in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
+// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
+// USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+var common = require('./common');
+var assert = require('assert');
+var events = require('../');
+var test = require('tape');
+
+function expect(expected) {
+ var actual = [];
+ test.onFinish(function() {
+ var sortedActual = actual.sort();
+ var sortedExpected = expected.sort();
+ assert.strictEqual(sortedActual.length, sortedExpected.length);
+ for (var index = 0; index < sortedActual.length; index++) {
+ var value = sortedActual[index];
+ assert.strictEqual(value, sortedExpected[index]);
+ }
+ });
+ function listener(name) {
+ actual.push(name);
+ }
+ return common.mustCall(listener, expected.length);
+}
+
+{
+ var ee = new events.EventEmitter();
+ var noop = common.mustNotCall();
+ ee.on('foo', noop);
+ ee.on('bar', noop);
+ ee.on('baz', noop);
+ ee.on('baz', noop);
+ var fooListeners = ee.listeners('foo');
+ var barListeners = ee.listeners('bar');
+ var bazListeners = ee.listeners('baz');
+ ee.on('removeListener', expect(['bar', 'baz', 'baz']));
+ ee.removeAllListeners('bar');
+ ee.removeAllListeners('baz');
+
+ var listeners = ee.listeners('foo');
+ assert.ok(Array.isArray(listeners));
+ assert.strictEqual(listeners.length, 1);
+ assert.strictEqual(listeners[0], noop);
+
+ listeners = ee.listeners('bar');
+ assert.ok(Array.isArray(listeners));
+ assert.strictEqual(listeners.length, 0);
+ listeners = ee.listeners('baz');
+ assert.ok(Array.isArray(listeners));
+ assert.strictEqual(listeners.length, 0);
+ // After calling removeAllListeners(),
+ // the old listeners array should stay unchanged.
+ assert.strictEqual(fooListeners.length, 1);
+ assert.strictEqual(fooListeners[0], noop);
+ assert.strictEqual(barListeners.length, 1);
+ assert.strictEqual(barListeners[0], noop);
+ assert.strictEqual(bazListeners.length, 2);
+ assert.strictEqual(bazListeners[0], noop);
+ assert.strictEqual(bazListeners[1], noop);
+ // After calling removeAllListeners(),
+ // new listeners arrays is different from the old.
+ assert.notStrictEqual(ee.listeners('bar'), barListeners);
+ assert.notStrictEqual(ee.listeners('baz'), bazListeners);
+}
+
+{
+ var ee = new events.EventEmitter();
+ ee.on('foo', common.mustNotCall());
+ ee.on('bar', common.mustNotCall());
+ // Expect LIFO order
+ ee.on('removeListener', expect(['foo', 'bar', 'removeListener']));
+ ee.on('removeListener', expect(['foo', 'bar']));
+ ee.removeAllListeners();
+
+ var listeners = ee.listeners('foo');
+ assert.ok(Array.isArray(listeners));
+ assert.strictEqual(listeners.length, 0);
+ listeners = ee.listeners('bar');
+ assert.ok(Array.isArray(listeners));
+ assert.strictEqual(listeners.length, 0);
+}
+
+{
+ var ee = new events.EventEmitter();
+ ee.on('removeListener', common.mustNotCall());
+ // Check for regression where removeAllListeners() throws when
+ // there exists a 'removeListener' listener, but there exists
+ // no listeners for the provided event type.
+ assert.doesNotThrow(function () { ee.removeAllListeners(ee, 'foo') });
+}
+
+{
+ var ee = new events.EventEmitter();
+ var expectLength = 2;
+ ee.on('removeListener', function() {
+ assert.strictEqual(expectLength--, this.listeners('baz').length);
+ });
+ ee.on('baz', common.mustNotCall());
+ ee.on('baz', common.mustNotCall());
+ ee.on('baz', common.mustNotCall());
+ assert.strictEqual(ee.listeners('baz').length, expectLength + 1);
+ ee.removeAllListeners('baz');
+ assert.strictEqual(ee.listeners('baz').length, 0);
+}
+
+{
+ var ee = new events.EventEmitter();
+ assert.strictEqual(ee, ee.removeAllListeners());
+}
+
+{
+ var ee = new events.EventEmitter();
+ ee._events = undefined;
+ assert.strictEqual(ee, ee.removeAllListeners());
+}
diff --git a/temporary_modules/trezor-connect/node_modules/events/tests/remove-listeners.js b/temporary_modules/trezor-connect/node_modules/events/tests/remove-listeners.js
new file mode 100644
index 00000000..18e4d165
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/events/tests/remove-listeners.js
@@ -0,0 +1,212 @@
+// Copyright Joyent, Inc. and other Node contributors.
+//
+// Permission is hereby granted, free of charge, to any person obtaining a
+// copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to permit
+// persons to whom the Software is furnished to do so, subject to the
+// following conditions:
+//
+// The above copyright notice and this permission notice shall be included
+// in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
+// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
+// USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+var common = require('./common');
+var assert = require('assert');
+var EventEmitter = require('../');
+
+var listener1 = function listener1() {};
+var listener2 = function listener2() {};
+
+{
+ var ee = new EventEmitter();
+ ee.on('hello', listener1);
+ ee.on('removeListener', common.mustCall(function(name, cb) {
+ assert.strictEqual(name, 'hello');
+ assert.strictEqual(cb, listener1);
+ }));
+ ee.removeListener('hello', listener1);
+ var listeners = ee.listeners('hello');
+ assert.ok(Array.isArray(listeners));
+ assert.strictEqual(listeners.length, 0);
+}
+
+{
+ var ee = new EventEmitter();
+ ee.on('hello', listener1);
+ ee.on('removeListener', common.mustNotCall());
+ ee.removeListener('hello', listener2);
+
+ var listeners = ee.listeners('hello');
+ assert.ok(Array.isArray(listeners));
+ assert.strictEqual(listeners.length, 1);
+ assert.strictEqual(listeners[0], listener1);
+}
+
+{
+ var ee = new EventEmitter();
+ ee.on('hello', listener1);
+ ee.on('hello', listener2);
+
+ var listeners;
+ ee.once('removeListener', common.mustCall(function(name, cb) {
+ assert.strictEqual(name, 'hello');
+ assert.strictEqual(cb, listener1);
+ listeners = ee.listeners('hello');
+ assert.ok(Array.isArray(listeners));
+ assert.strictEqual(listeners.length, 1);
+ assert.strictEqual(listeners[0], listener2);
+ }));
+ ee.removeListener('hello', listener1);
+ listeners = ee.listeners('hello');
+ assert.ok(Array.isArray(listeners));
+ assert.strictEqual(listeners.length, 1);
+ assert.strictEqual(listeners[0], listener2);
+ ee.once('removeListener', common.mustCall(function(name, cb) {
+ assert.strictEqual(name, 'hello');
+ assert.strictEqual(cb, listener2);
+ listeners = ee.listeners('hello');
+ assert.ok(Array.isArray(listeners));
+ assert.strictEqual(listeners.length, 0);
+ }));
+ ee.removeListener('hello', listener2);
+ listeners = ee.listeners('hello');
+ assert.ok(Array.isArray(listeners));
+ assert.strictEqual(listeners.length, 0);
+}
+
+{
+ var ee = new EventEmitter();
+
+ function remove1() {
+ assert.fail('remove1 should not have been called');
+ }
+
+ function remove2() {
+ assert.fail('remove2 should not have been called');
+ }
+
+ ee.on('removeListener', common.mustCall(function(name, cb) {
+ if (cb !== remove1) return;
+ this.removeListener('quux', remove2);
+ this.emit('quux');
+ }, 2));
+ ee.on('quux', remove1);
+ ee.on('quux', remove2);
+ ee.removeListener('quux', remove1);
+}
+
+{
+ var ee = new EventEmitter();
+ ee.on('hello', listener1);
+ ee.on('hello', listener2);
+
+ var listeners;
+ ee.once('removeListener', common.mustCall(function(name, cb) {
+ assert.strictEqual(name, 'hello');
+ assert.strictEqual(cb, listener1);
+ listeners = ee.listeners('hello');
+ assert.ok(Array.isArray(listeners));
+ assert.strictEqual(listeners.length, 1);
+ assert.strictEqual(listeners[0], listener2);
+ ee.once('removeListener', common.mustCall(function(name, cb) {
+ assert.strictEqual(name, 'hello');
+ assert.strictEqual(cb, listener2);
+ listeners = ee.listeners('hello');
+ assert.ok(Array.isArray(listeners));
+ assert.strictEqual(listeners.length, 0);
+ }));
+ ee.removeListener('hello', listener2);
+ listeners = ee.listeners('hello');
+ assert.ok(Array.isArray(listeners));
+ assert.strictEqual(listeners.length, 0);
+ }));
+ ee.removeListener('hello', listener1);
+ listeners = ee.listeners('hello');
+ assert.ok(Array.isArray(listeners));
+ assert.strictEqual(listeners.length, 0);
+}
+
+{
+ var ee = new EventEmitter();
+ var listener3 = common.mustCall(function() {
+ ee.removeListener('hello', listener4);
+ }, 2);
+ var listener4 = common.mustCall();
+
+ ee.on('hello', listener3);
+ ee.on('hello', listener4);
+
+ // listener4 will still be called although it is removed by listener 3.
+ ee.emit('hello');
+ // This is so because the interal listener array at time of emit
+ // was [listener3,listener4]
+
+ // Interal listener array [listener3]
+ ee.emit('hello');
+}
+
+{
+ var ee = new EventEmitter();
+
+ ee.once('hello', listener1);
+ ee.on('removeListener', common.mustCall(function(eventName, listener) {
+ assert.strictEqual(eventName, 'hello');
+ assert.strictEqual(listener, listener1);
+ }));
+ ee.emit('hello');
+}
+
+{
+ var ee = new EventEmitter();
+
+ assert.strictEqual(ee, ee.removeListener('foo', function() {}));
+}
+
+// Verify that the removed listener must be a function
+assert.throws(function() {
+ var ee = new EventEmitter();
+
+ ee.removeListener('foo', null);
+}, /^TypeError: The "listener" argument must be of type Function\. Received type object$/);
+
+{
+ var ee = new EventEmitter();
+ var listener = function() {};
+ ee._events = undefined;
+ var e = ee.removeListener('foo', listener);
+ assert.strictEqual(e, ee);
+}
+
+{
+ var ee = new EventEmitter();
+
+ ee.on('foo', listener1);
+ ee.on('foo', listener2);
+ var listeners = ee.listeners('foo');
+ assert.ok(Array.isArray(listeners));
+ assert.strictEqual(listeners.length, 2);
+ assert.strictEqual(listeners[0], listener1);
+ assert.strictEqual(listeners[1], listener2);
+
+ ee.removeListener('foo', listener1);
+ assert.strictEqual(ee._events.foo, listener2);
+
+ ee.on('foo', listener1);
+ listeners = ee.listeners('foo');
+ assert.ok(Array.isArray(listeners));
+ assert.strictEqual(listeners.length, 2);
+ assert.strictEqual(listeners[0], listener2);
+ assert.strictEqual(listeners[1], listener1);
+
+ ee.removeListener('foo', listener1);
+ assert.strictEqual(ee._events.foo, listener2);
+}
diff --git a/temporary_modules/trezor-connect/node_modules/events/tests/set-max-listeners-side-effects.js b/temporary_modules/trezor-connect/node_modules/events/tests/set-max-listeners-side-effects.js
new file mode 100644
index 00000000..13dbb671
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/events/tests/set-max-listeners-side-effects.js
@@ -0,0 +1,31 @@
+// Copyright Joyent, Inc. and other Node contributors.
+//
+// Permission is hereby granted, free of charge, to any person obtaining a
+// copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to permit
+// persons to whom the Software is furnished to do so, subject to the
+// following conditions:
+//
+// The above copyright notice and this permission notice shall be included
+// in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
+// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
+// USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+require('./common');
+var assert = require('assert');
+var events = require('../');
+
+var e = new events.EventEmitter();
+
+if (Object.create) assert.ok(!(e._events instanceof Object));
+assert.strictEqual(Object.keys(e._events).length, 0);
+e.setMaxListeners(5);
+assert.strictEqual(Object.keys(e._events).length, 0);
diff --git a/temporary_modules/trezor-connect/node_modules/events/tests/special-event-names.js b/temporary_modules/trezor-connect/node_modules/events/tests/special-event-names.js
new file mode 100644
index 00000000..a2f0b744
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/events/tests/special-event-names.js
@@ -0,0 +1,45 @@
+'use strict';
+
+var common = require('./common');
+var EventEmitter = require('../');
+var assert = require('assert');
+
+var ee = new EventEmitter();
+var handler = function() {};
+
+assert.strictEqual(ee.eventNames().length, 0);
+
+assert.strictEqual(ee._events.hasOwnProperty, undefined);
+assert.strictEqual(ee._events.toString, undefined);
+
+ee.on('__defineGetter__', handler);
+ee.on('toString', handler);
+ee.on('__proto__', handler);
+
+assert.strictEqual(ee.eventNames()[0], '__defineGetter__');
+assert.strictEqual(ee.eventNames()[1], 'toString');
+
+assert.strictEqual(ee.listeners('__defineGetter__').length, 1);
+assert.strictEqual(ee.listeners('__defineGetter__')[0], handler);
+assert.strictEqual(ee.listeners('toString').length, 1);
+assert.strictEqual(ee.listeners('toString')[0], handler);
+
+// Only run __proto__ tests if that property can actually be set
+if ({ __proto__: 'ok' }.__proto__ === 'ok') {
+ assert.strictEqual(ee.eventNames().length, 3);
+ assert.strictEqual(ee.eventNames()[2], '__proto__');
+ assert.strictEqual(ee.listeners('__proto__').length, 1);
+ assert.strictEqual(ee.listeners('__proto__')[0], handler);
+
+ ee.on('__proto__', common.mustCall(function(val) {
+ assert.strictEqual(val, 1);
+ }));
+ ee.emit('__proto__', 1);
+
+ process.on('__proto__', common.mustCall(function(val) {
+ assert.strictEqual(val, 1);
+ }));
+ process.emit('__proto__', 1);
+} else {
+ console.log('# skipped __proto__')
+}
diff --git a/temporary_modules/trezor-connect/node_modules/events/tests/subclass.js b/temporary_modules/trezor-connect/node_modules/events/tests/subclass.js
new file mode 100644
index 00000000..bd033fff
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/events/tests/subclass.js
@@ -0,0 +1,66 @@
+// Copyright Joyent, Inc. and other Node contributors.
+//
+// Permission is hereby granted, free of charge, to any person obtaining a
+// copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to permit
+// persons to whom the Software is furnished to do so, subject to the
+// following conditions:
+//
+// The above copyright notice and this permission notice shall be included
+// in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
+// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
+// USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+var common = require('./common');
+var test = require('tape');
+var assert = require('assert');
+var EventEmitter = require('../').EventEmitter;
+var util = require('util');
+
+util.inherits(MyEE, EventEmitter);
+
+function MyEE(cb) {
+ this.once(1, cb);
+ this.emit(1);
+ this.removeAllListeners();
+ EventEmitter.call(this);
+}
+
+var myee = new MyEE(common.mustCall());
+
+
+util.inherits(ErrorEE, EventEmitter);
+function ErrorEE() {
+ this.emit('error', new Error('blerg'));
+}
+
+assert.throws(function() {
+ new ErrorEE();
+}, /blerg/);
+
+test.onFinish(function() {
+ assert.ok(!(myee._events instanceof Object));
+ assert.strictEqual(Object.keys(myee._events).length, 0);
+});
+
+
+function MyEE2() {
+ EventEmitter.call(this);
+}
+
+MyEE2.prototype = new EventEmitter();
+
+var ee1 = new MyEE2();
+var ee2 = new MyEE2();
+
+ee1.on('x', function() {});
+
+assert.strictEqual(ee2.listenerCount('x'), 0);
diff --git a/temporary_modules/trezor-connect/node_modules/events/tests/symbols.js b/temporary_modules/trezor-connect/node_modules/events/tests/symbols.js
new file mode 100644
index 00000000..0721f0ec
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/events/tests/symbols.js
@@ -0,0 +1,25 @@
+'use strict';
+
+var common = require('./common');
+var EventEmitter = require('../');
+var assert = require('assert');
+
+var ee = new EventEmitter();
+var foo = Symbol('foo');
+var listener = common.mustCall();
+
+ee.on(foo, listener);
+assert.strictEqual(ee.listeners(foo).length, 1);
+assert.strictEqual(ee.listeners(foo)[0], listener);
+
+ee.emit(foo);
+
+ee.removeAllListeners();
+assert.strictEqual(ee.listeners(foo).length, 0);
+
+ee.on(foo, listener);
+assert.strictEqual(ee.listeners(foo).length, 1);
+assert.strictEqual(ee.listeners(foo)[0], listener);
+
+ee.removeListener(foo, listener);
+assert.strictEqual(ee.listeners(foo).length, 0);
diff --git a/temporary_modules/trezor-connect/node_modules/fd-slicer/.npmignore b/temporary_modules/trezor-connect/node_modules/fd-slicer/.npmignore
new file mode 100644
index 00000000..ccc29308
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/fd-slicer/.npmignore
@@ -0,0 +1,2 @@
+/coverage
+/node_modules
diff --git a/temporary_modules/trezor-connect/node_modules/fd-slicer/.travis.yml b/temporary_modules/trezor-connect/node_modules/fd-slicer/.travis.yml
new file mode 100644
index 00000000..77b72028
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/fd-slicer/.travis.yml
@@ -0,0 +1,7 @@
+language: node_js
+node_js:
+ - "0.10"
+script:
+ - "npm run test-travis"
+after_script:
+ - "npm install coveralls@2 && cat ./coverage/lcov.info | ./node_modules/.bin/coveralls"
diff --git a/temporary_modules/trezor-connect/node_modules/fd-slicer/CHANGELOG.md b/temporary_modules/trezor-connect/node_modules/fd-slicer/CHANGELOG.md
new file mode 100644
index 00000000..783042f8
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/fd-slicer/CHANGELOG.md
@@ -0,0 +1,49 @@
+### 1.0.1
+
+ * use `setImmediate` instead of `nextTick`
+
+### 1.0.0
+
+ * `new FdSlicer(fd, options)` must now be `fdSlicer.createFromFd(fd, options)`
+ * fix behavior when `end` is 0.
+ * fix `createWriteStream` when using `createFromBuffer`
+
+### 0.4.0
+
+ * add ability to create an FdSlicer instance from a Buffer
+
+### 0.3.2
+
+ * fix write stream and read stream destroy behavior
+
+### 0.3.1
+
+ * write stream: fix end option behavior
+
+### 0.3.0
+
+ * write stream emits 'progress' events
+ * write stream supports 'end' option which causes the stream to emit an error
+ if a maximum size is exceeded
+ * improve documentation
+
+### 0.2.1
+
+ * Update pend dependency to latest bugfix version.
+
+### 0.2.0
+
+ * Add read and write functions
+
+### 0.1.0
+
+ * Add `autoClose` option and `ref()` and `unref()`.
+
+### 0.0.2
+
+ * Add API documentation
+ * read stream: create buffer at last possible moment
+
+### 0.0.1
+
+ * Initial release
diff --git a/temporary_modules/trezor-connect/node_modules/fd-slicer/LICENSE b/temporary_modules/trezor-connect/node_modules/fd-slicer/LICENSE
new file mode 100644
index 00000000..e57596d2
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/fd-slicer/LICENSE
@@ -0,0 +1,21 @@
+Copyright (c) 2014 Andrew Kelley
+
+Permission is hereby granted, free of charge, to any person
+obtaining a copy of this software and associated documentation files
+(the "Software"), to deal in the Software without restriction,
+including without limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of the Software,
+and to permit persons to whom the Software is furnished to do so,
+subject to the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
+BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/temporary_modules/trezor-connect/node_modules/fd-slicer/README.md b/temporary_modules/trezor-connect/node_modules/fd-slicer/README.md
new file mode 100644
index 00000000..ad7f0ec7
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/fd-slicer/README.md
@@ -0,0 +1,199 @@
+# fd-slicer
+
+[](https://travis-ci.org/andrewrk/node-fd-slicer)
+
+Safe `fs.ReadStream` and `fs.WriteStream` using the same fd.
+
+Let's say that you want to perform a parallel upload of a file to a remote
+server. To do this, we want to create multiple read streams. The first thing
+you might think of is to use the `{start: 0, end: 0}` API of
+`fs.createReadStream`. This gives you two choices:
+
+ 0. Use the same file descriptor for all `fs.ReadStream` objects.
+ 0. Open the file multiple times, resulting in a separate file descriptor
+ for each read stream.
+
+Neither of these are acceptable options. The first one is a severe bug,
+because the API docs for `fs.write` state:
+
+> Note that it is unsafe to use `fs.write` multiple times on the same file
+> without waiting for the callback. For this scenario, `fs.createWriteStream`
+> is strongly recommended.
+
+`fs.createWriteStream` will solve the problem if you only create one of them
+for the file descriptor, but it will exhibit this unsafety if you create
+multiple write streams per file descriptor.
+
+The second option suffers from a race condition. For each additional time the
+file is opened after the first, it is possible that the file is modified. So
+in our parallel uploading example, we might upload a corrupt file that never
+existed on the client's computer.
+
+This module solves this problem by providing `createReadStream` and
+`createWriteStream` that operate on a shared file descriptor and provides
+the convenient stream API while still allowing slicing and dicing.
+
+This module also gives you some additional power that the builtin
+`fs.createWriteStream` do not give you. These features are:
+
+ * Emitting a 'progress' event on write.
+ * Ability to set a maximum size and emit an error if this size is exceeded.
+ * Ability to create an `FdSlicer` instance from a `Buffer`. This enables you
+ to provide API for handling files as well as buffers using the same API.
+
+## Usage
+
+```js
+var fdSlicer = require('fd-slicer');
+var fs = require('fs');
+
+fs.open("file.txt", 'r', function(err, fd) {
+ if (err) throw err;
+ var slicer = fdSlicer.createFromFd(fd);
+ var firstPart = slicer.createReadStream({start: 0, end: 100});
+ var secondPart = slicer.createReadStream({start: 100});
+ var firstOut = fs.createWriteStream("first.txt");
+ var secondOut = fs.createWriteStream("second.txt");
+ firstPart.pipe(firstOut);
+ secondPart.pipe(secondOut);
+});
+```
+
+You can also create from a buffer:
+
+```js
+var fdSlicer = require('fd-slicer');
+var slicer = FdSlicer.createFromBuffer(someBuffer);
+var firstPart = slicer.createReadStream({start: 0, end: 100});
+var secondPart = slicer.createReadStream({start: 100});
+var firstOut = fs.createWriteStream("first.txt");
+var secondOut = fs.createWriteStream("second.txt");
+firstPart.pipe(firstOut);
+secondPart.pipe(secondOut);
+```
+
+## API Documentation
+
+### fdSlicer.createFromFd(fd, [options])
+
+```js
+var fdSlicer = require('fd-slicer');
+fs.open("file.txt", 'r', function(err, fd) {
+ if (err) throw err;
+ var slicer = fdSlicer.createFromFd(fd);
+ // ...
+});
+```
+
+Make sure `fd` is a properly initialized file descriptor. If you want to
+use `createReadStream` make sure you open it for reading and if you want
+to use `createWriteStream` make sure you open it for writing.
+
+`options` is an optional object which can contain:
+
+ * `autoClose` - if set to `true`, the file descriptor will be automatically
+ closed once the last stream that references it is closed. Defaults to
+ `false`. `ref()` and `unref()` can be used to increase or decrease the
+ reference count, respectively.
+
+### fdSlicer.createFromBuffer(buffer, [options])
+
+```js
+var fdSlicer = require('fd-slicer');
+var slicer = fdSlicer.createFromBuffer(someBuffer);
+// ...
+```
+
+`options` is an optional object which can contain:
+
+ * `maxChunkSize` - A `Number` of bytes. see `createReadStream()`.
+ If falsey, defaults to unlimited.
+
+#### Properties
+
+##### fd
+
+The file descriptor passed in. `undefined` if created from a buffer.
+
+#### Methods
+
+##### createReadStream(options)
+
+Available `options`:
+
+ * `start` - Number. The offset into the file to start reading from. Defaults
+ to 0.
+ * `end` - Number. Exclusive upper bound offset into the file to stop reading
+ from.
+ * `highWaterMark` - Number. The maximum number of bytes to store in the
+ internal buffer before ceasing to read from the underlying resource.
+ Defaults to 16 KB.
+ * `encoding` - String. If specified, then buffers will be decoded to strings
+ using the specified encoding. Defaults to `null`.
+
+The ReadableStream that this returns has these additional methods:
+
+ * `destroy(err)` - stop streaming. `err` is optional and is the error that
+ will be emitted in order to cause the streaming to stop. Defaults to
+ `new Error("stream destroyed")`.
+
+If `maxChunkSize` was specified (see `createFromBuffer()`), the read stream
+will provide chunks of at most that size. Normally, the read stream provides
+the entire range requested in a single chunk, but this can cause performance
+problems in some circumstances.
+See [thejoshwolfe/yauzl#87](https://github.com/thejoshwolfe/yauzl/issues/87).
+
+##### createWriteStream(options)
+
+Available `options`:
+
+ * `start` - Number. The offset into the file to start writing to. Defaults to
+ 0.
+ * `end` - Number. Exclusive upper bound offset into the file. If this offset
+ is reached, the write stream will emit an 'error' event and stop functioning.
+ In this situation, `err.code === 'ETOOBIG'`. Defaults to `Infinity`.
+ * `highWaterMark` - Number. Buffer level when `write()` starts returning
+ false. Defaults to 16KB.
+ * `decodeStrings` - Boolean. Whether or not to decode strings into Buffers
+ before passing them to` _write()`. Defaults to `true`.
+
+The WritableStream that this returns has these additional methods:
+
+ * `destroy()` - stop streaming
+
+And these additional properties:
+
+ * `bytesWritten` - number of bytes written to the stream
+
+And these additional events:
+
+ * 'progress' - emitted when `bytesWritten` changes.
+
+##### read(buffer, offset, length, position, callback)
+
+Equivalent to `fs.read`, but with concurrency protection.
+`callback` must be defined.
+
+##### write(buffer, offset, length, position, callback)
+
+Equivalent to `fs.write`, but with concurrency protection.
+`callback` must be defined.
+
+##### ref()
+
+Increase the `autoClose` reference count by 1.
+
+##### unref()
+
+Decrease the `autoClose` reference count by 1.
+
+#### Events
+
+##### 'error'
+
+Emitted if `fs.close` returns an error when auto closing.
+
+##### 'close'
+
+Emitted when fd-slicer closes the file descriptor due to `autoClose`. Never
+emitted if created from a buffer.
diff --git a/temporary_modules/trezor-connect/node_modules/fd-slicer/index.js b/temporary_modules/trezor-connect/node_modules/fd-slicer/index.js
new file mode 100644
index 00000000..65d32a3e
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/fd-slicer/index.js
@@ -0,0 +1,296 @@
+var fs = require('fs');
+var util = require('util');
+var stream = require('stream');
+var Readable = stream.Readable;
+var Writable = stream.Writable;
+var PassThrough = stream.PassThrough;
+var Pend = require('pend');
+var EventEmitter = require('events').EventEmitter;
+
+exports.createFromBuffer = createFromBuffer;
+exports.createFromFd = createFromFd;
+exports.BufferSlicer = BufferSlicer;
+exports.FdSlicer = FdSlicer;
+
+util.inherits(FdSlicer, EventEmitter);
+function FdSlicer(fd, options) {
+ options = options || {};
+ EventEmitter.call(this);
+
+ this.fd = fd;
+ this.pend = new Pend();
+ this.pend.max = 1;
+ this.refCount = 0;
+ this.autoClose = !!options.autoClose;
+}
+
+FdSlicer.prototype.read = function(buffer, offset, length, position, callback) {
+ var self = this;
+ self.pend.go(function(cb) {
+ fs.read(self.fd, buffer, offset, length, position, function(err, bytesRead, buffer) {
+ cb();
+ callback(err, bytesRead, buffer);
+ });
+ });
+};
+
+FdSlicer.prototype.write = function(buffer, offset, length, position, callback) {
+ var self = this;
+ self.pend.go(function(cb) {
+ fs.write(self.fd, buffer, offset, length, position, function(err, written, buffer) {
+ cb();
+ callback(err, written, buffer);
+ });
+ });
+};
+
+FdSlicer.prototype.createReadStream = function(options) {
+ return new ReadStream(this, options);
+};
+
+FdSlicer.prototype.createWriteStream = function(options) {
+ return new WriteStream(this, options);
+};
+
+FdSlicer.prototype.ref = function() {
+ this.refCount += 1;
+};
+
+FdSlicer.prototype.unref = function() {
+ var self = this;
+ self.refCount -= 1;
+
+ if (self.refCount > 0) return;
+ if (self.refCount < 0) throw new Error("invalid unref");
+
+ if (self.autoClose) {
+ fs.close(self.fd, onCloseDone);
+ }
+
+ function onCloseDone(err) {
+ if (err) {
+ self.emit('error', err);
+ } else {
+ self.emit('close');
+ }
+ }
+};
+
+util.inherits(ReadStream, Readable);
+function ReadStream(context, options) {
+ options = options || {};
+ Readable.call(this, options);
+
+ this.context = context;
+ this.context.ref();
+
+ this.start = options.start || 0;
+ this.endOffset = options.end;
+ this.pos = this.start;
+ this.destroyed = false;
+}
+
+ReadStream.prototype._read = function(n) {
+ var self = this;
+ if (self.destroyed) return;
+
+ var toRead = Math.min(self._readableState.highWaterMark, n);
+ if (self.endOffset != null) {
+ toRead = Math.min(toRead, self.endOffset - self.pos);
+ }
+ if (toRead <= 0) {
+ self.destroyed = true;
+ self.push(null);
+ self.context.unref();
+ return;
+ }
+ self.context.pend.go(function(cb) {
+ if (self.destroyed) return cb();
+ var buffer = new Buffer(toRead);
+ fs.read(self.context.fd, buffer, 0, toRead, self.pos, function(err, bytesRead) {
+ if (err) {
+ self.destroy(err);
+ } else if (bytesRead === 0) {
+ self.destroyed = true;
+ self.push(null);
+ self.context.unref();
+ } else {
+ self.pos += bytesRead;
+ self.push(buffer.slice(0, bytesRead));
+ }
+ cb();
+ });
+ });
+};
+
+ReadStream.prototype.destroy = function(err) {
+ if (this.destroyed) return;
+ err = err || new Error("stream destroyed");
+ this.destroyed = true;
+ this.emit('error', err);
+ this.context.unref();
+};
+
+util.inherits(WriteStream, Writable);
+function WriteStream(context, options) {
+ options = options || {};
+ Writable.call(this, options);
+
+ this.context = context;
+ this.context.ref();
+
+ this.start = options.start || 0;
+ this.endOffset = (options.end == null) ? Infinity : +options.end;
+ this.bytesWritten = 0;
+ this.pos = this.start;
+ this.destroyed = false;
+
+ this.on('finish', this.destroy.bind(this));
+}
+
+WriteStream.prototype._write = function(buffer, encoding, callback) {
+ var self = this;
+ if (self.destroyed) return;
+
+ if (self.pos + buffer.length > self.endOffset) {
+ var err = new Error("maximum file length exceeded");
+ err.code = 'ETOOBIG';
+ self.destroy();
+ callback(err);
+ return;
+ }
+ self.context.pend.go(function(cb) {
+ if (self.destroyed) return cb();
+ fs.write(self.context.fd, buffer, 0, buffer.length, self.pos, function(err, bytes) {
+ if (err) {
+ self.destroy();
+ cb();
+ callback(err);
+ } else {
+ self.bytesWritten += bytes;
+ self.pos += bytes;
+ self.emit('progress');
+ cb();
+ callback();
+ }
+ });
+ });
+};
+
+WriteStream.prototype.destroy = function() {
+ if (this.destroyed) return;
+ this.destroyed = true;
+ this.context.unref();
+};
+
+util.inherits(BufferSlicer, EventEmitter);
+function BufferSlicer(buffer, options) {
+ EventEmitter.call(this);
+
+ options = options || {};
+ this.refCount = 0;
+ this.buffer = buffer;
+ this.maxChunkSize = options.maxChunkSize || Number.MAX_SAFE_INTEGER;
+}
+
+BufferSlicer.prototype.read = function(buffer, offset, length, position, callback) {
+ var end = position + length;
+ var delta = end - this.buffer.length;
+ var written = (delta > 0) ? delta : length;
+ this.buffer.copy(buffer, offset, position, end);
+ setImmediate(function() {
+ callback(null, written);
+ });
+};
+
+BufferSlicer.prototype.write = function(buffer, offset, length, position, callback) {
+ buffer.copy(this.buffer, position, offset, offset + length);
+ setImmediate(function() {
+ callback(null, length, buffer);
+ });
+};
+
+BufferSlicer.prototype.createReadStream = function(options) {
+ options = options || {};
+ var readStream = new PassThrough(options);
+ readStream.destroyed = false;
+ readStream.start = options.start || 0;
+ readStream.endOffset = options.end;
+ // by the time this function returns, we'll be done.
+ readStream.pos = readStream.endOffset || this.buffer.length;
+
+ // respect the maxChunkSize option to slice up the chunk into smaller pieces.
+ var entireSlice = this.buffer.slice(readStream.start, readStream.pos);
+ var offset = 0;
+ while (true) {
+ var nextOffset = offset + this.maxChunkSize;
+ if (nextOffset >= entireSlice.length) {
+ // last chunk
+ if (offset < entireSlice.length) {
+ readStream.write(entireSlice.slice(offset, entireSlice.length));
+ }
+ break;
+ }
+ readStream.write(entireSlice.slice(offset, nextOffset));
+ offset = nextOffset;
+ }
+
+ readStream.end();
+ readStream.destroy = function() {
+ readStream.destroyed = true;
+ };
+ return readStream;
+};
+
+BufferSlicer.prototype.createWriteStream = function(options) {
+ var bufferSlicer = this;
+ options = options || {};
+ var writeStream = new Writable(options);
+ writeStream.start = options.start || 0;
+ writeStream.endOffset = (options.end == null) ? this.buffer.length : +options.end;
+ writeStream.bytesWritten = 0;
+ writeStream.pos = writeStream.start;
+ writeStream.destroyed = false;
+ writeStream._write = function(buffer, encoding, callback) {
+ if (writeStream.destroyed) return;
+
+ var end = writeStream.pos + buffer.length;
+ if (end > writeStream.endOffset) {
+ var err = new Error("maximum file length exceeded");
+ err.code = 'ETOOBIG';
+ writeStream.destroyed = true;
+ callback(err);
+ return;
+ }
+ buffer.copy(bufferSlicer.buffer, writeStream.pos, 0, buffer.length);
+
+ writeStream.bytesWritten += buffer.length;
+ writeStream.pos = end;
+ writeStream.emit('progress');
+ callback();
+ };
+ writeStream.destroy = function() {
+ writeStream.destroyed = true;
+ };
+ return writeStream;
+};
+
+BufferSlicer.prototype.ref = function() {
+ this.refCount += 1;
+};
+
+BufferSlicer.prototype.unref = function() {
+ this.refCount -= 1;
+
+ if (this.refCount < 0) {
+ throw new Error("invalid unref");
+ }
+};
+
+function createFromBuffer(buffer, options) {
+ return new BufferSlicer(buffer, options);
+}
+
+function createFromFd(fd, options) {
+ return new FdSlicer(fd, options);
+}
diff --git a/temporary_modules/trezor-connect/node_modules/fd-slicer/package.json b/temporary_modules/trezor-connect/node_modules/fd-slicer/package.json
new file mode 100644
index 00000000..407f6772
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/fd-slicer/package.json
@@ -0,0 +1,36 @@
+{
+ "name": "fd-slicer",
+ "version": "1.1.0",
+ "description": "safely create multiple ReadStream or WriteStream objects from the same file descriptor",
+ "main": "index.js",
+ "scripts": {
+ "test": "mocha --reporter spec --check-leaks",
+ "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/test.js",
+ "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --timeout 10000 --reporter spec --check-leaks test/test.js"
+ },
+ "author": "Andrew Kelley ",
+ "license": "MIT",
+ "devDependencies": {
+ "istanbul": "~0.3.3",
+ "mocha": "~2.0.1",
+ "stream-equal": "~0.1.5",
+ "streamsink": "~1.2.0"
+ },
+ "dependencies": {
+ "pend": "~1.2.0"
+ },
+ "directories": {
+ "test": "test"
+ },
+ "repository": {
+ "type": "git",
+ "url": "git://github.com/andrewrk/node-fd-slicer.git"
+ },
+ "bugs": {
+ "url": "https://github.com/andrewrk/node-fd-slicer/issues"
+ },
+ "keywords": [
+ "createReadStream",
+ "createWriteStream"
+ ]
+}
diff --git a/temporary_modules/trezor-connect/node_modules/fd-slicer/test/test.js b/temporary_modules/trezor-connect/node_modules/fd-slicer/test/test.js
new file mode 100644
index 00000000..d05ab003
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/fd-slicer/test/test.js
@@ -0,0 +1,350 @@
+var fdSlicer = require('../');
+var fs = require('fs');
+var crypto = require('crypto');
+var path = require('path');
+var streamEqual = require('stream-equal');
+var assert = require('assert');
+var Pend = require('pend');
+var StreamSink = require('streamsink');
+
+var describe = global.describe;
+var it = global.it;
+var before = global.before;
+var beforeEach = global.beforeEach;
+var after = global.after;
+
+var testBlobFile = path.join(__dirname, "test-blob.bin");
+var testBlobFileSize = 20 * 1024 * 1024;
+var testOutBlobFile = path.join(__dirname, "test-blob-out.bin");
+
+describe("FdSlicer", function() {
+ before(function(done) {
+ var out = fs.createWriteStream(testBlobFile);
+ for (var i = 0; i < testBlobFileSize / 1024; i += 1) {
+ out.write(crypto.pseudoRandomBytes(1024));
+ }
+ out.end();
+ out.on('close', done);
+ });
+ beforeEach(function() {
+ try {
+ fs.unlinkSync(testOutBlobFile);
+ } catch (err) {
+ }
+ });
+ after(function() {
+ try {
+ fs.unlinkSync(testBlobFile);
+ fs.unlinkSync(testOutBlobFile);
+ } catch (err) {
+ }
+ });
+ it("reads a 20MB file (autoClose on)", function(done) {
+ fs.open(testBlobFile, 'r', function(err, fd) {
+ if (err) return done(err);
+ var slicer = fdSlicer.createFromFd(fd, {autoClose: true});
+ var actualStream = slicer.createReadStream();
+ var expectedStream = fs.createReadStream(testBlobFile);
+
+ var pend = new Pend();
+ pend.go(function(cb) {
+ slicer.on('close', cb);
+ });
+ pend.go(function(cb) {
+ streamEqual(expectedStream, actualStream, function(err, equal) {
+ if (err) return done(err);
+ assert.ok(equal);
+ cb();
+ });
+ });
+ pend.wait(done);
+ });
+ });
+ it("reads 4 chunks simultaneously", function(done) {
+ fs.open(testBlobFile, 'r', function(err, fd) {
+ if (err) return done(err);
+ var slicer = fdSlicer.createFromFd(fd);
+ var actualPart1 = slicer.createReadStream({start: testBlobFileSize * 0/4, end: testBlobFileSize * 1/4});
+ var actualPart2 = slicer.createReadStream({start: testBlobFileSize * 1/4, end: testBlobFileSize * 2/4});
+ var actualPart3 = slicer.createReadStream({start: testBlobFileSize * 2/4, end: testBlobFileSize * 3/4});
+ var actualPart4 = slicer.createReadStream({start: testBlobFileSize * 3/4, end: testBlobFileSize * 4/4});
+ var expectedPart1 = slicer.createReadStream({start: testBlobFileSize * 0/4, end: testBlobFileSize * 1/4});
+ var expectedPart2 = slicer.createReadStream({start: testBlobFileSize * 1/4, end: testBlobFileSize * 2/4});
+ var expectedPart3 = slicer.createReadStream({start: testBlobFileSize * 2/4, end: testBlobFileSize * 3/4});
+ var expectedPart4 = slicer.createReadStream({start: testBlobFileSize * 3/4, end: testBlobFileSize * 4/4});
+ var pend = new Pend();
+ pend.go(function(cb) {
+ streamEqual(expectedPart1, actualPart1, function(err, equal) {
+ assert.ok(equal);
+ cb(err);
+ });
+ });
+ pend.go(function(cb) {
+ streamEqual(expectedPart2, actualPart2, function(err, equal) {
+ assert.ok(equal);
+ cb(err);
+ });
+ });
+ pend.go(function(cb) {
+ streamEqual(expectedPart3, actualPart3, function(err, equal) {
+ assert.ok(equal);
+ cb(err);
+ });
+ });
+ pend.go(function(cb) {
+ streamEqual(expectedPart4, actualPart4, function(err, equal) {
+ assert.ok(equal);
+ cb(err);
+ });
+ });
+ pend.wait(function(err) {
+ if (err) return done(err);
+ fs.close(fd, done);
+ });
+ });
+ });
+
+ it("writes a 20MB file (autoClose on)", function(done) {
+ fs.open(testOutBlobFile, 'w', function(err, fd) {
+ if (err) return done(err);
+ var slicer = fdSlicer.createFromFd(fd, {autoClose: true});
+ var actualStream = slicer.createWriteStream();
+ var inStream = fs.createReadStream(testBlobFile);
+
+ slicer.on('close', function() {
+ var expected = fs.createReadStream(testBlobFile);
+ var actual = fs.createReadStream(testOutBlobFile);
+
+ streamEqual(expected, actual, function(err, equal) {
+ if (err) return done(err);
+ assert.ok(equal);
+ done();
+ });
+ });
+ inStream.pipe(actualStream);
+ });
+ });
+
+ it("writes 4 chunks simultaneously", function(done) {
+ fs.open(testOutBlobFile, 'w', function(err, fd) {
+ if (err) return done(err);
+ var slicer = fdSlicer.createFromFd(fd);
+ var actualPart1 = slicer.createWriteStream({start: testBlobFileSize * 0/4});
+ var actualPart2 = slicer.createWriteStream({start: testBlobFileSize * 1/4});
+ var actualPart3 = slicer.createWriteStream({start: testBlobFileSize * 2/4});
+ var actualPart4 = slicer.createWriteStream({start: testBlobFileSize * 3/4});
+ var in1 = fs.createReadStream(testBlobFile, {start: testBlobFileSize * 0/4, end: testBlobFileSize * 1/4});
+ var in2 = fs.createReadStream(testBlobFile, {start: testBlobFileSize * 1/4, end: testBlobFileSize * 2/4});
+ var in3 = fs.createReadStream(testBlobFile, {start: testBlobFileSize * 2/4, end: testBlobFileSize * 3/4});
+ var in4 = fs.createReadStream(testBlobFile, {start: testBlobFileSize * 3/4, end: testBlobFileSize * 4/4});
+ var pend = new Pend();
+ pend.go(function(cb) {
+ actualPart1.on('finish', cb);
+ });
+ pend.go(function(cb) {
+ actualPart2.on('finish', cb);
+ });
+ pend.go(function(cb) {
+ actualPart3.on('finish', cb);
+ });
+ pend.go(function(cb) {
+ actualPart4.on('finish', cb);
+ });
+ in1.pipe(actualPart1);
+ in2.pipe(actualPart2);
+ in3.pipe(actualPart3);
+ in4.pipe(actualPart4);
+ pend.wait(function() {
+ fs.close(fd, function(err) {
+ if (err) return done(err);
+ var expected = fs.createReadStream(testBlobFile);
+ var actual = fs.createReadStream(testOutBlobFile);
+ streamEqual(expected, actual, function(err, equal) {
+ if (err) return done(err);
+ assert.ok(equal);
+ done();
+ });
+ });
+ });
+ });
+ });
+
+ it("throws on invalid ref", function(done) {
+ fs.open(testOutBlobFile, 'w', function(err, fd) {
+ if (err) return done(err);
+ var slicer = fdSlicer.createFromFd(fd, {autoClose: true});
+ assert.throws(function() {
+ slicer.unref();
+ }, /invalid unref/);
+ fs.close(fd, done);
+ });
+ });
+
+ it("write stream emits error when max size exceeded", function(done) {
+ fs.open(testOutBlobFile, 'w', function(err, fd) {
+ if (err) return done(err);
+ var slicer = fdSlicer.createFromFd(fd, {autoClose: true});
+ var ws = slicer.createWriteStream({start: 0, end: 1000});
+ ws.on('error', function(err) {
+ assert.strictEqual(err.code, 'ETOOBIG');
+ slicer.on('close', done);
+ });
+ ws.end(new Buffer(1001));
+ });
+ });
+
+ it("write stream does not emit error when max size not exceeded", function(done) {
+ fs.open(testOutBlobFile, 'w', function(err, fd) {
+ if (err) return done(err);
+ var slicer = fdSlicer.createFromFd(fd, {autoClose: true});
+ var ws = slicer.createWriteStream({end: 1000});
+ slicer.on('close', done);
+ ws.end(new Buffer(1000));
+ });
+ });
+
+ it("write stream start and end work together", function(done) {
+ fs.open(testOutBlobFile, 'w', function(err, fd) {
+ if (err) return done(err);
+ var slicer = fdSlicer.createFromFd(fd, {autoClose: true});
+ var ws = slicer.createWriteStream({start: 1, end: 1000});
+ ws.on('error', function(err) {
+ assert.strictEqual(err.code, 'ETOOBIG');
+ slicer.on('close', done);
+ });
+ ws.end(new Buffer(1000));
+ });
+ });
+
+ it("write stream emits progress events", function(done) {
+ fs.open(testOutBlobFile, 'w', function(err, fd) {
+ if (err) return done(err);
+ var slicer = fdSlicer.createFromFd(fd, {autoClose: true});
+ var ws = slicer.createWriteStream();
+ var progressEventCount = 0;
+ var prevBytesWritten = 0;
+ ws.on('progress', function() {
+ progressEventCount += 1;
+ assert.ok(ws.bytesWritten > prevBytesWritten);
+ prevBytesWritten = ws.bytesWritten;
+ });
+ slicer.on('close', function() {
+ assert.ok(progressEventCount > 5);
+ done();
+ });
+ for (var i = 0; i < 10; i += 1) {
+ ws.write(new Buffer(16 * 1024 * 2));
+ }
+ ws.end();
+ });
+ });
+
+ it("write stream unrefs when destroyed", function(done) {
+ fs.open(testOutBlobFile, 'w', function(err, fd) {
+ if (err) return done(err);
+ var slicer = fdSlicer.createFromFd(fd, {autoClose: true});
+ var ws = slicer.createWriteStream();
+ slicer.on('close', done);
+ ws.write(new Buffer(1000));
+ ws.destroy();
+ });
+ });
+
+ it("read stream unrefs when destroyed", function(done) {
+ fs.open(testBlobFile, 'r', function(err, fd) {
+ if (err) return done(err);
+ var slicer = fdSlicer.createFromFd(fd, {autoClose: true});
+ var rs = slicer.createReadStream();
+ rs.on('error', function(err) {
+ assert.strictEqual(err.message, "stream destroyed");
+ slicer.on('close', done);
+ });
+ rs.destroy();
+ });
+ });
+
+ it("fdSlicer.read", function(done) {
+ fs.open(testBlobFile, 'r', function(err, fd) {
+ if (err) return done(err);
+ var slicer = fdSlicer.createFromFd(fd);
+ var outBuf = new Buffer(1024);
+ slicer.read(outBuf, 0, 10, 0, function(err, bytesRead, buf) {
+ assert.strictEqual(bytesRead, 10);
+ fs.close(fd, done);
+ });
+ });
+ });
+
+ it("fdSlicer.write", function(done) {
+ fs.open(testOutBlobFile, 'w', function(err, fd) {
+ if (err) return done(err);
+ var slicer = fdSlicer.createFromFd(fd);
+ slicer.write(new Buffer("blah\n"), 0, 5, 0, function() {
+ if (err) return done(err);
+ fs.close(fd, done);
+ });
+ });
+ });
+});
+
+describe("BufferSlicer", function() {
+ it("invalid ref", function() {
+ var slicer = fdSlicer.createFromBuffer(new Buffer(16));
+ slicer.ref();
+ slicer.unref();
+ assert.throws(function() {
+ slicer.unref();
+ }, /invalid unref/);
+ });
+ it("read and write", function(done) {
+ var buf = new Buffer("through the tangled thread the needle finds its way");
+ var slicer = fdSlicer.createFromBuffer(buf);
+ var outBuf = new Buffer(1024);
+ slicer.read(outBuf, 10, 11, 8, function(err) {
+ if (err) return done(err);
+ assert.strictEqual(outBuf.toString('utf8', 10, 21), "the tangled");
+ slicer.write(new Buffer("derp"), 0, 4, 7, function(err) {
+ if (err) return done(err);
+ assert.strictEqual(buf.toString('utf8', 7, 19), "derp tangled");
+ done();
+ });
+ });
+ });
+ it("createReadStream", function(done) {
+ var str = "I never conquered rarely came, 16 just held such better days";
+ var buf = new Buffer(str);
+ var slicer = fdSlicer.createFromBuffer(buf);
+ var inStream = slicer.createReadStream();
+ var sink = new StreamSink();
+ inStream.pipe(sink);
+ sink.on('finish', function() {
+ assert.strictEqual(sink.toString(), str);
+ inStream.destroy();
+ done();
+ });
+ });
+ it("createWriteStream exceed buffer size", function(done) {
+ var slicer = fdSlicer.createFromBuffer(new Buffer(4));
+ var outStream = slicer.createWriteStream();
+ outStream.on('error', function(err) {
+ assert.strictEqual(err.code, 'ETOOBIG');
+ done();
+ });
+ outStream.write("hi!\n");
+ outStream.write("it warked\n");
+ outStream.end();
+ });
+ it("createWriteStream ok", function(done) {
+ var buf = new Buffer(1024);
+ var slicer = fdSlicer.createFromBuffer(buf);
+ var outStream = slicer.createWriteStream();
+ outStream.on('finish', function() {
+ assert.strictEqual(buf.toString('utf8', 0, "hi!\nit warked\n".length), "hi!\nit warked\n");
+ outStream.destroy();
+ done();
+ });
+ outStream.write("hi!\n");
+ outStream.write("it warked\n");
+ outStream.end();
+ });
+});
diff --git a/temporary_modules/trezor-connect/node_modules/fs-extra/CHANGELOG.md b/temporary_modules/trezor-connect/node_modules/fs-extra/CHANGELOG.md
new file mode 100644
index 00000000..225fdcaa
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/fs-extra/CHANGELOG.md
@@ -0,0 +1,902 @@
+9.1.0 / 2021-01-19
+------------------
+
+- Add promise support for `fs.rm()` ([#841](https://github.com/jprichardson/node-fs-extra/issues/841), [#860](https://github.com/jprichardson/node-fs-extra/pull/860))
+- Upgrade universalify for performance improvments ([#825](https://github.com/jprichardson/node-fs-extra/pull/825))
+
+9.0.1 / 2020-06-03
+------------------
+
+- Fix issue with `ensureFile()` when used with Jest on Windows ([#804](https://github.com/jprichardson/node-fs-extra/issues/804), [#805](https://github.com/jprichardson/node-fs-extra/pull/805))
+- Remove unneeded `process.umask()` call ([#791](https://github.com/jprichardson/node-fs-extra/pull/791))
+- Docs improvements ([#753](https://github.com/jprichardson/node-fs-extra/pull/753), [#795](https://github.com/jprichardson/node-fs-extra/pull/795), [#797](https://github.com/jprichardson/node-fs-extra/pull/797))
+
+9.0.0 / 2020-03-19
+------------------
+
+### Breaking changes
+
+- Requires Node.js version 10 or greater ([#725](https://github.com/jprichardson/node-fs-extra/issues/725), [#751](https://github.com/jprichardson/node-fs-extra/pull/751))
+- Switched `ensureDir*` to use a fork of https://github.com/sindresorhus/make-dir to make use of native recursive `fs.mkdir` where possible ([#619](https://github.com/jprichardson/node-fs-extra/issues/619), [#756](https://github.com/jprichardson/node-fs-extra/pull/756))
+- Properly preserve `atime` for `copy*` with `preserveTimestamps` option ([#633](https://github.com/jprichardson/node-fs-extra/pull/633))
+
+**The following changes, allthough technically breaking, will not affect the vast majority of users:**
+
+- `outputJson` now outputs objects as they were when the function was called, even if they are mutated later ([#702](https://github.com/jprichardson/node-fs-extra/issues/702), [#768](https://github.com/jprichardson/node-fs-extra/pull/768))
+- Cannot pass `null` as an options parameter to `*Json*` methods ([#745](https://github.com/jprichardson/node-fs-extra/issues/745), [#768](https://github.com/jprichardson/node-fs-extra/pull/768))
+
+### Improvements
+
+- Add promise shims for `fs.writev` & `fs.opendir` ([#747](https://github.com/jprichardson/node-fs-extra/pull/747))
+- Better errors for `ensureFile` ([#696](https://github.com/jprichardson/node-fs-extra/issues/696), [#744](https://github.com/jprichardson/node-fs-extra/pull/744))
+- Better file comparison for older Node versions ([#694](https://github.com/jprichardson/node-fs-extra/pull/694))
+
+### Miscellaneous changes
+- Peformance optimizations ([#762](https://github.com/jprichardson/node-fs-extra/issues/762), [#764](https://github.com/jprichardson/node-fs-extra/pull/764))
+- Add missing documentation for aliases ([#758](https://github.com/jprichardson/node-fs-extra/issues/758), [#766](https://github.com/jprichardson/node-fs-extra/pull/766))
+- Update `universalify` dependency ([#767](https://github.com/jprichardson/node-fs-extra/pull/767))
+
+8.1.0 / 2019-06-28
+------------------
+
+- Add support for promisified `fs.realpath.native` in Node v9.2+ ([#650](https://github.com/jprichardson/node-fs-extra/issues/650), [#682](https://github.com/jprichardson/node-fs-extra/pull/682))
+- Update `graceful-fs` dependency ([#700](https://github.com/jprichardson/node-fs-extra/pull/700))
+- Use `graceful-fs` everywhere ([#700](https://github.com/jprichardson/node-fs-extra/pull/700))
+
+8.0.1 / 2019-05-13
+------------------
+
+- Fix bug `Maximum call stack size exceeded` error in `util/stat` ([#679](https://github.com/jprichardson/node-fs-extra/pull/679))
+
+8.0.0 / 2019-05-11
+------------------
+
+**NOTE:** Node.js v6 support is deprecated, and will be dropped in the next major release.
+
+- Use `renameSync()` under the hood in `moveSync()`
+- Fix bug with bind-mounted directories in `copy*()` ([#613](https://github.com/jprichardson/node-fs-extra/issues/613), [#618](https://github.com/jprichardson/node-fs-extra/pull/618))
+- Fix bug in `move()` with case-insensitive file systems
+- Use `fs.stat()`'s `bigint` option in `copy*()` & `move*()` where possible ([#657](https://github.com/jprichardson/node-fs-extra/issues/657))
+
+7.0.1 / 2018-11-07
+------------------
+
+- Fix `removeSync()` on Windows, in some cases, it would error out with `ENOTEMPTY` ([#646](https://github.com/jprichardson/node-fs-extra/pull/646))
+- Document `mode` option for `ensureDir*()` ([#587](https://github.com/jprichardson/node-fs-extra/pull/587))
+- Don't include documentation files in npm package tarball ([#642](https://github.com/jprichardson/node-fs-extra/issues/642), [#643](https://github.com/jprichardson/node-fs-extra/pull/643))
+
+7.0.0 / 2018-07-16
+------------------
+
+- **BREAKING:** Refine `copy*()` handling of symlinks to properly detect symlinks that point to the same file. ([#582](https://github.com/jprichardson/node-fs-extra/pull/582))
+- Fix bug with copying write-protected directories ([#600](https://github.com/jprichardson/node-fs-extra/pull/600))
+- Universalify `fs.lchmod()` ([#596](https://github.com/jprichardson/node-fs-extra/pull/596))
+- Add `engines` field to `package.json` ([#580](https://github.com/jprichardson/node-fs-extra/pull/580))
+
+6.0.1 / 2018-05-09
+------------------
+
+- Fix `fs.promises` `ExperimentalWarning` on Node v10.1.0 ([#578](https://github.com/jprichardson/node-fs-extra/pull/578))
+
+6.0.0 / 2018-05-01
+------------------
+
+- Drop support for Node.js versions 4, 5, & 7 ([#564](https://github.com/jprichardson/node-fs-extra/pull/564))
+- Rewrite `move` to use `fs.rename` where possible ([#549](https://github.com/jprichardson/node-fs-extra/pull/549))
+- Don't convert relative paths to absolute paths for `filter` ([#554](https://github.com/jprichardson/node-fs-extra/pull/554))
+- `copy*`'s behavior when `preserveTimestamps` is `false` has been OS-dependent since 5.0.0, but that's now explicitly noted in the docs ([#563](https://github.com/jprichardson/node-fs-extra/pull/563))
+- Fix subdirectory detection for `copy*` & `move*` ([#541](https://github.com/jprichardson/node-fs-extra/pull/541))
+- Handle case-insensitive paths correctly in `copy*` ([#568](https://github.com/jprichardson/node-fs-extra/pull/568))
+
+5.0.0 / 2017-12-11
+------------------
+
+Significant refactor of `copy()` & `copySync()`, including breaking changes. No changes to other functions in this release.
+
+Huge thanks to **[@manidlou](https://github.com/manidlou)** for doing most of the work on this release.
+
+- The `filter` option can no longer be a RegExp (must be a function). This was deprecated since fs-extra v1.0.0. [#512](https://github.com/jprichardson/node-fs-extra/pull/512)
+- `copy()`'s `filter` option can now be a function that returns a Promise. [#518](https://github.com/jprichardson/node-fs-extra/pull/518)
+- `copy()` & `copySync()` now use `fs.copyFile()`/`fs.copyFileSync()` in environments that support it (currently Node 8.5.0+). Older Node versions still get the old implementation. [#505](https://github.com/jprichardson/node-fs-extra/pull/505)
+- Don't allow copying a directory into itself. [#83](https://github.com/jprichardson/node-fs-extra/issues/83)
+- Handle copying between identical files. [#198](https://github.com/jprichardson/node-fs-extra/issues/198)
+- Error out when copying an empty folder to a path that already exists. [#464](https://github.com/jprichardson/node-fs-extra/issues/464)
+- Don't create `dest`'s parent if the `filter` function aborts the `copy()` operation. [#517](https://github.com/jprichardson/node-fs-extra/pull/517)
+- Fix `writeStream` not being closed if there was an error in `copy()`. [#516](https://github.com/jprichardson/node-fs-extra/pull/516)
+
+4.0.3 / 2017-12-05
+------------------
+
+- Fix wrong `chmod` values in `fs.remove()` [#501](https://github.com/jprichardson/node-fs-extra/pull/501)
+- Fix `TypeError` on systems that don't have some `fs` operations like `lchown` [#520](https://github.com/jprichardson/node-fs-extra/pull/520)
+
+4.0.2 / 2017-09-12
+------------------
+
+- Added `EOL` option to `writeJson*` & `outputJson*` (via upgrade to jsonfile v4)
+- Added promise support to [`fs.copyFile()`](https://nodejs.org/api/fs.html#fs_fs_copyfile_src_dest_flags_callback) in Node 8.5+
+- Added `.js` extension to `main` field in `package.json` for better tooling compatibility. [#485](https://github.com/jprichardson/node-fs-extra/pull/485)
+
+4.0.1 / 2017-07-31
+------------------
+
+### Fixed
+
+- Previously, `ensureFile()` & `ensureFileSync()` would do nothing if the path was a directory. Now, they error out for consistency with `ensureDir()`. [#465](https://github.com/jprichardson/node-fs-extra/issues/465), [#466](https://github.com/jprichardson/node-fs-extra/pull/466), [#470](https://github.com/jprichardson/node-fs-extra/issues/470)
+
+4.0.0 / 2017-07-14
+------------------
+
+### Changed
+
+- **BREAKING:** The promisified versions of `fs.read()` & `fs.write()` now return objects. See [the docs](docs/fs-read-write.md) for details. [#436](https://github.com/jprichardson/node-fs-extra/issues/436), [#449](https://github.com/jprichardson/node-fs-extra/pull/449)
+- `fs.move()` now errors out when destination is a subdirectory of source. [#458](https://github.com/jprichardson/node-fs-extra/pull/458)
+- Applied upstream fixes from `rimraf` to `fs.remove()` & `fs.removeSync()`. [#459](https://github.com/jprichardson/node-fs-extra/pull/459)
+
+### Fixed
+
+- Got `fs.outputJSONSync()` working again; it was broken due to refactoring. [#428](https://github.com/jprichardson/node-fs-extra/pull/428)
+
+Also clarified the docs in a few places.
+
+3.0.1 / 2017-05-04
+------------------
+
+- Fix bug in `move()` & `moveSync()` when source and destination are the same, and source does not exist. [#415](https://github.com/jprichardson/node-fs-extra/pull/415)
+
+3.0.0 / 2017-04-27
+------------------
+
+### Added
+
+- **BREAKING:** Added Promise support. All asynchronous native fs methods and fs-extra methods now return a promise if the callback is not passed. [#403](https://github.com/jprichardson/node-fs-extra/pull/403)
+- `pathExists()`, a replacement for the deprecated `fs.exists`. `pathExists` has a normal error-first callback signature. Also added `pathExistsSync`, an alias to `fs.existsSync`, for completeness. [#406](https://github.com/jprichardson/node-fs-extra/pull/406)
+
+### Removed
+
+- **BREAKING:** Removed support for setting the default spaces for `writeJson()`, `writeJsonSync()`, `outputJson()`, & `outputJsonSync()`. This was undocumented. [#402](https://github.com/jprichardson/node-fs-extra/pull/402)
+
+### Changed
+
+- Upgraded jsonfile dependency to v3.0.0:
+ - **BREAKING:** Changed behavior of `throws` option for `readJsonSync()`; now does not throw filesystem errors when `throws` is `false`.
+- **BREAKING:** `writeJson()`, `writeJsonSync()`, `outputJson()`, & `outputJsonSync()` now output minified JSON by default for consistency with `JSON.stringify()`; set the `spaces` option to `2` to override this new behavior. [#402](https://github.com/jprichardson/node-fs-extra/pull/402)
+- Use `Buffer.allocUnsafe()` instead of `new Buffer()` in environments that support it. [#394](https://github.com/jprichardson/node-fs-extra/pull/394)
+
+### Fixed
+
+- `removeSync()` silently failed on Windows in some cases. Now throws an `EBUSY` error. [#408](https://github.com/jprichardson/node-fs-extra/pull/408)
+
+2.1.2 / 2017-03-16
+------------------
+
+### Fixed
+
+- Weird windows bug that resulted in `ensureDir()`'s callback being called twice in some cases. This bug may have also affected `remove()`. See [#392](https://github.com/jprichardson/node-fs-extra/issues/392), [#393](https://github.com/jprichardson/node-fs-extra/pull/393)
+
+2.1.1 / 2017-03-15
+------------------
+
+### Fixed
+
+- Reverted [`5597bd`](https://github.com/jprichardson/node-fs-extra/commit/5597bd5b67f7d060f5f5bf26e9635be48330f5d7), this broke compatibility with Node.js versions v4+ but less than `v4.5.0`.
+- Remove `Buffer.alloc()` usage in `moveSync()`.
+
+2.1.0 / 2017-03-15
+------------------
+
+Thanks to [Mani Maghsoudlou (@manidlou)](https://github.com/manidlou) & [Jan Peer Stöcklmair (@JPeer264)](https://github.com/JPeer264) for their extraordinary help with this release!
+
+### Added
+- `moveSync()` See [#309], [#381](https://github.com/jprichardson/node-fs-extra/pull/381). ([@manidlou](https://github.com/manidlou))
+- `copy()` and `copySync()`'s `filter` option now gets the destination path passed as the second parameter. [#366](https://github.com/jprichardson/node-fs-extra/pull/366) ([@manidlou](https://github.com/manidlou))
+
+### Changed
+- Use `Buffer.alloc()` instead of deprecated `new Buffer()` in `copySync()`. [#380](https://github.com/jprichardson/node-fs-extra/pull/380) ([@manidlou](https://github.com/manidlou))
+- Refactored entire codebase to use ES6 features supported by Node.js v4+ [#355](https://github.com/jprichardson/node-fs-extra/issues/355). [(@JPeer264)](https://github.com/JPeer264)
+- Refactored docs. ([@manidlou](https://github.com/manidlou))
+
+### Fixed
+
+- `move()` shouldn't error out when source and dest are the same. [#377](https://github.com/jprichardson/node-fs-extra/issues/377), [#378](https://github.com/jprichardson/node-fs-extra/pull/378) ([@jdalton](https://github.com/jdalton))
+
+2.0.0 / 2017-01-16
+------------------
+
+### Removed
+- **BREAKING:** Removed support for Node `v0.12`. The Node foundation stopped officially supporting it
+on Jan 1st, 2017.
+- **BREAKING:** Remove `walk()` and `walkSync()`. `walkSync()` was only part of `fs-extra` for a little
+over two months. Use [klaw](https://github.com/jprichardson/node-klaw) instead of `walk()`, in fact, `walk()` was just
+an alias to klaw. For `walkSync()` use [klaw-sync](https://github.com/mawni/node-klaw-sync). See: [#338], [#339]
+
+### Changed
+- **BREAKING:** Renamed `clobber` to `overwrite`. This affects `copy()`, `copySync()`, and `move()`. [#330], [#333]
+- Moved docs, to `docs/`. [#340]
+
+### Fixed
+- Apply filters to directories in `copySync()` like in `copy()`. [#324]
+- A specific condition when disk is under heavy use, `copy()` can fail. [#326]
+
+
+1.0.0 / 2016-11-01
+------------------
+
+After five years of development, we finally have reach the 1.0.0 milestone! Big thanks goes
+to [Ryan Zim](https://github.com/RyanZim) for leading the charge on this release!
+
+### Added
+- `walkSync()`
+
+### Changed
+- **BREAKING**: dropped Node v0.10 support.
+- disabled `rimaf` globbing, wasn't used. [#280]
+- deprecate `copy()/copySync()` option `filter` if it's a `RegExp`. `filter` should now be a function.
+- inline `rimraf`. This is temporary and was done because `rimraf` depended upon the beefy `glob` which `fs-extra` does not use. [#300]
+
+### Fixed
+- bug fix proper closing of file handle on `utimesMillis()` [#271]
+- proper escaping of files with dollar signs [#291]
+- `copySync()` failed if user didn't own file. [#199], [#301]
+
+
+0.30.0 / 2016-04-28
+-------------------
+- Brought back Node v0.10 support. I didn't realize there was still demand. Official support will end **2016-10-01**.
+
+0.29.0 / 2016-04-27
+-------------------
+- **BREAKING**: removed support for Node v0.10. If you still want to use Node v0.10, everything should work except for `ensureLink()/ensureSymlink()`. Node v0.12 is still supported but will be dropped in the near future as well.
+
+0.28.0 / 2016-04-17
+-------------------
+- **BREAKING**: removed `createOutputStream()`. Use https://www.npmjs.com/package/create-output-stream. See: [#192][#192]
+- `mkdirs()/mkdirsSync()` check for invalid win32 path chars. See: [#209][#209], [#237][#237]
+- `mkdirs()/mkdirsSync()` if drive not mounted, error. See: [#93][#93]
+
+0.27.0 / 2016-04-15
+-------------------
+- add `dereference` option to `copySync()`. [#235][#235]
+
+0.26.7 / 2016-03-16
+-------------------
+- fixed `copy()` if source and dest are the same. [#230][#230]
+
+0.26.6 / 2016-03-15
+-------------------
+- fixed if `emptyDir()` does not have a callback: [#229][#229]
+
+0.26.5 / 2016-01-27
+-------------------
+- `copy()` with two arguments (w/o callback) was broken. See: [#215][#215]
+
+0.26.4 / 2016-01-05
+-------------------
+- `copySync()` made `preserveTimestamps` default consistent with `copy()` which is `false`. See: [#208][#208]
+
+0.26.3 / 2015-12-17
+-------------------
+- fixed `copy()` hangup in copying blockDevice / characterDevice / `/dev/null`. See: [#193][#193]
+
+0.26.2 / 2015-11-02
+-------------------
+- fixed `outputJson{Sync}()` spacing adherence to `fs.spaces`
+
+0.26.1 / 2015-11-02
+-------------------
+- fixed `copySync()` when `clogger=true` and the destination is read only. See: [#190][#190]
+
+0.26.0 / 2015-10-25
+-------------------
+- extracted the `walk()` function into its own module [`klaw`](https://github.com/jprichardson/node-klaw).
+
+0.25.0 / 2015-10-24
+-------------------
+- now has a file walker `walk()`
+
+0.24.0 / 2015-08-28
+-------------------
+- removed alias `delete()` and `deleteSync()`. See: [#171][#171]
+
+0.23.1 / 2015-08-07
+-------------------
+- Better handling of errors for `move()` when moving across devices. [#170][#170]
+- `ensureSymlink()` and `ensureLink()` should not throw errors if link exists. [#169][#169]
+
+0.23.0 / 2015-08-06
+-------------------
+- added `ensureLink{Sync}()` and `ensureSymlink{Sync}()`. See: [#165][#165]
+
+0.22.1 / 2015-07-09
+-------------------
+- Prevent calling `hasMillisResSync()` on module load. See: [#149][#149].
+Fixes regression that was introduced in `0.21.0`.
+
+0.22.0 / 2015-07-09
+-------------------
+- preserve permissions / ownership in `copy()`. See: [#54][#54]
+
+0.21.0 / 2015-07-04
+-------------------
+- add option to preserve timestamps in `copy()` and `copySync()`. See: [#141][#141]
+- updated `graceful-fs@3.x` to `4.x`. This brings in features from `amazing-graceful-fs` (much cleaner code / less hacks)
+
+0.20.1 / 2015-06-23
+-------------------
+- fixed regression caused by latest jsonfile update: See: https://github.com/jprichardson/node-jsonfile/issues/26
+
+0.20.0 / 2015-06-19
+-------------------
+- removed `jsonfile` aliases with `File` in the name, they weren't documented and probably weren't in use e.g.
+this package had both `fs.readJsonFile` and `fs.readJson` that were aliases to each other, now use `fs.readJson`.
+- preliminary walker created. Intentionally not documented. If you use it, it will almost certainly change and break your code.
+- started moving tests inline
+- upgraded to `jsonfile@2.1.0`, can now pass JSON revivers/replacers to `readJson()`, `writeJson()`, `outputJson()`
+
+0.19.0 / 2015-06-08
+-------------------
+- `fs.copy()` had support for Node v0.8, dropped support
+
+0.18.4 / 2015-05-22
+-------------------
+- fixed license field according to this: [#136][#136] and https://github.com/npm/npm/releases/tag/v2.10.0
+
+0.18.3 / 2015-05-08
+-------------------
+- bugfix: handle `EEXIST` when clobbering on some Linux systems. [#134][#134]
+
+0.18.2 / 2015-04-17
+-------------------
+- bugfix: allow `F_OK` ([#120][#120])
+
+0.18.1 / 2015-04-15
+-------------------
+- improved windows support for `move()` a bit. https://github.com/jprichardson/node-fs-extra/commit/92838980f25dc2ee4ec46b43ee14d3c4a1d30c1b
+- fixed a lot of tests for Windows (appveyor)
+
+0.18.0 / 2015-03-31
+-------------------
+- added `emptyDir()` and `emptyDirSync()`
+
+0.17.0 / 2015-03-28
+-------------------
+- `copySync` added `clobber` option (before always would clobber, now if `clobber` is `false` it throws an error if the destination exists).
+**Only works with files at the moment.**
+- `createOutputStream()` added. See: [#118][#118]
+
+0.16.5 / 2015-03-08
+-------------------
+- fixed `fs.move` when `clobber` is `true` and destination is a directory, it should clobber. [#114][#114]
+
+0.16.4 / 2015-03-01
+-------------------
+- `fs.mkdirs` fix infinite loop on Windows. See: See https://github.com/substack/node-mkdirp/pull/74 and https://github.com/substack/node-mkdirp/issues/66
+
+0.16.3 / 2015-01-28
+-------------------
+- reverted https://github.com/jprichardson/node-fs-extra/commit/1ee77c8a805eba5b99382a2591ff99667847c9c9
+
+
+0.16.2 / 2015-01-28
+-------------------
+- fixed `fs.copy` for Node v0.8 (support is temporary and will be removed in the near future)
+
+0.16.1 / 2015-01-28
+-------------------
+- if `setImmediate` is not available, fall back to `process.nextTick`
+
+0.16.0 / 2015-01-28
+-------------------
+- bugfix `fs.move()` into itself. Closes [#104]
+- bugfix `fs.move()` moving directory across device. Closes [#108]
+- added coveralls support
+- bugfix: nasty multiple callback `fs.copy()` bug. Closes [#98]
+- misc fs.copy code cleanups
+
+0.15.0 / 2015-01-21
+-------------------
+- dropped `ncp`, imported code in
+- because of previous, now supports `io.js`
+- `graceful-fs` is now a dependency
+
+0.14.0 / 2015-01-05
+-------------------
+- changed `copy`/`copySync` from `fs.copy(src, dest, [filters], callback)` to `fs.copy(src, dest, [options], callback)` [#100][#100]
+- removed mockfs tests for mkdirp (this may be temporary, but was getting in the way of other tests)
+
+0.13.0 / 2014-12-10
+-------------------
+- removed `touch` and `touchSync` methods (they didn't handle permissions like UNIX touch)
+- updated `"ncp": "^0.6.0"` to `"ncp": "^1.0.1"`
+- imported `mkdirp` => `minimist` and `mkdirp` are no longer dependences, should now appease people who wanted `mkdirp` to be `--use_strict` safe. See [#59]([#59][#59])
+
+0.12.0 / 2014-09-22
+-------------------
+- copy symlinks in `copySync()` [#85][#85]
+
+0.11.1 / 2014-09-02
+-------------------
+- bugfix `copySync()` preserve file permissions [#80][#80]
+
+0.11.0 / 2014-08-11
+-------------------
+- upgraded `"ncp": "^0.5.1"` to `"ncp": "^0.6.0"`
+- upgrade `jsonfile": "^1.2.0"` to `jsonfile": "^2.0.0"` => on write, json files now have `\n` at end. Also adds `options.throws` to `readJsonSync()`
+see https://github.com/jprichardson/node-jsonfile#readfilesyncfilename-options for more details.
+
+0.10.0 / 2014-06-29
+------------------
+* bugfix: upgaded `"jsonfile": "~1.1.0"` to `"jsonfile": "^1.2.0"`, bumped minor because of `jsonfile` dep change
+from `~` to `^`. [#67]
+
+0.9.1 / 2014-05-22
+------------------
+* removed Node.js `0.8.x` support, `0.9.0` was published moments ago and should have been done there
+
+0.9.0 / 2014-05-22
+------------------
+* upgraded `ncp` from `~0.4.2` to `^0.5.1`, [#58]
+* upgraded `rimraf` from `~2.2.6` to `^2.2.8`
+* upgraded `mkdirp` from `0.3.x` to `^0.5.0`
+* added methods `ensureFile()`, `ensureFileSync()`
+* added methods `ensureDir()`, `ensureDirSync()` [#31]
+* added `move()` method. From: https://github.com/andrewrk/node-mv
+
+
+0.8.1 / 2013-10-24
+------------------
+* copy failed to return an error to the callback if a file doesn't exist (ulikoehler [#38], [#39])
+
+0.8.0 / 2013-10-14
+------------------
+* `filter` implemented on `copy()` and `copySync()`. (Srirangan / [#36])
+
+0.7.1 / 2013-10-12
+------------------
+* `copySync()` implemented (Srirangan / [#33])
+* updated to the latest `jsonfile` version `1.1.0` which gives `options` params for the JSON methods. Closes [#32]
+
+0.7.0 / 2013-10-07
+------------------
+* update readme conventions
+* `copy()` now works if destination directory does not exist. Closes [#29]
+
+0.6.4 / 2013-09-05
+------------------
+* changed `homepage` field in package.json to remove NPM warning
+
+0.6.3 / 2013-06-28
+------------------
+* changed JSON spacing default from `4` to `2` to follow Node conventions
+* updated `jsonfile` dep
+* updated `rimraf` dep
+
+0.6.2 / 2013-06-28
+------------------
+* added .npmignore, [#25]
+
+0.6.1 / 2013-05-14
+------------------
+* modified for `strict` mode, closes [#24]
+* added `outputJson()/outputJsonSync()`, closes [#23]
+
+0.6.0 / 2013-03-18
+------------------
+* removed node 0.6 support
+* added node 0.10 support
+* upgraded to latest `ncp` and `rimraf`.
+* optional `graceful-fs` support. Closes [#17]
+
+
+0.5.0 / 2013-02-03
+------------------
+* Removed `readTextFile`.
+* Renamed `readJSONFile` to `readJSON` and `readJson`, same with write.
+* Restructured documentation a bit. Added roadmap.
+
+0.4.0 / 2013-01-28
+------------------
+* Set default spaces in `jsonfile` from 4 to 2.
+* Updated `testutil` deps for tests.
+* Renamed `touch()` to `createFile()`
+* Added `outputFile()` and `outputFileSync()`
+* Changed creation of testing diretories so the /tmp dir is not littered.
+* Added `readTextFile()` and `readTextFileSync()`.
+
+0.3.2 / 2012-11-01
+------------------
+* Added `touch()` and `touchSync()` methods.
+
+0.3.1 / 2012-10-11
+------------------
+* Fixed some stray globals.
+
+0.3.0 / 2012-10-09
+------------------
+* Removed all CoffeeScript from tests.
+* Renamed `mkdir` to `mkdirs`/`mkdirp`.
+
+0.2.1 / 2012-09-11
+------------------
+* Updated `rimraf` dep.
+
+0.2.0 / 2012-09-10
+------------------
+* Rewrote module into JavaScript. (Must still rewrite tests into JavaScript)
+* Added all methods of [jsonfile](https://github.com/jprichardson/node-jsonfile)
+* Added Travis-CI.
+
+0.1.3 / 2012-08-13
+------------------
+* Added method `readJSONFile`.
+
+0.1.2 / 2012-06-15
+------------------
+* Bug fix: `deleteSync()` didn't exist.
+* Verified Node v0.8 compatibility.
+
+0.1.1 / 2012-06-15
+------------------
+* Fixed bug in `remove()`/`delete()` that wouldn't execute the function if a callback wasn't passed.
+
+0.1.0 / 2012-05-31
+------------------
+* Renamed `copyFile()` to `copy()`. `copy()` can now copy directories (recursively) too.
+* Renamed `rmrf()` to `remove()`.
+* `remove()` aliased with `delete()`.
+* Added `mkdirp` capabilities. Named: `mkdir()`. Hides Node.js native `mkdir()`.
+* Instead of exporting the native `fs` module with new functions, I now copy over the native methods to a new object and export that instead.
+
+0.0.4 / 2012-03-14
+------------------
+* Removed CoffeeScript dependency
+
+0.0.3 / 2012-01-11
+------------------
+* Added methods rmrf and rmrfSync
+* Moved tests from Jasmine to Mocha
+
+
+[#344]: https://github.com/jprichardson/node-fs-extra/issues/344 "Licence Year"
+[#343]: https://github.com/jprichardson/node-fs-extra/pull/343 "Add klaw-sync link to readme"
+[#342]: https://github.com/jprichardson/node-fs-extra/pull/342 "allow preserveTimestamps when use move"
+[#341]: https://github.com/jprichardson/node-fs-extra/issues/341 "mkdirp(path.dirname(dest) in move() logic needs cleaning up [question]"
+[#340]: https://github.com/jprichardson/node-fs-extra/pull/340 "Move docs to seperate docs folder [documentation]"
+[#339]: https://github.com/jprichardson/node-fs-extra/pull/339 "Remove walk() & walkSync() [feature-walk]"
+[#338]: https://github.com/jprichardson/node-fs-extra/issues/338 "Remove walk() and walkSync() [feature-walk]"
+[#337]: https://github.com/jprichardson/node-fs-extra/issues/337 "copy doesn't return a yieldable value"
+[#336]: https://github.com/jprichardson/node-fs-extra/pull/336 "Docs enhanced walk sync [documentation, feature-walk]"
+[#335]: https://github.com/jprichardson/node-fs-extra/pull/335 "Refactor move() tests [feature-move]"
+[#334]: https://github.com/jprichardson/node-fs-extra/pull/334 "Cleanup lib/move/index.js [feature-move]"
+[#333]: https://github.com/jprichardson/node-fs-extra/pull/333 "Rename clobber to overwrite [feature-copy, feature-move]"
+[#332]: https://github.com/jprichardson/node-fs-extra/pull/332 "BREAKING: Drop Node v0.12 & io.js support"
+[#331]: https://github.com/jprichardson/node-fs-extra/issues/331 "Add support for chmodr [enhancement, future]"
+[#330]: https://github.com/jprichardson/node-fs-extra/pull/330 "BREAKING: Do not error when copy destination exists & clobber: false [feature-copy]"
+[#329]: https://github.com/jprichardson/node-fs-extra/issues/329 "Does .walk() scale to large directories? [question]"
+[#328]: https://github.com/jprichardson/node-fs-extra/issues/328 "Copying files corrupts [feature-copy, needs-confirmed]"
+[#327]: https://github.com/jprichardson/node-fs-extra/pull/327 "Use writeStream 'finish' event instead of 'close' [bug, feature-copy]"
+[#326]: https://github.com/jprichardson/node-fs-extra/issues/326 "fs.copy fails with chmod error when disk under heavy use [bug, feature-copy]"
+[#325]: https://github.com/jprichardson/node-fs-extra/issues/325 "ensureDir is difficult to promisify [enhancement]"
+[#324]: https://github.com/jprichardson/node-fs-extra/pull/324 "copySync() should apply filter to directories like copy() [bug, feature-copy]"
+[#323]: https://github.com/jprichardson/node-fs-extra/issues/323 "Support for `dest` being a directory when using `copy*()`?"
+[#322]: https://github.com/jprichardson/node-fs-extra/pull/322 "Add fs-promise as fs-extra-promise alternative"
+[#321]: https://github.com/jprichardson/node-fs-extra/issues/321 "fs.copy() with clobber set to false return EEXIST error [feature-copy]"
+[#320]: https://github.com/jprichardson/node-fs-extra/issues/320 "fs.copySync: Error: EPERM: operation not permitted, unlink "
+[#319]: https://github.com/jprichardson/node-fs-extra/issues/319 "Create directory if not exists"
+[#318]: https://github.com/jprichardson/node-fs-extra/issues/318 "Support glob patterns [enhancement, future]"
+[#317]: https://github.com/jprichardson/node-fs-extra/pull/317 "Adding copy sync test for src file without write perms"
+[#316]: https://github.com/jprichardson/node-fs-extra/pull/316 "Remove move()'s broken limit option [feature-move]"
+[#315]: https://github.com/jprichardson/node-fs-extra/pull/315 "Fix move clobber tests to work around graceful-fs bug."
+[#314]: https://github.com/jprichardson/node-fs-extra/issues/314 "move() limit option [documentation, enhancement, feature-move]"
+[#313]: https://github.com/jprichardson/node-fs-extra/pull/313 "Test that remove() ignores glob characters."
+[#312]: https://github.com/jprichardson/node-fs-extra/pull/312 "Enhance walkSync() to return items with path and stats [feature-walk]"
+[#311]: https://github.com/jprichardson/node-fs-extra/issues/311 "move() not work when dest name not provided [feature-move]"
+[#310]: https://github.com/jprichardson/node-fs-extra/issues/310 "Edit walkSync to return items like what walk emits [documentation, enhancement, feature-walk]"
+[#309]: https://github.com/jprichardson/node-fs-extra/issues/309 "moveSync support [enhancement, feature-move]"
+[#308]: https://github.com/jprichardson/node-fs-extra/pull/308 "Fix incorrect anchor link"
+[#307]: https://github.com/jprichardson/node-fs-extra/pull/307 "Fix coverage"
+[#306]: https://github.com/jprichardson/node-fs-extra/pull/306 "Update devDeps, fix lint error"
+[#305]: https://github.com/jprichardson/node-fs-extra/pull/305 "Re-add Coveralls"
+[#304]: https://github.com/jprichardson/node-fs-extra/pull/304 "Remove path-is-absolute [enhancement]"
+[#303]: https://github.com/jprichardson/node-fs-extra/pull/303 "Document copySync filter inconsistency [documentation, feature-copy]"
+[#302]: https://github.com/jprichardson/node-fs-extra/pull/302 "fix(console): depreciated -> deprecated"
+[#301]: https://github.com/jprichardson/node-fs-extra/pull/301 "Remove chmod call from copySync [feature-copy]"
+[#300]: https://github.com/jprichardson/node-fs-extra/pull/300 "Inline Rimraf [enhancement, feature-move, feature-remove]"
+[#299]: https://github.com/jprichardson/node-fs-extra/pull/299 "Warn when filter is a RegExp [feature-copy]"
+[#298]: https://github.com/jprichardson/node-fs-extra/issues/298 "API Docs [documentation]"
+[#297]: https://github.com/jprichardson/node-fs-extra/pull/297 "Warn about using preserveTimestamps on 32-bit node"
+[#296]: https://github.com/jprichardson/node-fs-extra/pull/296 "Improve EEXIST error message for copySync [enhancement]"
+[#295]: https://github.com/jprichardson/node-fs-extra/pull/295 "Depreciate using regular expressions for copy's filter option [documentation]"
+[#294]: https://github.com/jprichardson/node-fs-extra/pull/294 "BREAKING: Refactor lib/copy/ncp.js [feature-copy]"
+[#293]: https://github.com/jprichardson/node-fs-extra/pull/293 "Update CI configs"
+[#292]: https://github.com/jprichardson/node-fs-extra/issues/292 "Rewrite lib/copy/ncp.js [enhancement, feature-copy]"
+[#291]: https://github.com/jprichardson/node-fs-extra/pull/291 "Escape '$' in replacement string for async file copying"
+[#290]: https://github.com/jprichardson/node-fs-extra/issues/290 "Exclude files pattern while copying using copy.config.js [question]"
+[#289]: https://github.com/jprichardson/node-fs-extra/pull/289 "(Closes #271) lib/util/utimes: properly close file descriptors in the event of an error"
+[#288]: https://github.com/jprichardson/node-fs-extra/pull/288 "(Closes #271) lib/util/utimes: properly close file descriptors in the event of an error"
+[#287]: https://github.com/jprichardson/node-fs-extra/issues/287 "emptyDir() callback arguments are inconsistent [enhancement, feature-remove]"
+[#286]: https://github.com/jprichardson/node-fs-extra/pull/286 "Added walkSync function"
+[#285]: https://github.com/jprichardson/node-fs-extra/issues/285 "CITGM test failing on s390"
+[#284]: https://github.com/jprichardson/node-fs-extra/issues/284 "outputFile method is missing a check to determine if existing item is a folder or not"
+[#283]: https://github.com/jprichardson/node-fs-extra/pull/283 "Apply filter also on directories and symlinks for copySync()"
+[#282]: https://github.com/jprichardson/node-fs-extra/pull/282 "Apply filter also on directories and symlinks for copySync()"
+[#281]: https://github.com/jprichardson/node-fs-extra/issues/281 "remove function executes 'successfully' but doesn't do anything?"
+[#280]: https://github.com/jprichardson/node-fs-extra/pull/280 "Disable rimraf globbing"
+[#279]: https://github.com/jprichardson/node-fs-extra/issues/279 "Some code is vendored instead of included [awaiting-reply]"
+[#278]: https://github.com/jprichardson/node-fs-extra/issues/278 "copy() does not preserve file/directory ownership"
+[#277]: https://github.com/jprichardson/node-fs-extra/pull/277 "Mention defaults for clobber and dereference options"
+[#276]: https://github.com/jprichardson/node-fs-extra/issues/276 "Cannot connect to Shared Folder [awaiting-reply]"
+[#275]: https://github.com/jprichardson/node-fs-extra/issues/275 "EMFILE, too many open files on Mac OS with JSON API"
+[#274]: https://github.com/jprichardson/node-fs-extra/issues/274 "Use with memory-fs? [enhancement, future]"
+[#273]: https://github.com/jprichardson/node-fs-extra/pull/273 "tests: rename `remote.test.js` to `remove.test.js`"
+[#272]: https://github.com/jprichardson/node-fs-extra/issues/272 "Copy clobber flag never err even when true [bug, feature-copy]"
+[#271]: https://github.com/jprichardson/node-fs-extra/issues/271 "Unclosed file handle on futimes error"
+[#270]: https://github.com/jprichardson/node-fs-extra/issues/270 "copy not working as desired on Windows [feature-copy, platform-windows]"
+[#269]: https://github.com/jprichardson/node-fs-extra/issues/269 "Copying with preserveTimeStamps: true is inaccurate using 32bit node [feature-copy]"
+[#268]: https://github.com/jprichardson/node-fs-extra/pull/268 "port fix for mkdirp issue #111"
+[#267]: https://github.com/jprichardson/node-fs-extra/issues/267 "WARN deprecated wrench@1.5.9: wrench.js is deprecated!"
+[#266]: https://github.com/jprichardson/node-fs-extra/issues/266 "fs-extra"
+[#265]: https://github.com/jprichardson/node-fs-extra/issues/265 "Link the `fs.stat fs.exists` etc. methods for replace the `fs` module forever?"
+[#264]: https://github.com/jprichardson/node-fs-extra/issues/264 "Renaming a file using move fails when a file inside is open (at least on windows) [wont-fix]"
+[#263]: https://github.com/jprichardson/node-fs-extra/issues/263 "ENOSYS: function not implemented, link [needs-confirmed]"
+[#262]: https://github.com/jprichardson/node-fs-extra/issues/262 "Add .exists() and .existsSync()"
+[#261]: https://github.com/jprichardson/node-fs-extra/issues/261 "Cannot read property 'prototype' of undefined"
+[#260]: https://github.com/jprichardson/node-fs-extra/pull/260 "use more specific path for method require"
+[#259]: https://github.com/jprichardson/node-fs-extra/issues/259 "Feature Request: isEmpty"
+[#258]: https://github.com/jprichardson/node-fs-extra/issues/258 "copy files does not preserve file timestamp"
+[#257]: https://github.com/jprichardson/node-fs-extra/issues/257 "Copying a file on windows fails"
+[#256]: https://github.com/jprichardson/node-fs-extra/pull/256 "Updated Readme "
+[#255]: https://github.com/jprichardson/node-fs-extra/issues/255 "Update rimraf required version"
+[#254]: https://github.com/jprichardson/node-fs-extra/issues/254 "request for readTree, readTreeSync, walkSync method"
+[#253]: https://github.com/jprichardson/node-fs-extra/issues/253 "outputFile does not touch mtime when file exists"
+[#252]: https://github.com/jprichardson/node-fs-extra/pull/252 "Fixing problem when copying file with no write permission"
+[#251]: https://github.com/jprichardson/node-fs-extra/issues/251 "Just wanted to say thank you"
+[#250]: https://github.com/jprichardson/node-fs-extra/issues/250 "`fs.remove()` not removing files (works with `rm -rf`)"
+[#249]: https://github.com/jprichardson/node-fs-extra/issues/249 "Just a Question ... Remove Servers"
+[#248]: https://github.com/jprichardson/node-fs-extra/issues/248 "Allow option to not preserve permissions for copy"
+[#247]: https://github.com/jprichardson/node-fs-extra/issues/247 "Add TypeScript typing directly in the fs-extra package"
+[#246]: https://github.com/jprichardson/node-fs-extra/issues/246 "fse.remove() && fse.removeSync() don't throw error on ENOENT file"
+[#245]: https://github.com/jprichardson/node-fs-extra/issues/245 "filter for empty dir [enhancement]"
+[#244]: https://github.com/jprichardson/node-fs-extra/issues/244 "copySync doesn't apply the filter to directories"
+[#243]: https://github.com/jprichardson/node-fs-extra/issues/243 "Can I request fs.walk() to be synchronous?"
+[#242]: https://github.com/jprichardson/node-fs-extra/issues/242 "Accidentally truncates file names ending with $$ [bug, feature-copy]"
+[#241]: https://github.com/jprichardson/node-fs-extra/pull/241 "Remove link to createOutputStream"
+[#240]: https://github.com/jprichardson/node-fs-extra/issues/240 "walkSync request"
+[#239]: https://github.com/jprichardson/node-fs-extra/issues/239 "Depreciate regular expressions for copy's filter [documentation, feature-copy]"
+[#238]: https://github.com/jprichardson/node-fs-extra/issues/238 "Can't write to files while in a worker thread."
+[#237]: https://github.com/jprichardson/node-fs-extra/issues/237 ".ensureDir(..) fails silently when passed an invalid path..."
+[#236]: https://github.com/jprichardson/node-fs-extra/issues/236 "[Removed] Filed under wrong repo"
+[#235]: https://github.com/jprichardson/node-fs-extra/pull/235 "Adds symlink dereference option to `fse.copySync` (#191)"
+[#234]: https://github.com/jprichardson/node-fs-extra/issues/234 "ensureDirSync fails silent when EACCES: permission denied on travis-ci"
+[#233]: https://github.com/jprichardson/node-fs-extra/issues/233 "please make sure the first argument in callback is error object [feature-copy]"
+[#232]: https://github.com/jprichardson/node-fs-extra/issues/232 "Copy a folder content to its child folder. "
+[#231]: https://github.com/jprichardson/node-fs-extra/issues/231 "Adding read/write/output functions for YAML"
+[#230]: https://github.com/jprichardson/node-fs-extra/pull/230 "throw error if src and dest are the same to avoid zeroing out + test"
+[#229]: https://github.com/jprichardson/node-fs-extra/pull/229 "fix 'TypeError: callback is not a function' in emptyDir"
+[#228]: https://github.com/jprichardson/node-fs-extra/pull/228 "Throw error when target is empty so file is not accidentally zeroed out"
+[#227]: https://github.com/jprichardson/node-fs-extra/issues/227 "Uncatchable errors when there are invalid arguments [feature-move]"
+[#226]: https://github.com/jprichardson/node-fs-extra/issues/226 "Moving to the current directory"
+[#225]: https://github.com/jprichardson/node-fs-extra/issues/225 "EBUSY: resource busy or locked, unlink"
+[#224]: https://github.com/jprichardson/node-fs-extra/issues/224 "fse.copy ENOENT error"
+[#223]: https://github.com/jprichardson/node-fs-extra/issues/223 "Suspicious behavior of fs.existsSync"
+[#222]: https://github.com/jprichardson/node-fs-extra/pull/222 "A clearer description of emtpyDir function"
+[#221]: https://github.com/jprichardson/node-fs-extra/pull/221 "Update README.md"
+[#220]: https://github.com/jprichardson/node-fs-extra/pull/220 "Non-breaking feature: add option 'passStats' to copy methods."
+[#219]: https://github.com/jprichardson/node-fs-extra/pull/219 "Add closing parenthesis in copySync example"
+[#218]: https://github.com/jprichardson/node-fs-extra/pull/218 "fix #187 #70 options.filter bug"
+[#217]: https://github.com/jprichardson/node-fs-extra/pull/217 "fix #187 #70 options.filter bug"
+[#216]: https://github.com/jprichardson/node-fs-extra/pull/216 "fix #187 #70 options.filter bug"
+[#215]: https://github.com/jprichardson/node-fs-extra/pull/215 "fse.copy throws error when only src and dest provided [bug, documentation, feature-copy]"
+[#214]: https://github.com/jprichardson/node-fs-extra/pull/214 "Fixing copySync anchor tag"
+[#213]: https://github.com/jprichardson/node-fs-extra/issues/213 "Merge extfs with this repo"
+[#212]: https://github.com/jprichardson/node-fs-extra/pull/212 "Update year to 2016 in README.md and LICENSE"
+[#211]: https://github.com/jprichardson/node-fs-extra/issues/211 "Not copying all files"
+[#210]: https://github.com/jprichardson/node-fs-extra/issues/210 "copy/copySync behave differently when copying a symbolic file [bug, documentation, feature-copy]"
+[#209]: https://github.com/jprichardson/node-fs-extra/issues/209 "In Windows invalid directory name causes infinite loop in ensureDir(). [bug]"
+[#208]: https://github.com/jprichardson/node-fs-extra/pull/208 "fix options.preserveTimestamps to false in copy-sync by default [feature-copy]"
+[#207]: https://github.com/jprichardson/node-fs-extra/issues/207 "Add `compare` suite of functions"
+[#206]: https://github.com/jprichardson/node-fs-extra/issues/206 "outputFileSync"
+[#205]: https://github.com/jprichardson/node-fs-extra/issues/205 "fix documents about copy/copySync [documentation, feature-copy]"
+[#204]: https://github.com/jprichardson/node-fs-extra/pull/204 "allow copy of block and character device files"
+[#203]: https://github.com/jprichardson/node-fs-extra/issues/203 "copy method's argument options couldn't be undefined [bug, feature-copy]"
+[#202]: https://github.com/jprichardson/node-fs-extra/issues/202 "why there is not a walkSync method?"
+[#201]: https://github.com/jprichardson/node-fs-extra/issues/201 "clobber for directories [feature-copy, future]"
+[#200]: https://github.com/jprichardson/node-fs-extra/issues/200 "'copySync' doesn't work in sync"
+[#199]: https://github.com/jprichardson/node-fs-extra/issues/199 "fs.copySync fails if user does not own file [bug, feature-copy]"
+[#198]: https://github.com/jprichardson/node-fs-extra/issues/198 "handle copying between identical files [feature-copy]"
+[#197]: https://github.com/jprichardson/node-fs-extra/issues/197 "Missing documentation for `outputFile` `options` 3rd parameter [documentation]"
+[#196]: https://github.com/jprichardson/node-fs-extra/issues/196 "copy filter: async function and/or function called with `fs.stat` result [future]"
+[#195]: https://github.com/jprichardson/node-fs-extra/issues/195 "How to override with outputFile?"
+[#194]: https://github.com/jprichardson/node-fs-extra/pull/194 "allow ensureFile(Sync) to provide data to be written to created file"
+[#193]: https://github.com/jprichardson/node-fs-extra/issues/193 "`fs.copy` fails silently if source file is /dev/null [bug, feature-copy]"
+[#192]: https://github.com/jprichardson/node-fs-extra/issues/192 "Remove fs.createOutputStream()"
+[#191]: https://github.com/jprichardson/node-fs-extra/issues/191 "How to copy symlinks to target as normal folders [feature-copy]"
+[#190]: https://github.com/jprichardson/node-fs-extra/pull/190 "copySync to overwrite destination file if readonly and clobber true"
+[#189]: https://github.com/jprichardson/node-fs-extra/pull/189 "move.test fix to support CRLF on Windows"
+[#188]: https://github.com/jprichardson/node-fs-extra/issues/188 "move.test failing on windows platform"
+[#187]: https://github.com/jprichardson/node-fs-extra/issues/187 "Not filter each file, stops on first false [feature-copy]"
+[#186]: https://github.com/jprichardson/node-fs-extra/issues/186 "Do you need a .size() function in this module? [future]"
+[#185]: https://github.com/jprichardson/node-fs-extra/issues/185 "Doesn't work on NodeJS v4.x"
+[#184]: https://github.com/jprichardson/node-fs-extra/issues/184 "CLI equivalent for fs-extra"
+[#183]: https://github.com/jprichardson/node-fs-extra/issues/183 "with clobber true, copy and copySync behave differently if destination file is read only [bug, feature-copy]"
+[#182]: https://github.com/jprichardson/node-fs-extra/issues/182 "ensureDir(dir, callback) second callback parameter not specified"
+[#181]: https://github.com/jprichardson/node-fs-extra/issues/181 "Add ability to remove file securely [enhancement, wont-fix]"
+[#180]: https://github.com/jprichardson/node-fs-extra/issues/180 "Filter option doesn't work the same way in copy and copySync [bug, feature-copy]"
+[#179]: https://github.com/jprichardson/node-fs-extra/issues/179 "Include opendir"
+[#178]: https://github.com/jprichardson/node-fs-extra/issues/178 "ENOTEMPTY is thrown on removeSync "
+[#177]: https://github.com/jprichardson/node-fs-extra/issues/177 "fix `remove()` wildcards (introduced by rimraf) [feature-remove]"
+[#176]: https://github.com/jprichardson/node-fs-extra/issues/176 "createOutputStream doesn't emit 'end' event"
+[#175]: https://github.com/jprichardson/node-fs-extra/issues/175 "[Feature Request].moveSync support [feature-move, future]"
+[#174]: https://github.com/jprichardson/node-fs-extra/pull/174 "Fix copy formatting and document options.filter"
+[#173]: https://github.com/jprichardson/node-fs-extra/issues/173 "Feature Request: writeJson should mkdirs"
+[#172]: https://github.com/jprichardson/node-fs-extra/issues/172 "rename `clobber` flags to `overwrite`"
+[#171]: https://github.com/jprichardson/node-fs-extra/issues/171 "remove unnecessary aliases"
+[#170]: https://github.com/jprichardson/node-fs-extra/pull/170 "More robust handling of errors moving across virtual drives"
+[#169]: https://github.com/jprichardson/node-fs-extra/pull/169 "suppress ensureLink & ensureSymlink dest exists error"
+[#168]: https://github.com/jprichardson/node-fs-extra/pull/168 "suppress ensurelink dest exists error"
+[#167]: https://github.com/jprichardson/node-fs-extra/pull/167 "Adds basic (string, buffer) support for ensureFile content [future]"
+[#166]: https://github.com/jprichardson/node-fs-extra/pull/166 "Adds basic (string, buffer) support for ensureFile content"
+[#165]: https://github.com/jprichardson/node-fs-extra/pull/165 "ensure for link & symlink"
+[#164]: https://github.com/jprichardson/node-fs-extra/issues/164 "Feature Request: ensureFile to take optional argument for file content"
+[#163]: https://github.com/jprichardson/node-fs-extra/issues/163 "ouputJson not formatted out of the box [bug]"
+[#162]: https://github.com/jprichardson/node-fs-extra/pull/162 "ensure symlink & link"
+[#161]: https://github.com/jprichardson/node-fs-extra/pull/161 "ensure symlink & link"
+[#160]: https://github.com/jprichardson/node-fs-extra/pull/160 "ensure symlink & link"
+[#159]: https://github.com/jprichardson/node-fs-extra/pull/159 "ensure symlink & link"
+[#158]: https://github.com/jprichardson/node-fs-extra/issues/158 "Feature Request: ensureLink and ensureSymlink methods"
+[#157]: https://github.com/jprichardson/node-fs-extra/issues/157 "writeJson isn't formatted"
+[#156]: https://github.com/jprichardson/node-fs-extra/issues/156 "Promise.promisifyAll doesn't work for some methods"
+[#155]: https://github.com/jprichardson/node-fs-extra/issues/155 "Readme"
+[#154]: https://github.com/jprichardson/node-fs-extra/issues/154 "/tmp/millis-test-sync"
+[#153]: https://github.com/jprichardson/node-fs-extra/pull/153 "Make preserveTimes also work on read-only files. Closes #152"
+[#152]: https://github.com/jprichardson/node-fs-extra/issues/152 "fs.copy fails for read-only files with preserveTimestamp=true [feature-copy]"
+[#151]: https://github.com/jprichardson/node-fs-extra/issues/151 "TOC does not work correctly on npm [documentation]"
+[#150]: https://github.com/jprichardson/node-fs-extra/issues/150 "Remove test file fixtures, create with code."
+[#149]: https://github.com/jprichardson/node-fs-extra/issues/149 "/tmp/millis-test-sync"
+[#148]: https://github.com/jprichardson/node-fs-extra/issues/148 "split out `Sync` methods in documentation"
+[#147]: https://github.com/jprichardson/node-fs-extra/issues/147 "Adding rmdirIfEmpty"
+[#146]: https://github.com/jprichardson/node-fs-extra/pull/146 "ensure test.js works"
+[#145]: https://github.com/jprichardson/node-fs-extra/issues/145 "Add `fs.exists` and `fs.existsSync` if it doesn't exist."
+[#144]: https://github.com/jprichardson/node-fs-extra/issues/144 "tests failing"
+[#143]: https://github.com/jprichardson/node-fs-extra/issues/143 "update graceful-fs"
+[#142]: https://github.com/jprichardson/node-fs-extra/issues/142 "PrependFile Feature"
+[#141]: https://github.com/jprichardson/node-fs-extra/pull/141 "Add option to preserve timestamps"
+[#140]: https://github.com/jprichardson/node-fs-extra/issues/140 "Json file reading fails with 'utf8'"
+[#139]: https://github.com/jprichardson/node-fs-extra/pull/139 "Preserve file timestamp on copy. Closes #138"
+[#138]: https://github.com/jprichardson/node-fs-extra/issues/138 "Preserve timestamps on copying files"
+[#137]: https://github.com/jprichardson/node-fs-extra/issues/137 "outputFile/outputJson: Unexpected end of input"
+[#136]: https://github.com/jprichardson/node-fs-extra/pull/136 "Update license attribute"
+[#135]: https://github.com/jprichardson/node-fs-extra/issues/135 "emptyDir throws Error if no callback is provided"
+[#134]: https://github.com/jprichardson/node-fs-extra/pull/134 "Handle EEXIST error when clobbering dir"
+[#133]: https://github.com/jprichardson/node-fs-extra/pull/133 "Travis runs with `sudo: false`"
+[#132]: https://github.com/jprichardson/node-fs-extra/pull/132 "isDirectory method"
+[#131]: https://github.com/jprichardson/node-fs-extra/issues/131 "copySync is not working iojs 1.8.4 on linux [feature-copy]"
+[#130]: https://github.com/jprichardson/node-fs-extra/pull/130 "Please review additional features."
+[#129]: https://github.com/jprichardson/node-fs-extra/pull/129 "can you review this feature?"
+[#128]: https://github.com/jprichardson/node-fs-extra/issues/128 "fsExtra.move(filepath, newPath) broken;"
+[#127]: https://github.com/jprichardson/node-fs-extra/issues/127 "consider using fs.access to remove deprecated warnings for fs.exists"
+[#126]: https://github.com/jprichardson/node-fs-extra/issues/126 " TypeError: Object # has no method 'access'"
+[#125]: https://github.com/jprichardson/node-fs-extra/issues/125 "Question: What do the *Sync function do different from non-sync"
+[#124]: https://github.com/jprichardson/node-fs-extra/issues/124 "move with clobber option 'ENOTEMPTY'"
+[#123]: https://github.com/jprichardson/node-fs-extra/issues/123 "Only copy the content of a directory"
+[#122]: https://github.com/jprichardson/node-fs-extra/pull/122 "Update section links in README to match current section ids."
+[#121]: https://github.com/jprichardson/node-fs-extra/issues/121 "emptyDir is undefined"
+[#120]: https://github.com/jprichardson/node-fs-extra/issues/120 "usage bug caused by shallow cloning methods of 'graceful-fs'"
+[#119]: https://github.com/jprichardson/node-fs-extra/issues/119 "mkdirs and ensureDir never invoke callback and consume CPU indefinitely if provided a path with invalid characters on Windows"
+[#118]: https://github.com/jprichardson/node-fs-extra/pull/118 "createOutputStream"
+[#117]: https://github.com/jprichardson/node-fs-extra/pull/117 "Fixed issue with slash separated paths on windows"
+[#116]: https://github.com/jprichardson/node-fs-extra/issues/116 "copySync can only copy directories not files [documentation, feature-copy]"
+[#115]: https://github.com/jprichardson/node-fs-extra/issues/115 ".Copy & .CopySync [feature-copy]"
+[#114]: https://github.com/jprichardson/node-fs-extra/issues/114 "Fails to move (rename) directory to non-empty directory even with clobber: true"
+[#113]: https://github.com/jprichardson/node-fs-extra/issues/113 "fs.copy seems to callback early if the destination file already exists"
+[#112]: https://github.com/jprichardson/node-fs-extra/pull/112 "Copying a file into an existing directory"
+[#111]: https://github.com/jprichardson/node-fs-extra/pull/111 "Moving a file into an existing directory "
+[#110]: https://github.com/jprichardson/node-fs-extra/pull/110 "Moving a file into an existing directory"
+[#109]: https://github.com/jprichardson/node-fs-extra/issues/109 "fs.move across windows drives fails"
+[#108]: https://github.com/jprichardson/node-fs-extra/issues/108 "fse.move directories across multiple devices doesn't work"
+[#107]: https://github.com/jprichardson/node-fs-extra/pull/107 "Check if dest path is an existing dir and copy or move source in it"
+[#106]: https://github.com/jprichardson/node-fs-extra/issues/106 "fse.copySync crashes while copying across devices D: [feature-copy]"
+[#105]: https://github.com/jprichardson/node-fs-extra/issues/105 "fs.copy hangs on iojs"
+[#104]: https://github.com/jprichardson/node-fs-extra/issues/104 "fse.move deletes folders [bug]"
+[#103]: https://github.com/jprichardson/node-fs-extra/issues/103 "Error: EMFILE with copy"
+[#102]: https://github.com/jprichardson/node-fs-extra/issues/102 "touch / touchSync was removed ?"
+[#101]: https://github.com/jprichardson/node-fs-extra/issues/101 "fs-extra promisified"
+[#100]: https://github.com/jprichardson/node-fs-extra/pull/100 "copy: options object or filter to pass to ncp"
+[#99]: https://github.com/jprichardson/node-fs-extra/issues/99 "ensureDir() modes [future]"
+[#98]: https://github.com/jprichardson/node-fs-extra/issues/98 "fs.copy() incorrect async behavior [bug]"
+[#97]: https://github.com/jprichardson/node-fs-extra/pull/97 "use path.join; fix copySync bug"
+[#96]: https://github.com/jprichardson/node-fs-extra/issues/96 "destFolderExists in copySync is always undefined."
+[#95]: https://github.com/jprichardson/node-fs-extra/pull/95 "Using graceful-ncp instead of ncp"
+[#94]: https://github.com/jprichardson/node-fs-extra/issues/94 "Error: EEXIST, file already exists '../mkdirp/bin/cmd.js' on fs.copySync() [enhancement, feature-copy]"
+[#93]: https://github.com/jprichardson/node-fs-extra/issues/93 "Confusing error if drive not mounted [enhancement]"
+[#92]: https://github.com/jprichardson/node-fs-extra/issues/92 "Problems with Bluebird"
+[#91]: https://github.com/jprichardson/node-fs-extra/issues/91 "fs.copySync('/test', '/haha') is different with 'cp -r /test /haha' [enhancement]"
+[#90]: https://github.com/jprichardson/node-fs-extra/issues/90 "Folder creation and file copy is Happening in 64 bit machine but not in 32 bit machine"
+[#89]: https://github.com/jprichardson/node-fs-extra/issues/89 "Error: EEXIST using fs-extra's fs.copy to copy a directory on Windows"
+[#88]: https://github.com/jprichardson/node-fs-extra/issues/88 "Stacking those libraries"
+[#87]: https://github.com/jprichardson/node-fs-extra/issues/87 "createWriteStream + outputFile = ?"
+[#86]: https://github.com/jprichardson/node-fs-extra/issues/86 "no moveSync?"
+[#85]: https://github.com/jprichardson/node-fs-extra/pull/85 "Copy symlinks in copySync"
+[#84]: https://github.com/jprichardson/node-fs-extra/issues/84 "Push latest version to npm ?"
+[#83]: https://github.com/jprichardson/node-fs-extra/issues/83 "Prevent copying a directory into itself [feature-copy]"
+[#82]: https://github.com/jprichardson/node-fs-extra/pull/82 "README updates for move"
+[#81]: https://github.com/jprichardson/node-fs-extra/issues/81 "fd leak after fs.move"
+[#80]: https://github.com/jprichardson/node-fs-extra/pull/80 "Preserve file mode in copySync"
+[#79]: https://github.com/jprichardson/node-fs-extra/issues/79 "fs.copy only .html file empty"
+[#78]: https://github.com/jprichardson/node-fs-extra/pull/78 "copySync was not applying filters to directories"
+[#77]: https://github.com/jprichardson/node-fs-extra/issues/77 "Create README reference to bluebird"
+[#76]: https://github.com/jprichardson/node-fs-extra/issues/76 "Create README reference to typescript"
+[#75]: https://github.com/jprichardson/node-fs-extra/issues/75 "add glob as a dep? [question]"
+[#74]: https://github.com/jprichardson/node-fs-extra/pull/74 "including new emptydir module"
+[#73]: https://github.com/jprichardson/node-fs-extra/pull/73 "add dependency status in readme"
+[#72]: https://github.com/jprichardson/node-fs-extra/pull/72 "Use svg instead of png to get better image quality"
+[#71]: https://github.com/jprichardson/node-fs-extra/issues/71 "fse.copy not working on Windows 7 x64 OS, but, copySync does work"
+[#70]: https://github.com/jprichardson/node-fs-extra/issues/70 "Not filter each file, stops on first false [bug]"
+[#69]: https://github.com/jprichardson/node-fs-extra/issues/69 "How to check if folder exist and read the folder name"
+[#68]: https://github.com/jprichardson/node-fs-extra/issues/68 "consider flag to readJsonSync (throw false) [enhancement]"
+[#67]: https://github.com/jprichardson/node-fs-extra/issues/67 "docs for readJson incorrectly states that is accepts options"
+[#66]: https://github.com/jprichardson/node-fs-extra/issues/66 "ENAMETOOLONG"
+[#65]: https://github.com/jprichardson/node-fs-extra/issues/65 "exclude filter in fs.copy"
+[#64]: https://github.com/jprichardson/node-fs-extra/issues/64 "Announce: mfs - monitor your fs-extra calls"
+[#63]: https://github.com/jprichardson/node-fs-extra/issues/63 "Walk"
+[#62]: https://github.com/jprichardson/node-fs-extra/issues/62 "npm install fs-extra doesn't work"
+[#61]: https://github.com/jprichardson/node-fs-extra/issues/61 "No longer supports node 0.8 due to use of `^` in package.json dependencies"
+[#60]: https://github.com/jprichardson/node-fs-extra/issues/60 "chmod & chown for mkdirs"
+[#59]: https://github.com/jprichardson/node-fs-extra/issues/59 "Consider including mkdirp and making fs-extra '--use_strict' safe [question]"
+[#58]: https://github.com/jprichardson/node-fs-extra/issues/58 "Stack trace not included in fs.copy error"
+[#57]: https://github.com/jprichardson/node-fs-extra/issues/57 "Possible to include wildcards in delete?"
+[#56]: https://github.com/jprichardson/node-fs-extra/issues/56 "Crash when have no access to write to destination file in copy "
+[#55]: https://github.com/jprichardson/node-fs-extra/issues/55 "Is it possible to have any console output similar to Grunt copy module?"
+[#54]: https://github.com/jprichardson/node-fs-extra/issues/54 "`copy` does not preserve file ownership and permissons"
+[#53]: https://github.com/jprichardson/node-fs-extra/issues/53 "outputFile() - ability to write data in appending mode"
+[#52]: https://github.com/jprichardson/node-fs-extra/pull/52 "This fixes (what I think) is a bug in copySync"
+[#51]: https://github.com/jprichardson/node-fs-extra/pull/51 "Add a Bitdeli Badge to README"
+[#50]: https://github.com/jprichardson/node-fs-extra/issues/50 "Replace mechanism in createFile"
+[#49]: https://github.com/jprichardson/node-fs-extra/pull/49 "update rimraf to v2.2.6"
+[#48]: https://github.com/jprichardson/node-fs-extra/issues/48 "fs.copy issue [bug]"
+[#47]: https://github.com/jprichardson/node-fs-extra/issues/47 "Bug in copy - callback called on readStream 'close' - Fixed in ncp 0.5.0"
+[#46]: https://github.com/jprichardson/node-fs-extra/pull/46 "update copyright year"
+[#45]: https://github.com/jprichardson/node-fs-extra/pull/45 "Added note about fse.outputFile() being the one that overwrites"
+[#44]: https://github.com/jprichardson/node-fs-extra/pull/44 "Proposal: Stream support"
+[#43]: https://github.com/jprichardson/node-fs-extra/issues/43 "Better error reporting "
+[#42]: https://github.com/jprichardson/node-fs-extra/issues/42 "Performance issue?"
+[#41]: https://github.com/jprichardson/node-fs-extra/pull/41 "There does seem to be a synchronous version now"
+[#40]: https://github.com/jprichardson/node-fs-extra/issues/40 "fs.copy throw unexplained error ENOENT, utime "
+[#39]: https://github.com/jprichardson/node-fs-extra/pull/39 "Added regression test for copy() return callback on error"
+[#38]: https://github.com/jprichardson/node-fs-extra/pull/38 "Return err in copy() fstat cb, because stat could be undefined or null"
+[#37]: https://github.com/jprichardson/node-fs-extra/issues/37 "Maybe include a line reader? [enhancement, question]"
+[#36]: https://github.com/jprichardson/node-fs-extra/pull/36 "`filter` parameter `fs.copy` and `fs.copySync`"
+[#35]: https://github.com/jprichardson/node-fs-extra/pull/35 "`filter` parameter `fs.copy` and `fs.copySync` "
+[#34]: https://github.com/jprichardson/node-fs-extra/issues/34 "update docs to include options for JSON methods [enhancement]"
+[#33]: https://github.com/jprichardson/node-fs-extra/pull/33 "fs_extra.copySync"
+[#32]: https://github.com/jprichardson/node-fs-extra/issues/32 "update to latest jsonfile [enhancement]"
+[#31]: https://github.com/jprichardson/node-fs-extra/issues/31 "Add ensure methods [enhancement]"
+[#30]: https://github.com/jprichardson/node-fs-extra/issues/30 "update package.json optional dep `graceful-fs`"
+[#29]: https://github.com/jprichardson/node-fs-extra/issues/29 "Copy failing if dest directory doesn't exist. Is this intended?"
+[#28]: https://github.com/jprichardson/node-fs-extra/issues/28 "homepage field must be a string url. Deleted."
+[#27]: https://github.com/jprichardson/node-fs-extra/issues/27 "Update Readme"
+[#26]: https://github.com/jprichardson/node-fs-extra/issues/26 "Add readdir recursive method. [enhancement]"
+[#25]: https://github.com/jprichardson/node-fs-extra/pull/25 "adding an `.npmignore` file"
+[#24]: https://github.com/jprichardson/node-fs-extra/issues/24 "[bug] cannot run in strict mode [bug]"
+[#23]: https://github.com/jprichardson/node-fs-extra/issues/23 "`writeJSON()` should create parent directories"
+[#22]: https://github.com/jprichardson/node-fs-extra/pull/22 "Add a limit option to mkdirs()"
+[#21]: https://github.com/jprichardson/node-fs-extra/issues/21 "touch() in 0.10.0"
+[#20]: https://github.com/jprichardson/node-fs-extra/issues/20 "fs.remove yields callback before directory is really deleted"
+[#19]: https://github.com/jprichardson/node-fs-extra/issues/19 "fs.copy err is empty array"
+[#18]: https://github.com/jprichardson/node-fs-extra/pull/18 "Exposed copyFile Function"
+[#17]: https://github.com/jprichardson/node-fs-extra/issues/17 "Use `require('graceful-fs')` if found instead of `require('fs')`"
+[#16]: https://github.com/jprichardson/node-fs-extra/pull/16 "Update README.md"
+[#15]: https://github.com/jprichardson/node-fs-extra/issues/15 "Implement cp -r but sync aka copySync. [enhancement]"
+[#14]: https://github.com/jprichardson/node-fs-extra/issues/14 "fs.mkdirSync is broken in 0.3.1"
+[#13]: https://github.com/jprichardson/node-fs-extra/issues/13 "Thoughts on including a directory tree / file watcher? [enhancement, question]"
+[#12]: https://github.com/jprichardson/node-fs-extra/issues/12 "copyFile & copyFileSync are global"
+[#11]: https://github.com/jprichardson/node-fs-extra/issues/11 "Thoughts on including a file walker? [enhancement, question]"
+[#10]: https://github.com/jprichardson/node-fs-extra/issues/10 "move / moveFile API [enhancement]"
+[#9]: https://github.com/jprichardson/node-fs-extra/issues/9 "don't import normal fs stuff into fs-extra"
+[#8]: https://github.com/jprichardson/node-fs-extra/pull/8 "Update rimraf to latest version"
+[#6]: https://github.com/jprichardson/node-fs-extra/issues/6 "Remove CoffeeScript development dependency"
+[#5]: https://github.com/jprichardson/node-fs-extra/issues/5 "comments on naming"
+[#4]: https://github.com/jprichardson/node-fs-extra/issues/4 "version bump to 0.2"
+[#3]: https://github.com/jprichardson/node-fs-extra/pull/3 "Hi! I fixed some code for you!"
+[#2]: https://github.com/jprichardson/node-fs-extra/issues/2 "Merge with fs.extra and mkdirp"
+[#1]: https://github.com/jprichardson/node-fs-extra/issues/1 "file-extra npm !exist"
diff --git a/temporary_modules/trezor-connect/node_modules/fs-extra/LICENSE b/temporary_modules/trezor-connect/node_modules/fs-extra/LICENSE
new file mode 100644
index 00000000..93546dfb
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/fs-extra/LICENSE
@@ -0,0 +1,15 @@
+(The MIT License)
+
+Copyright (c) 2011-2017 JP Richardson
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files
+(the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify,
+ merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
+WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
+OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+ ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/temporary_modules/trezor-connect/node_modules/fs-extra/README.md b/temporary_modules/trezor-connect/node_modules/fs-extra/README.md
new file mode 100644
index 00000000..b4a5370b
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/fs-extra/README.md
@@ -0,0 +1,264 @@
+Node.js: fs-extra
+=================
+
+`fs-extra` adds file system methods that aren't included in the native `fs` module and adds promise support to the `fs` methods. It also uses [`graceful-fs`](https://github.com/isaacs/node-graceful-fs) to prevent `EMFILE` errors. It should be a drop in replacement for `fs`.
+
+[](https://www.npmjs.org/package/fs-extra)
+[](https://github.com/jprichardson/node-fs-extra/blob/master/LICENSE)
+[](http://travis-ci.org/jprichardson/node-fs-extra)
+[](https://ci.appveyor.com/project/jprichardson/node-fs-extra/branch/master)
+[](https://www.npmjs.org/package/fs-extra)
+[](https://coveralls.io/github/jprichardson/node-fs-extra)
+[](https://standardjs.com)
+
+Why?
+----
+
+I got tired of including `mkdirp`, `rimraf`, and `ncp` in most of my projects.
+
+
+
+
+Installation
+------------
+
+ npm install fs-extra
+
+
+
+Usage
+-----
+
+`fs-extra` is a drop in replacement for native `fs`. All methods in `fs` are attached to `fs-extra`. All `fs` methods return promises if the callback isn't passed.
+
+You don't ever need to include the original `fs` module again:
+
+```js
+const fs = require('fs') // this is no longer necessary
+```
+
+you can now do this:
+
+```js
+const fs = require('fs-extra')
+```
+
+or if you prefer to make it clear that you're using `fs-extra` and not `fs`, you may want
+to name your `fs` variable `fse` like so:
+
+```js
+const fse = require('fs-extra')
+```
+
+you can also keep both, but it's redundant:
+
+```js
+const fs = require('fs')
+const fse = require('fs-extra')
+```
+
+Sync vs Async vs Async/Await
+-------------
+Most methods are async by default. All async methods will return a promise if the callback isn't passed.
+
+Sync methods on the other hand will throw if an error occurs.
+
+Also Async/Await will throw an error if one occurs.
+
+Example:
+
+```js
+const fs = require('fs-extra')
+
+// Async with promises:
+fs.copy('/tmp/myfile', '/tmp/mynewfile')
+ .then(() => console.log('success!'))
+ .catch(err => console.error(err))
+
+// Async with callbacks:
+fs.copy('/tmp/myfile', '/tmp/mynewfile', err => {
+ if (err) return console.error(err)
+ console.log('success!')
+})
+
+// Sync:
+try {
+ fs.copySync('/tmp/myfile', '/tmp/mynewfile')
+ console.log('success!')
+} catch (err) {
+ console.error(err)
+}
+
+// Async/Await:
+async function copyFiles () {
+ try {
+ await fs.copy('/tmp/myfile', '/tmp/mynewfile')
+ console.log('success!')
+ } catch (err) {
+ console.error(err)
+ }
+}
+
+copyFiles()
+```
+
+
+Methods
+-------
+
+### Async
+
+- [copy](docs/copy.md)
+- [emptyDir](docs/emptyDir.md)
+- [ensureFile](docs/ensureFile.md)
+- [ensureDir](docs/ensureDir.md)
+- [ensureLink](docs/ensureLink.md)
+- [ensureSymlink](docs/ensureSymlink.md)
+- [mkdirp](docs/ensureDir.md)
+- [mkdirs](docs/ensureDir.md)
+- [move](docs/move.md)
+- [outputFile](docs/outputFile.md)
+- [outputJson](docs/outputJson.md)
+- [pathExists](docs/pathExists.md)
+- [readJson](docs/readJson.md)
+- [remove](docs/remove.md)
+- [writeJson](docs/writeJson.md)
+
+### Sync
+
+- [copySync](docs/copy-sync.md)
+- [emptyDirSync](docs/emptyDir-sync.md)
+- [ensureFileSync](docs/ensureFile-sync.md)
+- [ensureDirSync](docs/ensureDir-sync.md)
+- [ensureLinkSync](docs/ensureLink-sync.md)
+- [ensureSymlinkSync](docs/ensureSymlink-sync.md)
+- [mkdirpSync](docs/ensureDir-sync.md)
+- [mkdirsSync](docs/ensureDir-sync.md)
+- [moveSync](docs/move-sync.md)
+- [outputFileSync](docs/outputFile-sync.md)
+- [outputJsonSync](docs/outputJson-sync.md)
+- [pathExistsSync](docs/pathExists-sync.md)
+- [readJsonSync](docs/readJson-sync.md)
+- [removeSync](docs/remove-sync.md)
+- [writeJsonSync](docs/writeJson-sync.md)
+
+
+**NOTE:** You can still use the native Node.js methods. They are promisified and copied over to `fs-extra`. See [notes on `fs.read()`, `fs.write()`, & `fs.writev()`](docs/fs-read-write-writev.md)
+
+### What happened to `walk()` and `walkSync()`?
+
+They were removed from `fs-extra` in v2.0.0. If you need the functionality, `walk` and `walkSync` are available as separate packages, [`klaw`](https://github.com/jprichardson/node-klaw) and [`klaw-sync`](https://github.com/manidlou/node-klaw-sync).
+
+
+Third Party
+-----------
+
+### CLI
+
+[fse-cli](https://www.npmjs.com/package/@atao60/fse-cli) allows you to run `fs-extra` from a console or from [npm](https://www.npmjs.com) scripts.
+
+### TypeScript
+
+If you like TypeScript, you can use `fs-extra` with it: https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/fs-extra
+
+
+### File / Directory Watching
+
+If you want to watch for changes to files or directories, then you should use [chokidar](https://github.com/paulmillr/chokidar).
+
+### Obtain Filesystem (Devices, Partitions) Information
+
+[fs-filesystem](https://github.com/arthurintelligence/node-fs-filesystem) allows you to read the state of the filesystem of the host on which it is run. It returns information about both the devices and the partitions (volumes) of the system.
+
+### Misc.
+
+- [fs-extra-debug](https://github.com/jdxcode/fs-extra-debug) - Send your fs-extra calls to [debug](https://npmjs.org/package/debug).
+- [mfs](https://github.com/cadorn/mfs) - Monitor your fs-extra calls.
+
+
+
+Hacking on fs-extra
+-------------------
+
+Wanna hack on `fs-extra`? Great! Your help is needed! [fs-extra is one of the most depended upon Node.js packages](http://nodei.co/npm/fs-extra.png?downloads=true&downloadRank=true&stars=true). This project
+uses [JavaScript Standard Style](https://github.com/feross/standard) - if the name or style choices bother you,
+you're gonna have to get over it :) If `standard` is good enough for `npm`, it's good enough for `fs-extra`.
+
+[](https://github.com/feross/standard)
+
+What's needed?
+- First, take a look at existing issues. Those are probably going to be where the priority lies.
+- More tests for edge cases. Specifically on different platforms. There can never be enough tests.
+- Improve test coverage. See coveralls output for more info.
+
+Note: If you make any big changes, **you should definitely file an issue for discussion first.**
+
+### Running the Test Suite
+
+fs-extra contains hundreds of tests.
+
+- `npm run lint`: runs the linter ([standard](http://standardjs.com/))
+- `npm run unit`: runs the unit tests
+- `npm test`: runs both the linter and the tests
+
+
+### Windows
+
+If you run the tests on the Windows and receive a lot of symbolic link `EPERM` permission errors, it's
+because on Windows you need elevated privilege to create symbolic links. You can add this to your Windows's
+account by following the instructions here: http://superuser.com/questions/104845/permission-to-make-symbolic-links-in-windows-7
+However, I didn't have much luck doing this.
+
+Since I develop on Mac OS X, I use VMWare Fusion for Windows testing. I create a shared folder that I map to a drive on Windows.
+I open the `Node.js command prompt` and run as `Administrator`. I then map the network drive running the following command:
+
+ net use z: "\\vmware-host\Shared Folders"
+
+I can then navigate to my `fs-extra` directory and run the tests.
+
+
+Naming
+------
+
+I put a lot of thought into the naming of these functions. Inspired by @coolaj86's request. So he deserves much of the credit for raising the issue. See discussion(s) here:
+
+* https://github.com/jprichardson/node-fs-extra/issues/2
+* https://github.com/flatiron/utile/issues/11
+* https://github.com/ryanmcgrath/wrench-js/issues/29
+* https://github.com/substack/node-mkdirp/issues/17
+
+First, I believe that in as many cases as possible, the [Node.js naming schemes](http://nodejs.org/api/fs.html) should be chosen. However, there are problems with the Node.js own naming schemes.
+
+For example, `fs.readFile()` and `fs.readdir()`: the **F** is capitalized in *File* and the **d** is not capitalized in *dir*. Perhaps a bit pedantic, but they should still be consistent. Also, Node.js has chosen a lot of POSIX naming schemes, which I believe is great. See: `fs.mkdir()`, `fs.rmdir()`, `fs.chown()`, etc.
+
+We have a dilemma though. How do you consistently name methods that perform the following POSIX commands: `cp`, `cp -r`, `mkdir -p`, and `rm -rf`?
+
+My perspective: when in doubt, err on the side of simplicity. A directory is just a hierarchical grouping of directories and files. Consider that for a moment. So when you want to copy it or remove it, in most cases you'll want to copy or remove all of its contents. When you want to create a directory, if the directory that it's suppose to be contained in does not exist, then in most cases you'll want to create that too.
+
+So, if you want to remove a file or a directory regardless of whether it has contents, just call `fs.remove(path)`. If you want to copy a file or a directory whether it has contents, just call `fs.copy(source, destination)`. If you want to create a directory regardless of whether its parent directories exist, just call `fs.mkdirs(path)` or `fs.mkdirp(path)`.
+
+
+Credit
+------
+
+`fs-extra` wouldn't be possible without using the modules from the following authors:
+
+- [Isaac Shlueter](https://github.com/isaacs)
+- [Charlie McConnel](https://github.com/avianflu)
+- [James Halliday](https://github.com/substack)
+- [Andrew Kelley](https://github.com/andrewrk)
+
+
+
+
+License
+-------
+
+Licensed under MIT
+
+Copyright (c) 2011-2017 [JP Richardson](https://github.com/jprichardson)
+
+[1]: http://nodejs.org/docs/latest/api/fs.html
+
+
+[jsonfile]: https://github.com/jprichardson/node-jsonfile
diff --git a/temporary_modules/trezor-connect/node_modules/fs-extra/lib/copy-sync/copy-sync.js b/temporary_modules/trezor-connect/node_modules/fs-extra/lib/copy-sync/copy-sync.js
new file mode 100644
index 00000000..31f06e44
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/fs-extra/lib/copy-sync/copy-sync.js
@@ -0,0 +1,166 @@
+'use strict'
+
+const fs = require('graceful-fs')
+const path = require('path')
+const mkdirsSync = require('../mkdirs').mkdirsSync
+const utimesMillisSync = require('../util/utimes').utimesMillisSync
+const stat = require('../util/stat')
+
+function copySync (src, dest, opts) {
+ if (typeof opts === 'function') {
+ opts = { filter: opts }
+ }
+
+ opts = opts || {}
+ opts.clobber = 'clobber' in opts ? !!opts.clobber : true // default to true for now
+ opts.overwrite = 'overwrite' in opts ? !!opts.overwrite : opts.clobber // overwrite falls back to clobber
+
+ // Warn about using preserveTimestamps on 32-bit node
+ if (opts.preserveTimestamps && process.arch === 'ia32') {
+ console.warn(`fs-extra: Using the preserveTimestamps option in 32-bit node is not recommended;\n
+ see https://github.com/jprichardson/node-fs-extra/issues/269`)
+ }
+
+ const { srcStat, destStat } = stat.checkPathsSync(src, dest, 'copy')
+ stat.checkParentPathsSync(src, srcStat, dest, 'copy')
+ return handleFilterAndCopy(destStat, src, dest, opts)
+}
+
+function handleFilterAndCopy (destStat, src, dest, opts) {
+ if (opts.filter && !opts.filter(src, dest)) return
+ const destParent = path.dirname(dest)
+ if (!fs.existsSync(destParent)) mkdirsSync(destParent)
+ return startCopy(destStat, src, dest, opts)
+}
+
+function startCopy (destStat, src, dest, opts) {
+ if (opts.filter && !opts.filter(src, dest)) return
+ return getStats(destStat, src, dest, opts)
+}
+
+function getStats (destStat, src, dest, opts) {
+ const statSync = opts.dereference ? fs.statSync : fs.lstatSync
+ const srcStat = statSync(src)
+
+ if (srcStat.isDirectory()) return onDir(srcStat, destStat, src, dest, opts)
+ else if (srcStat.isFile() ||
+ srcStat.isCharacterDevice() ||
+ srcStat.isBlockDevice()) return onFile(srcStat, destStat, src, dest, opts)
+ else if (srcStat.isSymbolicLink()) return onLink(destStat, src, dest, opts)
+}
+
+function onFile (srcStat, destStat, src, dest, opts) {
+ if (!destStat) return copyFile(srcStat, src, dest, opts)
+ return mayCopyFile(srcStat, src, dest, opts)
+}
+
+function mayCopyFile (srcStat, src, dest, opts) {
+ if (opts.overwrite) {
+ fs.unlinkSync(dest)
+ return copyFile(srcStat, src, dest, opts)
+ } else if (opts.errorOnExist) {
+ throw new Error(`'${dest}' already exists`)
+ }
+}
+
+function copyFile (srcStat, src, dest, opts) {
+ fs.copyFileSync(src, dest)
+ if (opts.preserveTimestamps) handleTimestamps(srcStat.mode, src, dest)
+ return setDestMode(dest, srcStat.mode)
+}
+
+function handleTimestamps (srcMode, src, dest) {
+ // Make sure the file is writable before setting the timestamp
+ // otherwise open fails with EPERM when invoked with 'r+'
+ // (through utimes call)
+ if (fileIsNotWritable(srcMode)) makeFileWritable(dest, srcMode)
+ return setDestTimestamps(src, dest)
+}
+
+function fileIsNotWritable (srcMode) {
+ return (srcMode & 0o200) === 0
+}
+
+function makeFileWritable (dest, srcMode) {
+ return setDestMode(dest, srcMode | 0o200)
+}
+
+function setDestMode (dest, srcMode) {
+ return fs.chmodSync(dest, srcMode)
+}
+
+function setDestTimestamps (src, dest) {
+ // The initial srcStat.atime cannot be trusted
+ // because it is modified by the read(2) system call
+ // (See https://nodejs.org/api/fs.html#fs_stat_time_values)
+ const updatedSrcStat = fs.statSync(src)
+ return utimesMillisSync(dest, updatedSrcStat.atime, updatedSrcStat.mtime)
+}
+
+function onDir (srcStat, destStat, src, dest, opts) {
+ if (!destStat) return mkDirAndCopy(srcStat.mode, src, dest, opts)
+ if (destStat && !destStat.isDirectory()) {
+ throw new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`)
+ }
+ return copyDir(src, dest, opts)
+}
+
+function mkDirAndCopy (srcMode, src, dest, opts) {
+ fs.mkdirSync(dest)
+ copyDir(src, dest, opts)
+ return setDestMode(dest, srcMode)
+}
+
+function copyDir (src, dest, opts) {
+ fs.readdirSync(src).forEach(item => copyDirItem(item, src, dest, opts))
+}
+
+function copyDirItem (item, src, dest, opts) {
+ const srcItem = path.join(src, item)
+ const destItem = path.join(dest, item)
+ const { destStat } = stat.checkPathsSync(srcItem, destItem, 'copy')
+ return startCopy(destStat, srcItem, destItem, opts)
+}
+
+function onLink (destStat, src, dest, opts) {
+ let resolvedSrc = fs.readlinkSync(src)
+ if (opts.dereference) {
+ resolvedSrc = path.resolve(process.cwd(), resolvedSrc)
+ }
+
+ if (!destStat) {
+ return fs.symlinkSync(resolvedSrc, dest)
+ } else {
+ let resolvedDest
+ try {
+ resolvedDest = fs.readlinkSync(dest)
+ } catch (err) {
+ // dest exists and is a regular file or directory,
+ // Windows may throw UNKNOWN error. If dest already exists,
+ // fs throws error anyway, so no need to guard against it here.
+ if (err.code === 'EINVAL' || err.code === 'UNKNOWN') return fs.symlinkSync(resolvedSrc, dest)
+ throw err
+ }
+ if (opts.dereference) {
+ resolvedDest = path.resolve(process.cwd(), resolvedDest)
+ }
+ if (stat.isSrcSubdir(resolvedSrc, resolvedDest)) {
+ throw new Error(`Cannot copy '${resolvedSrc}' to a subdirectory of itself, '${resolvedDest}'.`)
+ }
+
+ // prevent copy if src is a subdir of dest since unlinking
+ // dest in this case would result in removing src contents
+ // and therefore a broken symlink would be created.
+ if (fs.statSync(dest).isDirectory() && stat.isSrcSubdir(resolvedDest, resolvedSrc)) {
+ throw new Error(`Cannot overwrite '${resolvedDest}' with '${resolvedSrc}'.`)
+ }
+ return copyLink(resolvedSrc, dest)
+ }
+}
+
+function copyLink (resolvedSrc, dest) {
+ fs.unlinkSync(dest)
+ return fs.symlinkSync(resolvedSrc, dest)
+}
+
+module.exports = copySync
diff --git a/temporary_modules/trezor-connect/node_modules/fs-extra/lib/copy-sync/index.js b/temporary_modules/trezor-connect/node_modules/fs-extra/lib/copy-sync/index.js
new file mode 100644
index 00000000..65945aed
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/fs-extra/lib/copy-sync/index.js
@@ -0,0 +1,5 @@
+'use strict'
+
+module.exports = {
+ copySync: require('./copy-sync')
+}
diff --git a/temporary_modules/trezor-connect/node_modules/fs-extra/lib/copy/copy.js b/temporary_modules/trezor-connect/node_modules/fs-extra/lib/copy/copy.js
new file mode 100644
index 00000000..328f1025
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/fs-extra/lib/copy/copy.js
@@ -0,0 +1,232 @@
+'use strict'
+
+const fs = require('graceful-fs')
+const path = require('path')
+const mkdirs = require('../mkdirs').mkdirs
+const pathExists = require('../path-exists').pathExists
+const utimesMillis = require('../util/utimes').utimesMillis
+const stat = require('../util/stat')
+
+function copy (src, dest, opts, cb) {
+ if (typeof opts === 'function' && !cb) {
+ cb = opts
+ opts = {}
+ } else if (typeof opts === 'function') {
+ opts = { filter: opts }
+ }
+
+ cb = cb || function () {}
+ opts = opts || {}
+
+ opts.clobber = 'clobber' in opts ? !!opts.clobber : true // default to true for now
+ opts.overwrite = 'overwrite' in opts ? !!opts.overwrite : opts.clobber // overwrite falls back to clobber
+
+ // Warn about using preserveTimestamps on 32-bit node
+ if (opts.preserveTimestamps && process.arch === 'ia32') {
+ console.warn(`fs-extra: Using the preserveTimestamps option in 32-bit node is not recommended;\n
+ see https://github.com/jprichardson/node-fs-extra/issues/269`)
+ }
+
+ stat.checkPaths(src, dest, 'copy', (err, stats) => {
+ if (err) return cb(err)
+ const { srcStat, destStat } = stats
+ stat.checkParentPaths(src, srcStat, dest, 'copy', err => {
+ if (err) return cb(err)
+ if (opts.filter) return handleFilter(checkParentDir, destStat, src, dest, opts, cb)
+ return checkParentDir(destStat, src, dest, opts, cb)
+ })
+ })
+}
+
+function checkParentDir (destStat, src, dest, opts, cb) {
+ const destParent = path.dirname(dest)
+ pathExists(destParent, (err, dirExists) => {
+ if (err) return cb(err)
+ if (dirExists) return startCopy(destStat, src, dest, opts, cb)
+ mkdirs(destParent, err => {
+ if (err) return cb(err)
+ return startCopy(destStat, src, dest, opts, cb)
+ })
+ })
+}
+
+function handleFilter (onInclude, destStat, src, dest, opts, cb) {
+ Promise.resolve(opts.filter(src, dest)).then(include => {
+ if (include) return onInclude(destStat, src, dest, opts, cb)
+ return cb()
+ }, error => cb(error))
+}
+
+function startCopy (destStat, src, dest, opts, cb) {
+ if (opts.filter) return handleFilter(getStats, destStat, src, dest, opts, cb)
+ return getStats(destStat, src, dest, opts, cb)
+}
+
+function getStats (destStat, src, dest, opts, cb) {
+ const stat = opts.dereference ? fs.stat : fs.lstat
+ stat(src, (err, srcStat) => {
+ if (err) return cb(err)
+
+ if (srcStat.isDirectory()) return onDir(srcStat, destStat, src, dest, opts, cb)
+ else if (srcStat.isFile() ||
+ srcStat.isCharacterDevice() ||
+ srcStat.isBlockDevice()) return onFile(srcStat, destStat, src, dest, opts, cb)
+ else if (srcStat.isSymbolicLink()) return onLink(destStat, src, dest, opts, cb)
+ })
+}
+
+function onFile (srcStat, destStat, src, dest, opts, cb) {
+ if (!destStat) return copyFile(srcStat, src, dest, opts, cb)
+ return mayCopyFile(srcStat, src, dest, opts, cb)
+}
+
+function mayCopyFile (srcStat, src, dest, opts, cb) {
+ if (opts.overwrite) {
+ fs.unlink(dest, err => {
+ if (err) return cb(err)
+ return copyFile(srcStat, src, dest, opts, cb)
+ })
+ } else if (opts.errorOnExist) {
+ return cb(new Error(`'${dest}' already exists`))
+ } else return cb()
+}
+
+function copyFile (srcStat, src, dest, opts, cb) {
+ fs.copyFile(src, dest, err => {
+ if (err) return cb(err)
+ if (opts.preserveTimestamps) return handleTimestampsAndMode(srcStat.mode, src, dest, cb)
+ return setDestMode(dest, srcStat.mode, cb)
+ })
+}
+
+function handleTimestampsAndMode (srcMode, src, dest, cb) {
+ // Make sure the file is writable before setting the timestamp
+ // otherwise open fails with EPERM when invoked with 'r+'
+ // (through utimes call)
+ if (fileIsNotWritable(srcMode)) {
+ return makeFileWritable(dest, srcMode, err => {
+ if (err) return cb(err)
+ return setDestTimestampsAndMode(srcMode, src, dest, cb)
+ })
+ }
+ return setDestTimestampsAndMode(srcMode, src, dest, cb)
+}
+
+function fileIsNotWritable (srcMode) {
+ return (srcMode & 0o200) === 0
+}
+
+function makeFileWritable (dest, srcMode, cb) {
+ return setDestMode(dest, srcMode | 0o200, cb)
+}
+
+function setDestTimestampsAndMode (srcMode, src, dest, cb) {
+ setDestTimestamps(src, dest, err => {
+ if (err) return cb(err)
+ return setDestMode(dest, srcMode, cb)
+ })
+}
+
+function setDestMode (dest, srcMode, cb) {
+ return fs.chmod(dest, srcMode, cb)
+}
+
+function setDestTimestamps (src, dest, cb) {
+ // The initial srcStat.atime cannot be trusted
+ // because it is modified by the read(2) system call
+ // (See https://nodejs.org/api/fs.html#fs_stat_time_values)
+ fs.stat(src, (err, updatedSrcStat) => {
+ if (err) return cb(err)
+ return utimesMillis(dest, updatedSrcStat.atime, updatedSrcStat.mtime, cb)
+ })
+}
+
+function onDir (srcStat, destStat, src, dest, opts, cb) {
+ if (!destStat) return mkDirAndCopy(srcStat.mode, src, dest, opts, cb)
+ if (destStat && !destStat.isDirectory()) {
+ return cb(new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`))
+ }
+ return copyDir(src, dest, opts, cb)
+}
+
+function mkDirAndCopy (srcMode, src, dest, opts, cb) {
+ fs.mkdir(dest, err => {
+ if (err) return cb(err)
+ copyDir(src, dest, opts, err => {
+ if (err) return cb(err)
+ return setDestMode(dest, srcMode, cb)
+ })
+ })
+}
+
+function copyDir (src, dest, opts, cb) {
+ fs.readdir(src, (err, items) => {
+ if (err) return cb(err)
+ return copyDirItems(items, src, dest, opts, cb)
+ })
+}
+
+function copyDirItems (items, src, dest, opts, cb) {
+ const item = items.pop()
+ if (!item) return cb()
+ return copyDirItem(items, item, src, dest, opts, cb)
+}
+
+function copyDirItem (items, item, src, dest, opts, cb) {
+ const srcItem = path.join(src, item)
+ const destItem = path.join(dest, item)
+ stat.checkPaths(srcItem, destItem, 'copy', (err, stats) => {
+ if (err) return cb(err)
+ const { destStat } = stats
+ startCopy(destStat, srcItem, destItem, opts, err => {
+ if (err) return cb(err)
+ return copyDirItems(items, src, dest, opts, cb)
+ })
+ })
+}
+
+function onLink (destStat, src, dest, opts, cb) {
+ fs.readlink(src, (err, resolvedSrc) => {
+ if (err) return cb(err)
+ if (opts.dereference) {
+ resolvedSrc = path.resolve(process.cwd(), resolvedSrc)
+ }
+
+ if (!destStat) {
+ return fs.symlink(resolvedSrc, dest, cb)
+ } else {
+ fs.readlink(dest, (err, resolvedDest) => {
+ if (err) {
+ // dest exists and is a regular file or directory,
+ // Windows may throw UNKNOWN error. If dest already exists,
+ // fs throws error anyway, so no need to guard against it here.
+ if (err.code === 'EINVAL' || err.code === 'UNKNOWN') return fs.symlink(resolvedSrc, dest, cb)
+ return cb(err)
+ }
+ if (opts.dereference) {
+ resolvedDest = path.resolve(process.cwd(), resolvedDest)
+ }
+ if (stat.isSrcSubdir(resolvedSrc, resolvedDest)) {
+ return cb(new Error(`Cannot copy '${resolvedSrc}' to a subdirectory of itself, '${resolvedDest}'.`))
+ }
+
+ // do not copy if src is a subdir of dest since unlinking
+ // dest in this case would result in removing src contents
+ // and therefore a broken symlink would be created.
+ if (destStat.isDirectory() && stat.isSrcSubdir(resolvedDest, resolvedSrc)) {
+ return cb(new Error(`Cannot overwrite '${resolvedDest}' with '${resolvedSrc}'.`))
+ }
+ return copyLink(resolvedSrc, dest, cb)
+ })
+ }
+ })
+}
+
+function copyLink (resolvedSrc, dest, cb) {
+ fs.unlink(dest, err => {
+ if (err) return cb(err)
+ return fs.symlink(resolvedSrc, dest, cb)
+ })
+}
+
+module.exports = copy
diff --git a/temporary_modules/trezor-connect/node_modules/fs-extra/lib/copy/index.js b/temporary_modules/trezor-connect/node_modules/fs-extra/lib/copy/index.js
new file mode 100644
index 00000000..b7e4f7f8
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/fs-extra/lib/copy/index.js
@@ -0,0 +1,6 @@
+'use strict'
+
+const u = require('universalify').fromCallback
+module.exports = {
+ copy: u(require('./copy'))
+}
diff --git a/temporary_modules/trezor-connect/node_modules/fs-extra/lib/empty/index.js b/temporary_modules/trezor-connect/node_modules/fs-extra/lib/empty/index.js
new file mode 100644
index 00000000..90fb4699
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/fs-extra/lib/empty/index.js
@@ -0,0 +1,48 @@
+'use strict'
+
+const u = require('universalify').fromCallback
+const fs = require('graceful-fs')
+const path = require('path')
+const mkdir = require('../mkdirs')
+const remove = require('../remove')
+
+const emptyDir = u(function emptyDir (dir, callback) {
+ callback = callback || function () {}
+ fs.readdir(dir, (err, items) => {
+ if (err) return mkdir.mkdirs(dir, callback)
+
+ items = items.map(item => path.join(dir, item))
+
+ deleteItem()
+
+ function deleteItem () {
+ const item = items.pop()
+ if (!item) return callback()
+ remove.remove(item, err => {
+ if (err) return callback(err)
+ deleteItem()
+ })
+ }
+ })
+})
+
+function emptyDirSync (dir) {
+ let items
+ try {
+ items = fs.readdirSync(dir)
+ } catch {
+ return mkdir.mkdirsSync(dir)
+ }
+
+ items.forEach(item => {
+ item = path.join(dir, item)
+ remove.removeSync(item)
+ })
+}
+
+module.exports = {
+ emptyDirSync,
+ emptydirSync: emptyDirSync,
+ emptyDir,
+ emptydir: emptyDir
+}
diff --git a/temporary_modules/trezor-connect/node_modules/fs-extra/lib/ensure/file.js b/temporary_modules/trezor-connect/node_modules/fs-extra/lib/ensure/file.js
new file mode 100644
index 00000000..15cc473c
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/fs-extra/lib/ensure/file.js
@@ -0,0 +1,69 @@
+'use strict'
+
+const u = require('universalify').fromCallback
+const path = require('path')
+const fs = require('graceful-fs')
+const mkdir = require('../mkdirs')
+
+function createFile (file, callback) {
+ function makeFile () {
+ fs.writeFile(file, '', err => {
+ if (err) return callback(err)
+ callback()
+ })
+ }
+
+ fs.stat(file, (err, stats) => { // eslint-disable-line handle-callback-err
+ if (!err && stats.isFile()) return callback()
+ const dir = path.dirname(file)
+ fs.stat(dir, (err, stats) => {
+ if (err) {
+ // if the directory doesn't exist, make it
+ if (err.code === 'ENOENT') {
+ return mkdir.mkdirs(dir, err => {
+ if (err) return callback(err)
+ makeFile()
+ })
+ }
+ return callback(err)
+ }
+
+ if (stats.isDirectory()) makeFile()
+ else {
+ // parent is not a directory
+ // This is just to cause an internal ENOTDIR error to be thrown
+ fs.readdir(dir, err => {
+ if (err) return callback(err)
+ })
+ }
+ })
+ })
+}
+
+function createFileSync (file) {
+ let stats
+ try {
+ stats = fs.statSync(file)
+ } catch {}
+ if (stats && stats.isFile()) return
+
+ const dir = path.dirname(file)
+ try {
+ if (!fs.statSync(dir).isDirectory()) {
+ // parent is not a directory
+ // This is just to cause an internal ENOTDIR error to be thrown
+ fs.readdirSync(dir)
+ }
+ } catch (err) {
+ // If the stat call above failed because the directory doesn't exist, create it
+ if (err && err.code === 'ENOENT') mkdir.mkdirsSync(dir)
+ else throw err
+ }
+
+ fs.writeFileSync(file, '')
+}
+
+module.exports = {
+ createFile: u(createFile),
+ createFileSync
+}
diff --git a/temporary_modules/trezor-connect/node_modules/fs-extra/lib/ensure/index.js b/temporary_modules/trezor-connect/node_modules/fs-extra/lib/ensure/index.js
new file mode 100644
index 00000000..c1f67b71
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/fs-extra/lib/ensure/index.js
@@ -0,0 +1,23 @@
+'use strict'
+
+const file = require('./file')
+const link = require('./link')
+const symlink = require('./symlink')
+
+module.exports = {
+ // file
+ createFile: file.createFile,
+ createFileSync: file.createFileSync,
+ ensureFile: file.createFile,
+ ensureFileSync: file.createFileSync,
+ // link
+ createLink: link.createLink,
+ createLinkSync: link.createLinkSync,
+ ensureLink: link.createLink,
+ ensureLinkSync: link.createLinkSync,
+ // symlink
+ createSymlink: symlink.createSymlink,
+ createSymlinkSync: symlink.createSymlinkSync,
+ ensureSymlink: symlink.createSymlink,
+ ensureSymlinkSync: symlink.createSymlinkSync
+}
diff --git a/temporary_modules/trezor-connect/node_modules/fs-extra/lib/ensure/link.js b/temporary_modules/trezor-connect/node_modules/fs-extra/lib/ensure/link.js
new file mode 100644
index 00000000..2cd41962
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/fs-extra/lib/ensure/link.js
@@ -0,0 +1,61 @@
+'use strict'
+
+const u = require('universalify').fromCallback
+const path = require('path')
+const fs = require('graceful-fs')
+const mkdir = require('../mkdirs')
+const pathExists = require('../path-exists').pathExists
+
+function createLink (srcpath, dstpath, callback) {
+ function makeLink (srcpath, dstpath) {
+ fs.link(srcpath, dstpath, err => {
+ if (err) return callback(err)
+ callback(null)
+ })
+ }
+
+ pathExists(dstpath, (err, destinationExists) => {
+ if (err) return callback(err)
+ if (destinationExists) return callback(null)
+ fs.lstat(srcpath, (err) => {
+ if (err) {
+ err.message = err.message.replace('lstat', 'ensureLink')
+ return callback(err)
+ }
+
+ const dir = path.dirname(dstpath)
+ pathExists(dir, (err, dirExists) => {
+ if (err) return callback(err)
+ if (dirExists) return makeLink(srcpath, dstpath)
+ mkdir.mkdirs(dir, err => {
+ if (err) return callback(err)
+ makeLink(srcpath, dstpath)
+ })
+ })
+ })
+ })
+}
+
+function createLinkSync (srcpath, dstpath) {
+ const destinationExists = fs.existsSync(dstpath)
+ if (destinationExists) return undefined
+
+ try {
+ fs.lstatSync(srcpath)
+ } catch (err) {
+ err.message = err.message.replace('lstat', 'ensureLink')
+ throw err
+ }
+
+ const dir = path.dirname(dstpath)
+ const dirExists = fs.existsSync(dir)
+ if (dirExists) return fs.linkSync(srcpath, dstpath)
+ mkdir.mkdirsSync(dir)
+
+ return fs.linkSync(srcpath, dstpath)
+}
+
+module.exports = {
+ createLink: u(createLink),
+ createLinkSync
+}
diff --git a/temporary_modules/trezor-connect/node_modules/fs-extra/lib/ensure/symlink-paths.js b/temporary_modules/trezor-connect/node_modules/fs-extra/lib/ensure/symlink-paths.js
new file mode 100644
index 00000000..33cd7600
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/fs-extra/lib/ensure/symlink-paths.js
@@ -0,0 +1,99 @@
+'use strict'
+
+const path = require('path')
+const fs = require('graceful-fs')
+const pathExists = require('../path-exists').pathExists
+
+/**
+ * Function that returns two types of paths, one relative to symlink, and one
+ * relative to the current working directory. Checks if path is absolute or
+ * relative. If the path is relative, this function checks if the path is
+ * relative to symlink or relative to current working directory. This is an
+ * initiative to find a smarter `srcpath` to supply when building symlinks.
+ * This allows you to determine which path to use out of one of three possible
+ * types of source paths. The first is an absolute path. This is detected by
+ * `path.isAbsolute()`. When an absolute path is provided, it is checked to
+ * see if it exists. If it does it's used, if not an error is returned
+ * (callback)/ thrown (sync). The other two options for `srcpath` are a
+ * relative url. By default Node's `fs.symlink` works by creating a symlink
+ * using `dstpath` and expects the `srcpath` to be relative to the newly
+ * created symlink. If you provide a `srcpath` that does not exist on the file
+ * system it results in a broken symlink. To minimize this, the function
+ * checks to see if the 'relative to symlink' source file exists, and if it
+ * does it will use it. If it does not, it checks if there's a file that
+ * exists that is relative to the current working directory, if does its used.
+ * This preserves the expectations of the original fs.symlink spec and adds
+ * the ability to pass in `relative to current working direcotry` paths.
+ */
+
+function symlinkPaths (srcpath, dstpath, callback) {
+ if (path.isAbsolute(srcpath)) {
+ return fs.lstat(srcpath, (err) => {
+ if (err) {
+ err.message = err.message.replace('lstat', 'ensureSymlink')
+ return callback(err)
+ }
+ return callback(null, {
+ toCwd: srcpath,
+ toDst: srcpath
+ })
+ })
+ } else {
+ const dstdir = path.dirname(dstpath)
+ const relativeToDst = path.join(dstdir, srcpath)
+ return pathExists(relativeToDst, (err, exists) => {
+ if (err) return callback(err)
+ if (exists) {
+ return callback(null, {
+ toCwd: relativeToDst,
+ toDst: srcpath
+ })
+ } else {
+ return fs.lstat(srcpath, (err) => {
+ if (err) {
+ err.message = err.message.replace('lstat', 'ensureSymlink')
+ return callback(err)
+ }
+ return callback(null, {
+ toCwd: srcpath,
+ toDst: path.relative(dstdir, srcpath)
+ })
+ })
+ }
+ })
+ }
+}
+
+function symlinkPathsSync (srcpath, dstpath) {
+ let exists
+ if (path.isAbsolute(srcpath)) {
+ exists = fs.existsSync(srcpath)
+ if (!exists) throw new Error('absolute srcpath does not exist')
+ return {
+ toCwd: srcpath,
+ toDst: srcpath
+ }
+ } else {
+ const dstdir = path.dirname(dstpath)
+ const relativeToDst = path.join(dstdir, srcpath)
+ exists = fs.existsSync(relativeToDst)
+ if (exists) {
+ return {
+ toCwd: relativeToDst,
+ toDst: srcpath
+ }
+ } else {
+ exists = fs.existsSync(srcpath)
+ if (!exists) throw new Error('relative srcpath does not exist')
+ return {
+ toCwd: srcpath,
+ toDst: path.relative(dstdir, srcpath)
+ }
+ }
+ }
+}
+
+module.exports = {
+ symlinkPaths,
+ symlinkPathsSync
+}
diff --git a/temporary_modules/trezor-connect/node_modules/fs-extra/lib/ensure/symlink-type.js b/temporary_modules/trezor-connect/node_modules/fs-extra/lib/ensure/symlink-type.js
new file mode 100644
index 00000000..42dc0ce7
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/fs-extra/lib/ensure/symlink-type.js
@@ -0,0 +1,31 @@
+'use strict'
+
+const fs = require('graceful-fs')
+
+function symlinkType (srcpath, type, callback) {
+ callback = (typeof type === 'function') ? type : callback
+ type = (typeof type === 'function') ? false : type
+ if (type) return callback(null, type)
+ fs.lstat(srcpath, (err, stats) => {
+ if (err) return callback(null, 'file')
+ type = (stats && stats.isDirectory()) ? 'dir' : 'file'
+ callback(null, type)
+ })
+}
+
+function symlinkTypeSync (srcpath, type) {
+ let stats
+
+ if (type) return type
+ try {
+ stats = fs.lstatSync(srcpath)
+ } catch {
+ return 'file'
+ }
+ return (stats && stats.isDirectory()) ? 'dir' : 'file'
+}
+
+module.exports = {
+ symlinkType,
+ symlinkTypeSync
+}
diff --git a/temporary_modules/trezor-connect/node_modules/fs-extra/lib/ensure/symlink.js b/temporary_modules/trezor-connect/node_modules/fs-extra/lib/ensure/symlink.js
new file mode 100644
index 00000000..fe68b799
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/fs-extra/lib/ensure/symlink.js
@@ -0,0 +1,63 @@
+'use strict'
+
+const u = require('universalify').fromCallback
+const path = require('path')
+const fs = require('graceful-fs')
+const _mkdirs = require('../mkdirs')
+const mkdirs = _mkdirs.mkdirs
+const mkdirsSync = _mkdirs.mkdirsSync
+
+const _symlinkPaths = require('./symlink-paths')
+const symlinkPaths = _symlinkPaths.symlinkPaths
+const symlinkPathsSync = _symlinkPaths.symlinkPathsSync
+
+const _symlinkType = require('./symlink-type')
+const symlinkType = _symlinkType.symlinkType
+const symlinkTypeSync = _symlinkType.symlinkTypeSync
+
+const pathExists = require('../path-exists').pathExists
+
+function createSymlink (srcpath, dstpath, type, callback) {
+ callback = (typeof type === 'function') ? type : callback
+ type = (typeof type === 'function') ? false : type
+
+ pathExists(dstpath, (err, destinationExists) => {
+ if (err) return callback(err)
+ if (destinationExists) return callback(null)
+ symlinkPaths(srcpath, dstpath, (err, relative) => {
+ if (err) return callback(err)
+ srcpath = relative.toDst
+ symlinkType(relative.toCwd, type, (err, type) => {
+ if (err) return callback(err)
+ const dir = path.dirname(dstpath)
+ pathExists(dir, (err, dirExists) => {
+ if (err) return callback(err)
+ if (dirExists) return fs.symlink(srcpath, dstpath, type, callback)
+ mkdirs(dir, err => {
+ if (err) return callback(err)
+ fs.symlink(srcpath, dstpath, type, callback)
+ })
+ })
+ })
+ })
+ })
+}
+
+function createSymlinkSync (srcpath, dstpath, type) {
+ const destinationExists = fs.existsSync(dstpath)
+ if (destinationExists) return undefined
+
+ const relative = symlinkPathsSync(srcpath, dstpath)
+ srcpath = relative.toDst
+ type = symlinkTypeSync(relative.toCwd, type)
+ const dir = path.dirname(dstpath)
+ const exists = fs.existsSync(dir)
+ if (exists) return fs.symlinkSync(srcpath, dstpath, type)
+ mkdirsSync(dir)
+ return fs.symlinkSync(srcpath, dstpath, type)
+}
+
+module.exports = {
+ createSymlink: u(createSymlink),
+ createSymlinkSync
+}
diff --git a/temporary_modules/trezor-connect/node_modules/fs-extra/lib/fs/index.js b/temporary_modules/trezor-connect/node_modules/fs-extra/lib/fs/index.js
new file mode 100644
index 00000000..9bbaea4e
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/fs-extra/lib/fs/index.js
@@ -0,0 +1,130 @@
+'use strict'
+// This is adapted from https://github.com/normalize/mz
+// Copyright (c) 2014-2016 Jonathan Ong me@jongleberry.com and Contributors
+const u = require('universalify').fromCallback
+const fs = require('graceful-fs')
+
+const api = [
+ 'access',
+ 'appendFile',
+ 'chmod',
+ 'chown',
+ 'close',
+ 'copyFile',
+ 'fchmod',
+ 'fchown',
+ 'fdatasync',
+ 'fstat',
+ 'fsync',
+ 'ftruncate',
+ 'futimes',
+ 'lchmod',
+ 'lchown',
+ 'link',
+ 'lstat',
+ 'mkdir',
+ 'mkdtemp',
+ 'open',
+ 'opendir',
+ 'readdir',
+ 'readFile',
+ 'readlink',
+ 'realpath',
+ 'rename',
+ 'rm',
+ 'rmdir',
+ 'stat',
+ 'symlink',
+ 'truncate',
+ 'unlink',
+ 'utimes',
+ 'writeFile'
+].filter(key => {
+ // Some commands are not available on some systems. Ex:
+ // fs.opendir was added in Node.js v12.12.0
+ // fs.rm was added in Node.js v14.14.0
+ // fs.lchown is not available on at least some Linux
+ return typeof fs[key] === 'function'
+})
+
+// Export all keys:
+Object.keys(fs).forEach(key => {
+ if (key === 'promises') {
+ // fs.promises is a getter property that triggers ExperimentalWarning
+ // Don't re-export it here, the getter is defined in "lib/index.js"
+ return
+ }
+ exports[key] = fs[key]
+})
+
+// Universalify async methods:
+api.forEach(method => {
+ exports[method] = u(fs[method])
+})
+
+// We differ from mz/fs in that we still ship the old, broken, fs.exists()
+// since we are a drop-in replacement for the native module
+exports.exists = function (filename, callback) {
+ if (typeof callback === 'function') {
+ return fs.exists(filename, callback)
+ }
+ return new Promise(resolve => {
+ return fs.exists(filename, resolve)
+ })
+}
+
+// fs.read(), fs.write(), & fs.writev() need special treatment due to multiple callback args
+
+exports.read = function (fd, buffer, offset, length, position, callback) {
+ if (typeof callback === 'function') {
+ return fs.read(fd, buffer, offset, length, position, callback)
+ }
+ return new Promise((resolve, reject) => {
+ fs.read(fd, buffer, offset, length, position, (err, bytesRead, buffer) => {
+ if (err) return reject(err)
+ resolve({ bytesRead, buffer })
+ })
+ })
+}
+
+// Function signature can be
+// fs.write(fd, buffer[, offset[, length[, position]]], callback)
+// OR
+// fs.write(fd, string[, position[, encoding]], callback)
+// We need to handle both cases, so we use ...args
+exports.write = function (fd, buffer, ...args) {
+ if (typeof args[args.length - 1] === 'function') {
+ return fs.write(fd, buffer, ...args)
+ }
+
+ return new Promise((resolve, reject) => {
+ fs.write(fd, buffer, ...args, (err, bytesWritten, buffer) => {
+ if (err) return reject(err)
+ resolve({ bytesWritten, buffer })
+ })
+ })
+}
+
+// fs.writev only available in Node v12.9.0+
+if (typeof fs.writev === 'function') {
+ // Function signature is
+ // s.writev(fd, buffers[, position], callback)
+ // We need to handle the optional arg, so we use ...args
+ exports.writev = function (fd, buffers, ...args) {
+ if (typeof args[args.length - 1] === 'function') {
+ return fs.writev(fd, buffers, ...args)
+ }
+
+ return new Promise((resolve, reject) => {
+ fs.writev(fd, buffers, ...args, (err, bytesWritten, buffers) => {
+ if (err) return reject(err)
+ resolve({ bytesWritten, buffers })
+ })
+ })
+ }
+}
+
+// fs.realpath.native only available in Node v9.2+
+if (typeof fs.realpath.native === 'function') {
+ exports.realpath.native = u(fs.realpath.native)
+}
diff --git a/temporary_modules/trezor-connect/node_modules/fs-extra/lib/index.js b/temporary_modules/trezor-connect/node_modules/fs-extra/lib/index.js
new file mode 100644
index 00000000..d9468e69
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/fs-extra/lib/index.js
@@ -0,0 +1,27 @@
+'use strict'
+
+module.exports = {
+ // Export promiseified graceful-fs:
+ ...require('./fs'),
+ // Export extra methods:
+ ...require('./copy-sync'),
+ ...require('./copy'),
+ ...require('./empty'),
+ ...require('./ensure'),
+ ...require('./json'),
+ ...require('./mkdirs'),
+ ...require('./move-sync'),
+ ...require('./move'),
+ ...require('./output'),
+ ...require('./path-exists'),
+ ...require('./remove')
+}
+
+// Export fs.promises as a getter property so that we don't trigger
+// ExperimentalWarning before fs.promises is actually accessed.
+const fs = require('fs')
+if (Object.getOwnPropertyDescriptor(fs, 'promises')) {
+ Object.defineProperty(module.exports, 'promises', {
+ get () { return fs.promises }
+ })
+}
diff --git a/temporary_modules/trezor-connect/node_modules/fs-extra/lib/json/index.js b/temporary_modules/trezor-connect/node_modules/fs-extra/lib/json/index.js
new file mode 100644
index 00000000..900126ad
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/fs-extra/lib/json/index.js
@@ -0,0 +1,16 @@
+'use strict'
+
+const u = require('universalify').fromPromise
+const jsonFile = require('./jsonfile')
+
+jsonFile.outputJson = u(require('./output-json'))
+jsonFile.outputJsonSync = require('./output-json-sync')
+// aliases
+jsonFile.outputJSON = jsonFile.outputJson
+jsonFile.outputJSONSync = jsonFile.outputJsonSync
+jsonFile.writeJSON = jsonFile.writeJson
+jsonFile.writeJSONSync = jsonFile.writeJsonSync
+jsonFile.readJSON = jsonFile.readJson
+jsonFile.readJSONSync = jsonFile.readJsonSync
+
+module.exports = jsonFile
diff --git a/temporary_modules/trezor-connect/node_modules/fs-extra/lib/json/jsonfile.js b/temporary_modules/trezor-connect/node_modules/fs-extra/lib/json/jsonfile.js
new file mode 100644
index 00000000..f11d34d6
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/fs-extra/lib/json/jsonfile.js
@@ -0,0 +1,11 @@
+'use strict'
+
+const jsonFile = require('jsonfile')
+
+module.exports = {
+ // jsonfile exports
+ readJson: jsonFile.readFile,
+ readJsonSync: jsonFile.readFileSync,
+ writeJson: jsonFile.writeFile,
+ writeJsonSync: jsonFile.writeFileSync
+}
diff --git a/temporary_modules/trezor-connect/node_modules/fs-extra/lib/json/output-json-sync.js b/temporary_modules/trezor-connect/node_modules/fs-extra/lib/json/output-json-sync.js
new file mode 100644
index 00000000..f76b4744
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/fs-extra/lib/json/output-json-sync.js
@@ -0,0 +1,12 @@
+'use strict'
+
+const { stringify } = require('jsonfile/utils')
+const { outputFileSync } = require('../output')
+
+function outputJsonSync (file, data, options) {
+ const str = stringify(data, options)
+
+ outputFileSync(file, str, options)
+}
+
+module.exports = outputJsonSync
diff --git a/temporary_modules/trezor-connect/node_modules/fs-extra/lib/json/output-json.js b/temporary_modules/trezor-connect/node_modules/fs-extra/lib/json/output-json.js
new file mode 100644
index 00000000..0fc66897
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/fs-extra/lib/json/output-json.js
@@ -0,0 +1,12 @@
+'use strict'
+
+const { stringify } = require('jsonfile/utils')
+const { outputFile } = require('../output')
+
+async function outputJson (file, data, options = {}) {
+ const str = stringify(data, options)
+
+ await outputFile(file, str, options)
+}
+
+module.exports = outputJson
diff --git a/temporary_modules/trezor-connect/node_modules/fs-extra/lib/mkdirs/index.js b/temporary_modules/trezor-connect/node_modules/fs-extra/lib/mkdirs/index.js
new file mode 100644
index 00000000..9edecee0
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/fs-extra/lib/mkdirs/index.js
@@ -0,0 +1,14 @@
+'use strict'
+const u = require('universalify').fromPromise
+const { makeDir: _makeDir, makeDirSync } = require('./make-dir')
+const makeDir = u(_makeDir)
+
+module.exports = {
+ mkdirs: makeDir,
+ mkdirsSync: makeDirSync,
+ // alias
+ mkdirp: makeDir,
+ mkdirpSync: makeDirSync,
+ ensureDir: makeDir,
+ ensureDirSync: makeDirSync
+}
diff --git a/temporary_modules/trezor-connect/node_modules/fs-extra/lib/mkdirs/make-dir.js b/temporary_modules/trezor-connect/node_modules/fs-extra/lib/mkdirs/make-dir.js
new file mode 100644
index 00000000..3e7e8360
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/fs-extra/lib/mkdirs/make-dir.js
@@ -0,0 +1,141 @@
+// Adapted from https://github.com/sindresorhus/make-dir
+// Copyright (c) Sindre Sorhus (sindresorhus.com)
+// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+'use strict'
+const fs = require('../fs')
+const path = require('path')
+const atLeastNode = require('at-least-node')
+
+const useNativeRecursiveOption = atLeastNode('10.12.0')
+
+// https://github.com/nodejs/node/issues/8987
+// https://github.com/libuv/libuv/pull/1088
+const checkPath = pth => {
+ if (process.platform === 'win32') {
+ const pathHasInvalidWinCharacters = /[<>:"|?*]/.test(pth.replace(path.parse(pth).root, ''))
+
+ if (pathHasInvalidWinCharacters) {
+ const error = new Error(`Path contains invalid characters: ${pth}`)
+ error.code = 'EINVAL'
+ throw error
+ }
+ }
+}
+
+const processOptions = options => {
+ const defaults = { mode: 0o777 }
+ if (typeof options === 'number') options = { mode: options }
+ return { ...defaults, ...options }
+}
+
+const permissionError = pth => {
+ // This replicates the exception of `fs.mkdir` with native the
+ // `recusive` option when run on an invalid drive under Windows.
+ const error = new Error(`operation not permitted, mkdir '${pth}'`)
+ error.code = 'EPERM'
+ error.errno = -4048
+ error.path = pth
+ error.syscall = 'mkdir'
+ return error
+}
+
+module.exports.makeDir = async (input, options) => {
+ checkPath(input)
+ options = processOptions(options)
+
+ if (useNativeRecursiveOption) {
+ const pth = path.resolve(input)
+
+ return fs.mkdir(pth, {
+ mode: options.mode,
+ recursive: true
+ })
+ }
+
+ const make = async pth => {
+ try {
+ await fs.mkdir(pth, options.mode)
+ } catch (error) {
+ if (error.code === 'EPERM') {
+ throw error
+ }
+
+ if (error.code === 'ENOENT') {
+ if (path.dirname(pth) === pth) {
+ throw permissionError(pth)
+ }
+
+ if (error.message.includes('null bytes')) {
+ throw error
+ }
+
+ await make(path.dirname(pth))
+ return make(pth)
+ }
+
+ try {
+ const stats = await fs.stat(pth)
+ if (!stats.isDirectory()) {
+ // This error is never exposed to the user
+ // it is caught below, and the original error is thrown
+ throw new Error('The path is not a directory')
+ }
+ } catch {
+ throw error
+ }
+ }
+ }
+
+ return make(path.resolve(input))
+}
+
+module.exports.makeDirSync = (input, options) => {
+ checkPath(input)
+ options = processOptions(options)
+
+ if (useNativeRecursiveOption) {
+ const pth = path.resolve(input)
+
+ return fs.mkdirSync(pth, {
+ mode: options.mode,
+ recursive: true
+ })
+ }
+
+ const make = pth => {
+ try {
+ fs.mkdirSync(pth, options.mode)
+ } catch (error) {
+ if (error.code === 'EPERM') {
+ throw error
+ }
+
+ if (error.code === 'ENOENT') {
+ if (path.dirname(pth) === pth) {
+ throw permissionError(pth)
+ }
+
+ if (error.message.includes('null bytes')) {
+ throw error
+ }
+
+ make(path.dirname(pth))
+ return make(pth)
+ }
+
+ try {
+ if (!fs.statSync(pth).isDirectory()) {
+ // This error is never exposed to the user
+ // it is caught below, and the original error is thrown
+ throw new Error('The path is not a directory')
+ }
+ } catch {
+ throw error
+ }
+ }
+ }
+
+ return make(path.resolve(input))
+}
diff --git a/temporary_modules/trezor-connect/node_modules/fs-extra/lib/move-sync/index.js b/temporary_modules/trezor-connect/node_modules/fs-extra/lib/move-sync/index.js
new file mode 100644
index 00000000..af90b06b
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/fs-extra/lib/move-sync/index.js
@@ -0,0 +1,5 @@
+'use strict'
+
+module.exports = {
+ moveSync: require('./move-sync')
+}
diff --git a/temporary_modules/trezor-connect/node_modules/fs-extra/lib/move-sync/move-sync.js b/temporary_modules/trezor-connect/node_modules/fs-extra/lib/move-sync/move-sync.js
new file mode 100644
index 00000000..20f910cc
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/fs-extra/lib/move-sync/move-sync.js
@@ -0,0 +1,47 @@
+'use strict'
+
+const fs = require('graceful-fs')
+const path = require('path')
+const copySync = require('../copy-sync').copySync
+const removeSync = require('../remove').removeSync
+const mkdirpSync = require('../mkdirs').mkdirpSync
+const stat = require('../util/stat')
+
+function moveSync (src, dest, opts) {
+ opts = opts || {}
+ const overwrite = opts.overwrite || opts.clobber || false
+
+ const { srcStat } = stat.checkPathsSync(src, dest, 'move')
+ stat.checkParentPathsSync(src, srcStat, dest, 'move')
+ mkdirpSync(path.dirname(dest))
+ return doRename(src, dest, overwrite)
+}
+
+function doRename (src, dest, overwrite) {
+ if (overwrite) {
+ removeSync(dest)
+ return rename(src, dest, overwrite)
+ }
+ if (fs.existsSync(dest)) throw new Error('dest already exists.')
+ return rename(src, dest, overwrite)
+}
+
+function rename (src, dest, overwrite) {
+ try {
+ fs.renameSync(src, dest)
+ } catch (err) {
+ if (err.code !== 'EXDEV') throw err
+ return moveAcrossDevice(src, dest, overwrite)
+ }
+}
+
+function moveAcrossDevice (src, dest, overwrite) {
+ const opts = {
+ overwrite,
+ errorOnExist: true
+ }
+ copySync(src, dest, opts)
+ return removeSync(src)
+}
+
+module.exports = moveSync
diff --git a/temporary_modules/trezor-connect/node_modules/fs-extra/lib/move/index.js b/temporary_modules/trezor-connect/node_modules/fs-extra/lib/move/index.js
new file mode 100644
index 00000000..3785345b
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/fs-extra/lib/move/index.js
@@ -0,0 +1,6 @@
+'use strict'
+
+const u = require('universalify').fromCallback
+module.exports = {
+ move: u(require('./move'))
+}
diff --git a/temporary_modules/trezor-connect/node_modules/fs-extra/lib/move/move.js b/temporary_modules/trezor-connect/node_modules/fs-extra/lib/move/move.js
new file mode 100644
index 00000000..fa3ea618
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/fs-extra/lib/move/move.js
@@ -0,0 +1,65 @@
+'use strict'
+
+const fs = require('graceful-fs')
+const path = require('path')
+const copy = require('../copy').copy
+const remove = require('../remove').remove
+const mkdirp = require('../mkdirs').mkdirp
+const pathExists = require('../path-exists').pathExists
+const stat = require('../util/stat')
+
+function move (src, dest, opts, cb) {
+ if (typeof opts === 'function') {
+ cb = opts
+ opts = {}
+ }
+
+ const overwrite = opts.overwrite || opts.clobber || false
+
+ stat.checkPaths(src, dest, 'move', (err, stats) => {
+ if (err) return cb(err)
+ const { srcStat } = stats
+ stat.checkParentPaths(src, srcStat, dest, 'move', err => {
+ if (err) return cb(err)
+ mkdirp(path.dirname(dest), err => {
+ if (err) return cb(err)
+ return doRename(src, dest, overwrite, cb)
+ })
+ })
+ })
+}
+
+function doRename (src, dest, overwrite, cb) {
+ if (overwrite) {
+ return remove(dest, err => {
+ if (err) return cb(err)
+ return rename(src, dest, overwrite, cb)
+ })
+ }
+ pathExists(dest, (err, destExists) => {
+ if (err) return cb(err)
+ if (destExists) return cb(new Error('dest already exists.'))
+ return rename(src, dest, overwrite, cb)
+ })
+}
+
+function rename (src, dest, overwrite, cb) {
+ fs.rename(src, dest, err => {
+ if (!err) return cb()
+ if (err.code !== 'EXDEV') return cb(err)
+ return moveAcrossDevice(src, dest, overwrite, cb)
+ })
+}
+
+function moveAcrossDevice (src, dest, overwrite, cb) {
+ const opts = {
+ overwrite,
+ errorOnExist: true
+ }
+ copy(src, dest, opts, err => {
+ if (err) return cb(err)
+ return remove(src, cb)
+ })
+}
+
+module.exports = move
diff --git a/temporary_modules/trezor-connect/node_modules/fs-extra/lib/output/index.js b/temporary_modules/trezor-connect/node_modules/fs-extra/lib/output/index.js
new file mode 100644
index 00000000..92297ca3
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/fs-extra/lib/output/index.js
@@ -0,0 +1,40 @@
+'use strict'
+
+const u = require('universalify').fromCallback
+const fs = require('graceful-fs')
+const path = require('path')
+const mkdir = require('../mkdirs')
+const pathExists = require('../path-exists').pathExists
+
+function outputFile (file, data, encoding, callback) {
+ if (typeof encoding === 'function') {
+ callback = encoding
+ encoding = 'utf8'
+ }
+
+ const dir = path.dirname(file)
+ pathExists(dir, (err, itDoes) => {
+ if (err) return callback(err)
+ if (itDoes) return fs.writeFile(file, data, encoding, callback)
+
+ mkdir.mkdirs(dir, err => {
+ if (err) return callback(err)
+
+ fs.writeFile(file, data, encoding, callback)
+ })
+ })
+}
+
+function outputFileSync (file, ...args) {
+ const dir = path.dirname(file)
+ if (fs.existsSync(dir)) {
+ return fs.writeFileSync(file, ...args)
+ }
+ mkdir.mkdirsSync(dir)
+ fs.writeFileSync(file, ...args)
+}
+
+module.exports = {
+ outputFile: u(outputFile),
+ outputFileSync
+}
diff --git a/temporary_modules/trezor-connect/node_modules/fs-extra/lib/path-exists/index.js b/temporary_modules/trezor-connect/node_modules/fs-extra/lib/path-exists/index.js
new file mode 100644
index 00000000..ddd9bc71
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/fs-extra/lib/path-exists/index.js
@@ -0,0 +1,12 @@
+'use strict'
+const u = require('universalify').fromPromise
+const fs = require('../fs')
+
+function pathExists (path) {
+ return fs.access(path).then(() => true).catch(() => false)
+}
+
+module.exports = {
+ pathExists: u(pathExists),
+ pathExistsSync: fs.existsSync
+}
diff --git a/temporary_modules/trezor-connect/node_modules/fs-extra/lib/remove/index.js b/temporary_modules/trezor-connect/node_modules/fs-extra/lib/remove/index.js
new file mode 100644
index 00000000..cee53400
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/fs-extra/lib/remove/index.js
@@ -0,0 +1,9 @@
+'use strict'
+
+const u = require('universalify').fromCallback
+const rimraf = require('./rimraf')
+
+module.exports = {
+ remove: u(rimraf),
+ removeSync: rimraf.sync
+}
diff --git a/temporary_modules/trezor-connect/node_modules/fs-extra/lib/remove/rimraf.js b/temporary_modules/trezor-connect/node_modules/fs-extra/lib/remove/rimraf.js
new file mode 100644
index 00000000..2c771026
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/fs-extra/lib/remove/rimraf.js
@@ -0,0 +1,302 @@
+'use strict'
+
+const fs = require('graceful-fs')
+const path = require('path')
+const assert = require('assert')
+
+const isWindows = (process.platform === 'win32')
+
+function defaults (options) {
+ const methods = [
+ 'unlink',
+ 'chmod',
+ 'stat',
+ 'lstat',
+ 'rmdir',
+ 'readdir'
+ ]
+ methods.forEach(m => {
+ options[m] = options[m] || fs[m]
+ m = m + 'Sync'
+ options[m] = options[m] || fs[m]
+ })
+
+ options.maxBusyTries = options.maxBusyTries || 3
+}
+
+function rimraf (p, options, cb) {
+ let busyTries = 0
+
+ if (typeof options === 'function') {
+ cb = options
+ options = {}
+ }
+
+ assert(p, 'rimraf: missing path')
+ assert.strictEqual(typeof p, 'string', 'rimraf: path should be a string')
+ assert.strictEqual(typeof cb, 'function', 'rimraf: callback function required')
+ assert(options, 'rimraf: invalid options argument provided')
+ assert.strictEqual(typeof options, 'object', 'rimraf: options should be object')
+
+ defaults(options)
+
+ rimraf_(p, options, function CB (er) {
+ if (er) {
+ if ((er.code === 'EBUSY' || er.code === 'ENOTEMPTY' || er.code === 'EPERM') &&
+ busyTries < options.maxBusyTries) {
+ busyTries++
+ const time = busyTries * 100
+ // try again, with the same exact callback as this one.
+ return setTimeout(() => rimraf_(p, options, CB), time)
+ }
+
+ // already gone
+ if (er.code === 'ENOENT') er = null
+ }
+
+ cb(er)
+ })
+}
+
+// Two possible strategies.
+// 1. Assume it's a file. unlink it, then do the dir stuff on EPERM or EISDIR
+// 2. Assume it's a directory. readdir, then do the file stuff on ENOTDIR
+//
+// Both result in an extra syscall when you guess wrong. However, there
+// are likely far more normal files in the world than directories. This
+// is based on the assumption that a the average number of files per
+// directory is >= 1.
+//
+// If anyone ever complains about this, then I guess the strategy could
+// be made configurable somehow. But until then, YAGNI.
+function rimraf_ (p, options, cb) {
+ assert(p)
+ assert(options)
+ assert(typeof cb === 'function')
+
+ // sunos lets the root user unlink directories, which is... weird.
+ // so we have to lstat here and make sure it's not a dir.
+ options.lstat(p, (er, st) => {
+ if (er && er.code === 'ENOENT') {
+ return cb(null)
+ }
+
+ // Windows can EPERM on stat. Life is suffering.
+ if (er && er.code === 'EPERM' && isWindows) {
+ return fixWinEPERM(p, options, er, cb)
+ }
+
+ if (st && st.isDirectory()) {
+ return rmdir(p, options, er, cb)
+ }
+
+ options.unlink(p, er => {
+ if (er) {
+ if (er.code === 'ENOENT') {
+ return cb(null)
+ }
+ if (er.code === 'EPERM') {
+ return (isWindows)
+ ? fixWinEPERM(p, options, er, cb)
+ : rmdir(p, options, er, cb)
+ }
+ if (er.code === 'EISDIR') {
+ return rmdir(p, options, er, cb)
+ }
+ }
+ return cb(er)
+ })
+ })
+}
+
+function fixWinEPERM (p, options, er, cb) {
+ assert(p)
+ assert(options)
+ assert(typeof cb === 'function')
+
+ options.chmod(p, 0o666, er2 => {
+ if (er2) {
+ cb(er2.code === 'ENOENT' ? null : er)
+ } else {
+ options.stat(p, (er3, stats) => {
+ if (er3) {
+ cb(er3.code === 'ENOENT' ? null : er)
+ } else if (stats.isDirectory()) {
+ rmdir(p, options, er, cb)
+ } else {
+ options.unlink(p, cb)
+ }
+ })
+ }
+ })
+}
+
+function fixWinEPERMSync (p, options, er) {
+ let stats
+
+ assert(p)
+ assert(options)
+
+ try {
+ options.chmodSync(p, 0o666)
+ } catch (er2) {
+ if (er2.code === 'ENOENT') {
+ return
+ } else {
+ throw er
+ }
+ }
+
+ try {
+ stats = options.statSync(p)
+ } catch (er3) {
+ if (er3.code === 'ENOENT') {
+ return
+ } else {
+ throw er
+ }
+ }
+
+ if (stats.isDirectory()) {
+ rmdirSync(p, options, er)
+ } else {
+ options.unlinkSync(p)
+ }
+}
+
+function rmdir (p, options, originalEr, cb) {
+ assert(p)
+ assert(options)
+ assert(typeof cb === 'function')
+
+ // try to rmdir first, and only readdir on ENOTEMPTY or EEXIST (SunOS)
+ // if we guessed wrong, and it's not a directory, then
+ // raise the original error.
+ options.rmdir(p, er => {
+ if (er && (er.code === 'ENOTEMPTY' || er.code === 'EEXIST' || er.code === 'EPERM')) {
+ rmkids(p, options, cb)
+ } else if (er && er.code === 'ENOTDIR') {
+ cb(originalEr)
+ } else {
+ cb(er)
+ }
+ })
+}
+
+function rmkids (p, options, cb) {
+ assert(p)
+ assert(options)
+ assert(typeof cb === 'function')
+
+ options.readdir(p, (er, files) => {
+ if (er) return cb(er)
+
+ let n = files.length
+ let errState
+
+ if (n === 0) return options.rmdir(p, cb)
+
+ files.forEach(f => {
+ rimraf(path.join(p, f), options, er => {
+ if (errState) {
+ return
+ }
+ if (er) return cb(errState = er)
+ if (--n === 0) {
+ options.rmdir(p, cb)
+ }
+ })
+ })
+ })
+}
+
+// this looks simpler, and is strictly *faster*, but will
+// tie up the JavaScript thread and fail on excessively
+// deep directory trees.
+function rimrafSync (p, options) {
+ let st
+
+ options = options || {}
+ defaults(options)
+
+ assert(p, 'rimraf: missing path')
+ assert.strictEqual(typeof p, 'string', 'rimraf: path should be a string')
+ assert(options, 'rimraf: missing options')
+ assert.strictEqual(typeof options, 'object', 'rimraf: options should be object')
+
+ try {
+ st = options.lstatSync(p)
+ } catch (er) {
+ if (er.code === 'ENOENT') {
+ return
+ }
+
+ // Windows can EPERM on stat. Life is suffering.
+ if (er.code === 'EPERM' && isWindows) {
+ fixWinEPERMSync(p, options, er)
+ }
+ }
+
+ try {
+ // sunos lets the root user unlink directories, which is... weird.
+ if (st && st.isDirectory()) {
+ rmdirSync(p, options, null)
+ } else {
+ options.unlinkSync(p)
+ }
+ } catch (er) {
+ if (er.code === 'ENOENT') {
+ return
+ } else if (er.code === 'EPERM') {
+ return isWindows ? fixWinEPERMSync(p, options, er) : rmdirSync(p, options, er)
+ } else if (er.code !== 'EISDIR') {
+ throw er
+ }
+ rmdirSync(p, options, er)
+ }
+}
+
+function rmdirSync (p, options, originalEr) {
+ assert(p)
+ assert(options)
+
+ try {
+ options.rmdirSync(p)
+ } catch (er) {
+ if (er.code === 'ENOTDIR') {
+ throw originalEr
+ } else if (er.code === 'ENOTEMPTY' || er.code === 'EEXIST' || er.code === 'EPERM') {
+ rmkidsSync(p, options)
+ } else if (er.code !== 'ENOENT') {
+ throw er
+ }
+ }
+}
+
+function rmkidsSync (p, options) {
+ assert(p)
+ assert(options)
+ options.readdirSync(p).forEach(f => rimrafSync(path.join(p, f), options))
+
+ if (isWindows) {
+ // We only end up here once we got ENOTEMPTY at least once, and
+ // at this point, we are guaranteed to have removed all the kids.
+ // So, we know that it won't be ENOENT or ENOTDIR or anything else.
+ // try really hard to delete stuff on windows, because it has a
+ // PROFOUNDLY annoying habit of not closing handles promptly when
+ // files are deleted, resulting in spurious ENOTEMPTY errors.
+ const startTime = Date.now()
+ do {
+ try {
+ const ret = options.rmdirSync(p, options)
+ return ret
+ } catch {}
+ } while (Date.now() - startTime < 500) // give up after 500ms
+ } else {
+ const ret = options.rmdirSync(p, options)
+ return ret
+ }
+}
+
+module.exports = rimraf
+rimraf.sync = rimrafSync
diff --git a/temporary_modules/trezor-connect/node_modules/fs-extra/lib/util/stat.js b/temporary_modules/trezor-connect/node_modules/fs-extra/lib/util/stat.js
new file mode 100644
index 00000000..0b1c1b09
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/fs-extra/lib/util/stat.js
@@ -0,0 +1,139 @@
+'use strict'
+
+const fs = require('../fs')
+const path = require('path')
+const util = require('util')
+const atLeastNode = require('at-least-node')
+
+const nodeSupportsBigInt = atLeastNode('10.5.0')
+const stat = (file) => nodeSupportsBigInt ? fs.stat(file, { bigint: true }) : fs.stat(file)
+const statSync = (file) => nodeSupportsBigInt ? fs.statSync(file, { bigint: true }) : fs.statSync(file)
+
+function getStats (src, dest) {
+ return Promise.all([
+ stat(src),
+ stat(dest).catch(err => {
+ if (err.code === 'ENOENT') return null
+ throw err
+ })
+ ]).then(([srcStat, destStat]) => ({ srcStat, destStat }))
+}
+
+function getStatsSync (src, dest) {
+ let destStat
+ const srcStat = statSync(src)
+ try {
+ destStat = statSync(dest)
+ } catch (err) {
+ if (err.code === 'ENOENT') return { srcStat, destStat: null }
+ throw err
+ }
+ return { srcStat, destStat }
+}
+
+function checkPaths (src, dest, funcName, cb) {
+ util.callbackify(getStats)(src, dest, (err, stats) => {
+ if (err) return cb(err)
+ const { srcStat, destStat } = stats
+ if (destStat && areIdentical(srcStat, destStat)) {
+ return cb(new Error('Source and destination must not be the same.'))
+ }
+ if (srcStat.isDirectory() && isSrcSubdir(src, dest)) {
+ return cb(new Error(errMsg(src, dest, funcName)))
+ }
+ return cb(null, { srcStat, destStat })
+ })
+}
+
+function checkPathsSync (src, dest, funcName) {
+ const { srcStat, destStat } = getStatsSync(src, dest)
+ if (destStat && areIdentical(srcStat, destStat)) {
+ throw new Error('Source and destination must not be the same.')
+ }
+ if (srcStat.isDirectory() && isSrcSubdir(src, dest)) {
+ throw new Error(errMsg(src, dest, funcName))
+ }
+ return { srcStat, destStat }
+}
+
+// recursively check if dest parent is a subdirectory of src.
+// It works for all file types including symlinks since it
+// checks the src and dest inodes. It starts from the deepest
+// parent and stops once it reaches the src parent or the root path.
+function checkParentPaths (src, srcStat, dest, funcName, cb) {
+ const srcParent = path.resolve(path.dirname(src))
+ const destParent = path.resolve(path.dirname(dest))
+ if (destParent === srcParent || destParent === path.parse(destParent).root) return cb()
+ const callback = (err, destStat) => {
+ if (err) {
+ if (err.code === 'ENOENT') return cb()
+ return cb(err)
+ }
+ if (areIdentical(srcStat, destStat)) {
+ return cb(new Error(errMsg(src, dest, funcName)))
+ }
+ return checkParentPaths(src, srcStat, destParent, funcName, cb)
+ }
+ if (nodeSupportsBigInt) fs.stat(destParent, { bigint: true }, callback)
+ else fs.stat(destParent, callback)
+}
+
+function checkParentPathsSync (src, srcStat, dest, funcName) {
+ const srcParent = path.resolve(path.dirname(src))
+ const destParent = path.resolve(path.dirname(dest))
+ if (destParent === srcParent || destParent === path.parse(destParent).root) return
+ let destStat
+ try {
+ destStat = statSync(destParent)
+ } catch (err) {
+ if (err.code === 'ENOENT') return
+ throw err
+ }
+ if (areIdentical(srcStat, destStat)) {
+ throw new Error(errMsg(src, dest, funcName))
+ }
+ return checkParentPathsSync(src, srcStat, destParent, funcName)
+}
+
+function areIdentical (srcStat, destStat) {
+ if (destStat.ino && destStat.dev && destStat.ino === srcStat.ino && destStat.dev === srcStat.dev) {
+ if (nodeSupportsBigInt || destStat.ino < Number.MAX_SAFE_INTEGER) {
+ // definitive answer
+ return true
+ }
+ // Use additional heuristics if we can't use 'bigint'.
+ // Different 'ino' could be represented the same if they are >= Number.MAX_SAFE_INTEGER
+ // See issue 657
+ if (destStat.size === srcStat.size &&
+ destStat.mode === srcStat.mode &&
+ destStat.nlink === srcStat.nlink &&
+ destStat.atimeMs === srcStat.atimeMs &&
+ destStat.mtimeMs === srcStat.mtimeMs &&
+ destStat.ctimeMs === srcStat.ctimeMs &&
+ destStat.birthtimeMs === srcStat.birthtimeMs) {
+ // heuristic answer
+ return true
+ }
+ }
+ return false
+}
+
+// return true if dest is a subdir of src, otherwise false.
+// It only checks the path strings.
+function isSrcSubdir (src, dest) {
+ const srcArr = path.resolve(src).split(path.sep).filter(i => i)
+ const destArr = path.resolve(dest).split(path.sep).filter(i => i)
+ return srcArr.reduce((acc, cur, i) => acc && destArr[i] === cur, true)
+}
+
+function errMsg (src, dest, funcName) {
+ return `Cannot ${funcName} '${src}' to a subdirectory of itself, '${dest}'.`
+}
+
+module.exports = {
+ checkPaths,
+ checkPathsSync,
+ checkParentPaths,
+ checkParentPathsSync,
+ isSrcSubdir
+}
diff --git a/temporary_modules/trezor-connect/node_modules/fs-extra/lib/util/utimes.js b/temporary_modules/trezor-connect/node_modules/fs-extra/lib/util/utimes.js
new file mode 100644
index 00000000..75395def
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/fs-extra/lib/util/utimes.js
@@ -0,0 +1,26 @@
+'use strict'
+
+const fs = require('graceful-fs')
+
+function utimesMillis (path, atime, mtime, callback) {
+ // if (!HAS_MILLIS_RES) return fs.utimes(path, atime, mtime, callback)
+ fs.open(path, 'r+', (err, fd) => {
+ if (err) return callback(err)
+ fs.futimes(fd, atime, mtime, futimesErr => {
+ fs.close(fd, closeErr => {
+ if (callback) callback(futimesErr || closeErr)
+ })
+ })
+ })
+}
+
+function utimesMillisSync (path, atime, mtime) {
+ const fd = fs.openSync(path, 'r+')
+ fs.futimesSync(fd, atime, mtime)
+ return fs.closeSync(fd)
+}
+
+module.exports = {
+ utimesMillis,
+ utimesMillisSync
+}
diff --git a/temporary_modules/trezor-connect/node_modules/fs-extra/package.json b/temporary_modules/trezor-connect/node_modules/fs-extra/package.json
new file mode 100644
index 00000000..6f7d8ddb
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/fs-extra/package.json
@@ -0,0 +1,70 @@
+{
+ "name": "fs-extra",
+ "version": "9.1.0",
+ "description": "fs-extra contains methods that aren't included in the vanilla Node.js fs package. Such as recursive mkdir, copy, and remove.",
+ "engines": {
+ "node": ">=10"
+ },
+ "homepage": "https://github.com/jprichardson/node-fs-extra",
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/jprichardson/node-fs-extra"
+ },
+ "keywords": [
+ "fs",
+ "file",
+ "file system",
+ "copy",
+ "directory",
+ "extra",
+ "mkdirp",
+ "mkdir",
+ "mkdirs",
+ "recursive",
+ "json",
+ "read",
+ "write",
+ "extra",
+ "delete",
+ "remove",
+ "touch",
+ "create",
+ "text",
+ "output",
+ "move",
+ "promise"
+ ],
+ "author": "JP Richardson ",
+ "license": "MIT",
+ "dependencies": {
+ "at-least-node": "^1.0.0",
+ "graceful-fs": "^4.2.0",
+ "jsonfile": "^6.0.1",
+ "universalify": "^2.0.0"
+ },
+ "devDependencies": {
+ "coveralls": "^3.0.0",
+ "klaw": "^2.1.1",
+ "klaw-sync": "^3.0.2",
+ "minimist": "^1.1.1",
+ "mocha": "^5.0.5",
+ "nyc": "^15.0.0",
+ "proxyquire": "^2.0.1",
+ "read-dir-files": "^0.1.1",
+ "standard": "^14.1.0"
+ },
+ "main": "./lib/index.js",
+ "files": [
+ "lib/",
+ "!lib/**/__tests__/"
+ ],
+ "scripts": {
+ "full-ci": "npm run lint && npm run coverage",
+ "coverage": "nyc -r lcovonly npm run unit",
+ "coveralls": "coveralls < coverage/lcov.info",
+ "lint": "standard",
+ "test-find": "find ./lib/**/__tests__ -name *.test.js | xargs mocha",
+ "test": "npm run lint && npm run unit",
+ "unit": "node test.js"
+ }
+}
diff --git a/temporary_modules/trezor-connect/node_modules/fs-minipass/LICENSE b/temporary_modules/trezor-connect/node_modules/fs-minipass/LICENSE
new file mode 100644
index 00000000..19129e31
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/fs-minipass/LICENSE
@@ -0,0 +1,15 @@
+The ISC License
+
+Copyright (c) Isaac Z. Schlueter and Contributors
+
+Permission to use, copy, modify, and/or distribute this software for any
+purpose with or without fee is hereby granted, provided that the above
+copyright notice and this permission notice appear in all copies.
+
+THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
+IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
diff --git a/temporary_modules/trezor-connect/node_modules/fs-minipass/README.md b/temporary_modules/trezor-connect/node_modules/fs-minipass/README.md
new file mode 100644
index 00000000..1e61241c
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/fs-minipass/README.md
@@ -0,0 +1,70 @@
+# fs-minipass
+
+Filesystem streams based on [minipass](http://npm.im/minipass).
+
+4 classes are exported:
+
+- ReadStream
+- ReadStreamSync
+- WriteStream
+- WriteStreamSync
+
+When using `ReadStreamSync`, all of the data is made available
+immediately upon consuming the stream. Nothing is buffered in memory
+when the stream is constructed. If the stream is piped to a writer,
+then it will synchronously `read()` and emit data into the writer as
+fast as the writer can consume it. (That is, it will respect
+backpressure.) If you call `stream.read()` then it will read the
+entire file and return the contents.
+
+When using `WriteStreamSync`, every write is flushed to the file
+synchronously. If your writes all come in a single tick, then it'll
+write it all out in a single tick. It's as synchronous as you are.
+
+The async versions work much like their node builtin counterparts,
+with the exception of introducing significantly less Stream machinery
+overhead.
+
+## USAGE
+
+It's just streams, you pipe them or read() them or write() to them.
+
+```js
+const fsm = require('fs-minipass')
+const readStream = new fsm.ReadStream('file.txt')
+const writeStream = new fsm.WriteStream('output.txt')
+writeStream.write('some file header or whatever\n')
+readStream.pipe(writeStream)
+```
+
+## ReadStream(path, options)
+
+Path string is required, but somewhat irrelevant if an open file
+descriptor is passed in as an option.
+
+Options:
+
+- `fd` Pass in a numeric file descriptor, if the file is already open.
+- `readSize` The size of reads to do, defaults to 16MB
+- `size` The size of the file, if known. Prevents zero-byte read()
+ call at the end.
+- `autoClose` Set to `false` to prevent the file descriptor from being
+ closed when the file is done being read.
+
+## WriteStream(path, options)
+
+Path string is required, but somewhat irrelevant if an open file
+descriptor is passed in as an option.
+
+Options:
+
+- `fd` Pass in a numeric file descriptor, if the file is already open.
+- `mode` The mode to create the file with. Defaults to `0o666`.
+- `start` The position in the file to start reading. If not
+ specified, then the file will start writing at position zero, and be
+ truncated by default.
+- `autoClose` Set to `false` to prevent the file descriptor from being
+ closed when the stream is ended.
+- `flags` Flags to use when opening the file. Irrelevant if `fd` is
+ passed in, since file won't be opened in that case. Defaults to
+ `'a'` if a `pos` is specified, or `'w'` otherwise.
diff --git a/temporary_modules/trezor-connect/node_modules/fs-minipass/index.js b/temporary_modules/trezor-connect/node_modules/fs-minipass/index.js
new file mode 100644
index 00000000..9b0779c8
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/fs-minipass/index.js
@@ -0,0 +1,422 @@
+'use strict'
+const MiniPass = require('minipass')
+const EE = require('events').EventEmitter
+const fs = require('fs')
+
+let writev = fs.writev
+/* istanbul ignore next */
+if (!writev) {
+ // This entire block can be removed if support for earlier than Node.js
+ // 12.9.0 is not needed.
+ const binding = process.binding('fs')
+ const FSReqWrap = binding.FSReqWrap || binding.FSReqCallback
+
+ writev = (fd, iovec, pos, cb) => {
+ const done = (er, bw) => cb(er, bw, iovec)
+ const req = new FSReqWrap()
+ req.oncomplete = done
+ binding.writeBuffers(fd, iovec, pos, req)
+ }
+}
+
+const _autoClose = Symbol('_autoClose')
+const _close = Symbol('_close')
+const _ended = Symbol('_ended')
+const _fd = Symbol('_fd')
+const _finished = Symbol('_finished')
+const _flags = Symbol('_flags')
+const _flush = Symbol('_flush')
+const _handleChunk = Symbol('_handleChunk')
+const _makeBuf = Symbol('_makeBuf')
+const _mode = Symbol('_mode')
+const _needDrain = Symbol('_needDrain')
+const _onerror = Symbol('_onerror')
+const _onopen = Symbol('_onopen')
+const _onread = Symbol('_onread')
+const _onwrite = Symbol('_onwrite')
+const _open = Symbol('_open')
+const _path = Symbol('_path')
+const _pos = Symbol('_pos')
+const _queue = Symbol('_queue')
+const _read = Symbol('_read')
+const _readSize = Symbol('_readSize')
+const _reading = Symbol('_reading')
+const _remain = Symbol('_remain')
+const _size = Symbol('_size')
+const _write = Symbol('_write')
+const _writing = Symbol('_writing')
+const _defaultFlag = Symbol('_defaultFlag')
+const _errored = Symbol('_errored')
+
+class ReadStream extends MiniPass {
+ constructor (path, opt) {
+ opt = opt || {}
+ super(opt)
+
+ this.readable = true
+ this.writable = false
+
+ if (typeof path !== 'string')
+ throw new TypeError('path must be a string')
+
+ this[_errored] = false
+ this[_fd] = typeof opt.fd === 'number' ? opt.fd : null
+ this[_path] = path
+ this[_readSize] = opt.readSize || 16*1024*1024
+ this[_reading] = false
+ this[_size] = typeof opt.size === 'number' ? opt.size : Infinity
+ this[_remain] = this[_size]
+ this[_autoClose] = typeof opt.autoClose === 'boolean' ?
+ opt.autoClose : true
+
+ if (typeof this[_fd] === 'number')
+ this[_read]()
+ else
+ this[_open]()
+ }
+
+ get fd () { return this[_fd] }
+ get path () { return this[_path] }
+
+ write () {
+ throw new TypeError('this is a readable stream')
+ }
+
+ end () {
+ throw new TypeError('this is a readable stream')
+ }
+
+ [_open] () {
+ fs.open(this[_path], 'r', (er, fd) => this[_onopen](er, fd))
+ }
+
+ [_onopen] (er, fd) {
+ if (er)
+ this[_onerror](er)
+ else {
+ this[_fd] = fd
+ this.emit('open', fd)
+ this[_read]()
+ }
+ }
+
+ [_makeBuf] () {
+ return Buffer.allocUnsafe(Math.min(this[_readSize], this[_remain]))
+ }
+
+ [_read] () {
+ if (!this[_reading]) {
+ this[_reading] = true
+ const buf = this[_makeBuf]()
+ /* istanbul ignore if */
+ if (buf.length === 0)
+ return process.nextTick(() => this[_onread](null, 0, buf))
+ fs.read(this[_fd], buf, 0, buf.length, null, (er, br, buf) =>
+ this[_onread](er, br, buf))
+ }
+ }
+
+ [_onread] (er, br, buf) {
+ this[_reading] = false
+ if (er)
+ this[_onerror](er)
+ else if (this[_handleChunk](br, buf))
+ this[_read]()
+ }
+
+ [_close] () {
+ if (this[_autoClose] && typeof this[_fd] === 'number') {
+ const fd = this[_fd]
+ this[_fd] = null
+ fs.close(fd, er => er ? this.emit('error', er) : this.emit('close'))
+ }
+ }
+
+ [_onerror] (er) {
+ this[_reading] = true
+ this[_close]()
+ this.emit('error', er)
+ }
+
+ [_handleChunk] (br, buf) {
+ let ret = false
+ // no effect if infinite
+ this[_remain] -= br
+ if (br > 0)
+ ret = super.write(br < buf.length ? buf.slice(0, br) : buf)
+
+ if (br === 0 || this[_remain] <= 0) {
+ ret = false
+ this[_close]()
+ super.end()
+ }
+
+ return ret
+ }
+
+ emit (ev, data) {
+ switch (ev) {
+ case 'prefinish':
+ case 'finish':
+ break
+
+ case 'drain':
+ if (typeof this[_fd] === 'number')
+ this[_read]()
+ break
+
+ case 'error':
+ if (this[_errored])
+ return
+ this[_errored] = true
+ return super.emit(ev, data)
+
+ default:
+ return super.emit(ev, data)
+ }
+ }
+}
+
+class ReadStreamSync extends ReadStream {
+ [_open] () {
+ let threw = true
+ try {
+ this[_onopen](null, fs.openSync(this[_path], 'r'))
+ threw = false
+ } finally {
+ if (threw)
+ this[_close]()
+ }
+ }
+
+ [_read] () {
+ let threw = true
+ try {
+ if (!this[_reading]) {
+ this[_reading] = true
+ do {
+ const buf = this[_makeBuf]()
+ /* istanbul ignore next */
+ const br = buf.length === 0 ? 0
+ : fs.readSync(this[_fd], buf, 0, buf.length, null)
+ if (!this[_handleChunk](br, buf))
+ break
+ } while (true)
+ this[_reading] = false
+ }
+ threw = false
+ } finally {
+ if (threw)
+ this[_close]()
+ }
+ }
+
+ [_close] () {
+ if (this[_autoClose] && typeof this[_fd] === 'number') {
+ const fd = this[_fd]
+ this[_fd] = null
+ fs.closeSync(fd)
+ this.emit('close')
+ }
+ }
+}
+
+class WriteStream extends EE {
+ constructor (path, opt) {
+ opt = opt || {}
+ super(opt)
+ this.readable = false
+ this.writable = true
+ this[_errored] = false
+ this[_writing] = false
+ this[_ended] = false
+ this[_needDrain] = false
+ this[_queue] = []
+ this[_path] = path
+ this[_fd] = typeof opt.fd === 'number' ? opt.fd : null
+ this[_mode] = opt.mode === undefined ? 0o666 : opt.mode
+ this[_pos] = typeof opt.start === 'number' ? opt.start : null
+ this[_autoClose] = typeof opt.autoClose === 'boolean' ?
+ opt.autoClose : true
+
+ // truncating makes no sense when writing into the middle
+ const defaultFlag = this[_pos] !== null ? 'r+' : 'w'
+ this[_defaultFlag] = opt.flags === undefined
+ this[_flags] = this[_defaultFlag] ? defaultFlag : opt.flags
+
+ if (this[_fd] === null)
+ this[_open]()
+ }
+
+ emit (ev, data) {
+ if (ev === 'error') {
+ if (this[_errored])
+ return
+ this[_errored] = true
+ }
+ return super.emit(ev, data)
+ }
+
+
+ get fd () { return this[_fd] }
+ get path () { return this[_path] }
+
+ [_onerror] (er) {
+ this[_close]()
+ this[_writing] = true
+ this.emit('error', er)
+ }
+
+ [_open] () {
+ fs.open(this[_path], this[_flags], this[_mode],
+ (er, fd) => this[_onopen](er, fd))
+ }
+
+ [_onopen] (er, fd) {
+ if (this[_defaultFlag] &&
+ this[_flags] === 'r+' &&
+ er && er.code === 'ENOENT') {
+ this[_flags] = 'w'
+ this[_open]()
+ } else if (er)
+ this[_onerror](er)
+ else {
+ this[_fd] = fd
+ this.emit('open', fd)
+ this[_flush]()
+ }
+ }
+
+ end (buf, enc) {
+ if (buf)
+ this.write(buf, enc)
+
+ this[_ended] = true
+
+ // synthetic after-write logic, where drain/finish live
+ if (!this[_writing] && !this[_queue].length &&
+ typeof this[_fd] === 'number')
+ this[_onwrite](null, 0)
+ return this
+ }
+
+ write (buf, enc) {
+ if (typeof buf === 'string')
+ buf = Buffer.from(buf, enc)
+
+ if (this[_ended]) {
+ this.emit('error', new Error('write() after end()'))
+ return false
+ }
+
+ if (this[_fd] === null || this[_writing] || this[_queue].length) {
+ this[_queue].push(buf)
+ this[_needDrain] = true
+ return false
+ }
+
+ this[_writing] = true
+ this[_write](buf)
+ return true
+ }
+
+ [_write] (buf) {
+ fs.write(this[_fd], buf, 0, buf.length, this[_pos], (er, bw) =>
+ this[_onwrite](er, bw))
+ }
+
+ [_onwrite] (er, bw) {
+ if (er)
+ this[_onerror](er)
+ else {
+ if (this[_pos] !== null)
+ this[_pos] += bw
+ if (this[_queue].length)
+ this[_flush]()
+ else {
+ this[_writing] = false
+
+ if (this[_ended] && !this[_finished]) {
+ this[_finished] = true
+ this[_close]()
+ this.emit('finish')
+ } else if (this[_needDrain]) {
+ this[_needDrain] = false
+ this.emit('drain')
+ }
+ }
+ }
+ }
+
+ [_flush] () {
+ if (this[_queue].length === 0) {
+ if (this[_ended])
+ this[_onwrite](null, 0)
+ } else if (this[_queue].length === 1)
+ this[_write](this[_queue].pop())
+ else {
+ const iovec = this[_queue]
+ this[_queue] = []
+ writev(this[_fd], iovec, this[_pos],
+ (er, bw) => this[_onwrite](er, bw))
+ }
+ }
+
+ [_close] () {
+ if (this[_autoClose] && typeof this[_fd] === 'number') {
+ const fd = this[_fd]
+ this[_fd] = null
+ fs.close(fd, er => er ? this.emit('error', er) : this.emit('close'))
+ }
+ }
+}
+
+class WriteStreamSync extends WriteStream {
+ [_open] () {
+ let fd
+ // only wrap in a try{} block if we know we'll retry, to avoid
+ // the rethrow obscuring the error's source frame in most cases.
+ if (this[_defaultFlag] && this[_flags] === 'r+') {
+ try {
+ fd = fs.openSync(this[_path], this[_flags], this[_mode])
+ } catch (er) {
+ if (er.code === 'ENOENT') {
+ this[_flags] = 'w'
+ return this[_open]()
+ } else
+ throw er
+ }
+ } else
+ fd = fs.openSync(this[_path], this[_flags], this[_mode])
+
+ this[_onopen](null, fd)
+ }
+
+ [_close] () {
+ if (this[_autoClose] && typeof this[_fd] === 'number') {
+ const fd = this[_fd]
+ this[_fd] = null
+ fs.closeSync(fd)
+ this.emit('close')
+ }
+ }
+
+ [_write] (buf) {
+ // throw the original, but try to close if it fails
+ let threw = true
+ try {
+ this[_onwrite](null,
+ fs.writeSync(this[_fd], buf, 0, buf.length, this[_pos]))
+ threw = false
+ } finally {
+ if (threw)
+ try { this[_close]() } catch (_) {}
+ }
+ }
+}
+
+exports.ReadStream = ReadStream
+exports.ReadStreamSync = ReadStreamSync
+
+exports.WriteStream = WriteStream
+exports.WriteStreamSync = WriteStreamSync
diff --git a/temporary_modules/trezor-connect/node_modules/fs-minipass/package.json b/temporary_modules/trezor-connect/node_modules/fs-minipass/package.json
new file mode 100644
index 00000000..2f2436cb
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/fs-minipass/package.json
@@ -0,0 +1,39 @@
+{
+ "name": "fs-minipass",
+ "version": "2.1.0",
+ "main": "index.js",
+ "scripts": {
+ "test": "tap",
+ "preversion": "npm test",
+ "postversion": "npm publish",
+ "postpublish": "git push origin --follow-tags"
+ },
+ "keywords": [],
+ "author": "Isaac Z. Schlueter (http://blog.izs.me/)",
+ "license": "ISC",
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/npm/fs-minipass.git"
+ },
+ "bugs": {
+ "url": "https://github.com/npm/fs-minipass/issues"
+ },
+ "homepage": "https://github.com/npm/fs-minipass#readme",
+ "description": "fs read and write streams based on minipass",
+ "dependencies": {
+ "minipass": "^3.0.0"
+ },
+ "devDependencies": {
+ "mutate-fs": "^2.0.1",
+ "tap": "^14.6.4"
+ },
+ "files": [
+ "index.js"
+ ],
+ "tap": {
+ "check-coverage": true
+ },
+ "engines": {
+ "node": ">= 8"
+ }
+}
diff --git a/temporary_modules/trezor-connect/node_modules/graceful-fs/LICENSE b/temporary_modules/trezor-connect/node_modules/graceful-fs/LICENSE
new file mode 100644
index 00000000..e906a25a
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/graceful-fs/LICENSE
@@ -0,0 +1,15 @@
+The ISC License
+
+Copyright (c) 2011-2022 Isaac Z. Schlueter, Ben Noordhuis, and Contributors
+
+Permission to use, copy, modify, and/or distribute this software for any
+purpose with or without fee is hereby granted, provided that the above
+copyright notice and this permission notice appear in all copies.
+
+THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
+IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
diff --git a/temporary_modules/trezor-connect/node_modules/graceful-fs/README.md b/temporary_modules/trezor-connect/node_modules/graceful-fs/README.md
new file mode 100644
index 00000000..82d6e4da
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/graceful-fs/README.md
@@ -0,0 +1,143 @@
+# graceful-fs
+
+graceful-fs functions as a drop-in replacement for the fs module,
+making various improvements.
+
+The improvements are meant to normalize behavior across different
+platforms and environments, and to make filesystem access more
+resilient to errors.
+
+## Improvements over [fs module](https://nodejs.org/api/fs.html)
+
+* Queues up `open` and `readdir` calls, and retries them once
+ something closes if there is an EMFILE error from too many file
+ descriptors.
+* fixes `lchmod` for Node versions prior to 0.6.2.
+* implements `fs.lutimes` if possible. Otherwise it becomes a noop.
+* ignores `EINVAL` and `EPERM` errors in `chown`, `fchown` or
+ `lchown` if the user isn't root.
+* makes `lchmod` and `lchown` become noops, if not available.
+* retries reading a file if `read` results in EAGAIN error.
+
+On Windows, it retries renaming a file for up to one second if `EACCESS`
+or `EPERM` error occurs, likely because antivirus software has locked
+the directory.
+
+## USAGE
+
+```javascript
+// use just like fs
+var fs = require('graceful-fs')
+
+// now go and do stuff with it...
+fs.readFile('some-file-or-whatever', (err, data) => {
+ // Do stuff here.
+})
+```
+
+## Sync methods
+
+This module cannot intercept or handle `EMFILE` or `ENFILE` errors from sync
+methods. If you use sync methods which open file descriptors then you are
+responsible for dealing with any errors.
+
+This is a known limitation, not a bug.
+
+## Global Patching
+
+If you want to patch the global fs module (or any other fs-like
+module) you can do this:
+
+```javascript
+// Make sure to read the caveat below.
+var realFs = require('fs')
+var gracefulFs = require('graceful-fs')
+gracefulFs.gracefulify(realFs)
+```
+
+This should only ever be done at the top-level application layer, in
+order to delay on EMFILE errors from any fs-using dependencies. You
+should **not** do this in a library, because it can cause unexpected
+delays in other parts of the program.
+
+## Changes
+
+This module is fairly stable at this point, and used by a lot of
+things. That being said, because it implements a subtle behavior
+change in a core part of the node API, even modest changes can be
+extremely breaking, and the versioning is thus biased towards
+bumping the major when in doubt.
+
+The main change between major versions has been switching between
+providing a fully-patched `fs` module vs monkey-patching the node core
+builtin, and the approach by which a non-monkey-patched `fs` was
+created.
+
+The goal is to trade `EMFILE` errors for slower fs operations. So, if
+you try to open a zillion files, rather than crashing, `open`
+operations will be queued up and wait for something else to `close`.
+
+There are advantages to each approach. Monkey-patching the fs means
+that no `EMFILE` errors can possibly occur anywhere in your
+application, because everything is using the same core `fs` module,
+which is patched. However, it can also obviously cause undesirable
+side-effects, especially if the module is loaded multiple times.
+
+Implementing a separate-but-identical patched `fs` module is more
+surgical (and doesn't run the risk of patching multiple times), but
+also imposes the challenge of keeping in sync with the core module.
+
+The current approach loads the `fs` module, and then creates a
+lookalike object that has all the same methods, except a few that are
+patched. It is safe to use in all versions of Node from 0.8 through
+7.0.
+
+### v4
+
+* Do not monkey-patch the fs module. This module may now be used as a
+ drop-in dep, and users can opt into monkey-patching the fs builtin
+ if their app requires it.
+
+### v3
+
+* Monkey-patch fs, because the eval approach no longer works on recent
+ node.
+* fixed possible type-error throw if rename fails on windows
+* verify that we *never* get EMFILE errors
+* Ignore ENOSYS from chmod/chown
+* clarify that graceful-fs must be used as a drop-in
+
+### v2.1.0
+
+* Use eval rather than monkey-patching fs.
+* readdir: Always sort the results
+* win32: requeue a file if error has an OK status
+
+### v2.0
+
+* A return to monkey patching
+* wrap process.cwd
+
+### v1.1
+
+* wrap readFile
+* Wrap fs.writeFile.
+* readdir protection
+* Don't clobber the fs builtin
+* Handle fs.read EAGAIN errors by trying again
+* Expose the curOpen counter
+* No-op lchown/lchmod if not implemented
+* fs.rename patch only for win32
+* Patch fs.rename to handle AV software on Windows
+* Close #4 Chown should not fail on einval or eperm if non-root
+* Fix isaacs/fstream#1 Only wrap fs one time
+* Fix #3 Start at 1024 max files, then back off on EMFILE
+* lutimes that doens't blow up on Linux
+* A full on-rewrite using a queue instead of just swallowing the EMFILE error
+* Wrap Read/Write streams as well
+
+### 1.0
+
+* Update engines for node 0.6
+* Be lstat-graceful on Windows
+* first
diff --git a/temporary_modules/trezor-connect/node_modules/graceful-fs/clone.js b/temporary_modules/trezor-connect/node_modules/graceful-fs/clone.js
new file mode 100644
index 00000000..dff3cc8c
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/graceful-fs/clone.js
@@ -0,0 +1,23 @@
+'use strict'
+
+module.exports = clone
+
+var getPrototypeOf = Object.getPrototypeOf || function (obj) {
+ return obj.__proto__
+}
+
+function clone (obj) {
+ if (obj === null || typeof obj !== 'object')
+ return obj
+
+ if (obj instanceof Object)
+ var copy = { __proto__: getPrototypeOf(obj) }
+ else
+ var copy = Object.create(null)
+
+ Object.getOwnPropertyNames(obj).forEach(function (key) {
+ Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key))
+ })
+
+ return copy
+}
diff --git a/temporary_modules/trezor-connect/node_modules/graceful-fs/graceful-fs.js b/temporary_modules/trezor-connect/node_modules/graceful-fs/graceful-fs.js
new file mode 100644
index 00000000..8d5b89e4
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/graceful-fs/graceful-fs.js
@@ -0,0 +1,448 @@
+var fs = require('fs')
+var polyfills = require('./polyfills.js')
+var legacy = require('./legacy-streams.js')
+var clone = require('./clone.js')
+
+var util = require('util')
+
+/* istanbul ignore next - node 0.x polyfill */
+var gracefulQueue
+var previousSymbol
+
+/* istanbul ignore else - node 0.x polyfill */
+if (typeof Symbol === 'function' && typeof Symbol.for === 'function') {
+ gracefulQueue = Symbol.for('graceful-fs.queue')
+ // This is used in testing by future versions
+ previousSymbol = Symbol.for('graceful-fs.previous')
+} else {
+ gracefulQueue = '___graceful-fs.queue'
+ previousSymbol = '___graceful-fs.previous'
+}
+
+function noop () {}
+
+function publishQueue(context, queue) {
+ Object.defineProperty(context, gracefulQueue, {
+ get: function() {
+ return queue
+ }
+ })
+}
+
+var debug = noop
+if (util.debuglog)
+ debug = util.debuglog('gfs4')
+else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || ''))
+ debug = function() {
+ var m = util.format.apply(util, arguments)
+ m = 'GFS4: ' + m.split(/\n/).join('\nGFS4: ')
+ console.error(m)
+ }
+
+// Once time initialization
+if (!fs[gracefulQueue]) {
+ // This queue can be shared by multiple loaded instances
+ var queue = global[gracefulQueue] || []
+ publishQueue(fs, queue)
+
+ // Patch fs.close/closeSync to shared queue version, because we need
+ // to retry() whenever a close happens *anywhere* in the program.
+ // This is essential when multiple graceful-fs instances are
+ // in play at the same time.
+ fs.close = (function (fs$close) {
+ function close (fd, cb) {
+ return fs$close.call(fs, fd, function (err) {
+ // This function uses the graceful-fs shared queue
+ if (!err) {
+ resetQueue()
+ }
+
+ if (typeof cb === 'function')
+ cb.apply(this, arguments)
+ })
+ }
+
+ Object.defineProperty(close, previousSymbol, {
+ value: fs$close
+ })
+ return close
+ })(fs.close)
+
+ fs.closeSync = (function (fs$closeSync) {
+ function closeSync (fd) {
+ // This function uses the graceful-fs shared queue
+ fs$closeSync.apply(fs, arguments)
+ resetQueue()
+ }
+
+ Object.defineProperty(closeSync, previousSymbol, {
+ value: fs$closeSync
+ })
+ return closeSync
+ })(fs.closeSync)
+
+ if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) {
+ process.on('exit', function() {
+ debug(fs[gracefulQueue])
+ require('assert').equal(fs[gracefulQueue].length, 0)
+ })
+ }
+}
+
+if (!global[gracefulQueue]) {
+ publishQueue(global, fs[gracefulQueue]);
+}
+
+module.exports = patch(clone(fs))
+if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs.__patched) {
+ module.exports = patch(fs)
+ fs.__patched = true;
+}
+
+function patch (fs) {
+ // Everything that references the open() function needs to be in here
+ polyfills(fs)
+ fs.gracefulify = patch
+
+ fs.createReadStream = createReadStream
+ fs.createWriteStream = createWriteStream
+ var fs$readFile = fs.readFile
+ fs.readFile = readFile
+ function readFile (path, options, cb) {
+ if (typeof options === 'function')
+ cb = options, options = null
+
+ return go$readFile(path, options, cb)
+
+ function go$readFile (path, options, cb, startTime) {
+ return fs$readFile(path, options, function (err) {
+ if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
+ enqueue([go$readFile, [path, options, cb], err, startTime || Date.now(), Date.now()])
+ else {
+ if (typeof cb === 'function')
+ cb.apply(this, arguments)
+ }
+ })
+ }
+ }
+
+ var fs$writeFile = fs.writeFile
+ fs.writeFile = writeFile
+ function writeFile (path, data, options, cb) {
+ if (typeof options === 'function')
+ cb = options, options = null
+
+ return go$writeFile(path, data, options, cb)
+
+ function go$writeFile (path, data, options, cb, startTime) {
+ return fs$writeFile(path, data, options, function (err) {
+ if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
+ enqueue([go$writeFile, [path, data, options, cb], err, startTime || Date.now(), Date.now()])
+ else {
+ if (typeof cb === 'function')
+ cb.apply(this, arguments)
+ }
+ })
+ }
+ }
+
+ var fs$appendFile = fs.appendFile
+ if (fs$appendFile)
+ fs.appendFile = appendFile
+ function appendFile (path, data, options, cb) {
+ if (typeof options === 'function')
+ cb = options, options = null
+
+ return go$appendFile(path, data, options, cb)
+
+ function go$appendFile (path, data, options, cb, startTime) {
+ return fs$appendFile(path, data, options, function (err) {
+ if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
+ enqueue([go$appendFile, [path, data, options, cb], err, startTime || Date.now(), Date.now()])
+ else {
+ if (typeof cb === 'function')
+ cb.apply(this, arguments)
+ }
+ })
+ }
+ }
+
+ var fs$copyFile = fs.copyFile
+ if (fs$copyFile)
+ fs.copyFile = copyFile
+ function copyFile (src, dest, flags, cb) {
+ if (typeof flags === 'function') {
+ cb = flags
+ flags = 0
+ }
+ return go$copyFile(src, dest, flags, cb)
+
+ function go$copyFile (src, dest, flags, cb, startTime) {
+ return fs$copyFile(src, dest, flags, function (err) {
+ if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
+ enqueue([go$copyFile, [src, dest, flags, cb], err, startTime || Date.now(), Date.now()])
+ else {
+ if (typeof cb === 'function')
+ cb.apply(this, arguments)
+ }
+ })
+ }
+ }
+
+ var fs$readdir = fs.readdir
+ fs.readdir = readdir
+ var noReaddirOptionVersions = /^v[0-5]\./
+ function readdir (path, options, cb) {
+ if (typeof options === 'function')
+ cb = options, options = null
+
+ var go$readdir = noReaddirOptionVersions.test(process.version)
+ ? function go$readdir (path, options, cb, startTime) {
+ return fs$readdir(path, fs$readdirCallback(
+ path, options, cb, startTime
+ ))
+ }
+ : function go$readdir (path, options, cb, startTime) {
+ return fs$readdir(path, options, fs$readdirCallback(
+ path, options, cb, startTime
+ ))
+ }
+
+ return go$readdir(path, options, cb)
+
+ function fs$readdirCallback (path, options, cb, startTime) {
+ return function (err, files) {
+ if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
+ enqueue([
+ go$readdir,
+ [path, options, cb],
+ err,
+ startTime || Date.now(),
+ Date.now()
+ ])
+ else {
+ if (files && files.sort)
+ files.sort()
+
+ if (typeof cb === 'function')
+ cb.call(this, err, files)
+ }
+ }
+ }
+ }
+
+ if (process.version.substr(0, 4) === 'v0.8') {
+ var legStreams = legacy(fs)
+ ReadStream = legStreams.ReadStream
+ WriteStream = legStreams.WriteStream
+ }
+
+ var fs$ReadStream = fs.ReadStream
+ if (fs$ReadStream) {
+ ReadStream.prototype = Object.create(fs$ReadStream.prototype)
+ ReadStream.prototype.open = ReadStream$open
+ }
+
+ var fs$WriteStream = fs.WriteStream
+ if (fs$WriteStream) {
+ WriteStream.prototype = Object.create(fs$WriteStream.prototype)
+ WriteStream.prototype.open = WriteStream$open
+ }
+
+ Object.defineProperty(fs, 'ReadStream', {
+ get: function () {
+ return ReadStream
+ },
+ set: function (val) {
+ ReadStream = val
+ },
+ enumerable: true,
+ configurable: true
+ })
+ Object.defineProperty(fs, 'WriteStream', {
+ get: function () {
+ return WriteStream
+ },
+ set: function (val) {
+ WriteStream = val
+ },
+ enumerable: true,
+ configurable: true
+ })
+
+ // legacy names
+ var FileReadStream = ReadStream
+ Object.defineProperty(fs, 'FileReadStream', {
+ get: function () {
+ return FileReadStream
+ },
+ set: function (val) {
+ FileReadStream = val
+ },
+ enumerable: true,
+ configurable: true
+ })
+ var FileWriteStream = WriteStream
+ Object.defineProperty(fs, 'FileWriteStream', {
+ get: function () {
+ return FileWriteStream
+ },
+ set: function (val) {
+ FileWriteStream = val
+ },
+ enumerable: true,
+ configurable: true
+ })
+
+ function ReadStream (path, options) {
+ if (this instanceof ReadStream)
+ return fs$ReadStream.apply(this, arguments), this
+ else
+ return ReadStream.apply(Object.create(ReadStream.prototype), arguments)
+ }
+
+ function ReadStream$open () {
+ var that = this
+ open(that.path, that.flags, that.mode, function (err, fd) {
+ if (err) {
+ if (that.autoClose)
+ that.destroy()
+
+ that.emit('error', err)
+ } else {
+ that.fd = fd
+ that.emit('open', fd)
+ that.read()
+ }
+ })
+ }
+
+ function WriteStream (path, options) {
+ if (this instanceof WriteStream)
+ return fs$WriteStream.apply(this, arguments), this
+ else
+ return WriteStream.apply(Object.create(WriteStream.prototype), arguments)
+ }
+
+ function WriteStream$open () {
+ var that = this
+ open(that.path, that.flags, that.mode, function (err, fd) {
+ if (err) {
+ that.destroy()
+ that.emit('error', err)
+ } else {
+ that.fd = fd
+ that.emit('open', fd)
+ }
+ })
+ }
+
+ function createReadStream (path, options) {
+ return new fs.ReadStream(path, options)
+ }
+
+ function createWriteStream (path, options) {
+ return new fs.WriteStream(path, options)
+ }
+
+ var fs$open = fs.open
+ fs.open = open
+ function open (path, flags, mode, cb) {
+ if (typeof mode === 'function')
+ cb = mode, mode = null
+
+ return go$open(path, flags, mode, cb)
+
+ function go$open (path, flags, mode, cb, startTime) {
+ return fs$open(path, flags, mode, function (err, fd) {
+ if (err && (err.code === 'EMFILE' || err.code === 'ENFILE'))
+ enqueue([go$open, [path, flags, mode, cb], err, startTime || Date.now(), Date.now()])
+ else {
+ if (typeof cb === 'function')
+ cb.apply(this, arguments)
+ }
+ })
+ }
+ }
+
+ return fs
+}
+
+function enqueue (elem) {
+ debug('ENQUEUE', elem[0].name, elem[1])
+ fs[gracefulQueue].push(elem)
+ retry()
+}
+
+// keep track of the timeout between retry() calls
+var retryTimer
+
+// reset the startTime and lastTime to now
+// this resets the start of the 60 second overall timeout as well as the
+// delay between attempts so that we'll retry these jobs sooner
+function resetQueue () {
+ var now = Date.now()
+ for (var i = 0; i < fs[gracefulQueue].length; ++i) {
+ // entries that are only a length of 2 are from an older version, don't
+ // bother modifying those since they'll be retried anyway.
+ if (fs[gracefulQueue][i].length > 2) {
+ fs[gracefulQueue][i][3] = now // startTime
+ fs[gracefulQueue][i][4] = now // lastTime
+ }
+ }
+ // call retry to make sure we're actively processing the queue
+ retry()
+}
+
+function retry () {
+ // clear the timer and remove it to help prevent unintended concurrency
+ clearTimeout(retryTimer)
+ retryTimer = undefined
+
+ if (fs[gracefulQueue].length === 0)
+ return
+
+ var elem = fs[gracefulQueue].shift()
+ var fn = elem[0]
+ var args = elem[1]
+ // these items may be unset if they were added by an older graceful-fs
+ var err = elem[2]
+ var startTime = elem[3]
+ var lastTime = elem[4]
+
+ // if we don't have a startTime we have no way of knowing if we've waited
+ // long enough, so go ahead and retry this item now
+ if (startTime === undefined) {
+ debug('RETRY', fn.name, args)
+ fn.apply(null, args)
+ } else if (Date.now() - startTime >= 60000) {
+ // it's been more than 60 seconds total, bail now
+ debug('TIMEOUT', fn.name, args)
+ var cb = args.pop()
+ if (typeof cb === 'function')
+ cb.call(null, err)
+ } else {
+ // the amount of time between the last attempt and right now
+ var sinceAttempt = Date.now() - lastTime
+ // the amount of time between when we first tried, and when we last tried
+ // rounded up to at least 1
+ var sinceStart = Math.max(lastTime - startTime, 1)
+ // backoff. wait longer than the total time we've been retrying, but only
+ // up to a maximum of 100ms
+ var desiredDelay = Math.min(sinceStart * 1.2, 100)
+ // it's been long enough since the last retry, do it again
+ if (sinceAttempt >= desiredDelay) {
+ debug('RETRY', fn.name, args)
+ fn.apply(null, args.concat([startTime]))
+ } else {
+ // if we can't do this job yet, push it to the end of the queue
+ // and let the next iteration check again
+ fs[gracefulQueue].push(elem)
+ }
+ }
+
+ // schedule our next run if one isn't already scheduled
+ if (retryTimer === undefined) {
+ retryTimer = setTimeout(retry, 0)
+ }
+}
diff --git a/temporary_modules/trezor-connect/node_modules/graceful-fs/legacy-streams.js b/temporary_modules/trezor-connect/node_modules/graceful-fs/legacy-streams.js
new file mode 100644
index 00000000..d617b50f
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/graceful-fs/legacy-streams.js
@@ -0,0 +1,118 @@
+var Stream = require('stream').Stream
+
+module.exports = legacy
+
+function legacy (fs) {
+ return {
+ ReadStream: ReadStream,
+ WriteStream: WriteStream
+ }
+
+ function ReadStream (path, options) {
+ if (!(this instanceof ReadStream)) return new ReadStream(path, options);
+
+ Stream.call(this);
+
+ var self = this;
+
+ this.path = path;
+ this.fd = null;
+ this.readable = true;
+ this.paused = false;
+
+ this.flags = 'r';
+ this.mode = 438; /*=0666*/
+ this.bufferSize = 64 * 1024;
+
+ options = options || {};
+
+ // Mixin options into this
+ var keys = Object.keys(options);
+ for (var index = 0, length = keys.length; index < length; index++) {
+ var key = keys[index];
+ this[key] = options[key];
+ }
+
+ if (this.encoding) this.setEncoding(this.encoding);
+
+ if (this.start !== undefined) {
+ if ('number' !== typeof this.start) {
+ throw TypeError('start must be a Number');
+ }
+ if (this.end === undefined) {
+ this.end = Infinity;
+ } else if ('number' !== typeof this.end) {
+ throw TypeError('end must be a Number');
+ }
+
+ if (this.start > this.end) {
+ throw new Error('start must be <= end');
+ }
+
+ this.pos = this.start;
+ }
+
+ if (this.fd !== null) {
+ process.nextTick(function() {
+ self._read();
+ });
+ return;
+ }
+
+ fs.open(this.path, this.flags, this.mode, function (err, fd) {
+ if (err) {
+ self.emit('error', err);
+ self.readable = false;
+ return;
+ }
+
+ self.fd = fd;
+ self.emit('open', fd);
+ self._read();
+ })
+ }
+
+ function WriteStream (path, options) {
+ if (!(this instanceof WriteStream)) return new WriteStream(path, options);
+
+ Stream.call(this);
+
+ this.path = path;
+ this.fd = null;
+ this.writable = true;
+
+ this.flags = 'w';
+ this.encoding = 'binary';
+ this.mode = 438; /*=0666*/
+ this.bytesWritten = 0;
+
+ options = options || {};
+
+ // Mixin options into this
+ var keys = Object.keys(options);
+ for (var index = 0, length = keys.length; index < length; index++) {
+ var key = keys[index];
+ this[key] = options[key];
+ }
+
+ if (this.start !== undefined) {
+ if ('number' !== typeof this.start) {
+ throw TypeError('start must be a Number');
+ }
+ if (this.start < 0) {
+ throw new Error('start must be >= zero');
+ }
+
+ this.pos = this.start;
+ }
+
+ this.busy = false;
+ this._queue = [];
+
+ if (this.fd === null) {
+ this._open = fs.open;
+ this._queue.push([this._open, this.path, this.flags, this.mode, undefined]);
+ this.flush();
+ }
+ }
+}
diff --git a/temporary_modules/trezor-connect/node_modules/graceful-fs/package.json b/temporary_modules/trezor-connect/node_modules/graceful-fs/package.json
new file mode 100644
index 00000000..30578568
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/graceful-fs/package.json
@@ -0,0 +1,50 @@
+{
+ "name": "graceful-fs",
+ "description": "A drop-in replacement for fs, making various improvements.",
+ "version": "4.2.10",
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/isaacs/node-graceful-fs"
+ },
+ "main": "graceful-fs.js",
+ "directories": {
+ "test": "test"
+ },
+ "scripts": {
+ "preversion": "npm test",
+ "postversion": "npm publish",
+ "postpublish": "git push origin --follow-tags",
+ "test": "nyc --silent node test.js | tap -c -",
+ "posttest": "nyc report"
+ },
+ "keywords": [
+ "fs",
+ "module",
+ "reading",
+ "retry",
+ "retries",
+ "queue",
+ "error",
+ "errors",
+ "handling",
+ "EMFILE",
+ "EAGAIN",
+ "EINVAL",
+ "EPERM",
+ "EACCESS"
+ ],
+ "license": "ISC",
+ "devDependencies": {
+ "import-fresh": "^2.0.0",
+ "mkdirp": "^0.5.0",
+ "rimraf": "^2.2.8",
+ "tap": "^12.7.0"
+ },
+ "files": [
+ "fs.js",
+ "graceful-fs.js",
+ "legacy-streams.js",
+ "polyfills.js",
+ "clone.js"
+ ]
+}
diff --git a/temporary_modules/trezor-connect/node_modules/graceful-fs/polyfills.js b/temporary_modules/trezor-connect/node_modules/graceful-fs/polyfills.js
new file mode 100644
index 00000000..46dea36c
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/graceful-fs/polyfills.js
@@ -0,0 +1,355 @@
+var constants = require('constants')
+
+var origCwd = process.cwd
+var cwd = null
+
+var platform = process.env.GRACEFUL_FS_PLATFORM || process.platform
+
+process.cwd = function() {
+ if (!cwd)
+ cwd = origCwd.call(process)
+ return cwd
+}
+try {
+ process.cwd()
+} catch (er) {}
+
+// This check is needed until node.js 12 is required
+if (typeof process.chdir === 'function') {
+ var chdir = process.chdir
+ process.chdir = function (d) {
+ cwd = null
+ chdir.call(process, d)
+ }
+ if (Object.setPrototypeOf) Object.setPrototypeOf(process.chdir, chdir)
+}
+
+module.exports = patch
+
+function patch (fs) {
+ // (re-)implement some things that are known busted or missing.
+
+ // lchmod, broken prior to 0.6.2
+ // back-port the fix here.
+ if (constants.hasOwnProperty('O_SYMLINK') &&
+ process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) {
+ patchLchmod(fs)
+ }
+
+ // lutimes implementation, or no-op
+ if (!fs.lutimes) {
+ patchLutimes(fs)
+ }
+
+ // https://github.com/isaacs/node-graceful-fs/issues/4
+ // Chown should not fail on einval or eperm if non-root.
+ // It should not fail on enosys ever, as this just indicates
+ // that a fs doesn't support the intended operation.
+
+ fs.chown = chownFix(fs.chown)
+ fs.fchown = chownFix(fs.fchown)
+ fs.lchown = chownFix(fs.lchown)
+
+ fs.chmod = chmodFix(fs.chmod)
+ fs.fchmod = chmodFix(fs.fchmod)
+ fs.lchmod = chmodFix(fs.lchmod)
+
+ fs.chownSync = chownFixSync(fs.chownSync)
+ fs.fchownSync = chownFixSync(fs.fchownSync)
+ fs.lchownSync = chownFixSync(fs.lchownSync)
+
+ fs.chmodSync = chmodFixSync(fs.chmodSync)
+ fs.fchmodSync = chmodFixSync(fs.fchmodSync)
+ fs.lchmodSync = chmodFixSync(fs.lchmodSync)
+
+ fs.stat = statFix(fs.stat)
+ fs.fstat = statFix(fs.fstat)
+ fs.lstat = statFix(fs.lstat)
+
+ fs.statSync = statFixSync(fs.statSync)
+ fs.fstatSync = statFixSync(fs.fstatSync)
+ fs.lstatSync = statFixSync(fs.lstatSync)
+
+ // if lchmod/lchown do not exist, then make them no-ops
+ if (fs.chmod && !fs.lchmod) {
+ fs.lchmod = function (path, mode, cb) {
+ if (cb) process.nextTick(cb)
+ }
+ fs.lchmodSync = function () {}
+ }
+ if (fs.chown && !fs.lchown) {
+ fs.lchown = function (path, uid, gid, cb) {
+ if (cb) process.nextTick(cb)
+ }
+ fs.lchownSync = function () {}
+ }
+
+ // on Windows, A/V software can lock the directory, causing this
+ // to fail with an EACCES or EPERM if the directory contains newly
+ // created files. Try again on failure, for up to 60 seconds.
+
+ // Set the timeout this long because some Windows Anti-Virus, such as Parity
+ // bit9, may lock files for up to a minute, causing npm package install
+ // failures. Also, take care to yield the scheduler. Windows scheduling gives
+ // CPU to a busy looping process, which can cause the program causing the lock
+ // contention to be starved of CPU by node, so the contention doesn't resolve.
+ if (platform === "win32") {
+ fs.rename = typeof fs.rename !== 'function' ? fs.rename
+ : (function (fs$rename) {
+ function rename (from, to, cb) {
+ var start = Date.now()
+ var backoff = 0;
+ fs$rename(from, to, function CB (er) {
+ if (er
+ && (er.code === "EACCES" || er.code === "EPERM")
+ && Date.now() - start < 60000) {
+ setTimeout(function() {
+ fs.stat(to, function (stater, st) {
+ if (stater && stater.code === "ENOENT")
+ fs$rename(from, to, CB);
+ else
+ cb(er)
+ })
+ }, backoff)
+ if (backoff < 100)
+ backoff += 10;
+ return;
+ }
+ if (cb) cb(er)
+ })
+ }
+ if (Object.setPrototypeOf) Object.setPrototypeOf(rename, fs$rename)
+ return rename
+ })(fs.rename)
+ }
+
+ // if read() returns EAGAIN, then just try it again.
+ fs.read = typeof fs.read !== 'function' ? fs.read
+ : (function (fs$read) {
+ function read (fd, buffer, offset, length, position, callback_) {
+ var callback
+ if (callback_ && typeof callback_ === 'function') {
+ var eagCounter = 0
+ callback = function (er, _, __) {
+ if (er && er.code === 'EAGAIN' && eagCounter < 10) {
+ eagCounter ++
+ return fs$read.call(fs, fd, buffer, offset, length, position, callback)
+ }
+ callback_.apply(this, arguments)
+ }
+ }
+ return fs$read.call(fs, fd, buffer, offset, length, position, callback)
+ }
+
+ // This ensures `util.promisify` works as it does for native `fs.read`.
+ if (Object.setPrototypeOf) Object.setPrototypeOf(read, fs$read)
+ return read
+ })(fs.read)
+
+ fs.readSync = typeof fs.readSync !== 'function' ? fs.readSync
+ : (function (fs$readSync) { return function (fd, buffer, offset, length, position) {
+ var eagCounter = 0
+ while (true) {
+ try {
+ return fs$readSync.call(fs, fd, buffer, offset, length, position)
+ } catch (er) {
+ if (er.code === 'EAGAIN' && eagCounter < 10) {
+ eagCounter ++
+ continue
+ }
+ throw er
+ }
+ }
+ }})(fs.readSync)
+
+ function patchLchmod (fs) {
+ fs.lchmod = function (path, mode, callback) {
+ fs.open( path
+ , constants.O_WRONLY | constants.O_SYMLINK
+ , mode
+ , function (err, fd) {
+ if (err) {
+ if (callback) callback(err)
+ return
+ }
+ // prefer to return the chmod error, if one occurs,
+ // but still try to close, and report closing errors if they occur.
+ fs.fchmod(fd, mode, function (err) {
+ fs.close(fd, function(err2) {
+ if (callback) callback(err || err2)
+ })
+ })
+ })
+ }
+
+ fs.lchmodSync = function (path, mode) {
+ var fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK, mode)
+
+ // prefer to return the chmod error, if one occurs,
+ // but still try to close, and report closing errors if they occur.
+ var threw = true
+ var ret
+ try {
+ ret = fs.fchmodSync(fd, mode)
+ threw = false
+ } finally {
+ if (threw) {
+ try {
+ fs.closeSync(fd)
+ } catch (er) {}
+ } else {
+ fs.closeSync(fd)
+ }
+ }
+ return ret
+ }
+ }
+
+ function patchLutimes (fs) {
+ if (constants.hasOwnProperty("O_SYMLINK") && fs.futimes) {
+ fs.lutimes = function (path, at, mt, cb) {
+ fs.open(path, constants.O_SYMLINK, function (er, fd) {
+ if (er) {
+ if (cb) cb(er)
+ return
+ }
+ fs.futimes(fd, at, mt, function (er) {
+ fs.close(fd, function (er2) {
+ if (cb) cb(er || er2)
+ })
+ })
+ })
+ }
+
+ fs.lutimesSync = function (path, at, mt) {
+ var fd = fs.openSync(path, constants.O_SYMLINK)
+ var ret
+ var threw = true
+ try {
+ ret = fs.futimesSync(fd, at, mt)
+ threw = false
+ } finally {
+ if (threw) {
+ try {
+ fs.closeSync(fd)
+ } catch (er) {}
+ } else {
+ fs.closeSync(fd)
+ }
+ }
+ return ret
+ }
+
+ } else if (fs.futimes) {
+ fs.lutimes = function (_a, _b, _c, cb) { if (cb) process.nextTick(cb) }
+ fs.lutimesSync = function () {}
+ }
+ }
+
+ function chmodFix (orig) {
+ if (!orig) return orig
+ return function (target, mode, cb) {
+ return orig.call(fs, target, mode, function (er) {
+ if (chownErOk(er)) er = null
+ if (cb) cb.apply(this, arguments)
+ })
+ }
+ }
+
+ function chmodFixSync (orig) {
+ if (!orig) return orig
+ return function (target, mode) {
+ try {
+ return orig.call(fs, target, mode)
+ } catch (er) {
+ if (!chownErOk(er)) throw er
+ }
+ }
+ }
+
+
+ function chownFix (orig) {
+ if (!orig) return orig
+ return function (target, uid, gid, cb) {
+ return orig.call(fs, target, uid, gid, function (er) {
+ if (chownErOk(er)) er = null
+ if (cb) cb.apply(this, arguments)
+ })
+ }
+ }
+
+ function chownFixSync (orig) {
+ if (!orig) return orig
+ return function (target, uid, gid) {
+ try {
+ return orig.call(fs, target, uid, gid)
+ } catch (er) {
+ if (!chownErOk(er)) throw er
+ }
+ }
+ }
+
+ function statFix (orig) {
+ if (!orig) return orig
+ // Older versions of Node erroneously returned signed integers for
+ // uid + gid.
+ return function (target, options, cb) {
+ if (typeof options === 'function') {
+ cb = options
+ options = null
+ }
+ function callback (er, stats) {
+ if (stats) {
+ if (stats.uid < 0) stats.uid += 0x100000000
+ if (stats.gid < 0) stats.gid += 0x100000000
+ }
+ if (cb) cb.apply(this, arguments)
+ }
+ return options ? orig.call(fs, target, options, callback)
+ : orig.call(fs, target, callback)
+ }
+ }
+
+ function statFixSync (orig) {
+ if (!orig) return orig
+ // Older versions of Node erroneously returned signed integers for
+ // uid + gid.
+ return function (target, options) {
+ var stats = options ? orig.call(fs, target, options)
+ : orig.call(fs, target)
+ if (stats) {
+ if (stats.uid < 0) stats.uid += 0x100000000
+ if (stats.gid < 0) stats.gid += 0x100000000
+ }
+ return stats;
+ }
+ }
+
+ // ENOSYS means that the fs doesn't support the op. Just ignore
+ // that, because it doesn't matter.
+ //
+ // if there's no getuid, or if getuid() is something other
+ // than 0, and the error is EINVAL or EPERM, then just ignore
+ // it.
+ //
+ // This specific case is a silent failure in cp, install, tar,
+ // and most other unix tools that manage permissions.
+ //
+ // When running as root, or if other types of errors are
+ // encountered, then it's strict.
+ function chownErOk (er) {
+ if (!er)
+ return true
+
+ if (er.code === "ENOSYS")
+ return true
+
+ var nonroot = !process.getuid || process.getuid() !== 0
+ if (nonroot) {
+ if (er.code === "EINVAL" || er.code === "EPERM")
+ return true
+ }
+
+ return false
+ }
+}
diff --git a/temporary_modules/trezor-connect/node_modules/inherits/LICENSE b/temporary_modules/trezor-connect/node_modules/inherits/LICENSE
new file mode 100644
index 00000000..dea3013d
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/inherits/LICENSE
@@ -0,0 +1,16 @@
+The ISC License
+
+Copyright (c) Isaac Z. Schlueter
+
+Permission to use, copy, modify, and/or distribute this software for any
+purpose with or without fee is hereby granted, provided that the above
+copyright notice and this permission notice appear in all copies.
+
+THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
+REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
+FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
+INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
+LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
+OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
+PERFORMANCE OF THIS SOFTWARE.
+
diff --git a/temporary_modules/trezor-connect/node_modules/inherits/README.md b/temporary_modules/trezor-connect/node_modules/inherits/README.md
new file mode 100644
index 00000000..b1c56658
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/inherits/README.md
@@ -0,0 +1,42 @@
+Browser-friendly inheritance fully compatible with standard node.js
+[inherits](http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor).
+
+This package exports standard `inherits` from node.js `util` module in
+node environment, but also provides alternative browser-friendly
+implementation through [browser
+field](https://gist.github.com/shtylman/4339901). Alternative
+implementation is a literal copy of standard one located in standalone
+module to avoid requiring of `util`. It also has a shim for old
+browsers with no `Object.create` support.
+
+While keeping you sure you are using standard `inherits`
+implementation in node.js environment, it allows bundlers such as
+[browserify](https://github.com/substack/node-browserify) to not
+include full `util` package to your client code if all you need is
+just `inherits` function. It worth, because browser shim for `util`
+package is large and `inherits` is often the single function you need
+from it.
+
+It's recommended to use this package instead of
+`require('util').inherits` for any code that has chances to be used
+not only in node.js but in browser too.
+
+## usage
+
+```js
+var inherits = require('inherits');
+// then use exactly as the standard one
+```
+
+## note on version ~1.0
+
+Version ~1.0 had completely different motivation and is not compatible
+neither with 2.0 nor with standard node.js `inherits`.
+
+If you are using version ~1.0 and planning to switch to ~2.0, be
+careful:
+
+* new version uses `super_` instead of `super` for referencing
+ superclass
+* new version overwrites current prototype while old one preserves any
+ existing fields on it
diff --git a/temporary_modules/trezor-connect/node_modules/inherits/inherits.js b/temporary_modules/trezor-connect/node_modules/inherits/inherits.js
new file mode 100644
index 00000000..f71f2d93
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/inherits/inherits.js
@@ -0,0 +1,9 @@
+try {
+ var util = require('util');
+ /* istanbul ignore next */
+ if (typeof util.inherits !== 'function') throw '';
+ module.exports = util.inherits;
+} catch (e) {
+ /* istanbul ignore next */
+ module.exports = require('./inherits_browser.js');
+}
diff --git a/temporary_modules/trezor-connect/node_modules/inherits/inherits_browser.js b/temporary_modules/trezor-connect/node_modules/inherits/inherits_browser.js
new file mode 100644
index 00000000..86bbb3dc
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/inherits/inherits_browser.js
@@ -0,0 +1,27 @@
+if (typeof Object.create === 'function') {
+ // implementation from standard node.js 'util' module
+ module.exports = function inherits(ctor, superCtor) {
+ if (superCtor) {
+ ctor.super_ = superCtor
+ ctor.prototype = Object.create(superCtor.prototype, {
+ constructor: {
+ value: ctor,
+ enumerable: false,
+ writable: true,
+ configurable: true
+ }
+ })
+ }
+ };
+} else {
+ // old school shim for old browsers
+ module.exports = function inherits(ctor, superCtor) {
+ if (superCtor) {
+ ctor.super_ = superCtor
+ var TempCtor = function () {}
+ TempCtor.prototype = superCtor.prototype
+ ctor.prototype = new TempCtor()
+ ctor.prototype.constructor = ctor
+ }
+ }
+}
diff --git a/temporary_modules/trezor-connect/node_modules/inherits/package.json b/temporary_modules/trezor-connect/node_modules/inherits/package.json
new file mode 100644
index 00000000..37b4366b
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/inherits/package.json
@@ -0,0 +1,29 @@
+{
+ "name": "inherits",
+ "description": "Browser-friendly inheritance fully compatible with standard node.js inherits()",
+ "version": "2.0.4",
+ "keywords": [
+ "inheritance",
+ "class",
+ "klass",
+ "oop",
+ "object-oriented",
+ "inherits",
+ "browser",
+ "browserify"
+ ],
+ "main": "./inherits.js",
+ "browser": "./inherits_browser.js",
+ "repository": "git://github.com/isaacs/inherits",
+ "license": "ISC",
+ "scripts": {
+ "test": "tap"
+ },
+ "devDependencies": {
+ "tap": "^14.2.4"
+ },
+ "files": [
+ "inherits.js",
+ "inherits_browser.js"
+ ]
+}
diff --git a/temporary_modules/trezor-connect/node_modules/ini/LICENSE b/temporary_modules/trezor-connect/node_modules/ini/LICENSE
new file mode 100644
index 00000000..19129e31
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/ini/LICENSE
@@ -0,0 +1,15 @@
+The ISC License
+
+Copyright (c) Isaac Z. Schlueter and Contributors
+
+Permission to use, copy, modify, and/or distribute this software for any
+purpose with or without fee is hereby granted, provided that the above
+copyright notice and this permission notice appear in all copies.
+
+THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
+IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
diff --git a/temporary_modules/trezor-connect/node_modules/ini/README.md b/temporary_modules/trezor-connect/node_modules/ini/README.md
new file mode 100644
index 00000000..33df2582
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/ini/README.md
@@ -0,0 +1,102 @@
+An ini format parser and serializer for node.
+
+Sections are treated as nested objects. Items before the first
+heading are saved on the object directly.
+
+## Usage
+
+Consider an ini-file `config.ini` that looks like this:
+
+ ; this comment is being ignored
+ scope = global
+
+ [database]
+ user = dbuser
+ password = dbpassword
+ database = use_this_database
+
+ [paths.default]
+ datadir = /var/lib/data
+ array[] = first value
+ array[] = second value
+ array[] = third value
+
+You can read, manipulate and write the ini-file like so:
+
+ var fs = require('fs')
+ , ini = require('ini')
+
+ var config = ini.parse(fs.readFileSync('./config.ini', 'utf-8'))
+
+ config.scope = 'local'
+ config.database.database = 'use_another_database'
+ config.paths.default.tmpdir = '/tmp'
+ delete config.paths.default.datadir
+ config.paths.default.array.push('fourth value')
+
+ fs.writeFileSync('./config_modified.ini', ini.stringify(config, { section: 'section' }))
+
+This will result in a file called `config_modified.ini` being written
+to the filesystem with the following content:
+
+ [section]
+ scope=local
+ [section.database]
+ user=dbuser
+ password=dbpassword
+ database=use_another_database
+ [section.paths.default]
+ tmpdir=/tmp
+ array[]=first value
+ array[]=second value
+ array[]=third value
+ array[]=fourth value
+
+
+## API
+
+### decode(inistring)
+
+Decode the ini-style formatted `inistring` into a nested object.
+
+### parse(inistring)
+
+Alias for `decode(inistring)`
+
+### encode(object, [options])
+
+Encode the object `object` into an ini-style formatted string. If the
+optional parameter `section` is given, then all top-level properties
+of the object are put into this section and the `section`-string is
+prepended to all sub-sections, see the usage example above.
+
+The `options` object may contain the following:
+
+* `section` A string which will be the first `section` in the encoded
+ ini data. Defaults to none.
+* `whitespace` Boolean to specify whether to put whitespace around the
+ `=` character. By default, whitespace is omitted, to be friendly to
+ some persnickety old parsers that don't tolerate it well. But some
+ find that it's more human-readable and pretty with the whitespace.
+
+For backwards compatibility reasons, if a `string` options is passed
+in, then it is assumed to be the `section` value.
+
+### stringify(object, [options])
+
+Alias for `encode(object, [options])`
+
+### safe(val)
+
+Escapes the string `val` such that it is safe to be used as a key or
+value in an ini-file. Basically escapes quotes. For example
+
+ ini.safe('"unsafe string"')
+
+would result in
+
+ "\"unsafe string\""
+
+### unsafe(val)
+
+Unescapes the string `val`
diff --git a/temporary_modules/trezor-connect/node_modules/ini/ini.js b/temporary_modules/trezor-connect/node_modules/ini/ini.js
new file mode 100644
index 00000000..b576f08d
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/ini/ini.js
@@ -0,0 +1,206 @@
+exports.parse = exports.decode = decode
+
+exports.stringify = exports.encode = encode
+
+exports.safe = safe
+exports.unsafe = unsafe
+
+var eol = typeof process !== 'undefined' &&
+ process.platform === 'win32' ? '\r\n' : '\n'
+
+function encode (obj, opt) {
+ var children = []
+ var out = ''
+
+ if (typeof opt === 'string') {
+ opt = {
+ section: opt,
+ whitespace: false,
+ }
+ } else {
+ opt = opt || {}
+ opt.whitespace = opt.whitespace === true
+ }
+
+ var separator = opt.whitespace ? ' = ' : '='
+
+ Object.keys(obj).forEach(function (k, _, __) {
+ var val = obj[k]
+ if (val && Array.isArray(val)) {
+ val.forEach(function (item) {
+ out += safe(k + '[]') + separator + safe(item) + '\n'
+ })
+ } else if (val && typeof val === 'object')
+ children.push(k)
+ else
+ out += safe(k) + separator + safe(val) + eol
+ })
+
+ if (opt.section && out.length)
+ out = '[' + safe(opt.section) + ']' + eol + out
+
+ children.forEach(function (k, _, __) {
+ var nk = dotSplit(k).join('\\.')
+ var section = (opt.section ? opt.section + '.' : '') + nk
+ var child = encode(obj[k], {
+ section: section,
+ whitespace: opt.whitespace,
+ })
+ if (out.length && child.length)
+ out += eol
+
+ out += child
+ })
+
+ return out
+}
+
+function dotSplit (str) {
+ return str.replace(/\1/g, '\u0002LITERAL\\1LITERAL\u0002')
+ .replace(/\\\./g, '\u0001')
+ .split(/\./).map(function (part) {
+ return part.replace(/\1/g, '\\.')
+ .replace(/\2LITERAL\\1LITERAL\2/g, '\u0001')
+ })
+}
+
+function decode (str) {
+ var out = {}
+ var p = out
+ var section = null
+ // section |key = value
+ var re = /^\[([^\]]*)\]$|^([^=]+)(=(.*))?$/i
+ var lines = str.split(/[\r\n]+/g)
+
+ lines.forEach(function (line, _, __) {
+ if (!line || line.match(/^\s*[;#]/))
+ return
+ var match = line.match(re)
+ if (!match)
+ return
+ if (match[1] !== undefined) {
+ section = unsafe(match[1])
+ if (section === '__proto__') {
+ // not allowed
+ // keep parsing the section, but don't attach it.
+ p = {}
+ return
+ }
+ p = out[section] = out[section] || {}
+ return
+ }
+ var key = unsafe(match[2])
+ if (key === '__proto__')
+ return
+ var value = match[3] ? unsafe(match[4]) : true
+ switch (value) {
+ case 'true':
+ case 'false':
+ case 'null': value = JSON.parse(value)
+ }
+
+ // Convert keys with '[]' suffix to an array
+ if (key.length > 2 && key.slice(-2) === '[]') {
+ key = key.substring(0, key.length - 2)
+ if (key === '__proto__')
+ return
+ if (!p[key])
+ p[key] = []
+ else if (!Array.isArray(p[key]))
+ p[key] = [p[key]]
+ }
+
+ // safeguard against resetting a previously defined
+ // array by accidentally forgetting the brackets
+ if (Array.isArray(p[key]))
+ p[key].push(value)
+ else
+ p[key] = value
+ })
+
+ // {a:{y:1},"a.b":{x:2}} --> {a:{y:1,b:{x:2}}}
+ // use a filter to return the keys that have to be deleted.
+ Object.keys(out).filter(function (k, _, __) {
+ if (!out[k] ||
+ typeof out[k] !== 'object' ||
+ Array.isArray(out[k]))
+ return false
+
+ // see if the parent section is also an object.
+ // if so, add it to that, and mark this one for deletion
+ var parts = dotSplit(k)
+ var p = out
+ var l = parts.pop()
+ var nl = l.replace(/\\\./g, '.')
+ parts.forEach(function (part, _, __) {
+ if (part === '__proto__')
+ return
+ if (!p[part] || typeof p[part] !== 'object')
+ p[part] = {}
+ p = p[part]
+ })
+ if (p === out && nl === l)
+ return false
+
+ p[nl] = out[k]
+ return true
+ }).forEach(function (del, _, __) {
+ delete out[del]
+ })
+
+ return out
+}
+
+function isQuoted (val) {
+ return (val.charAt(0) === '"' && val.slice(-1) === '"') ||
+ (val.charAt(0) === "'" && val.slice(-1) === "'")
+}
+
+function safe (val) {
+ return (typeof val !== 'string' ||
+ val.match(/[=\r\n]/) ||
+ val.match(/^\[/) ||
+ (val.length > 1 &&
+ isQuoted(val)) ||
+ val !== val.trim())
+ ? JSON.stringify(val)
+ : val.replace(/;/g, '\\;').replace(/#/g, '\\#')
+}
+
+function unsafe (val, doUnesc) {
+ val = (val || '').trim()
+ if (isQuoted(val)) {
+ // remove the single quotes before calling JSON.parse
+ if (val.charAt(0) === "'")
+ val = val.substr(1, val.length - 2)
+
+ try {
+ val = JSON.parse(val)
+ } catch (_) {}
+ } else {
+ // walk the val to find the first not-escaped ; character
+ var esc = false
+ var unesc = ''
+ for (var i = 0, l = val.length; i < l; i++) {
+ var c = val.charAt(i)
+ if (esc) {
+ if ('\\;#'.indexOf(c) !== -1)
+ unesc += c
+ else
+ unesc += '\\' + c
+
+ esc = false
+ } else if (';#'.indexOf(c) !== -1)
+ break
+ else if (c === '\\')
+ esc = true
+ else
+ unesc += c
+ }
+ if (esc)
+ unesc += '\\'
+
+ return unesc.trim()
+ }
+ return val
+}
diff --git a/temporary_modules/trezor-connect/node_modules/ini/package.json b/temporary_modules/trezor-connect/node_modules/ini/package.json
new file mode 100644
index 00000000..c830a355
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/ini/package.json
@@ -0,0 +1,33 @@
+{
+ "author": "Isaac Z. Schlueter (http://blog.izs.me/)",
+ "name": "ini",
+ "description": "An ini encoder/decoder for node",
+ "version": "1.3.8",
+ "repository": {
+ "type": "git",
+ "url": "git://github.com/isaacs/ini.git"
+ },
+ "main": "ini.js",
+ "scripts": {
+ "eslint": "eslint",
+ "lint": "npm run eslint -- ini.js test/*.js",
+ "lintfix": "npm run lint -- --fix",
+ "test": "tap",
+ "posttest": "npm run lint",
+ "preversion": "npm test",
+ "postversion": "npm publish",
+ "prepublishOnly": "git push origin --follow-tags"
+ },
+ "devDependencies": {
+ "eslint": "^7.9.0",
+ "eslint-plugin-import": "^2.22.0",
+ "eslint-plugin-node": "^11.1.0",
+ "eslint-plugin-promise": "^4.2.1",
+ "eslint-plugin-standard": "^4.0.1",
+ "tap": "14"
+ },
+ "license": "ISC",
+ "files": [
+ "ini.js"
+ ]
+}
diff --git a/temporary_modules/trezor-connect/node_modules/is-docker/cli.js b/temporary_modules/trezor-connect/node_modules/is-docker/cli.js
new file mode 100644
index 00000000..58f2861f
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/is-docker/cli.js
@@ -0,0 +1,5 @@
+#!/usr/bin/env node
+'use strict';
+const isDocker = require('.');
+
+process.exitCode = isDocker() ? 0 : 2;
diff --git a/temporary_modules/trezor-connect/node_modules/is-docker/index.d.ts b/temporary_modules/trezor-connect/node_modules/is-docker/index.d.ts
new file mode 100644
index 00000000..c801881d
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/is-docker/index.d.ts
@@ -0,0 +1,15 @@
+/**
+Check if the process is running inside a Docker container.
+
+@example
+```
+import isDocker = require('is-docker');
+
+if (isDocker()) {
+ console.log('Running inside a Docker container');
+}
+```
+*/
+declare function isDocker(): boolean;
+
+export = isDocker;
diff --git a/temporary_modules/trezor-connect/node_modules/is-docker/index.js b/temporary_modules/trezor-connect/node_modules/is-docker/index.js
new file mode 100644
index 00000000..cbb7b6f7
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/is-docker/index.js
@@ -0,0 +1,29 @@
+'use strict';
+const fs = require('fs');
+
+let isDocker;
+
+function hasDockerEnv() {
+ try {
+ fs.statSync('/.dockerenv');
+ return true;
+ } catch (_) {
+ return false;
+ }
+}
+
+function hasDockerCGroup() {
+ try {
+ return fs.readFileSync('/proc/self/cgroup', 'utf8').includes('docker');
+ } catch (_) {
+ return false;
+ }
+}
+
+module.exports = () => {
+ if (isDocker === undefined) {
+ isDocker = hasDockerEnv() || hasDockerCGroup();
+ }
+
+ return isDocker;
+};
diff --git a/temporary_modules/trezor-connect/node_modules/is-docker/license b/temporary_modules/trezor-connect/node_modules/is-docker/license
new file mode 100644
index 00000000..fa7ceba3
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/is-docker/license
@@ -0,0 +1,9 @@
+MIT License
+
+Copyright (c) Sindre Sorhus (https://sindresorhus.com)
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/temporary_modules/trezor-connect/node_modules/is-docker/package.json b/temporary_modules/trezor-connect/node_modules/is-docker/package.json
new file mode 100644
index 00000000..ae282258
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/is-docker/package.json
@@ -0,0 +1,42 @@
+{
+ "name": "is-docker",
+ "version": "2.2.1",
+ "description": "Check if the process is running inside a Docker container",
+ "license": "MIT",
+ "repository": "sindresorhus/is-docker",
+ "funding": "https://github.com/sponsors/sindresorhus",
+ "author": {
+ "name": "Sindre Sorhus",
+ "email": "sindresorhus@gmail.com",
+ "url": "https://sindresorhus.com"
+ },
+ "bin": "cli.js",
+ "engines": {
+ "node": ">=8"
+ },
+ "scripts": {
+ "test": "xo && ava && tsd"
+ },
+ "files": [
+ "index.js",
+ "index.d.ts",
+ "cli.js"
+ ],
+ "keywords": [
+ "detect",
+ "docker",
+ "dockerized",
+ "container",
+ "inside",
+ "is",
+ "env",
+ "environment",
+ "process"
+ ],
+ "devDependencies": {
+ "ava": "^1.4.1",
+ "sinon": "^7.3.2",
+ "tsd": "^0.7.2",
+ "xo": "^0.24.0"
+ }
+}
diff --git a/temporary_modules/trezor-connect/node_modules/is-docker/readme.md b/temporary_modules/trezor-connect/node_modules/is-docker/readme.md
new file mode 100644
index 00000000..f09b254f
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/is-docker/readme.md
@@ -0,0 +1,27 @@
+# is-docker
+
+> Check if the process is running inside a Docker container
+
+## Install
+
+```
+$ npm install is-docker
+```
+
+## Usage
+
+```js
+const isDocker = require('is-docker');
+
+if (isDocker()) {
+ console.log('Running inside a Docker container');
+}
+```
+
+## CLI
+
+```
+$ is-docker
+```
+
+Exits with code 0 if inside a Docker container and 2 if not.
diff --git a/temporary_modules/trezor-connect/node_modules/is-fullwidth-code-point/index.d.ts b/temporary_modules/trezor-connect/node_modules/is-fullwidth-code-point/index.d.ts
new file mode 100644
index 00000000..729d2020
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/is-fullwidth-code-point/index.d.ts
@@ -0,0 +1,17 @@
+/**
+Check if the character represented by a given [Unicode code point](https://en.wikipedia.org/wiki/Code_point) is [fullwidth](https://en.wikipedia.org/wiki/Halfwidth_and_fullwidth_forms).
+
+@param codePoint - The [code point](https://en.wikipedia.org/wiki/Code_point) of a character.
+
+@example
+```
+import isFullwidthCodePoint from 'is-fullwidth-code-point';
+
+isFullwidthCodePoint('谢'.codePointAt(0));
+//=> true
+
+isFullwidthCodePoint('a'.codePointAt(0));
+//=> false
+```
+*/
+export default function isFullwidthCodePoint(codePoint: number): boolean;
diff --git a/temporary_modules/trezor-connect/node_modules/is-fullwidth-code-point/index.js b/temporary_modules/trezor-connect/node_modules/is-fullwidth-code-point/index.js
new file mode 100644
index 00000000..671f97f7
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/is-fullwidth-code-point/index.js
@@ -0,0 +1,50 @@
+/* eslint-disable yoda */
+'use strict';
+
+const isFullwidthCodePoint = codePoint => {
+ if (Number.isNaN(codePoint)) {
+ return false;
+ }
+
+ // Code points are derived from:
+ // http://www.unix.org/Public/UNIDATA/EastAsianWidth.txt
+ if (
+ codePoint >= 0x1100 && (
+ codePoint <= 0x115F || // Hangul Jamo
+ codePoint === 0x2329 || // LEFT-POINTING ANGLE BRACKET
+ codePoint === 0x232A || // RIGHT-POINTING ANGLE BRACKET
+ // CJK Radicals Supplement .. Enclosed CJK Letters and Months
+ (0x2E80 <= codePoint && codePoint <= 0x3247 && codePoint !== 0x303F) ||
+ // Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A
+ (0x3250 <= codePoint && codePoint <= 0x4DBF) ||
+ // CJK Unified Ideographs .. Yi Radicals
+ (0x4E00 <= codePoint && codePoint <= 0xA4C6) ||
+ // Hangul Jamo Extended-A
+ (0xA960 <= codePoint && codePoint <= 0xA97C) ||
+ // Hangul Syllables
+ (0xAC00 <= codePoint && codePoint <= 0xD7A3) ||
+ // CJK Compatibility Ideographs
+ (0xF900 <= codePoint && codePoint <= 0xFAFF) ||
+ // Vertical Forms
+ (0xFE10 <= codePoint && codePoint <= 0xFE19) ||
+ // CJK Compatibility Forms .. Small Form Variants
+ (0xFE30 <= codePoint && codePoint <= 0xFE6B) ||
+ // Halfwidth and Fullwidth Forms
+ (0xFF01 <= codePoint && codePoint <= 0xFF60) ||
+ (0xFFE0 <= codePoint && codePoint <= 0xFFE6) ||
+ // Kana Supplement
+ (0x1B000 <= codePoint && codePoint <= 0x1B001) ||
+ // Enclosed Ideographic Supplement
+ (0x1F200 <= codePoint && codePoint <= 0x1F251) ||
+ // CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane
+ (0x20000 <= codePoint && codePoint <= 0x3FFFD)
+ )
+ ) {
+ return true;
+ }
+
+ return false;
+};
+
+module.exports = isFullwidthCodePoint;
+module.exports.default = isFullwidthCodePoint;
diff --git a/temporary_modules/trezor-connect/node_modules/is-fullwidth-code-point/license b/temporary_modules/trezor-connect/node_modules/is-fullwidth-code-point/license
new file mode 100644
index 00000000..e7af2f77
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/is-fullwidth-code-point/license
@@ -0,0 +1,9 @@
+MIT License
+
+Copyright (c) Sindre Sorhus (sindresorhus.com)
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/temporary_modules/trezor-connect/node_modules/is-fullwidth-code-point/package.json b/temporary_modules/trezor-connect/node_modules/is-fullwidth-code-point/package.json
new file mode 100644
index 00000000..2137e888
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/is-fullwidth-code-point/package.json
@@ -0,0 +1,42 @@
+{
+ "name": "is-fullwidth-code-point",
+ "version": "3.0.0",
+ "description": "Check if the character represented by a given Unicode code point is fullwidth",
+ "license": "MIT",
+ "repository": "sindresorhus/is-fullwidth-code-point",
+ "author": {
+ "name": "Sindre Sorhus",
+ "email": "sindresorhus@gmail.com",
+ "url": "sindresorhus.com"
+ },
+ "engines": {
+ "node": ">=8"
+ },
+ "scripts": {
+ "test": "xo && ava && tsd-check"
+ },
+ "files": [
+ "index.js",
+ "index.d.ts"
+ ],
+ "keywords": [
+ "fullwidth",
+ "full-width",
+ "full",
+ "width",
+ "unicode",
+ "character",
+ "string",
+ "codepoint",
+ "code",
+ "point",
+ "is",
+ "detect",
+ "check"
+ ],
+ "devDependencies": {
+ "ava": "^1.3.1",
+ "tsd-check": "^0.5.0",
+ "xo": "^0.24.0"
+ }
+}
diff --git a/temporary_modules/trezor-connect/node_modules/is-fullwidth-code-point/readme.md b/temporary_modules/trezor-connect/node_modules/is-fullwidth-code-point/readme.md
new file mode 100644
index 00000000..4236bba9
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/is-fullwidth-code-point/readme.md
@@ -0,0 +1,39 @@
+# is-fullwidth-code-point [](https://travis-ci.org/sindresorhus/is-fullwidth-code-point)
+
+> Check if the character represented by a given [Unicode code point](https://en.wikipedia.org/wiki/Code_point) is [fullwidth](https://en.wikipedia.org/wiki/Halfwidth_and_fullwidth_forms)
+
+
+## Install
+
+```
+$ npm install is-fullwidth-code-point
+```
+
+
+## Usage
+
+```js
+const isFullwidthCodePoint = require('is-fullwidth-code-point');
+
+isFullwidthCodePoint('谢'.codePointAt(0));
+//=> true
+
+isFullwidthCodePoint('a'.codePointAt(0));
+//=> false
+```
+
+
+## API
+
+### isFullwidthCodePoint(codePoint)
+
+#### codePoint
+
+Type: `number`
+
+The [code point](https://en.wikipedia.org/wiki/Code_point) of a character.
+
+
+## License
+
+MIT © [Sindre Sorhus](https://sindresorhus.com)
diff --git a/temporary_modules/trezor-connect/node_modules/is-wsl/index.d.ts b/temporary_modules/trezor-connect/node_modules/is-wsl/index.d.ts
new file mode 100644
index 00000000..d54e4bac
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/is-wsl/index.d.ts
@@ -0,0 +1,15 @@
+/**
+Check if the process is running inside [Windows Subsystem for Linux](https://msdn.microsoft.com/commandline/wsl/about) (Bash on Windows).
+
+@example
+```
+import isWsl = require('is-wsl');
+
+// When running inside Windows Subsystem for Linux
+console.log(isWsl);
+//=> true
+```
+*/
+declare const isWsl: boolean;
+
+export = isWsl;
diff --git a/temporary_modules/trezor-connect/node_modules/is-wsl/index.js b/temporary_modules/trezor-connect/node_modules/is-wsl/index.js
new file mode 100644
index 00000000..eb6313f0
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/is-wsl/index.js
@@ -0,0 +1,31 @@
+'use strict';
+const os = require('os');
+const fs = require('fs');
+const isDocker = require('is-docker');
+
+const isWsl = () => {
+ if (process.platform !== 'linux') {
+ return false;
+ }
+
+ if (os.release().toLowerCase().includes('microsoft')) {
+ if (isDocker()) {
+ return false;
+ }
+
+ return true;
+ }
+
+ try {
+ return fs.readFileSync('/proc/version', 'utf8').toLowerCase().includes('microsoft') ?
+ !isDocker() : false;
+ } catch (_) {
+ return false;
+ }
+};
+
+if (process.env.__IS_WSL_TEST__) {
+ module.exports = isWsl;
+} else {
+ module.exports = isWsl();
+}
diff --git a/temporary_modules/trezor-connect/node_modules/is-wsl/license b/temporary_modules/trezor-connect/node_modules/is-wsl/license
new file mode 100644
index 00000000..e7af2f77
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/is-wsl/license
@@ -0,0 +1,9 @@
+MIT License
+
+Copyright (c) Sindre Sorhus (sindresorhus.com)
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/temporary_modules/trezor-connect/node_modules/is-wsl/package.json b/temporary_modules/trezor-connect/node_modules/is-wsl/package.json
new file mode 100644
index 00000000..2fa7f754
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/is-wsl/package.json
@@ -0,0 +1,45 @@
+{
+ "name": "is-wsl",
+ "version": "2.2.0",
+ "description": "Check if the process is running inside Windows Subsystem for Linux (Bash on Windows)",
+ "license": "MIT",
+ "repository": "sindresorhus/is-wsl",
+ "author": {
+ "name": "Sindre Sorhus",
+ "email": "sindresorhus@gmail.com",
+ "url": "sindresorhus.com"
+ },
+ "engines": {
+ "node": ">=8"
+ },
+ "scripts": {
+ "test": "xo && ava && tsd"
+ },
+ "files": [
+ "index.js",
+ "index.d.ts"
+ ],
+ "keywords": [
+ "check",
+ "wsl",
+ "windows",
+ "subsystem",
+ "linux",
+ "detect",
+ "bash",
+ "process",
+ "console",
+ "terminal",
+ "is"
+ ],
+ "dependencies": {
+ "is-docker": "^2.0.0"
+ },
+ "devDependencies": {
+ "ava": "^1.4.1",
+ "clear-module": "^3.2.0",
+ "proxyquire": "^2.1.0",
+ "tsd": "^0.7.2",
+ "xo": "^0.24.0"
+ }
+}
diff --git a/temporary_modules/trezor-connect/node_modules/is-wsl/readme.md b/temporary_modules/trezor-connect/node_modules/is-wsl/readme.md
new file mode 100644
index 00000000..5fe44fed
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/is-wsl/readme.md
@@ -0,0 +1,36 @@
+# is-wsl [](https://travis-ci.org/sindresorhus/is-wsl)
+
+> Check if the process is running inside [Windows Subsystem for Linux](https://msdn.microsoft.com/commandline/wsl/about) (Bash on Windows)
+
+Can be useful if you need to work around unimplemented or buggy features in WSL. Supports both WSL 1 and WSL 2.
+
+
+## Install
+
+```
+$ npm install is-wsl
+```
+
+
+## Usage
+
+```js
+const isWsl = require('is-wsl');
+
+// When running inside Windows Subsystem for Linux
+console.log(isWsl);
+//=> true
+```
+
+
+---
+
+
diff --git a/temporary_modules/trezor-connect/node_modules/isexe/.npmignore b/temporary_modules/trezor-connect/node_modules/isexe/.npmignore
new file mode 100644
index 00000000..c1cb757a
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/isexe/.npmignore
@@ -0,0 +1,2 @@
+.nyc_output/
+coverage/
diff --git a/temporary_modules/trezor-connect/node_modules/isexe/LICENSE b/temporary_modules/trezor-connect/node_modules/isexe/LICENSE
new file mode 100644
index 00000000..19129e31
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/isexe/LICENSE
@@ -0,0 +1,15 @@
+The ISC License
+
+Copyright (c) Isaac Z. Schlueter and Contributors
+
+Permission to use, copy, modify, and/or distribute this software for any
+purpose with or without fee is hereby granted, provided that the above
+copyright notice and this permission notice appear in all copies.
+
+THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
+IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
diff --git a/temporary_modules/trezor-connect/node_modules/isexe/README.md b/temporary_modules/trezor-connect/node_modules/isexe/README.md
new file mode 100644
index 00000000..35769e84
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/isexe/README.md
@@ -0,0 +1,51 @@
+# isexe
+
+Minimal module to check if a file is executable, and a normal file.
+
+Uses `fs.stat` and tests against the `PATHEXT` environment variable on
+Windows.
+
+## USAGE
+
+```javascript
+var isexe = require('isexe')
+isexe('some-file-name', function (err, isExe) {
+ if (err) {
+ console.error('probably file does not exist or something', err)
+ } else if (isExe) {
+ console.error('this thing can be run')
+ } else {
+ console.error('cannot be run')
+ }
+})
+
+// same thing but synchronous, throws errors
+var isExe = isexe.sync('some-file-name')
+
+// treat errors as just "not executable"
+isexe('maybe-missing-file', { ignoreErrors: true }, callback)
+var isExe = isexe.sync('maybe-missing-file', { ignoreErrors: true })
+```
+
+## API
+
+### `isexe(path, [options], [callback])`
+
+Check if the path is executable. If no callback provided, and a
+global `Promise` object is available, then a Promise will be returned.
+
+Will raise whatever errors may be raised by `fs.stat`, unless
+`options.ignoreErrors` is set to true.
+
+### `isexe.sync(path, [options])`
+
+Same as `isexe` but returns the value and throws any errors raised.
+
+### Options
+
+* `ignoreErrors` Treat all errors as "no, this is not executable", but
+ don't raise them.
+* `uid` Number to use as the user id
+* `gid` Number to use as the group id
+* `pathExt` List of path extensions to use instead of `PATHEXT`
+ environment variable on Windows.
diff --git a/temporary_modules/trezor-connect/node_modules/isexe/index.js b/temporary_modules/trezor-connect/node_modules/isexe/index.js
new file mode 100644
index 00000000..553fb32b
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/isexe/index.js
@@ -0,0 +1,57 @@
+var fs = require('fs')
+var core
+if (process.platform === 'win32' || global.TESTING_WINDOWS) {
+ core = require('./windows.js')
+} else {
+ core = require('./mode.js')
+}
+
+module.exports = isexe
+isexe.sync = sync
+
+function isexe (path, options, cb) {
+ if (typeof options === 'function') {
+ cb = options
+ options = {}
+ }
+
+ if (!cb) {
+ if (typeof Promise !== 'function') {
+ throw new TypeError('callback not provided')
+ }
+
+ return new Promise(function (resolve, reject) {
+ isexe(path, options || {}, function (er, is) {
+ if (er) {
+ reject(er)
+ } else {
+ resolve(is)
+ }
+ })
+ })
+ }
+
+ core(path, options || {}, function (er, is) {
+ // ignore EACCES because that just means we aren't allowed to run it
+ if (er) {
+ if (er.code === 'EACCES' || options && options.ignoreErrors) {
+ er = null
+ is = false
+ }
+ }
+ cb(er, is)
+ })
+}
+
+function sync (path, options) {
+ // my kingdom for a filtered catch
+ try {
+ return core.sync(path, options || {})
+ } catch (er) {
+ if (options && options.ignoreErrors || er.code === 'EACCES') {
+ return false
+ } else {
+ throw er
+ }
+ }
+}
diff --git a/temporary_modules/trezor-connect/node_modules/isexe/mode.js b/temporary_modules/trezor-connect/node_modules/isexe/mode.js
new file mode 100644
index 00000000..1995ea4a
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/isexe/mode.js
@@ -0,0 +1,41 @@
+module.exports = isexe
+isexe.sync = sync
+
+var fs = require('fs')
+
+function isexe (path, options, cb) {
+ fs.stat(path, function (er, stat) {
+ cb(er, er ? false : checkStat(stat, options))
+ })
+}
+
+function sync (path, options) {
+ return checkStat(fs.statSync(path), options)
+}
+
+function checkStat (stat, options) {
+ return stat.isFile() && checkMode(stat, options)
+}
+
+function checkMode (stat, options) {
+ var mod = stat.mode
+ var uid = stat.uid
+ var gid = stat.gid
+
+ var myUid = options.uid !== undefined ?
+ options.uid : process.getuid && process.getuid()
+ var myGid = options.gid !== undefined ?
+ options.gid : process.getgid && process.getgid()
+
+ var u = parseInt('100', 8)
+ var g = parseInt('010', 8)
+ var o = parseInt('001', 8)
+ var ug = u | g
+
+ var ret = (mod & o) ||
+ (mod & g) && gid === myGid ||
+ (mod & u) && uid === myUid ||
+ (mod & ug) && myUid === 0
+
+ return ret
+}
diff --git a/temporary_modules/trezor-connect/node_modules/isexe/package.json b/temporary_modules/trezor-connect/node_modules/isexe/package.json
new file mode 100644
index 00000000..e4526894
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/isexe/package.json
@@ -0,0 +1,31 @@
+{
+ "name": "isexe",
+ "version": "2.0.0",
+ "description": "Minimal module to check if a file is executable.",
+ "main": "index.js",
+ "directories": {
+ "test": "test"
+ },
+ "devDependencies": {
+ "mkdirp": "^0.5.1",
+ "rimraf": "^2.5.0",
+ "tap": "^10.3.0"
+ },
+ "scripts": {
+ "test": "tap test/*.js --100",
+ "preversion": "npm test",
+ "postversion": "npm publish",
+ "postpublish": "git push origin --all; git push origin --tags"
+ },
+ "author": "Isaac Z. Schlueter (http://blog.izs.me/)",
+ "license": "ISC",
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/isaacs/isexe.git"
+ },
+ "keywords": [],
+ "bugs": {
+ "url": "https://github.com/isaacs/isexe/issues"
+ },
+ "homepage": "https://github.com/isaacs/isexe#readme"
+}
diff --git a/temporary_modules/trezor-connect/node_modules/isexe/test/basic.js b/temporary_modules/trezor-connect/node_modules/isexe/test/basic.js
new file mode 100644
index 00000000..d926df64
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/isexe/test/basic.js
@@ -0,0 +1,221 @@
+var t = require('tap')
+var fs = require('fs')
+var path = require('path')
+var fixture = path.resolve(__dirname, 'fixtures')
+var meow = fixture + '/meow.cat'
+var mine = fixture + '/mine.cat'
+var ours = fixture + '/ours.cat'
+var fail = fixture + '/fail.false'
+var noent = fixture + '/enoent.exe'
+var mkdirp = require('mkdirp')
+var rimraf = require('rimraf')
+
+var isWindows = process.platform === 'win32'
+var hasAccess = typeof fs.access === 'function'
+var winSkip = isWindows && 'windows'
+var accessSkip = !hasAccess && 'no fs.access function'
+var hasPromise = typeof Promise === 'function'
+var promiseSkip = !hasPromise && 'no global Promise'
+
+function reset () {
+ delete require.cache[require.resolve('../')]
+ return require('../')
+}
+
+t.test('setup fixtures', function (t) {
+ rimraf.sync(fixture)
+ mkdirp.sync(fixture)
+ fs.writeFileSync(meow, '#!/usr/bin/env cat\nmeow\n')
+ fs.chmodSync(meow, parseInt('0755', 8))
+ fs.writeFileSync(fail, '#!/usr/bin/env false\n')
+ fs.chmodSync(fail, parseInt('0644', 8))
+ fs.writeFileSync(mine, '#!/usr/bin/env cat\nmine\n')
+ fs.chmodSync(mine, parseInt('0744', 8))
+ fs.writeFileSync(ours, '#!/usr/bin/env cat\nours\n')
+ fs.chmodSync(ours, parseInt('0754', 8))
+ t.end()
+})
+
+t.test('promise', { skip: promiseSkip }, function (t) {
+ var isexe = reset()
+ t.test('meow async', function (t) {
+ isexe(meow).then(function (is) {
+ t.ok(is)
+ t.end()
+ })
+ })
+ t.test('fail async', function (t) {
+ isexe(fail).then(function (is) {
+ t.notOk(is)
+ t.end()
+ })
+ })
+ t.test('noent async', function (t) {
+ isexe(noent).catch(function (er) {
+ t.ok(er)
+ t.end()
+ })
+ })
+ t.test('noent ignore async', function (t) {
+ isexe(noent, { ignoreErrors: true }).then(function (is) {
+ t.notOk(is)
+ t.end()
+ })
+ })
+ t.end()
+})
+
+t.test('no promise', function (t) {
+ global.Promise = null
+ var isexe = reset()
+ t.throws('try to meow a promise', function () {
+ isexe(meow)
+ })
+ t.end()
+})
+
+t.test('access', { skip: accessSkip || winSkip }, function (t) {
+ runTest(t)
+})
+
+t.test('mode', { skip: winSkip }, function (t) {
+ delete fs.access
+ delete fs.accessSync
+ var isexe = reset()
+ t.ok(isexe.sync(ours, { uid: 0, gid: 0 }))
+ t.ok(isexe.sync(mine, { uid: 0, gid: 0 }))
+ runTest(t)
+})
+
+t.test('windows', function (t) {
+ global.TESTING_WINDOWS = true
+ var pathExt = '.EXE;.CAT;.CMD;.COM'
+ t.test('pathExt option', function (t) {
+ runTest(t, { pathExt: '.EXE;.CAT;.CMD;.COM' })
+ })
+ t.test('pathExt env', function (t) {
+ process.env.PATHEXT = pathExt
+ runTest(t)
+ })
+ t.test('no pathExt', function (t) {
+ // with a pathExt of '', any filename is fine.
+ // so the "fail" one would still pass.
+ runTest(t, { pathExt: '', skipFail: true })
+ })
+ t.test('pathext with empty entry', function (t) {
+ // with a pathExt of '', any filename is fine.
+ // so the "fail" one would still pass.
+ runTest(t, { pathExt: ';' + pathExt, skipFail: true })
+ })
+ t.end()
+})
+
+t.test('cleanup', function (t) {
+ rimraf.sync(fixture)
+ t.end()
+})
+
+function runTest (t, options) {
+ var isexe = reset()
+
+ var optionsIgnore = Object.create(options || {})
+ optionsIgnore.ignoreErrors = true
+
+ if (!options || !options.skipFail) {
+ t.notOk(isexe.sync(fail, options))
+ }
+ t.notOk(isexe.sync(noent, optionsIgnore))
+ if (!options) {
+ t.ok(isexe.sync(meow))
+ } else {
+ t.ok(isexe.sync(meow, options))
+ }
+
+ t.ok(isexe.sync(mine, options))
+ t.ok(isexe.sync(ours, options))
+ t.throws(function () {
+ isexe.sync(noent, options)
+ })
+
+ t.test('meow async', function (t) {
+ if (!options) {
+ isexe(meow, function (er, is) {
+ if (er) {
+ throw er
+ }
+ t.ok(is)
+ t.end()
+ })
+ } else {
+ isexe(meow, options, function (er, is) {
+ if (er) {
+ throw er
+ }
+ t.ok(is)
+ t.end()
+ })
+ }
+ })
+
+ t.test('mine async', function (t) {
+ isexe(mine, options, function (er, is) {
+ if (er) {
+ throw er
+ }
+ t.ok(is)
+ t.end()
+ })
+ })
+
+ t.test('ours async', function (t) {
+ isexe(ours, options, function (er, is) {
+ if (er) {
+ throw er
+ }
+ t.ok(is)
+ t.end()
+ })
+ })
+
+ if (!options || !options.skipFail) {
+ t.test('fail async', function (t) {
+ isexe(fail, options, function (er, is) {
+ if (er) {
+ throw er
+ }
+ t.notOk(is)
+ t.end()
+ })
+ })
+ }
+
+ t.test('noent async', function (t) {
+ isexe(noent, options, function (er, is) {
+ t.ok(er)
+ t.notOk(is)
+ t.end()
+ })
+ })
+
+ t.test('noent ignore async', function (t) {
+ isexe(noent, optionsIgnore, function (er, is) {
+ if (er) {
+ throw er
+ }
+ t.notOk(is)
+ t.end()
+ })
+ })
+
+ t.test('directory is not executable', function (t) {
+ isexe(__dirname, options, function (er, is) {
+ if (er) {
+ throw er
+ }
+ t.notOk(is)
+ t.end()
+ })
+ })
+
+ t.end()
+}
diff --git a/temporary_modules/trezor-connect/node_modules/isexe/windows.js b/temporary_modules/trezor-connect/node_modules/isexe/windows.js
new file mode 100644
index 00000000..34996734
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/isexe/windows.js
@@ -0,0 +1,42 @@
+module.exports = isexe
+isexe.sync = sync
+
+var fs = require('fs')
+
+function checkPathExt (path, options) {
+ var pathext = options.pathExt !== undefined ?
+ options.pathExt : process.env.PATHEXT
+
+ if (!pathext) {
+ return true
+ }
+
+ pathext = pathext.split(';')
+ if (pathext.indexOf('') !== -1) {
+ return true
+ }
+ for (var i = 0; i < pathext.length; i++) {
+ var p = pathext[i].toLowerCase()
+ if (p && path.substr(-p.length).toLowerCase() === p) {
+ return true
+ }
+ }
+ return false
+}
+
+function checkStat (stat, path, options) {
+ if (!stat.isSymbolicLink() && !stat.isFile()) {
+ return false
+ }
+ return checkPathExt(path, options)
+}
+
+function isexe (path, options, cb) {
+ fs.stat(path, function (er, stat) {
+ cb(er, er ? false : checkStat(stat, path, options))
+ })
+}
+
+function sync (path, options) {
+ return checkStat(fs.statSync(path), path, options)
+}
diff --git a/temporary_modules/trezor-connect/node_modules/jsonfile/CHANGELOG.md b/temporary_modules/trezor-connect/node_modules/jsonfile/CHANGELOG.md
new file mode 100644
index 00000000..d772e438
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/jsonfile/CHANGELOG.md
@@ -0,0 +1,171 @@
+6.1.0 / 2020-10-31
+------------------
+
+- Add `finalEOL` option to disable writing final EOL ([#115](https://github.com/jprichardson/node-jsonfile/issues/115), [#137](https://github.com/jprichardson/node-jsonfile/pull/137))
+- Update dependency ([#138](https://github.com/jprichardson/node-jsonfile/pull/138))
+
+6.0.1 / 2020-03-07
+------------------
+
+- Update dependency ([#130](https://github.com/jprichardson/node-jsonfile/pull/130))
+- Fix code style ([#129](https://github.com/jprichardson/node-jsonfile/pull/129))
+
+6.0.0 / 2020-02-24
+------------------
+
+- **BREAKING:** Drop support for Node 6 & 8 ([#128](https://github.com/jprichardson/node-jsonfile/pull/128))
+- **BREAKING:** Do not allow passing `null` as options to `readFile()` or `writeFile()` ([#128](https://github.com/jprichardson/node-jsonfile/pull/128))
+- Refactor internals ([#128](https://github.com/jprichardson/node-jsonfile/pull/128))
+
+5.0.0 / 2018-09-08
+------------------
+
+- **BREAKING:** Drop Node 4 support
+- **BREAKING:** If no callback is passed to an asynchronous method, a promise is now returned ([#109](https://github.com/jprichardson/node-jsonfile/pull/109))
+- Cleanup docs
+
+4.0.0 / 2017-07-12
+------------------
+
+- **BREAKING:** Remove global `spaces` option.
+- **BREAKING:** Drop support for Node 0.10, 0.12, and io.js.
+- Remove undocumented `passParsingErrors` option.
+- Added `EOL` override option to `writeFile` when using `spaces`. [#89]
+
+3.0.1 / 2017-07-05
+------------------
+
+- Fixed bug in `writeFile` when there was a serialization error & no callback was passed. In previous versions, an empty file would be written; now no file is written.
+
+3.0.0 / 2017-04-25
+------------------
+
+- Changed behavior of `throws` option for `readFileSync`; now does not throw filesystem errors when `throws` is `false`
+
+2.4.0 / 2016-09-15
+------------------
+### Changed
+- added optional support for `graceful-fs` [#62]
+
+2.3.1 / 2016-05-13
+------------------
+- fix to support BOM. [#45][#45]
+
+2.3.0 / 2016-04-16
+------------------
+- add `throws` to `readFile()`. See [#39][#39]
+- add support for any arbitrary `fs` module. Useful with [mock-fs](https://www.npmjs.com/package/mock-fs)
+
+2.2.3 / 2015-10-14
+------------------
+- include file name in parse error. See: https://github.com/jprichardson/node-jsonfile/pull/34
+
+2.2.2 / 2015-09-16
+------------------
+- split out tests into separate files
+- fixed `throws` when set to `true` in `readFileSync()`. See: https://github.com/jprichardson/node-jsonfile/pull/33
+
+2.2.1 / 2015-06-25
+------------------
+- fixed regression when passing in string as encoding for options in `writeFile()` and `writeFileSync()`. See: https://github.com/jprichardson/node-jsonfile/issues/28
+
+2.2.0 / 2015-06-25
+------------------
+- added `options.spaces` to `writeFile()` and `writeFileSync()`
+
+2.1.2 / 2015-06-22
+------------------
+- fixed if passed `readFileSync(file, 'utf8')`. See: https://github.com/jprichardson/node-jsonfile/issues/25
+
+2.1.1 / 2015-06-19
+------------------
+- fixed regressions if `null` is passed for options. See: https://github.com/jprichardson/node-jsonfile/issues/24
+
+2.1.0 / 2015-06-19
+------------------
+- cleanup: JavaScript Standard Style, rename files, dropped terst for assert
+- methods now support JSON revivers/replacers
+
+2.0.1 / 2015-05-24
+------------------
+- update license attribute https://github.com/jprichardson/node-jsonfile/pull/21
+
+2.0.0 / 2014-07-28
+------------------
+* added `\n` to end of file on write. [#14](https://github.com/jprichardson/node-jsonfile/pull/14)
+* added `options.throws` to `readFileSync()`
+* dropped support for Node v0.8
+
+1.2.0 / 2014-06-29
+------------------
+* removed semicolons
+* bugfix: passed `options` to `fs.readFile` and `fs.readFileSync`. This technically changes behavior, but
+changes it according to docs. [#12][#12]
+
+1.1.1 / 2013-11-11
+------------------
+* fixed catching of callback bug (ffissore / #5)
+
+1.1.0 / 2013-10-11
+------------------
+* added `options` param to methods, (seanodell / #4)
+
+1.0.1 / 2013-09-05
+------------------
+* removed `homepage` field from package.json to remove NPM warning
+
+1.0.0 / 2013-06-28
+------------------
+* added `.npmignore`, #1
+* changed spacing default from `4` to `2` to follow Node conventions
+
+0.0.1 / 2012-09-10
+------------------
+* Initial release.
+
+[#89]: https://github.com/jprichardson/node-jsonfile/pull/89
+[#45]: https://github.com/jprichardson/node-jsonfile/issues/45 "Reading of UTF8-encoded (w/ BOM) files fails"
+[#44]: https://github.com/jprichardson/node-jsonfile/issues/44 "Extra characters in written file"
+[#43]: https://github.com/jprichardson/node-jsonfile/issues/43 "Prettyfy json when written to file"
+[#42]: https://github.com/jprichardson/node-jsonfile/pull/42 "Moved fs.readFileSync within the try/catch"
+[#41]: https://github.com/jprichardson/node-jsonfile/issues/41 "Linux: Hidden file not working"
+[#40]: https://github.com/jprichardson/node-jsonfile/issues/40 "autocreate folder doesn't work from Path-value"
+[#39]: https://github.com/jprichardson/node-jsonfile/pull/39 "Add `throws` option for readFile (async)"
+[#38]: https://github.com/jprichardson/node-jsonfile/pull/38 "Update README.md writeFile[Sync] signature"
+[#37]: https://github.com/jprichardson/node-jsonfile/pull/37 "support append file"
+[#36]: https://github.com/jprichardson/node-jsonfile/pull/36 "Add typescript definition file."
+[#35]: https://github.com/jprichardson/node-jsonfile/pull/35 "Add typescript definition file."
+[#34]: https://github.com/jprichardson/node-jsonfile/pull/34 "readFile JSON parse error includes filename"
+[#33]: https://github.com/jprichardson/node-jsonfile/pull/33 "fix throw->throws typo in readFileSync()"
+[#32]: https://github.com/jprichardson/node-jsonfile/issues/32 "readFile & readFileSync can possible have strip-comments as an option?"
+[#31]: https://github.com/jprichardson/node-jsonfile/pull/31 "[Modify] Support string include is unicode escape string"
+[#30]: https://github.com/jprichardson/node-jsonfile/issues/30 "How to use Jsonfile package in Meteor.js App?"
+[#29]: https://github.com/jprichardson/node-jsonfile/issues/29 "writefile callback if no error?"
+[#28]: https://github.com/jprichardson/node-jsonfile/issues/28 "writeFile options argument broken "
+[#27]: https://github.com/jprichardson/node-jsonfile/pull/27 "Use svg instead of png to get better image quality"
+[#26]: https://github.com/jprichardson/node-jsonfile/issues/26 "Breaking change to fs-extra"
+[#25]: https://github.com/jprichardson/node-jsonfile/issues/25 "support string encoding param for read methods"
+[#24]: https://github.com/jprichardson/node-jsonfile/issues/24 "readFile: Passing in null options with a callback throws an error"
+[#23]: https://github.com/jprichardson/node-jsonfile/pull/23 "Add appendFile and appendFileSync"
+[#22]: https://github.com/jprichardson/node-jsonfile/issues/22 "Default value for spaces in readme.md is outdated"
+[#21]: https://github.com/jprichardson/node-jsonfile/pull/21 "Update license attribute"
+[#20]: https://github.com/jprichardson/node-jsonfile/issues/20 "Add simple caching functionallity"
+[#19]: https://github.com/jprichardson/node-jsonfile/pull/19 "Add appendFileSync method"
+[#18]: https://github.com/jprichardson/node-jsonfile/issues/18 "Add updateFile and updateFileSync methods"
+[#17]: https://github.com/jprichardson/node-jsonfile/issues/17 "seem read & write sync has sequentially problem"
+[#16]: https://github.com/jprichardson/node-jsonfile/pull/16 "export spaces defaulted to null"
+[#15]: https://github.com/jprichardson/node-jsonfile/issues/15 "`jsonfile.spaces` should default to `null`"
+[#14]: https://github.com/jprichardson/node-jsonfile/pull/14 "Add EOL at EOF"
+[#13]: https://github.com/jprichardson/node-jsonfile/issues/13 "Add a final newline"
+[#12]: https://github.com/jprichardson/node-jsonfile/issues/12 "readFile doesn't accept options"
+[#11]: https://github.com/jprichardson/node-jsonfile/pull/11 "Added try,catch to readFileSync"
+[#10]: https://github.com/jprichardson/node-jsonfile/issues/10 "No output or error from writeFile"
+[#9]: https://github.com/jprichardson/node-jsonfile/pull/9 "Change 'js' to 'jf' in example."
+[#8]: https://github.com/jprichardson/node-jsonfile/pull/8 "Updated forgotten module.exports to me."
+[#7]: https://github.com/jprichardson/node-jsonfile/pull/7 "Add file name in error message"
+[#6]: https://github.com/jprichardson/node-jsonfile/pull/6 "Use graceful-fs when possible"
+[#5]: https://github.com/jprichardson/node-jsonfile/pull/5 "Jsonfile doesn't behave nicely when used inside a test suite."
+[#4]: https://github.com/jprichardson/node-jsonfile/pull/4 "Added options parameter to writeFile and writeFileSync"
+[#3]: https://github.com/jprichardson/node-jsonfile/issues/3 "test2"
+[#2]: https://github.com/jprichardson/node-jsonfile/issues/2 "homepage field must be a string url. Deleted."
+[#1]: https://github.com/jprichardson/node-jsonfile/pull/1 "adding an `.npmignore` file"
diff --git a/temporary_modules/trezor-connect/node_modules/jsonfile/LICENSE b/temporary_modules/trezor-connect/node_modules/jsonfile/LICENSE
new file mode 100644
index 00000000..cb7e807b
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/jsonfile/LICENSE
@@ -0,0 +1,15 @@
+(The MIT License)
+
+Copyright (c) 2012-2015, JP Richardson
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files
+(the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify,
+ merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
+WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
+OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+ ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/temporary_modules/trezor-connect/node_modules/jsonfile/README.md b/temporary_modules/trezor-connect/node_modules/jsonfile/README.md
new file mode 100644
index 00000000..910cde00
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/jsonfile/README.md
@@ -0,0 +1,230 @@
+Node.js - jsonfile
+================
+
+Easily read/write JSON files in Node.js. _Note: this module cannot be used in the browser._
+
+[](https://www.npmjs.org/package/jsonfile)
+[](http://travis-ci.org/jprichardson/node-jsonfile)
+[](https://ci.appveyor.com/project/jprichardson/node-jsonfile/branch/master)
+
+
+
+Why?
+----
+
+Writing `JSON.stringify()` and then `fs.writeFile()` and `JSON.parse()` with `fs.readFile()` enclosed in `try/catch` blocks became annoying.
+
+
+
+Installation
+------------
+
+ npm install --save jsonfile
+
+
+
+API
+---
+
+* [`readFile(filename, [options], callback)`](#readfilefilename-options-callback)
+* [`readFileSync(filename, [options])`](#readfilesyncfilename-options)
+* [`writeFile(filename, obj, [options], callback)`](#writefilefilename-obj-options-callback)
+* [`writeFileSync(filename, obj, [options])`](#writefilesyncfilename-obj-options)
+
+----
+
+### readFile(filename, [options], callback)
+
+`options` (`object`, default `undefined`): Pass in any [`fs.readFile`](https://nodejs.org/api/fs.html#fs_fs_readfile_path_options_callback) options or set `reviver` for a [JSON reviver](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse).
+ - `throws` (`boolean`, default: `true`). If `JSON.parse` throws an error, pass this error to the callback.
+ If `false`, returns `null` for the object.
+
+
+```js
+const jsonfile = require('jsonfile')
+const file = '/tmp/data.json'
+jsonfile.readFile(file, function (err, obj) {
+ if (err) console.error(err)
+ console.dir(obj)
+})
+```
+
+You can also use this method with promises. The `readFile` method will return a promise if you do not pass a callback function.
+
+```js
+const jsonfile = require('jsonfile')
+const file = '/tmp/data.json'
+jsonfile.readFile(file)
+ .then(obj => console.dir(obj))
+ .catch(error => console.error(error))
+```
+
+----
+
+### readFileSync(filename, [options])
+
+`options` (`object`, default `undefined`): Pass in any [`fs.readFileSync`](https://nodejs.org/api/fs.html#fs_fs_readfilesync_path_options) options or set `reviver` for a [JSON reviver](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse).
+- `throws` (`boolean`, default: `true`). If an error is encountered reading or parsing the file, throw the error. If `false`, returns `null` for the object.
+
+```js
+const jsonfile = require('jsonfile')
+const file = '/tmp/data.json'
+
+console.dir(jsonfile.readFileSync(file))
+```
+
+----
+
+### writeFile(filename, obj, [options], callback)
+
+`options`: Pass in any [`fs.writeFile`](https://nodejs.org/api/fs.html#fs_fs_writefile_file_data_options_callback) options or set `replacer` for a [JSON replacer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify). Can also pass in `spaces`, or override `EOL` string or set `finalEOL` flag as `false` to not save the file with `EOL` at the end.
+
+
+```js
+const jsonfile = require('jsonfile')
+
+const file = '/tmp/data.json'
+const obj = { name: 'JP' }
+
+jsonfile.writeFile(file, obj, function (err) {
+ if (err) console.error(err)
+})
+```
+Or use with promises as follows:
+
+```js
+const jsonfile = require('jsonfile')
+
+const file = '/tmp/data.json'
+const obj = { name: 'JP' }
+
+jsonfile.writeFile(file, obj)
+ .then(res => {
+ console.log('Write complete')
+ })
+ .catch(error => console.error(error))
+```
+
+
+**formatting with spaces:**
+
+```js
+const jsonfile = require('jsonfile')
+
+const file = '/tmp/data.json'
+const obj = { name: 'JP' }
+
+jsonfile.writeFile(file, obj, { spaces: 2 }, function (err) {
+ if (err) console.error(err)
+})
+```
+
+**overriding EOL:**
+
+```js
+const jsonfile = require('jsonfile')
+
+const file = '/tmp/data.json'
+const obj = { name: 'JP' }
+
+jsonfile.writeFile(file, obj, { spaces: 2, EOL: '\r\n' }, function (err) {
+ if (err) console.error(err)
+})
+```
+
+
+**disabling the EOL at the end of file:**
+
+```js
+const jsonfile = require('jsonfile')
+
+const file = '/tmp/data.json'
+const obj = { name: 'JP' }
+
+jsonfile.writeFile(file, obj, { spaces: 2, finalEOL: false }, function (err) {
+ if (err) console.log(err)
+})
+```
+
+**appending to an existing JSON file:**
+
+You can use `fs.writeFile` option `{ flag: 'a' }` to achieve this.
+
+```js
+const jsonfile = require('jsonfile')
+
+const file = '/tmp/mayAlreadyExistedData.json'
+const obj = { name: 'JP' }
+
+jsonfile.writeFile(file, obj, { flag: 'a' }, function (err) {
+ if (err) console.error(err)
+})
+```
+
+----
+
+### writeFileSync(filename, obj, [options])
+
+`options`: Pass in any [`fs.writeFileSync`](https://nodejs.org/api/fs.html#fs_fs_writefilesync_file_data_options) options or set `replacer` for a [JSON replacer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify). Can also pass in `spaces`, or override `EOL` string or set `finalEOL` flag as `false` to not save the file with `EOL` at the end.
+
+```js
+const jsonfile = require('jsonfile')
+
+const file = '/tmp/data.json'
+const obj = { name: 'JP' }
+
+jsonfile.writeFileSync(file, obj)
+```
+
+**formatting with spaces:**
+
+```js
+const jsonfile = require('jsonfile')
+
+const file = '/tmp/data.json'
+const obj = { name: 'JP' }
+
+jsonfile.writeFileSync(file, obj, { spaces: 2 })
+```
+
+**overriding EOL:**
+
+```js
+const jsonfile = require('jsonfile')
+
+const file = '/tmp/data.json'
+const obj = { name: 'JP' }
+
+jsonfile.writeFileSync(file, obj, { spaces: 2, EOL: '\r\n' })
+```
+
+**disabling the EOL at the end of file:**
+
+```js
+const jsonfile = require('jsonfile')
+
+const file = '/tmp/data.json'
+const obj = { name: 'JP' }
+
+jsonfile.writeFileSync(file, obj, { spaces: 2, finalEOL: false })
+```
+
+**appending to an existing JSON file:**
+
+You can use `fs.writeFileSync` option `{ flag: 'a' }` to achieve this.
+
+```js
+const jsonfile = require('jsonfile')
+
+const file = '/tmp/mayAlreadyExistedData.json'
+const obj = { name: 'JP' }
+
+jsonfile.writeFileSync(file, obj, { flag: 'a' })
+```
+
+License
+-------
+
+(MIT License)
+
+Copyright 2012-2016, JP Richardson
diff --git a/temporary_modules/trezor-connect/node_modules/jsonfile/index.js b/temporary_modules/trezor-connect/node_modules/jsonfile/index.js
new file mode 100644
index 00000000..0582868f
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/jsonfile/index.js
@@ -0,0 +1,88 @@
+let _fs
+try {
+ _fs = require('graceful-fs')
+} catch (_) {
+ _fs = require('fs')
+}
+const universalify = require('universalify')
+const { stringify, stripBom } = require('./utils')
+
+async function _readFile (file, options = {}) {
+ if (typeof options === 'string') {
+ options = { encoding: options }
+ }
+
+ const fs = options.fs || _fs
+
+ const shouldThrow = 'throws' in options ? options.throws : true
+
+ let data = await universalify.fromCallback(fs.readFile)(file, options)
+
+ data = stripBom(data)
+
+ let obj
+ try {
+ obj = JSON.parse(data, options ? options.reviver : null)
+ } catch (err) {
+ if (shouldThrow) {
+ err.message = `${file}: ${err.message}`
+ throw err
+ } else {
+ return null
+ }
+ }
+
+ return obj
+}
+
+const readFile = universalify.fromPromise(_readFile)
+
+function readFileSync (file, options = {}) {
+ if (typeof options === 'string') {
+ options = { encoding: options }
+ }
+
+ const fs = options.fs || _fs
+
+ const shouldThrow = 'throws' in options ? options.throws : true
+
+ try {
+ let content = fs.readFileSync(file, options)
+ content = stripBom(content)
+ return JSON.parse(content, options.reviver)
+ } catch (err) {
+ if (shouldThrow) {
+ err.message = `${file}: ${err.message}`
+ throw err
+ } else {
+ return null
+ }
+ }
+}
+
+async function _writeFile (file, obj, options = {}) {
+ const fs = options.fs || _fs
+
+ const str = stringify(obj, options)
+
+ await universalify.fromCallback(fs.writeFile)(file, str, options)
+}
+
+const writeFile = universalify.fromPromise(_writeFile)
+
+function writeFileSync (file, obj, options = {}) {
+ const fs = options.fs || _fs
+
+ const str = stringify(obj, options)
+ // not sure if fs.writeFileSync returns anything, but just in case
+ return fs.writeFileSync(file, str, options)
+}
+
+const jsonfile = {
+ readFile,
+ readFileSync,
+ writeFile,
+ writeFileSync
+}
+
+module.exports = jsonfile
diff --git a/temporary_modules/trezor-connect/node_modules/jsonfile/package.json b/temporary_modules/trezor-connect/node_modules/jsonfile/package.json
new file mode 100644
index 00000000..4d01eb1d
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/jsonfile/package.json
@@ -0,0 +1,40 @@
+{
+ "name": "jsonfile",
+ "version": "6.1.0",
+ "description": "Easily read/write JSON files.",
+ "repository": {
+ "type": "git",
+ "url": "git@github.com:jprichardson/node-jsonfile.git"
+ },
+ "keywords": [
+ "read",
+ "write",
+ "file",
+ "json",
+ "fs",
+ "fs-extra"
+ ],
+ "author": "JP Richardson ",
+ "license": "MIT",
+ "dependencies": {
+ "universalify": "^2.0.0"
+ },
+ "optionalDependencies": {
+ "graceful-fs": "^4.1.6"
+ },
+ "devDependencies": {
+ "mocha": "^8.2.0",
+ "rimraf": "^2.4.0",
+ "standard": "^16.0.1"
+ },
+ "main": "index.js",
+ "files": [
+ "index.js",
+ "utils.js"
+ ],
+ "scripts": {
+ "lint": "standard",
+ "test": "npm run lint && npm run unit",
+ "unit": "mocha"
+ }
+}
diff --git a/temporary_modules/trezor-connect/node_modules/jsonfile/utils.js b/temporary_modules/trezor-connect/node_modules/jsonfile/utils.js
new file mode 100644
index 00000000..b5ff48e5
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/jsonfile/utils.js
@@ -0,0 +1,14 @@
+function stringify (obj, { EOL = '\n', finalEOL = true, replacer = null, spaces } = {}) {
+ const EOF = finalEOL ? EOL : ''
+ const str = JSON.stringify(obj, replacer, spaces)
+
+ return str.replace(/\n/g, EOL) + EOF
+}
+
+function stripBom (content) {
+ // we do this because JSON.parse would convert it to a utf8 string if encoding wasn't specified
+ if (Buffer.isBuffer(content)) content = content.toString('utf8')
+ return content.replace(/^\uFEFF/, '')
+}
+
+module.exports = { stringify, stripBom }
diff --git a/temporary_modules/trezor-connect/node_modules/kleur/colors.d.ts b/temporary_modules/trezor-connect/node_modules/kleur/colors.d.ts
new file mode 100644
index 00000000..cab25c66
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/kleur/colors.d.ts
@@ -0,0 +1,38 @@
+declare function print(input: string | boolean | number): string;
+declare function print(input: undefined | void): undefined;
+declare function print(input: null): null;
+type Colorize = typeof print;
+
+export declare const $: { enabled: boolean };
+
+// Colors
+export declare const black: Colorize;
+export declare const red: Colorize;
+export declare const green: Colorize;
+export declare const yellow: Colorize;
+export declare const blue: Colorize;
+export declare const magenta: Colorize;
+export declare const cyan: Colorize;
+export declare const white: Colorize;
+export declare const gray: Colorize;
+export declare const grey: Colorize;
+
+// Backgrounds
+export declare const bgBlack: Colorize;
+export declare const bgRed: Colorize;
+export declare const bgGreen: Colorize;
+export declare const bgYellow: Colorize;
+export declare const bgBlue: Colorize;
+export declare const bgMagenta: Colorize;
+export declare const bgCyan: Colorize;
+export declare const bgWhite: Colorize;
+
+// Modifiers
+export declare const reset: Colorize;
+export declare const bold: Colorize;
+export declare const dim: Colorize;
+export declare const italic: Colorize;
+export declare const underline: Colorize;
+export declare const inverse: Colorize;
+export declare const hidden: Colorize;
+export declare const strikethrough: Colorize;
diff --git a/temporary_modules/trezor-connect/node_modules/kleur/colors.js b/temporary_modules/trezor-connect/node_modules/kleur/colors.js
new file mode 100644
index 00000000..695a538c
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/kleur/colors.js
@@ -0,0 +1,53 @@
+let FORCE_COLOR, NODE_DISABLE_COLORS, NO_COLOR, TERM, isTTY=true;
+if (typeof process !== 'undefined') {
+ ({ FORCE_COLOR, NODE_DISABLE_COLORS, NO_COLOR, TERM } = process.env);
+ isTTY = process.stdout && process.stdout.isTTY;
+}
+
+const $ = exports.$ = {
+ enabled: !NODE_DISABLE_COLORS && NO_COLOR == null && TERM !== 'dumb' && (
+ FORCE_COLOR != null && FORCE_COLOR !== '0' || isTTY
+ )
+}
+
+function init(x, y) {
+ let rgx = new RegExp(`\\x1b\\[${y}m`, 'g');
+ let open = `\x1b[${x}m`, close = `\x1b[${y}m`;
+
+ return function (txt) {
+ if (!$.enabled || txt == null) return txt;
+ return open + (!!~(''+txt).indexOf(close) ? txt.replace(rgx, close + open) : txt) + close;
+ };
+}
+
+// modifiers
+exports.reset = init(0, 0);
+exports.bold = init(1, 22);
+exports.dim = init(2, 22);
+exports.italic = init(3, 23);
+exports.underline = init(4, 24);
+exports.inverse = init(7, 27);
+exports.hidden = init(8, 28);
+exports.strikethrough = init(9, 29);
+
+// colors
+exports.black = init(30, 39);
+exports.red = init(31, 39);
+exports.green = init(32, 39);
+exports.yellow = init(33, 39);
+exports.blue = init(34, 39);
+exports.magenta = init(35, 39);
+exports.cyan = init(36, 39);
+exports.white = init(37, 39);
+exports.gray = init(90, 39);
+exports.grey = init(90, 39);
+
+// background colors
+exports.bgBlack = init(40, 49);
+exports.bgRed = init(41, 49);
+exports.bgGreen = init(42, 49);
+exports.bgYellow = init(43, 49);
+exports.bgBlue = init(44, 49);
+exports.bgMagenta = init(45, 49);
+exports.bgCyan = init(46, 49);
+exports.bgWhite = init(47, 49);
diff --git a/temporary_modules/trezor-connect/node_modules/kleur/colors.mjs b/temporary_modules/trezor-connect/node_modules/kleur/colors.mjs
new file mode 100644
index 00000000..401843cc
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/kleur/colors.mjs
@@ -0,0 +1,53 @@
+let FORCE_COLOR, NODE_DISABLE_COLORS, NO_COLOR, TERM, isTTY=true;
+if (typeof process !== 'undefined') {
+ ({ FORCE_COLOR, NODE_DISABLE_COLORS, NO_COLOR, TERM } = process.env);
+ isTTY = process.stdout && process.stdout.isTTY;
+}
+
+export const $ = {
+ enabled: !NODE_DISABLE_COLORS && NO_COLOR == null && TERM !== 'dumb' && (
+ FORCE_COLOR != null && FORCE_COLOR !== '0' || isTTY
+ )
+}
+
+function init(x, y) {
+ let rgx = new RegExp(`\\x1b\\[${y}m`, 'g');
+ let open = `\x1b[${x}m`, close = `\x1b[${y}m`;
+
+ return function (txt) {
+ if (!$.enabled || txt == null) return txt;
+ return open + (!!~(''+txt).indexOf(close) ? txt.replace(rgx, close + open) : txt) + close;
+ };
+}
+
+// modifiers
+export const reset = init(0, 0);
+export const bold = init(1, 22);
+export const dim = init(2, 22);
+export const italic = init(3, 23);
+export const underline = init(4, 24);
+export const inverse = init(7, 27);
+export const hidden = init(8, 28);
+export const strikethrough = init(9, 29);
+
+// colors
+export const black = init(30, 39);
+export const red = init(31, 39);
+export const green = init(32, 39);
+export const yellow = init(33, 39);
+export const blue = init(34, 39);
+export const magenta = init(35, 39);
+export const cyan = init(36, 39);
+export const white = init(37, 39);
+export const gray = init(90, 39);
+export const grey = init(90, 39);
+
+// background colors
+export const bgBlack = init(40, 49);
+export const bgRed = init(41, 49);
+export const bgGreen = init(42, 49);
+export const bgYellow = init(43, 49);
+export const bgBlue = init(44, 49);
+export const bgMagenta = init(45, 49);
+export const bgCyan = init(46, 49);
+export const bgWhite = init(47, 49);
diff --git a/temporary_modules/trezor-connect/node_modules/kleur/index.d.ts b/temporary_modules/trezor-connect/node_modules/kleur/index.d.ts
new file mode 100644
index 00000000..fdc26ca9
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/kleur/index.d.ts
@@ -0,0 +1,45 @@
+// Originally by: Rogier Schouten
+// Adapted by: Madhav Varshney
+declare namespace kleur {
+ interface Color {
+ (x: string | number): string;
+ (): Kleur;
+ }
+
+ interface Kleur {
+ // Colors
+ black: Color;
+ red: Color;
+ green: Color;
+ yellow: Color;
+ blue: Color;
+ magenta: Color;
+ cyan: Color;
+ white: Color;
+ gray: Color;
+ grey: Color;
+
+ // Backgrounds
+ bgBlack: Color;
+ bgRed: Color;
+ bgGreen: Color;
+ bgYellow: Color;
+ bgBlue: Color;
+ bgMagenta: Color;
+ bgCyan: Color;
+ bgWhite: Color;
+
+ // Modifiers
+ reset: Color;
+ bold: Color;
+ dim: Color;
+ italic: Color;
+ underline: Color;
+ inverse: Color;
+ hidden: Color;
+ strikethrough: Color;
+ }
+}
+
+declare let kleur: kleur.Kleur & { enabled: boolean };
+export = kleur;
diff --git a/temporary_modules/trezor-connect/node_modules/kleur/index.js b/temporary_modules/trezor-connect/node_modules/kleur/index.js
new file mode 100644
index 00000000..a4570cff
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/kleur/index.js
@@ -0,0 +1,110 @@
+'use strict';
+
+let FORCE_COLOR, NODE_DISABLE_COLORS, NO_COLOR, TERM, isTTY=true;
+if (typeof process !== 'undefined') {
+ ({ FORCE_COLOR, NODE_DISABLE_COLORS, NO_COLOR, TERM } = process.env);
+ isTTY = process.stdout && process.stdout.isTTY;
+}
+
+const $ = {
+ enabled: !NODE_DISABLE_COLORS && NO_COLOR == null && TERM !== 'dumb' && (
+ FORCE_COLOR != null && FORCE_COLOR !== '0' || isTTY
+ ),
+
+ // modifiers
+ reset: init(0, 0),
+ bold: init(1, 22),
+ dim: init(2, 22),
+ italic: init(3, 23),
+ underline: init(4, 24),
+ inverse: init(7, 27),
+ hidden: init(8, 28),
+ strikethrough: init(9, 29),
+
+ // colors
+ black: init(30, 39),
+ red: init(31, 39),
+ green: init(32, 39),
+ yellow: init(33, 39),
+ blue: init(34, 39),
+ magenta: init(35, 39),
+ cyan: init(36, 39),
+ white: init(37, 39),
+ gray: init(90, 39),
+ grey: init(90, 39),
+
+ // background colors
+ bgBlack: init(40, 49),
+ bgRed: init(41, 49),
+ bgGreen: init(42, 49),
+ bgYellow: init(43, 49),
+ bgBlue: init(44, 49),
+ bgMagenta: init(45, 49),
+ bgCyan: init(46, 49),
+ bgWhite: init(47, 49)
+};
+
+function run(arr, str) {
+ let i=0, tmp, beg='', end='';
+ for (; i < arr.length; i++) {
+ tmp = arr[i];
+ beg += tmp.open;
+ end += tmp.close;
+ if (!!~str.indexOf(tmp.close)) {
+ str = str.replace(tmp.rgx, tmp.close + tmp.open);
+ }
+ }
+ return beg + str + end;
+}
+
+function chain(has, keys) {
+ let ctx = { has, keys };
+
+ ctx.reset = $.reset.bind(ctx);
+ ctx.bold = $.bold.bind(ctx);
+ ctx.dim = $.dim.bind(ctx);
+ ctx.italic = $.italic.bind(ctx);
+ ctx.underline = $.underline.bind(ctx);
+ ctx.inverse = $.inverse.bind(ctx);
+ ctx.hidden = $.hidden.bind(ctx);
+ ctx.strikethrough = $.strikethrough.bind(ctx);
+
+ ctx.black = $.black.bind(ctx);
+ ctx.red = $.red.bind(ctx);
+ ctx.green = $.green.bind(ctx);
+ ctx.yellow = $.yellow.bind(ctx);
+ ctx.blue = $.blue.bind(ctx);
+ ctx.magenta = $.magenta.bind(ctx);
+ ctx.cyan = $.cyan.bind(ctx);
+ ctx.white = $.white.bind(ctx);
+ ctx.gray = $.gray.bind(ctx);
+ ctx.grey = $.grey.bind(ctx);
+
+ ctx.bgBlack = $.bgBlack.bind(ctx);
+ ctx.bgRed = $.bgRed.bind(ctx);
+ ctx.bgGreen = $.bgGreen.bind(ctx);
+ ctx.bgYellow = $.bgYellow.bind(ctx);
+ ctx.bgBlue = $.bgBlue.bind(ctx);
+ ctx.bgMagenta = $.bgMagenta.bind(ctx);
+ ctx.bgCyan = $.bgCyan.bind(ctx);
+ ctx.bgWhite = $.bgWhite.bind(ctx);
+
+ return ctx;
+}
+
+function init(open, close) {
+ let blk = {
+ open: `\x1b[${open}m`,
+ close: `\x1b[${close}m`,
+ rgx: new RegExp(`\\x1b\\[${close}m`, 'g')
+ };
+ return function (txt) {
+ if (this !== void 0 && this.has !== void 0) {
+ !!~this.has.indexOf(open) || (this.has.push(open),this.keys.push(blk));
+ return txt === void 0 ? this : $.enabled ? run(this.keys, txt+'') : txt+'';
+ }
+ return txt === void 0 ? chain([open], [blk]) : $.enabled ? run([blk], txt+'') : txt+'';
+ };
+}
+
+module.exports = $;
diff --git a/temporary_modules/trezor-connect/node_modules/kleur/index.mjs b/temporary_modules/trezor-connect/node_modules/kleur/index.mjs
new file mode 100644
index 00000000..32e7fa17
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/kleur/index.mjs
@@ -0,0 +1,110 @@
+'use strict';
+
+let FORCE_COLOR, NODE_DISABLE_COLORS, NO_COLOR, TERM, isTTY=true;
+if (typeof process !== 'undefined') {
+ ({ FORCE_COLOR, NODE_DISABLE_COLORS, NO_COLOR, TERM } = process.env);
+ isTTY = process.stdout && process.stdout.isTTY;
+}
+
+const $ = {
+ enabled: !NODE_DISABLE_COLORS && NO_COLOR == null && TERM !== 'dumb' && (
+ FORCE_COLOR != null && FORCE_COLOR !== '0' || isTTY
+ ),
+
+ // modifiers
+ reset: init(0, 0),
+ bold: init(1, 22),
+ dim: init(2, 22),
+ italic: init(3, 23),
+ underline: init(4, 24),
+ inverse: init(7, 27),
+ hidden: init(8, 28),
+ strikethrough: init(9, 29),
+
+ // colors
+ black: init(30, 39),
+ red: init(31, 39),
+ green: init(32, 39),
+ yellow: init(33, 39),
+ blue: init(34, 39),
+ magenta: init(35, 39),
+ cyan: init(36, 39),
+ white: init(37, 39),
+ gray: init(90, 39),
+ grey: init(90, 39),
+
+ // background colors
+ bgBlack: init(40, 49),
+ bgRed: init(41, 49),
+ bgGreen: init(42, 49),
+ bgYellow: init(43, 49),
+ bgBlue: init(44, 49),
+ bgMagenta: init(45, 49),
+ bgCyan: init(46, 49),
+ bgWhite: init(47, 49)
+};
+
+function run(arr, str) {
+ let i=0, tmp, beg='', end='';
+ for (; i < arr.length; i++) {
+ tmp = arr[i];
+ beg += tmp.open;
+ end += tmp.close;
+ if (!!~str.indexOf(tmp.close)) {
+ str = str.replace(tmp.rgx, tmp.close + tmp.open);
+ }
+ }
+ return beg + str + end;
+}
+
+function chain(has, keys) {
+ let ctx = { has, keys };
+
+ ctx.reset = $.reset.bind(ctx);
+ ctx.bold = $.bold.bind(ctx);
+ ctx.dim = $.dim.bind(ctx);
+ ctx.italic = $.italic.bind(ctx);
+ ctx.underline = $.underline.bind(ctx);
+ ctx.inverse = $.inverse.bind(ctx);
+ ctx.hidden = $.hidden.bind(ctx);
+ ctx.strikethrough = $.strikethrough.bind(ctx);
+
+ ctx.black = $.black.bind(ctx);
+ ctx.red = $.red.bind(ctx);
+ ctx.green = $.green.bind(ctx);
+ ctx.yellow = $.yellow.bind(ctx);
+ ctx.blue = $.blue.bind(ctx);
+ ctx.magenta = $.magenta.bind(ctx);
+ ctx.cyan = $.cyan.bind(ctx);
+ ctx.white = $.white.bind(ctx);
+ ctx.gray = $.gray.bind(ctx);
+ ctx.grey = $.grey.bind(ctx);
+
+ ctx.bgBlack = $.bgBlack.bind(ctx);
+ ctx.bgRed = $.bgRed.bind(ctx);
+ ctx.bgGreen = $.bgGreen.bind(ctx);
+ ctx.bgYellow = $.bgYellow.bind(ctx);
+ ctx.bgBlue = $.bgBlue.bind(ctx);
+ ctx.bgMagenta = $.bgMagenta.bind(ctx);
+ ctx.bgCyan = $.bgCyan.bind(ctx);
+ ctx.bgWhite = $.bgWhite.bind(ctx);
+
+ return ctx;
+}
+
+function init(open, close) {
+ let blk = {
+ open: `\x1b[${open}m`,
+ close: `\x1b[${close}m`,
+ rgx: new RegExp(`\\x1b\\[${close}m`, 'g')
+ };
+ return function (txt) {
+ if (this !== void 0 && this.has !== void 0) {
+ !!~this.has.indexOf(open) || (this.has.push(open),this.keys.push(blk));
+ return txt === void 0 ? this : $.enabled ? run(this.keys, txt+'') : txt+'';
+ }
+ return txt === void 0 ? chain([open], [blk]) : $.enabled ? run([blk], txt+'') : txt+'';
+ };
+}
+
+export default $;
diff --git a/temporary_modules/trezor-connect/node_modules/kleur/license b/temporary_modules/trezor-connect/node_modules/kleur/license
new file mode 100644
index 00000000..a3f96f82
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/kleur/license
@@ -0,0 +1,21 @@
+The MIT License (MIT)
+
+Copyright (c) Luke Edwards (lukeed.com)
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
diff --git a/temporary_modules/trezor-connect/node_modules/kleur/package.json b/temporary_modules/trezor-connect/node_modules/kleur/package.json
new file mode 100644
index 00000000..9993c44e
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/kleur/package.json
@@ -0,0 +1,49 @@
+{
+ "name": "kleur",
+ "version": "4.1.4",
+ "repository": "lukeed/kleur",
+ "description": "The fastest Node.js library for formatting terminal text with ANSI colors~!",
+ "module": "index.mjs",
+ "types": "index.d.ts",
+ "main": "index.js",
+ "license": "MIT",
+ "exports": {
+ ".": {
+ "import": "./index.mjs",
+ "require": "./index.js"
+ },
+ "./colors": {
+ "import": "./colors.mjs",
+ "require": "./colors.js"
+ }
+ },
+ "files": [
+ "*.d.ts",
+ "colors.*",
+ "index.*"
+ ],
+ "author": {
+ "name": "Luke Edwards",
+ "email": "luke.edwards05@gmail.com",
+ "url": "https://lukeed.com"
+ },
+ "scripts": {
+ "build": "node build",
+ "test": "uvu -r esm -i utils -i xyz"
+ },
+ "engines": {
+ "node": ">=6"
+ },
+ "keywords": [
+ "ansi",
+ "cli",
+ "color",
+ "colors",
+ "console",
+ "terminal"
+ ],
+ "devDependencies": {
+ "esm": "3.2.25",
+ "uvu": "0.3.3"
+ }
+}
diff --git a/temporary_modules/trezor-connect/node_modules/kleur/readme.md b/temporary_modules/trezor-connect/node_modules/kleur/readme.md
new file mode 100644
index 00000000..de7f5aa0
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/kleur/readme.md
@@ -0,0 +1,232 @@
+
+

+
+
+
+
+The fastest Node.js library for formatting terminal text with ANSI colors~!
+
+## Features
+
+* No dependencies
+* Super [lightweight](#load-time) & [performant](#performance)
+* Supports [nested](#nested-methods) & [chained](#chained-methods) colors
+* No `String.prototype` modifications
+* Conditional [color support](#conditional-support)
+* [Fully treeshakable](#individual-colors)
+* Familiar [API](#api)
+
+---
+
+As of `v3.0` the Chalk-style syntax (magical getter) is no longer used.
Please visit [History](#history) for migration paths supporting that syntax.
+
+---
+
+
+## Install
+
+```
+$ npm install --save kleur
+```
+
+
+## Usage
+
+```js
+import kleur from 'kleur';
+
+// basic usage
+kleur.red('red text');
+
+// chained methods
+kleur.blue().bold().underline('howdy partner');
+
+// nested methods
+kleur.bold(`${ white().bgRed('[ERROR]') } ${ kleur.red().italic('Something happened')}`);
+```
+
+### Chained Methods
+
+```js
+const { bold, green } = require('kleur');
+
+console.log(bold().red('this is a bold red message'));
+console.log(bold().italic('this is a bold italicized message'));
+console.log(bold().yellow().bgRed().italic('this is a bold yellow italicized message'));
+console.log(green().bold().underline('this is a bold green underlined message'));
+```
+
+
+
+### Nested Methods
+
+```js
+const { yellow, red, cyan } = require('kleur');
+
+console.log(yellow(`foo ${red().bold('red')} bar ${cyan('cyan')} baz`));
+console.log(yellow('foo ' + red().bold('red') + ' bar ' + cyan('cyan') + ' baz'));
+```
+
+
+
+
+### Conditional Support
+
+Toggle color support as needed; `kleur` includes simple auto-detection which may not cover all cases.
+
+> **Note:** Both `kleur` and `kleur/colors` share the same detection logic.
+
+```js
+import kleur from 'kleur';
+
+// manually disable
+kleur.enabled = false;
+
+// or use another library to detect support
+kleur.enabled = require('color-support').level > 0;
+
+console.log(kleur.red('I will only be colored red if the terminal supports colors'));
+```
+
+> **Important:**
Colors will be disabled automatically in non [TTY contexts](https://nodejs.org/api/process.html#process_a_note_on_process_i_o). For example, spawning another process or piping output into another process will disable colorization automatically. To force colors in your piped output, you may do so with the `FORCE_COLOR=1` environment variable:
+
+```sh
+$ node app.js #=> COLORS
+$ node app.js > log.txt #=> NO COLORS
+$ FORCE_COLOR=1 node app.js > log.txt #=> COLORS
+$ FORCE_COLOR=0 node app.js > log.txt #=> NO COLORS
+```
+
+## API
+
+Any `kleur` method returns a `String` when invoked with input; otherwise chaining is expected.
+
+> It's up to the developer to pass the output to destinations like `console.log`, `process.stdout.write`, etc.
+
+The methods below are grouped by type for legibility purposes only. They each can be [chained](#chained-methods) or [nested](#nested-methods) with one another.
+
+***Colors:***
+> black — red — green — yellow — blue — magenta — cyan — white — gray — grey
+
+***Backgrounds:***
+> bgBlack — bgRed — bgGreen — bgYellow — bgBlue — bgMagenta — bgCyan — bgWhite
+
+***Modifiers:***
+> reset — bold — dim — italic* — underline — inverse — hidden — strikethrough*
+
+* Not widely supported
+
+
+## Individual Colors
+
+When you only need a few colors, it doesn't make sense to import _all_ of `kleur` because, as small as it is, `kleur` is not treeshakeable, and so most of its code will be doing nothing. In order to fix this, you can import from the `kleur/colors` submodule which _fully_ supports tree-shaking.
+
+The caveat with this approach is that color functions **are not** chainable~!
Each function receives and colorizes its input. You may combine colors, backgrounds, and modifiers by nesting function calls within other functions.
+
+```js
+// or: import * as kleur from 'kleur/colors';
+import { red, underline, bgWhite } from 'kleur/colors';
+
+red('red text');
+//~> kleur.red('red text');
+
+underline(red('red underlined text'));
+//~> kleur.underline().red('red underlined text');
+
+bgWhite(underline(red('red underlined text w/ white background')));
+//~> kleur.bgWhite().underline().red('red underlined text w/ white background');
+```
+
+> **Note:** All the same [colors, backgrounds, and modifiers](#api) are available.
+
+***Conditional Support***
+
+The `kleur/colors` submodule also allows you to toggle color support, as needed.
+It includes the same initial assumptions as `kleur`, in an attempt to have colors enabled by default.
+
+Unlike `kleur`, this setting exists as `kleur.$.enabled` instead of `kleur.enabled`:
+
+```js
+import * as kleur from 'kleur/colors';
+// or: import { $, red } from 'kleur/colors';
+
+// manually disabled
+kleur.$.enabled = false;
+
+// or use another library to detect support
+kleur.$.enabled = require('color-support').level > 0;
+
+console.log(red('I will only be colored red if the terminal supports colors'));
+```
+
+
+## Benchmarks
+
+> Using Node v10.13.0
+
+### Load time
+
+```
+chalk :: 5.303ms
+kleur :: 0.488ms
+kleur/colors :: 0.369ms
+ansi-colors :: 1.504ms
+```
+
+### Performance
+
+```
+# All Colors
+ ansi-colors x 177,625 ops/sec ±1.47% (92 runs sampled)
+ chalk x 611,907 ops/sec ±0.20% (92 runs sampled)
+ kleur x 742,509 ops/sec ±1.47% (93 runs sampled)
+ kleur/colors x 881,742 ops/sec ±0.19% (98 runs sampled)
+
+# Stacked colors
+ ansi-colors x 23,331 ops/sec ±1.81% (94 runs sampled)
+ chalk x 337,178 ops/sec ±0.20% (98 runs sampled)
+ kleur x 78,299 ops/sec ±1.01% (97 runs sampled)
+ kleur/colors x 104,431 ops/sec ±0.22% (97 runs sampled)
+
+# Nested colors
+ ansi-colors x 67,181 ops/sec ±1.15% (92 runs sampled)
+ chalk x 116,361 ops/sec ±0.63% (94 runs sampled)
+ kleur x 139,514 ops/sec ±0.76% (95 runs sampled)
+ kleur/colors x 145,716 ops/sec ±0.97% (97 runs sampled)
+```
+
+
+## History
+
+This project originally forked [`ansi-colors`](https://github.com/doowb/ansi-colors).
+
+Beginning with `kleur@3.0`, the Chalk-style syntax (magical getter) has been replaced with function calls per key:
+
+```js
+// Old:
+c.red.bold.underline('old');
+
+// New:
+c.red().bold().underline('new');
+```
+> As I work more with Rust, the newer syntax feels so much better & more natural!
+
+If you prefer the old syntax, you may migrate to `ansi-colors` or newer `chalk` releases.
Versions below `kleur@3.0` have been officially deprecated.
+
+
+## License
+
+MIT © [Luke Edwards](https://lukeed.com)
diff --git a/temporary_modules/trezor-connect/node_modules/lru-cache/LICENSE b/temporary_modules/trezor-connect/node_modules/lru-cache/LICENSE
new file mode 100644
index 00000000..19129e31
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/lru-cache/LICENSE
@@ -0,0 +1,15 @@
+The ISC License
+
+Copyright (c) Isaac Z. Schlueter and Contributors
+
+Permission to use, copy, modify, and/or distribute this software for any
+purpose with or without fee is hereby granted, provided that the above
+copyright notice and this permission notice appear in all copies.
+
+THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
+IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
diff --git a/temporary_modules/trezor-connect/node_modules/lru-cache/README.md b/temporary_modules/trezor-connect/node_modules/lru-cache/README.md
new file mode 100644
index 00000000..435dfebb
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/lru-cache/README.md
@@ -0,0 +1,166 @@
+# lru cache
+
+A cache object that deletes the least-recently-used items.
+
+[](https://travis-ci.org/isaacs/node-lru-cache) [](https://coveralls.io/github/isaacs/node-lru-cache)
+
+## Installation:
+
+```javascript
+npm install lru-cache --save
+```
+
+## Usage:
+
+```javascript
+var LRU = require("lru-cache")
+ , options = { max: 500
+ , length: function (n, key) { return n * 2 + key.length }
+ , dispose: function (key, n) { n.close() }
+ , maxAge: 1000 * 60 * 60 }
+ , cache = new LRU(options)
+ , otherCache = new LRU(50) // sets just the max size
+
+cache.set("key", "value")
+cache.get("key") // "value"
+
+// non-string keys ARE fully supported
+// but note that it must be THE SAME object, not
+// just a JSON-equivalent object.
+var someObject = { a: 1 }
+cache.set(someObject, 'a value')
+// Object keys are not toString()-ed
+cache.set('[object Object]', 'a different value')
+assert.equal(cache.get(someObject), 'a value')
+// A similar object with same keys/values won't work,
+// because it's a different object identity
+assert.equal(cache.get({ a: 1 }), undefined)
+
+cache.reset() // empty the cache
+```
+
+If you put more stuff in it, then items will fall out.
+
+If you try to put an oversized thing in it, then it'll fall out right
+away.
+
+## Options
+
+* `max` The maximum size of the cache, checked by applying the length
+ function to all values in the cache. Not setting this is kind of
+ silly, since that's the whole purpose of this lib, but it defaults
+ to `Infinity`. Setting it to a non-number or negative number will
+ throw a `TypeError`. Setting it to 0 makes it be `Infinity`.
+* `maxAge` Maximum age in ms. Items are not pro-actively pruned out
+ as they age, but if you try to get an item that is too old, it'll
+ drop it and return undefined instead of giving it to you.
+ Setting this to a negative value will make everything seem old!
+ Setting it to a non-number will throw a `TypeError`.
+* `length` Function that is used to calculate the length of stored
+ items. If you're storing strings or buffers, then you probably want
+ to do something like `function(n, key){return n.length}`. The default is
+ `function(){return 1}`, which is fine if you want to store `max`
+ like-sized things. The item is passed as the first argument, and
+ the key is passed as the second argumnet.
+* `dispose` Function that is called on items when they are dropped
+ from the cache. This can be handy if you want to close file
+ descriptors or do other cleanup tasks when items are no longer
+ accessible. Called with `key, value`. It's called *before*
+ actually removing the item from the internal cache, so if you want
+ to immediately put it back in, you'll have to do that in a
+ `nextTick` or `setTimeout` callback or it won't do anything.
+* `stale` By default, if you set a `maxAge`, it'll only actually pull
+ stale items out of the cache when you `get(key)`. (That is, it's
+ not pre-emptively doing a `setTimeout` or anything.) If you set
+ `stale:true`, it'll return the stale value before deleting it. If
+ you don't set this, then it'll return `undefined` when you try to
+ get a stale entry, as if it had already been deleted.
+* `noDisposeOnSet` By default, if you set a `dispose()` method, then
+ it'll be called whenever a `set()` operation overwrites an existing
+ key. If you set this option, `dispose()` will only be called when a
+ key falls out of the cache, not when it is overwritten.
+* `updateAgeOnGet` When using time-expiring entries with `maxAge`,
+ setting this to `true` will make each item's effective time update
+ to the current time whenever it is retrieved from cache, causing it
+ to not expire. (It can still fall out of cache based on recency of
+ use, of course.)
+
+## API
+
+* `set(key, value, maxAge)`
+* `get(key) => value`
+
+ Both of these will update the "recently used"-ness of the key.
+ They do what you think. `maxAge` is optional and overrides the
+ cache `maxAge` option if provided.
+
+ If the key is not found, `get()` will return `undefined`.
+
+ The key and val can be any value.
+
+* `peek(key)`
+
+ Returns the key value (or `undefined` if not found) without
+ updating the "recently used"-ness of the key.
+
+ (If you find yourself using this a lot, you *might* be using the
+ wrong sort of data structure, but there are some use cases where
+ it's handy.)
+
+* `del(key)`
+
+ Deletes a key out of the cache.
+
+* `reset()`
+
+ Clear the cache entirely, throwing away all values.
+
+* `has(key)`
+
+ Check if a key is in the cache, without updating the recent-ness
+ or deleting it for being stale.
+
+* `forEach(function(value,key,cache), [thisp])`
+
+ Just like `Array.prototype.forEach`. Iterates over all the keys
+ in the cache, in order of recent-ness. (Ie, more recently used
+ items are iterated over first.)
+
+* `rforEach(function(value,key,cache), [thisp])`
+
+ The same as `cache.forEach(...)` but items are iterated over in
+ reverse order. (ie, less recently used items are iterated over
+ first.)
+
+* `keys()`
+
+ Return an array of the keys in the cache.
+
+* `values()`
+
+ Return an array of the values in the cache.
+
+* `length`
+
+ Return total length of objects in cache taking into account
+ `length` options function.
+
+* `itemCount`
+
+ Return total quantity of objects currently in cache. Note, that
+ `stale` (see options) items are returned as part of this item
+ count.
+
+* `dump()`
+
+ Return an array of the cache entries ready for serialization and usage
+ with 'destinationCache.load(arr)`.
+
+* `load(cacheEntriesArray)`
+
+ Loads another cache entries array, obtained with `sourceCache.dump()`,
+ into the cache. The destination cache is reset before loading new entries
+
+* `prune()`
+
+ Manually iterates over the entire cache proactively pruning old entries
diff --git a/temporary_modules/trezor-connect/node_modules/lru-cache/index.js b/temporary_modules/trezor-connect/node_modules/lru-cache/index.js
new file mode 100644
index 00000000..573b6b85
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/lru-cache/index.js
@@ -0,0 +1,334 @@
+'use strict'
+
+// A linked list to keep track of recently-used-ness
+const Yallist = require('yallist')
+
+const MAX = Symbol('max')
+const LENGTH = Symbol('length')
+const LENGTH_CALCULATOR = Symbol('lengthCalculator')
+const ALLOW_STALE = Symbol('allowStale')
+const MAX_AGE = Symbol('maxAge')
+const DISPOSE = Symbol('dispose')
+const NO_DISPOSE_ON_SET = Symbol('noDisposeOnSet')
+const LRU_LIST = Symbol('lruList')
+const CACHE = Symbol('cache')
+const UPDATE_AGE_ON_GET = Symbol('updateAgeOnGet')
+
+const naiveLength = () => 1
+
+// lruList is a yallist where the head is the youngest
+// item, and the tail is the oldest. the list contains the Hit
+// objects as the entries.
+// Each Hit object has a reference to its Yallist.Node. This
+// never changes.
+//
+// cache is a Map (or PseudoMap) that matches the keys to
+// the Yallist.Node object.
+class LRUCache {
+ constructor (options) {
+ if (typeof options === 'number')
+ options = { max: options }
+
+ if (!options)
+ options = {}
+
+ if (options.max && (typeof options.max !== 'number' || options.max < 0))
+ throw new TypeError('max must be a non-negative number')
+ // Kind of weird to have a default max of Infinity, but oh well.
+ const max = this[MAX] = options.max || Infinity
+
+ const lc = options.length || naiveLength
+ this[LENGTH_CALCULATOR] = (typeof lc !== 'function') ? naiveLength : lc
+ this[ALLOW_STALE] = options.stale || false
+ if (options.maxAge && typeof options.maxAge !== 'number')
+ throw new TypeError('maxAge must be a number')
+ this[MAX_AGE] = options.maxAge || 0
+ this[DISPOSE] = options.dispose
+ this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false
+ this[UPDATE_AGE_ON_GET] = options.updateAgeOnGet || false
+ this.reset()
+ }
+
+ // resize the cache when the max changes.
+ set max (mL) {
+ if (typeof mL !== 'number' || mL < 0)
+ throw new TypeError('max must be a non-negative number')
+
+ this[MAX] = mL || Infinity
+ trim(this)
+ }
+ get max () {
+ return this[MAX]
+ }
+
+ set allowStale (allowStale) {
+ this[ALLOW_STALE] = !!allowStale
+ }
+ get allowStale () {
+ return this[ALLOW_STALE]
+ }
+
+ set maxAge (mA) {
+ if (typeof mA !== 'number')
+ throw new TypeError('maxAge must be a non-negative number')
+
+ this[MAX_AGE] = mA
+ trim(this)
+ }
+ get maxAge () {
+ return this[MAX_AGE]
+ }
+
+ // resize the cache when the lengthCalculator changes.
+ set lengthCalculator (lC) {
+ if (typeof lC !== 'function')
+ lC = naiveLength
+
+ if (lC !== this[LENGTH_CALCULATOR]) {
+ this[LENGTH_CALCULATOR] = lC
+ this[LENGTH] = 0
+ this[LRU_LIST].forEach(hit => {
+ hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key)
+ this[LENGTH] += hit.length
+ })
+ }
+ trim(this)
+ }
+ get lengthCalculator () { return this[LENGTH_CALCULATOR] }
+
+ get length () { return this[LENGTH] }
+ get itemCount () { return this[LRU_LIST].length }
+
+ rforEach (fn, thisp) {
+ thisp = thisp || this
+ for (let walker = this[LRU_LIST].tail; walker !== null;) {
+ const prev = walker.prev
+ forEachStep(this, fn, walker, thisp)
+ walker = prev
+ }
+ }
+
+ forEach (fn, thisp) {
+ thisp = thisp || this
+ for (let walker = this[LRU_LIST].head; walker !== null;) {
+ const next = walker.next
+ forEachStep(this, fn, walker, thisp)
+ walker = next
+ }
+ }
+
+ keys () {
+ return this[LRU_LIST].toArray().map(k => k.key)
+ }
+
+ values () {
+ return this[LRU_LIST].toArray().map(k => k.value)
+ }
+
+ reset () {
+ if (this[DISPOSE] &&
+ this[LRU_LIST] &&
+ this[LRU_LIST].length) {
+ this[LRU_LIST].forEach(hit => this[DISPOSE](hit.key, hit.value))
+ }
+
+ this[CACHE] = new Map() // hash of items by key
+ this[LRU_LIST] = new Yallist() // list of items in order of use recency
+ this[LENGTH] = 0 // length of items in the list
+ }
+
+ dump () {
+ return this[LRU_LIST].map(hit =>
+ isStale(this, hit) ? false : {
+ k: hit.key,
+ v: hit.value,
+ e: hit.now + (hit.maxAge || 0)
+ }).toArray().filter(h => h)
+ }
+
+ dumpLru () {
+ return this[LRU_LIST]
+ }
+
+ set (key, value, maxAge) {
+ maxAge = maxAge || this[MAX_AGE]
+
+ if (maxAge && typeof maxAge !== 'number')
+ throw new TypeError('maxAge must be a number')
+
+ const now = maxAge ? Date.now() : 0
+ const len = this[LENGTH_CALCULATOR](value, key)
+
+ if (this[CACHE].has(key)) {
+ if (len > this[MAX]) {
+ del(this, this[CACHE].get(key))
+ return false
+ }
+
+ const node = this[CACHE].get(key)
+ const item = node.value
+
+ // dispose of the old one before overwriting
+ // split out into 2 ifs for better coverage tracking
+ if (this[DISPOSE]) {
+ if (!this[NO_DISPOSE_ON_SET])
+ this[DISPOSE](key, item.value)
+ }
+
+ item.now = now
+ item.maxAge = maxAge
+ item.value = value
+ this[LENGTH] += len - item.length
+ item.length = len
+ this.get(key)
+ trim(this)
+ return true
+ }
+
+ const hit = new Entry(key, value, len, now, maxAge)
+
+ // oversized objects fall out of cache automatically.
+ if (hit.length > this[MAX]) {
+ if (this[DISPOSE])
+ this[DISPOSE](key, value)
+
+ return false
+ }
+
+ this[LENGTH] += hit.length
+ this[LRU_LIST].unshift(hit)
+ this[CACHE].set(key, this[LRU_LIST].head)
+ trim(this)
+ return true
+ }
+
+ has (key) {
+ if (!this[CACHE].has(key)) return false
+ const hit = this[CACHE].get(key).value
+ return !isStale(this, hit)
+ }
+
+ get (key) {
+ return get(this, key, true)
+ }
+
+ peek (key) {
+ return get(this, key, false)
+ }
+
+ pop () {
+ const node = this[LRU_LIST].tail
+ if (!node)
+ return null
+
+ del(this, node)
+ return node.value
+ }
+
+ del (key) {
+ del(this, this[CACHE].get(key))
+ }
+
+ load (arr) {
+ // reset the cache
+ this.reset()
+
+ const now = Date.now()
+ // A previous serialized cache has the most recent items first
+ for (let l = arr.length - 1; l >= 0; l--) {
+ const hit = arr[l]
+ const expiresAt = hit.e || 0
+ if (expiresAt === 0)
+ // the item was created without expiration in a non aged cache
+ this.set(hit.k, hit.v)
+ else {
+ const maxAge = expiresAt - now
+ // dont add already expired items
+ if (maxAge > 0) {
+ this.set(hit.k, hit.v, maxAge)
+ }
+ }
+ }
+ }
+
+ prune () {
+ this[CACHE].forEach((value, key) => get(this, key, false))
+ }
+}
+
+const get = (self, key, doUse) => {
+ const node = self[CACHE].get(key)
+ if (node) {
+ const hit = node.value
+ if (isStale(self, hit)) {
+ del(self, node)
+ if (!self[ALLOW_STALE])
+ return undefined
+ } else {
+ if (doUse) {
+ if (self[UPDATE_AGE_ON_GET])
+ node.value.now = Date.now()
+ self[LRU_LIST].unshiftNode(node)
+ }
+ }
+ return hit.value
+ }
+}
+
+const isStale = (self, hit) => {
+ if (!hit || (!hit.maxAge && !self[MAX_AGE]))
+ return false
+
+ const diff = Date.now() - hit.now
+ return hit.maxAge ? diff > hit.maxAge
+ : self[MAX_AGE] && (diff > self[MAX_AGE])
+}
+
+const trim = self => {
+ if (self[LENGTH] > self[MAX]) {
+ for (let walker = self[LRU_LIST].tail;
+ self[LENGTH] > self[MAX] && walker !== null;) {
+ // We know that we're about to delete this one, and also
+ // what the next least recently used key will be, so just
+ // go ahead and set it now.
+ const prev = walker.prev
+ del(self, walker)
+ walker = prev
+ }
+ }
+}
+
+const del = (self, node) => {
+ if (node) {
+ const hit = node.value
+ if (self[DISPOSE])
+ self[DISPOSE](hit.key, hit.value)
+
+ self[LENGTH] -= hit.length
+ self[CACHE].delete(hit.key)
+ self[LRU_LIST].removeNode(node)
+ }
+}
+
+class Entry {
+ constructor (key, value, length, now, maxAge) {
+ this.key = key
+ this.value = value
+ this.length = length
+ this.now = now
+ this.maxAge = maxAge || 0
+ }
+}
+
+const forEachStep = (self, fn, node, thisp) => {
+ let hit = node.value
+ if (isStale(self, hit)) {
+ del(self, node)
+ if (!self[ALLOW_STALE])
+ hit = undefined
+ }
+ if (hit)
+ fn.call(thisp, hit.value, hit.key, self)
+}
+
+module.exports = LRUCache
diff --git a/temporary_modules/trezor-connect/node_modules/lru-cache/package.json b/temporary_modules/trezor-connect/node_modules/lru-cache/package.json
new file mode 100644
index 00000000..43b7502c
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/lru-cache/package.json
@@ -0,0 +1,34 @@
+{
+ "name": "lru-cache",
+ "description": "A cache object that deletes the least-recently-used items.",
+ "version": "6.0.0",
+ "author": "Isaac Z. Schlueter ",
+ "keywords": [
+ "mru",
+ "lru",
+ "cache"
+ ],
+ "scripts": {
+ "test": "tap",
+ "snap": "tap",
+ "preversion": "npm test",
+ "postversion": "npm publish",
+ "prepublishOnly": "git push origin --follow-tags"
+ },
+ "main": "index.js",
+ "repository": "git://github.com/isaacs/node-lru-cache.git",
+ "devDependencies": {
+ "benchmark": "^2.1.4",
+ "tap": "^14.10.7"
+ },
+ "license": "ISC",
+ "dependencies": {
+ "yallist": "^4.0.0"
+ },
+ "files": [
+ "index.js"
+ ],
+ "engines": {
+ "node": ">=10"
+ }
+}
diff --git a/temporary_modules/trezor-connect/node_modules/minipass/LICENSE b/temporary_modules/trezor-connect/node_modules/minipass/LICENSE
new file mode 100644
index 00000000..20a47625
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/minipass/LICENSE
@@ -0,0 +1,15 @@
+The ISC License
+
+Copyright (c) npm, Inc. and Contributors
+
+Permission to use, copy, modify, and/or distribute this software for any
+purpose with or without fee is hereby granted, provided that the above
+copyright notice and this permission notice appear in all copies.
+
+THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
+IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
diff --git a/temporary_modules/trezor-connect/node_modules/minipass/README.md b/temporary_modules/trezor-connect/node_modules/minipass/README.md
new file mode 100644
index 00000000..59fa6296
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/minipass/README.md
@@ -0,0 +1,613 @@
+# minipass
+
+A _very_ minimal implementation of a [PassThrough
+stream](https://nodejs.org/api/stream.html#stream_class_stream_passthrough)
+
+[It's very
+fast](https://docs.google.com/spreadsheets/d/1oObKSrVwLX_7Ut4Z6g3fZW-AX1j1-k6w-cDsrkaSbHM/edit#gid=0)
+for objects, strings, and buffers.
+
+Supports `pipe()`ing (including multi-`pipe()` and backpressure transmission),
+buffering data until either a `data` event handler or `pipe()` is added (so
+you don't lose the first chunk), and most other cases where PassThrough is
+a good idea.
+
+There is a `read()` method, but it's much more efficient to consume data
+from this stream via `'data'` events or by calling `pipe()` into some other
+stream. Calling `read()` requires the buffer to be flattened in some
+cases, which requires copying memory.
+
+There is also no `unpipe()` method. Once you start piping, there is no
+stopping it!
+
+If you set `objectMode: true` in the options, then whatever is written will
+be emitted. Otherwise, it'll do a minimal amount of Buffer copying to
+ensure proper Streams semantics when `read(n)` is called.
+
+`objectMode` can also be set by doing `stream.objectMode = true`, or by
+writing any non-string/non-buffer data. `objectMode` cannot be set to
+false once it is set.
+
+This is not a `through` or `through2` stream. It doesn't transform the
+data, it just passes it right through. If you want to transform the data,
+extend the class, and override the `write()` method. Once you're done
+transforming the data however you want, call `super.write()` with the
+transform output.
+
+For some examples of streams that extend Minipass in various ways, check
+out:
+
+- [minizlib](http://npm.im/minizlib)
+- [fs-minipass](http://npm.im/fs-minipass)
+- [tar](http://npm.im/tar)
+- [minipass-collect](http://npm.im/minipass-collect)
+- [minipass-flush](http://npm.im/minipass-flush)
+- [minipass-pipeline](http://npm.im/minipass-pipeline)
+- [tap](http://npm.im/tap)
+- [tap-parser](http://npm.im/tap-parser)
+- [treport](http://npm.im/treport)
+- [minipass-fetch](http://npm.im/minipass-fetch)
+- [pacote](http://npm.im/pacote)
+- [make-fetch-happen](http://npm.im/make-fetch-happen)
+- [cacache](http://npm.im/cacache)
+- [ssri](http://npm.im/ssri)
+- [npm-registry-fetch](http://npm.im/npm-registry-fetch)
+- [minipass-json-stream](http://npm.im/minipass-json-stream)
+- [minipass-sized](http://npm.im/minipass-sized)
+
+## Differences from Node.js Streams
+
+There are several things that make Minipass streams different from (and in
+some ways superior to) Node.js core streams.
+
+Please read these caveats if you are familiar with node-core streams and
+intend to use Minipass streams in your programs.
+
+### Timing
+
+Minipass streams are designed to support synchronous use-cases. Thus, data
+is emitted as soon as it is available, always. It is buffered until read,
+but no longer. Another way to look at it is that Minipass streams are
+exactly as synchronous as the logic that writes into them.
+
+This can be surprising if your code relies on `PassThrough.write()` always
+providing data on the next tick rather than the current one, or being able
+to call `resume()` and not have the entire buffer disappear immediately.
+
+However, without this synchronicity guarantee, there would be no way for
+Minipass to achieve the speeds it does, or support the synchronous use
+cases that it does. Simply put, waiting takes time.
+
+This non-deferring approach makes Minipass streams much easier to reason
+about, especially in the context of Promises and other flow-control
+mechanisms.
+
+### No High/Low Water Marks
+
+Node.js core streams will optimistically fill up a buffer, returning `true`
+on all writes until the limit is hit, even if the data has nowhere to go.
+Then, they will not attempt to draw more data in until the buffer size dips
+below a minimum value.
+
+Minipass streams are much simpler. The `write()` method will return `true`
+if the data has somewhere to go (which is to say, given the timing
+guarantees, that the data is already there by the time `write()` returns).
+
+If the data has nowhere to go, then `write()` returns false, and the data
+sits in a buffer, to be drained out immediately as soon as anyone consumes
+it.
+
+### Hazards of Buffering (or: Why Minipass Is So Fast)
+
+Since data written to a Minipass stream is immediately written all the way
+through the pipeline, and `write()` always returns true/false based on
+whether the data was fully flushed, backpressure is communicated
+immediately to the upstream caller. This minimizes buffering.
+
+Consider this case:
+
+```js
+const {PassThrough} = require('stream')
+const p1 = new PassThrough({ highWaterMark: 1024 })
+const p2 = new PassThrough({ highWaterMark: 1024 })
+const p3 = new PassThrough({ highWaterMark: 1024 })
+const p4 = new PassThrough({ highWaterMark: 1024 })
+
+p1.pipe(p2).pipe(p3).pipe(p4)
+p4.on('data', () => console.log('made it through'))
+
+// this returns false and buffers, then writes to p2 on next tick (1)
+// p2 returns false and buffers, pausing p1, then writes to p3 on next tick (2)
+// p3 returns false and buffers, pausing p2, then writes to p4 on next tick (3)
+// p4 returns false and buffers, pausing p3, then emits 'data' and 'drain'
+// on next tick (4)
+// p3 sees p4's 'drain' event, and calls resume(), emitting 'resume' and
+// 'drain' on next tick (5)
+// p2 sees p3's 'drain', calls resume(), emits 'resume' and 'drain' on next tick (6)
+// p1 sees p2's 'drain', calls resume(), emits 'resume' and 'drain' on next
+// tick (7)
+
+p1.write(Buffer.alloc(2048)) // returns false
+```
+
+Along the way, the data was buffered and deferred at each stage, and
+multiple event deferrals happened, for an unblocked pipeline where it was
+perfectly safe to write all the way through!
+
+Furthermore, setting a `highWaterMark` of `1024` might lead someone reading
+the code to think an advisory maximum of 1KiB is being set for the
+pipeline. However, the actual advisory buffering level is the _sum_ of
+`highWaterMark` values, since each one has its own bucket.
+
+Consider the Minipass case:
+
+```js
+const m1 = new Minipass()
+const m2 = new Minipass()
+const m3 = new Minipass()
+const m4 = new Minipass()
+
+m1.pipe(m2).pipe(m3).pipe(m4)
+m4.on('data', () => console.log('made it through'))
+
+// m1 is flowing, so it writes the data to m2 immediately
+// m2 is flowing, so it writes the data to m3 immediately
+// m3 is flowing, so it writes the data to m4 immediately
+// m4 is flowing, so it fires the 'data' event immediately, returns true
+// m4's write returned true, so m3 is still flowing, returns true
+// m3's write returned true, so m2 is still flowing, returns true
+// m2's write returned true, so m1 is still flowing, returns true
+// No event deferrals or buffering along the way!
+
+m1.write(Buffer.alloc(2048)) // returns true
+```
+
+It is extremely unlikely that you _don't_ want to buffer any data written,
+or _ever_ buffer data that can be flushed all the way through. Neither
+node-core streams nor Minipass ever fail to buffer written data, but
+node-core streams do a lot of unnecessary buffering and pausing.
+
+As always, the faster implementation is the one that does less stuff and
+waits less time to do it.
+
+### Immediately emit `end` for empty streams (when not paused)
+
+If a stream is not paused, and `end()` is called before writing any data
+into it, then it will emit `end` immediately.
+
+If you have logic that occurs on the `end` event which you don't want to
+potentially happen immediately (for example, closing file descriptors,
+moving on to the next entry in an archive parse stream, etc.) then be sure
+to call `stream.pause()` on creation, and then `stream.resume()` once you
+are ready to respond to the `end` event.
+
+### Emit `end` When Asked
+
+One hazard of immediately emitting `'end'` is that you may not yet have had
+a chance to add a listener. In order to avoid this hazard, Minipass
+streams safely re-emit the `'end'` event if a new listener is added after
+`'end'` has been emitted.
+
+Ie, if you do `stream.on('end', someFunction)`, and the stream has already
+emitted `end`, then it will call the handler right away. (You can think of
+this somewhat like attaching a new `.then(fn)` to a previously-resolved
+Promise.)
+
+To prevent calling handlers multiple times who would not expect multiple
+ends to occur, all listeners are removed from the `'end'` event whenever it
+is emitted.
+
+### Impact of "immediate flow" on Tee-streams
+
+A "tee stream" is a stream piping to multiple destinations:
+
+```js
+const tee = new Minipass()
+t.pipe(dest1)
+t.pipe(dest2)
+t.write('foo') // goes to both destinations
+```
+
+Since Minipass streams _immediately_ process any pending data through the
+pipeline when a new pipe destination is added, this can have surprising
+effects, especially when a stream comes in from some other function and may
+or may not have data in its buffer.
+
+```js
+// WARNING! WILL LOSE DATA!
+const src = new Minipass()
+src.write('foo')
+src.pipe(dest1) // 'foo' chunk flows to dest1 immediately, and is gone
+src.pipe(dest2) // gets nothing!
+```
+
+The solution is to create a dedicated tee-stream junction that pipes to
+both locations, and then pipe to _that_ instead.
+
+```js
+// Safe example: tee to both places
+const src = new Minipass()
+src.write('foo')
+const tee = new Minipass()
+tee.pipe(dest1)
+tee.pipe(dest2)
+src.pipe(tee) // tee gets 'foo', pipes to both locations
+```
+
+The same caveat applies to `on('data')` event listeners. The first one
+added will _immediately_ receive all of the data, leaving nothing for the
+second:
+
+```js
+// WARNING! WILL LOSE DATA!
+const src = new Minipass()
+src.write('foo')
+src.on('data', handler1) // receives 'foo' right away
+src.on('data', handler2) // nothing to see here!
+```
+
+Using a dedicated tee-stream can be used in this case as well:
+
+```js
+// Safe example: tee to both data handlers
+const src = new Minipass()
+src.write('foo')
+const tee = new Minipass()
+tee.on('data', handler1)
+tee.on('data', handler2)
+src.pipe(tee)
+```
+
+## USAGE
+
+It's a stream! Use it like a stream and it'll most likely do what you
+want.
+
+```js
+const Minipass = require('minipass')
+const mp = new Minipass(options) // optional: { encoding, objectMode }
+mp.write('foo')
+mp.pipe(someOtherStream)
+mp.end('bar')
+```
+
+### OPTIONS
+
+* `encoding` How would you like the data coming _out_ of the stream to be
+ encoded? Accepts any values that can be passed to `Buffer.toString()`.
+* `objectMode` Emit data exactly as it comes in. This will be flipped on
+ by default if you write() something other than a string or Buffer at any
+ point. Setting `objectMode: true` will prevent setting any encoding
+ value.
+
+### API
+
+Implements the user-facing portions of Node.js's `Readable` and `Writable`
+streams.
+
+### Methods
+
+* `write(chunk, [encoding], [callback])` - Put data in. (Note that, in the
+ base Minipass class, the same data will come out.) Returns `false` if
+ the stream will buffer the next write, or true if it's still in "flowing"
+ mode.
+* `end([chunk, [encoding]], [callback])` - Signal that you have no more
+ data to write. This will queue an `end` event to be fired when all the
+ data has been consumed.
+* `setEncoding(encoding)` - Set the encoding for data coming of the stream.
+ This can only be done once.
+* `pause()` - No more data for a while, please. This also prevents `end`
+ from being emitted for empty streams until the stream is resumed.
+* `resume()` - Resume the stream. If there's data in the buffer, it is all
+ discarded. Any buffered events are immediately emitted.
+* `pipe(dest)` - Send all output to the stream provided. There is no way
+ to unpipe. When data is emitted, it is immediately written to any and
+ all pipe destinations.
+* `on(ev, fn)`, `emit(ev, fn)` - Minipass streams are EventEmitters. Some
+ events are given special treatment, however. (See below under "events".)
+* `promise()` - Returns a Promise that resolves when the stream emits
+ `end`, or rejects if the stream emits `error`.
+* `collect()` - Return a Promise that resolves on `end` with an array
+ containing each chunk of data that was emitted, or rejects if the stream
+ emits `error`. Note that this consumes the stream data.
+* `concat()` - Same as `collect()`, but concatenates the data into a single
+ Buffer object. Will reject the returned promise if the stream is in
+ objectMode, or if it goes into objectMode by the end of the data.
+* `read(n)` - Consume `n` bytes of data out of the buffer. If `n` is not
+ provided, then consume all of it. If `n` bytes are not available, then
+ it returns null. **Note** consuming streams in this way is less
+ efficient, and can lead to unnecessary Buffer copying.
+* `destroy([er])` - Destroy the stream. If an error is provided, then an
+ `'error'` event is emitted. If the stream has a `close()` method, and
+ has not emitted a `'close'` event yet, then `stream.close()` will be
+ called. Any Promises returned by `.promise()`, `.collect()` or
+ `.concat()` will be rejected. After being destroyed, writing to the
+ stream will emit an error. No more data will be emitted if the stream is
+ destroyed, even if it was previously buffered.
+
+### Properties
+
+* `bufferLength` Read-only. Total number of bytes buffered, or in the case
+ of objectMode, the total number of objects.
+* `encoding` The encoding that has been set. (Setting this is equivalent
+ to calling `setEncoding(enc)` and has the same prohibition against
+ setting multiple times.)
+* `flowing` Read-only. Boolean indicating whether a chunk written to the
+ stream will be immediately emitted.
+* `emittedEnd` Read-only. Boolean indicating whether the end-ish events
+ (ie, `end`, `prefinish`, `finish`) have been emitted. Note that
+ listening on any end-ish event will immediateyl re-emit it if it has
+ already been emitted.
+* `writable` Whether the stream is writable. Default `true`. Set to
+ `false` when `end()`
+* `readable` Whether the stream is readable. Default `true`.
+* `buffer` A [yallist](http://npm.im/yallist) linked list of chunks written
+ to the stream that have not yet been emitted. (It's probably a bad idea
+ to mess with this.)
+* `pipes` A [yallist](http://npm.im/yallist) linked list of streams that
+ this stream is piping into. (It's probably a bad idea to mess with
+ this.)
+* `destroyed` A getter that indicates whether the stream was destroyed.
+* `paused` True if the stream has been explicitly paused, otherwise false.
+* `objectMode` Indicates whether the stream is in `objectMode`. Once set
+ to `true`, it cannot be set to `false`.
+
+### Events
+
+* `data` Emitted when there's data to read. Argument is the data to read.
+ This is never emitted while not flowing. If a listener is attached, that
+ will resume the stream.
+* `end` Emitted when there's no more data to read. This will be emitted
+ immediately for empty streams when `end()` is called. If a listener is
+ attached, and `end` was already emitted, then it will be emitted again.
+ All listeners are removed when `end` is emitted.
+* `prefinish` An end-ish event that follows the same logic as `end` and is
+ emitted in the same conditions where `end` is emitted. Emitted after
+ `'end'`.
+* `finish` An end-ish event that follows the same logic as `end` and is
+ emitted in the same conditions where `end` is emitted. Emitted after
+ `'prefinish'`.
+* `close` An indication that an underlying resource has been released.
+ Minipass does not emit this event, but will defer it until after `end`
+ has been emitted, since it throws off some stream libraries otherwise.
+* `drain` Emitted when the internal buffer empties, and it is again
+ suitable to `write()` into the stream.
+* `readable` Emitted when data is buffered and ready to be read by a
+ consumer.
+* `resume` Emitted when stream changes state from buffering to flowing
+ mode. (Ie, when `resume` is called, `pipe` is called, or a `data` event
+ listener is added.)
+
+### Static Methods
+
+* `Minipass.isStream(stream)` Returns `true` if the argument is a stream,
+ and false otherwise. To be considered a stream, the object must be
+ either an instance of Minipass, or an EventEmitter that has either a
+ `pipe()` method, or both `write()` and `end()` methods. (Pretty much any
+ stream in node-land will return `true` for this.)
+
+## EXAMPLES
+
+Here are some examples of things you can do with Minipass streams.
+
+### simple "are you done yet" promise
+
+```js
+mp.promise().then(() => {
+ // stream is finished
+}, er => {
+ // stream emitted an error
+})
+```
+
+### collecting
+
+```js
+mp.collect().then(all => {
+ // all is an array of all the data emitted
+ // encoding is supported in this case, so
+ // so the result will be a collection of strings if
+ // an encoding is specified, or buffers/objects if not.
+ //
+ // In an async function, you may do
+ // const data = await stream.collect()
+})
+```
+
+### collecting into a single blob
+
+This is a bit slower because it concatenates the data into one chunk for
+you, but if you're going to do it yourself anyway, it's convenient this
+way:
+
+```js
+mp.concat().then(onebigchunk => {
+ // onebigchunk is a string if the stream
+ // had an encoding set, or a buffer otherwise.
+})
+```
+
+### iteration
+
+You can iterate over streams synchronously or asynchronously in platforms
+that support it.
+
+Synchronous iteration will end when the currently available data is
+consumed, even if the `end` event has not been reached. In string and
+buffer mode, the data is concatenated, so unless multiple writes are
+occurring in the same tick as the `read()`, sync iteration loops will
+generally only have a single iteration.
+
+To consume chunks in this way exactly as they have been written, with no
+flattening, create the stream with the `{ objectMode: true }` option.
+
+```js
+const mp = new Minipass({ objectMode: true })
+mp.write('a')
+mp.write('b')
+for (let letter of mp) {
+ console.log(letter) // a, b
+}
+mp.write('c')
+mp.write('d')
+for (let letter of mp) {
+ console.log(letter) // c, d
+}
+mp.write('e')
+mp.end()
+for (let letter of mp) {
+ console.log(letter) // e
+}
+for (let letter of mp) {
+ console.log(letter) // nothing
+}
+```
+
+Asynchronous iteration will continue until the end event is reached,
+consuming all of the data.
+
+```js
+const mp = new Minipass({ encoding: 'utf8' })
+
+// some source of some data
+let i = 5
+const inter = setInterval(() => {
+ if (i-- > 0)
+ mp.write(Buffer.from('foo\n', 'utf8'))
+ else {
+ mp.end()
+ clearInterval(inter)
+ }
+}, 100)
+
+// consume the data with asynchronous iteration
+async function consume () {
+ for await (let chunk of mp) {
+ console.log(chunk)
+ }
+ return 'ok'
+}
+
+consume().then(res => console.log(res))
+// logs `foo\n` 5 times, and then `ok`
+```
+
+### subclass that `console.log()`s everything written into it
+
+```js
+class Logger extends Minipass {
+ write (chunk, encoding, callback) {
+ console.log('WRITE', chunk, encoding)
+ return super.write(chunk, encoding, callback)
+ }
+ end (chunk, encoding, callback) {
+ console.log('END', chunk, encoding)
+ return super.end(chunk, encoding, callback)
+ }
+}
+
+someSource.pipe(new Logger()).pipe(someDest)
+```
+
+### same thing, but using an inline anonymous class
+
+```js
+// js classes are fun
+someSource
+ .pipe(new (class extends Minipass {
+ emit (ev, ...data) {
+ // let's also log events, because debugging some weird thing
+ console.log('EMIT', ev)
+ return super.emit(ev, ...data)
+ }
+ write (chunk, encoding, callback) {
+ console.log('WRITE', chunk, encoding)
+ return super.write(chunk, encoding, callback)
+ }
+ end (chunk, encoding, callback) {
+ console.log('END', chunk, encoding)
+ return super.end(chunk, encoding, callback)
+ }
+ }))
+ .pipe(someDest)
+```
+
+### subclass that defers 'end' for some reason
+
+```js
+class SlowEnd extends Minipass {
+ emit (ev, ...args) {
+ if (ev === 'end') {
+ console.log('going to end, hold on a sec')
+ setTimeout(() => {
+ console.log('ok, ready to end now')
+ super.emit('end', ...args)
+ }, 100)
+ } else {
+ return super.emit(ev, ...args)
+ }
+ }
+}
+```
+
+### transform that creates newline-delimited JSON
+
+```js
+class NDJSONEncode extends Minipass {
+ write (obj, cb) {
+ try {
+ // JSON.stringify can throw, emit an error on that
+ return super.write(JSON.stringify(obj) + '\n', 'utf8', cb)
+ } catch (er) {
+ this.emit('error', er)
+ }
+ }
+ end (obj, cb) {
+ if (typeof obj === 'function') {
+ cb = obj
+ obj = undefined
+ }
+ if (obj !== undefined) {
+ this.write(obj)
+ }
+ return super.end(cb)
+ }
+}
+```
+
+### transform that parses newline-delimited JSON
+
+```js
+class NDJSONDecode extends Minipass {
+ constructor (options) {
+ // always be in object mode, as far as Minipass is concerned
+ super({ objectMode: true })
+ this._jsonBuffer = ''
+ }
+ write (chunk, encoding, cb) {
+ if (typeof chunk === 'string' &&
+ typeof encoding === 'string' &&
+ encoding !== 'utf8') {
+ chunk = Buffer.from(chunk, encoding).toString()
+ } else if (Buffer.isBuffer(chunk))
+ chunk = chunk.toString()
+ }
+ if (typeof encoding === 'function') {
+ cb = encoding
+ }
+ const jsonData = (this._jsonBuffer + chunk).split('\n')
+ this._jsonBuffer = jsonData.pop()
+ for (let i = 0; i < jsonData.length; i++) {
+ try {
+ // JSON.parse can throw, emit an error on that
+ super.write(JSON.parse(jsonData[i]))
+ } catch (er) {
+ this.emit('error', er)
+ continue
+ }
+ }
+ if (cb)
+ cb()
+ }
+}
+```
diff --git a/temporary_modules/trezor-connect/node_modules/minipass/index.js b/temporary_modules/trezor-connect/node_modules/minipass/index.js
new file mode 100644
index 00000000..1835dd9b
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/minipass/index.js
@@ -0,0 +1,560 @@
+'use strict'
+const proc = typeof process === 'object' && process ? process : {
+ stdout: null,
+ stderr: null,
+}
+const EE = require('events')
+const Stream = require('stream')
+const Yallist = require('yallist')
+const SD = require('string_decoder').StringDecoder
+
+const EOF = Symbol('EOF')
+const MAYBE_EMIT_END = Symbol('maybeEmitEnd')
+const EMITTED_END = Symbol('emittedEnd')
+const EMITTING_END = Symbol('emittingEnd')
+const EMITTED_ERROR = Symbol('emittedError')
+const CLOSED = Symbol('closed')
+const READ = Symbol('read')
+const FLUSH = Symbol('flush')
+const FLUSHCHUNK = Symbol('flushChunk')
+const ENCODING = Symbol('encoding')
+const DECODER = Symbol('decoder')
+const FLOWING = Symbol('flowing')
+const PAUSED = Symbol('paused')
+const RESUME = Symbol('resume')
+const BUFFERLENGTH = Symbol('bufferLength')
+const BUFFERPUSH = Symbol('bufferPush')
+const BUFFERSHIFT = Symbol('bufferShift')
+const OBJECTMODE = Symbol('objectMode')
+const DESTROYED = Symbol('destroyed')
+
+// TODO remove when Node v8 support drops
+const doIter = global._MP_NO_ITERATOR_SYMBOLS_ !== '1'
+const ASYNCITERATOR = doIter && Symbol.asyncIterator
+ || Symbol('asyncIterator not implemented')
+const ITERATOR = doIter && Symbol.iterator
+ || Symbol('iterator not implemented')
+
+// events that mean 'the stream is over'
+// these are treated specially, and re-emitted
+// if they are listened for after emitting.
+const isEndish = ev =>
+ ev === 'end' ||
+ ev === 'finish' ||
+ ev === 'prefinish'
+
+const isArrayBuffer = b => b instanceof ArrayBuffer ||
+ typeof b === 'object' &&
+ b.constructor &&
+ b.constructor.name === 'ArrayBuffer' &&
+ b.byteLength >= 0
+
+const isArrayBufferView = b => !Buffer.isBuffer(b) && ArrayBuffer.isView(b)
+
+module.exports = class Minipass extends Stream {
+ constructor (options) {
+ super()
+ this[FLOWING] = false
+ // whether we're explicitly paused
+ this[PAUSED] = false
+ this.pipes = new Yallist()
+ this.buffer = new Yallist()
+ this[OBJECTMODE] = options && options.objectMode || false
+ if (this[OBJECTMODE])
+ this[ENCODING] = null
+ else
+ this[ENCODING] = options && options.encoding || null
+ if (this[ENCODING] === 'buffer')
+ this[ENCODING] = null
+ this[DECODER] = this[ENCODING] ? new SD(this[ENCODING]) : null
+ this[EOF] = false
+ this[EMITTED_END] = false
+ this[EMITTING_END] = false
+ this[CLOSED] = false
+ this[EMITTED_ERROR] = null
+ this.writable = true
+ this.readable = true
+ this[BUFFERLENGTH] = 0
+ this[DESTROYED] = false
+ }
+
+ get bufferLength () { return this[BUFFERLENGTH] }
+
+ get encoding () { return this[ENCODING] }
+ set encoding (enc) {
+ if (this[OBJECTMODE])
+ throw new Error('cannot set encoding in objectMode')
+
+ if (this[ENCODING] && enc !== this[ENCODING] &&
+ (this[DECODER] && this[DECODER].lastNeed || this[BUFFERLENGTH]))
+ throw new Error('cannot change encoding')
+
+ if (this[ENCODING] !== enc) {
+ this[DECODER] = enc ? new SD(enc) : null
+ if (this.buffer.length)
+ this.buffer = this.buffer.map(chunk => this[DECODER].write(chunk))
+ }
+
+ this[ENCODING] = enc
+ }
+
+ setEncoding (enc) {
+ this.encoding = enc
+ }
+
+ get objectMode () { return this[OBJECTMODE] }
+ set objectMode (om) { this[OBJECTMODE] = this[OBJECTMODE] || !!om }
+
+ write (chunk, encoding, cb) {
+ if (this[EOF])
+ throw new Error('write after end')
+
+ if (this[DESTROYED]) {
+ this.emit('error', Object.assign(
+ new Error('Cannot call write after a stream was destroyed'),
+ { code: 'ERR_STREAM_DESTROYED' }
+ ))
+ return true
+ }
+
+ if (typeof encoding === 'function')
+ cb = encoding, encoding = 'utf8'
+
+ if (!encoding)
+ encoding = 'utf8'
+
+ // convert array buffers and typed array views into buffers
+ // at some point in the future, we may want to do the opposite!
+ // leave strings and buffers as-is
+ // anything else switches us into object mode
+ if (!this[OBJECTMODE] && !Buffer.isBuffer(chunk)) {
+ if (isArrayBufferView(chunk))
+ chunk = Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength)
+ else if (isArrayBuffer(chunk))
+ chunk = Buffer.from(chunk)
+ else if (typeof chunk !== 'string')
+ // use the setter so we throw if we have encoding set
+ this.objectMode = true
+ }
+
+ // this ensures at this point that the chunk is a buffer or string
+ // don't buffer it up or send it to the decoder
+ if (!this.objectMode && !chunk.length) {
+ if (this[BUFFERLENGTH] !== 0)
+ this.emit('readable')
+ if (cb)
+ cb()
+ return this.flowing
+ }
+
+ // fast-path writing strings of same encoding to a stream with
+ // an empty buffer, skipping the buffer/decoder dance
+ if (typeof chunk === 'string' && !this[OBJECTMODE] &&
+ // unless it is a string already ready for us to use
+ !(encoding === this[ENCODING] && !this[DECODER].lastNeed)) {
+ chunk = Buffer.from(chunk, encoding)
+ }
+
+ if (Buffer.isBuffer(chunk) && this[ENCODING])
+ chunk = this[DECODER].write(chunk)
+
+ if (this.flowing) {
+ // if we somehow have something in the buffer, but we think we're
+ // flowing, then we need to flush all that out first, or we get
+ // chunks coming in out of order. Can't emit 'drain' here though,
+ // because we're mid-write, so that'd be bad.
+ if (this[BUFFERLENGTH] !== 0)
+ this[FLUSH](true)
+
+ // if we are still flowing after flushing the buffer we can emit the
+ // chunk otherwise we have to buffer it.
+ this.flowing
+ ? this.emit('data', chunk)
+ : this[BUFFERPUSH](chunk)
+ } else
+ this[BUFFERPUSH](chunk)
+
+ if (this[BUFFERLENGTH] !== 0)
+ this.emit('readable')
+
+ if (cb)
+ cb()
+
+ return this.flowing
+ }
+
+ read (n) {
+ if (this[DESTROYED])
+ return null
+
+ try {
+ if (this[BUFFERLENGTH] === 0 || n === 0 || n > this[BUFFERLENGTH])
+ return null
+
+ if (this[OBJECTMODE])
+ n = null
+
+ if (this.buffer.length > 1 && !this[OBJECTMODE]) {
+ if (this.encoding)
+ this.buffer = new Yallist([
+ Array.from(this.buffer).join('')
+ ])
+ else
+ this.buffer = new Yallist([
+ Buffer.concat(Array.from(this.buffer), this[BUFFERLENGTH])
+ ])
+ }
+
+ return this[READ](n || null, this.buffer.head.value)
+ } finally {
+ this[MAYBE_EMIT_END]()
+ }
+ }
+
+ [READ] (n, chunk) {
+ if (n === chunk.length || n === null)
+ this[BUFFERSHIFT]()
+ else {
+ this.buffer.head.value = chunk.slice(n)
+ chunk = chunk.slice(0, n)
+ this[BUFFERLENGTH] -= n
+ }
+
+ this.emit('data', chunk)
+
+ if (!this.buffer.length && !this[EOF])
+ this.emit('drain')
+
+ return chunk
+ }
+
+ end (chunk, encoding, cb) {
+ if (typeof chunk === 'function')
+ cb = chunk, chunk = null
+ if (typeof encoding === 'function')
+ cb = encoding, encoding = 'utf8'
+ if (chunk)
+ this.write(chunk, encoding)
+ if (cb)
+ this.once('end', cb)
+ this[EOF] = true
+ this.writable = false
+
+ // if we haven't written anything, then go ahead and emit,
+ // even if we're not reading.
+ // we'll re-emit if a new 'end' listener is added anyway.
+ // This makes MP more suitable to write-only use cases.
+ if (this.flowing || !this[PAUSED])
+ this[MAYBE_EMIT_END]()
+ return this
+ }
+
+ // don't let the internal resume be overwritten
+ [RESUME] () {
+ if (this[DESTROYED])
+ return
+
+ this[PAUSED] = false
+ this[FLOWING] = true
+ this.emit('resume')
+ if (this.buffer.length)
+ this[FLUSH]()
+ else if (this[EOF])
+ this[MAYBE_EMIT_END]()
+ else
+ this.emit('drain')
+ }
+
+ resume () {
+ return this[RESUME]()
+ }
+
+ pause () {
+ this[FLOWING] = false
+ this[PAUSED] = true
+ }
+
+ get destroyed () {
+ return this[DESTROYED]
+ }
+
+ get flowing () {
+ return this[FLOWING]
+ }
+
+ get paused () {
+ return this[PAUSED]
+ }
+
+ [BUFFERPUSH] (chunk) {
+ if (this[OBJECTMODE])
+ this[BUFFERLENGTH] += 1
+ else
+ this[BUFFERLENGTH] += chunk.length
+ return this.buffer.push(chunk)
+ }
+
+ [BUFFERSHIFT] () {
+ if (this.buffer.length) {
+ if (this[OBJECTMODE])
+ this[BUFFERLENGTH] -= 1
+ else
+ this[BUFFERLENGTH] -= this.buffer.head.value.length
+ }
+ return this.buffer.shift()
+ }
+
+ [FLUSH] (noDrain) {
+ do {} while (this[FLUSHCHUNK](this[BUFFERSHIFT]()))
+
+ if (!noDrain && !this.buffer.length && !this[EOF])
+ this.emit('drain')
+ }
+
+ [FLUSHCHUNK] (chunk) {
+ return chunk ? (this.emit('data', chunk), this.flowing) : false
+ }
+
+ pipe (dest, opts) {
+ if (this[DESTROYED])
+ return
+
+ const ended = this[EMITTED_END]
+ opts = opts || {}
+ if (dest === proc.stdout || dest === proc.stderr)
+ opts.end = false
+ else
+ opts.end = opts.end !== false
+
+ const p = { dest: dest, opts: opts, ondrain: _ => this[RESUME]() }
+ this.pipes.push(p)
+
+ dest.on('drain', p.ondrain)
+ this[RESUME]()
+ // piping an ended stream ends immediately
+ if (ended && p.opts.end)
+ p.dest.end()
+ return dest
+ }
+
+ addListener (ev, fn) {
+ return this.on(ev, fn)
+ }
+
+ on (ev, fn) {
+ try {
+ return super.on(ev, fn)
+ } finally {
+ if (ev === 'data' && !this.pipes.length && !this.flowing)
+ this[RESUME]()
+ else if (isEndish(ev) && this[EMITTED_END]) {
+ super.emit(ev)
+ this.removeAllListeners(ev)
+ } else if (ev === 'error' && this[EMITTED_ERROR]) {
+ fn.call(this, this[EMITTED_ERROR])
+ }
+ }
+ }
+
+ get emittedEnd () {
+ return this[EMITTED_END]
+ }
+
+ [MAYBE_EMIT_END] () {
+ if (!this[EMITTING_END] &&
+ !this[EMITTED_END] &&
+ !this[DESTROYED] &&
+ this.buffer.length === 0 &&
+ this[EOF]) {
+ this[EMITTING_END] = true
+ this.emit('end')
+ this.emit('prefinish')
+ this.emit('finish')
+ if (this[CLOSED])
+ this.emit('close')
+ this[EMITTING_END] = false
+ }
+ }
+
+ emit (ev, data) {
+ // error and close are only events allowed after calling destroy()
+ if (ev !== 'error' && ev !== 'close' && ev !== DESTROYED && this[DESTROYED])
+ return
+ else if (ev === 'data') {
+ if (!data)
+ return
+
+ if (this.pipes.length)
+ this.pipes.forEach(p =>
+ p.dest.write(data) === false && this.pause())
+ } else if (ev === 'end') {
+ // only actual end gets this treatment
+ if (this[EMITTED_END] === true)
+ return
+
+ this[EMITTED_END] = true
+ this.readable = false
+
+ if (this[DECODER]) {
+ data = this[DECODER].end()
+ if (data) {
+ this.pipes.forEach(p => p.dest.write(data))
+ super.emit('data', data)
+ }
+ }
+
+ this.pipes.forEach(p => {
+ p.dest.removeListener('drain', p.ondrain)
+ if (p.opts.end)
+ p.dest.end()
+ })
+ } else if (ev === 'close') {
+ this[CLOSED] = true
+ // don't emit close before 'end' and 'finish'
+ if (!this[EMITTED_END] && !this[DESTROYED])
+ return
+ } else if (ev === 'error') {
+ this[EMITTED_ERROR] = data
+ }
+
+ // TODO: replace with a spread operator when Node v4 support drops
+ const args = new Array(arguments.length)
+ args[0] = ev
+ args[1] = data
+ if (arguments.length > 2) {
+ for (let i = 2; i < arguments.length; i++) {
+ args[i] = arguments[i]
+ }
+ }
+
+ try {
+ return super.emit.apply(this, args)
+ } finally {
+ if (!isEndish(ev))
+ this[MAYBE_EMIT_END]()
+ else
+ this.removeAllListeners(ev)
+ }
+ }
+
+ // const all = await stream.collect()
+ collect () {
+ const buf = []
+ if (!this[OBJECTMODE])
+ buf.dataLength = 0
+ // set the promise first, in case an error is raised
+ // by triggering the flow here.
+ const p = this.promise()
+ this.on('data', c => {
+ buf.push(c)
+ if (!this[OBJECTMODE])
+ buf.dataLength += c.length
+ })
+ return p.then(() => buf)
+ }
+
+ // const data = await stream.concat()
+ concat () {
+ return this[OBJECTMODE]
+ ? Promise.reject(new Error('cannot concat in objectMode'))
+ : this.collect().then(buf =>
+ this[OBJECTMODE]
+ ? Promise.reject(new Error('cannot concat in objectMode'))
+ : this[ENCODING] ? buf.join('') : Buffer.concat(buf, buf.dataLength))
+ }
+
+ // stream.promise().then(() => done, er => emitted error)
+ promise () {
+ return new Promise((resolve, reject) => {
+ this.on(DESTROYED, () => reject(new Error('stream destroyed')))
+ this.on('error', er => reject(er))
+ this.on('end', () => resolve())
+ })
+ }
+
+ // for await (let chunk of stream)
+ [ASYNCITERATOR] () {
+ const next = () => {
+ const res = this.read()
+ if (res !== null)
+ return Promise.resolve({ done: false, value: res })
+
+ if (this[EOF])
+ return Promise.resolve({ done: true })
+
+ let resolve = null
+ let reject = null
+ const onerr = er => {
+ this.removeListener('data', ondata)
+ this.removeListener('end', onend)
+ reject(er)
+ }
+ const ondata = value => {
+ this.removeListener('error', onerr)
+ this.removeListener('end', onend)
+ this.pause()
+ resolve({ value: value, done: !!this[EOF] })
+ }
+ const onend = () => {
+ this.removeListener('error', onerr)
+ this.removeListener('data', ondata)
+ resolve({ done: true })
+ }
+ const ondestroy = () => onerr(new Error('stream destroyed'))
+ return new Promise((res, rej) => {
+ reject = rej
+ resolve = res
+ this.once(DESTROYED, ondestroy)
+ this.once('error', onerr)
+ this.once('end', onend)
+ this.once('data', ondata)
+ })
+ }
+
+ return { next }
+ }
+
+ // for (let chunk of stream)
+ [ITERATOR] () {
+ const next = () => {
+ const value = this.read()
+ const done = value === null
+ return { value, done }
+ }
+ return { next }
+ }
+
+ destroy (er) {
+ if (this[DESTROYED]) {
+ if (er)
+ this.emit('error', er)
+ else
+ this.emit(DESTROYED)
+ return this
+ }
+
+ this[DESTROYED] = true
+
+ // throw away all buffered data, it's never coming out
+ this.buffer = new Yallist()
+ this[BUFFERLENGTH] = 0
+
+ if (typeof this.close === 'function' && !this[CLOSED])
+ this.close()
+
+ if (er)
+ this.emit('error', er)
+ else // if no error to emit, still reject pending promises
+ this.emit(DESTROYED)
+
+ return this
+ }
+
+ static isStream (s) {
+ return !!s && (s instanceof Minipass || s instanceof Stream ||
+ s instanceof EE && (
+ typeof s.pipe === 'function' || // readable
+ (typeof s.write === 'function' && typeof s.end === 'function') // writable
+ ))
+ }
+}
diff --git a/temporary_modules/trezor-connect/node_modules/minipass/package.json b/temporary_modules/trezor-connect/node_modules/minipass/package.json
new file mode 100644
index 00000000..1728e510
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/minipass/package.json
@@ -0,0 +1,39 @@
+{
+ "name": "minipass",
+ "version": "3.1.6",
+ "description": "minimal implementation of a PassThrough stream",
+ "main": "index.js",
+ "dependencies": {
+ "yallist": "^4.0.0"
+ },
+ "devDependencies": {
+ "end-of-stream": "^1.4.0",
+ "tap": "^15.0.9",
+ "through2": "^2.0.3"
+ },
+ "scripts": {
+ "test": "tap",
+ "preversion": "npm test",
+ "postversion": "npm publish --tag=next",
+ "postpublish": "git push origin --follow-tags"
+ },
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/isaacs/minipass.git"
+ },
+ "keywords": [
+ "passthrough",
+ "stream"
+ ],
+ "author": "Isaac Z. Schlueter (http://blog.izs.me/)",
+ "license": "ISC",
+ "files": [
+ "index.js"
+ ],
+ "tap": {
+ "check-coverage": true
+ },
+ "engines": {
+ "node": ">=8"
+ }
+}
diff --git a/temporary_modules/trezor-connect/node_modules/minizlib/LICENSE b/temporary_modules/trezor-connect/node_modules/minizlib/LICENSE
new file mode 100644
index 00000000..ffce7383
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/minizlib/LICENSE
@@ -0,0 +1,26 @@
+Minizlib was created by Isaac Z. Schlueter.
+It is a derivative work of the Node.js project.
+
+"""
+Copyright Isaac Z. Schlueter and Contributors
+Copyright Node.js contributors. All rights reserved.
+Copyright Joyent, Inc. and other Node contributors. All rights reserved.
+
+Permission is hereby granted, free of charge, to any person obtaining a
+copy of this software and associated documentation files (the "Software"),
+to deal in the Software without restriction, including without limitation
+the rights to use, copy, modify, merge, publish, distribute, sublicense,
+and/or sell copies of the Software, and to permit persons to whom the
+Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+"""
diff --git a/temporary_modules/trezor-connect/node_modules/minizlib/README.md b/temporary_modules/trezor-connect/node_modules/minizlib/README.md
new file mode 100644
index 00000000..80e067ab
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/minizlib/README.md
@@ -0,0 +1,60 @@
+# minizlib
+
+A fast zlib stream built on [minipass](http://npm.im/minipass) and
+Node.js's zlib binding.
+
+This module was created to serve the needs of
+[node-tar](http://npm.im/tar) and
+[minipass-fetch](http://npm.im/minipass-fetch).
+
+Brotli is supported in versions of node with a Brotli binding.
+
+## How does this differ from the streams in `require('zlib')`?
+
+First, there are no convenience methods to compress or decompress a
+buffer. If you want those, use the built-in `zlib` module. This is
+only streams. That being said, Minipass streams to make it fairly easy to
+use as one-liners: `new zlib.Deflate().end(data).read()` will return the
+deflate compressed result.
+
+This module compresses and decompresses the data as fast as you feed
+it in. It is synchronous, and runs on the main process thread. Zlib
+and Brotli operations can be high CPU, but they're very fast, and doing it
+this way means much less bookkeeping and artificial deferral.
+
+Node's built in zlib streams are built on top of `stream.Transform`.
+They do the maximally safe thing with respect to consistent
+asynchrony, buffering, and backpressure.
+
+See [Minipass](http://npm.im/minipass) for more on the differences between
+Node.js core streams and Minipass streams, and the convenience methods
+provided by that class.
+
+## Classes
+
+- Deflate
+- Inflate
+- Gzip
+- Gunzip
+- DeflateRaw
+- InflateRaw
+- Unzip
+- BrotliCompress (Node v10 and higher)
+- BrotliDecompress (Node v10 and higher)
+
+## USAGE
+
+```js
+const zlib = require('minizlib')
+const input = sourceOfCompressedData()
+const decode = new zlib.BrotliDecompress()
+const output = whereToWriteTheDecodedData()
+input.pipe(decode).pipe(output)
+```
+
+## REPRODUCIBLE BUILDS
+
+To create reproducible gzip compressed files across different operating
+systems, set `portable: true` in the options. This causes minizlib to set
+the `OS` indicator in byte 9 of the extended gzip header to `0xFF` for
+'unknown'.
diff --git a/temporary_modules/trezor-connect/node_modules/minizlib/constants.js b/temporary_modules/trezor-connect/node_modules/minizlib/constants.js
new file mode 100644
index 00000000..641ebc73
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/minizlib/constants.js
@@ -0,0 +1,115 @@
+// Update with any zlib constants that are added or changed in the future.
+// Node v6 didn't export this, so we just hard code the version and rely
+// on all the other hard-coded values from zlib v4736. When node v6
+// support drops, we can just export the realZlibConstants object.
+const realZlibConstants = require('zlib').constants ||
+ /* istanbul ignore next */ { ZLIB_VERNUM: 4736 }
+
+module.exports = Object.freeze(Object.assign(Object.create(null), {
+ Z_NO_FLUSH: 0,
+ Z_PARTIAL_FLUSH: 1,
+ Z_SYNC_FLUSH: 2,
+ Z_FULL_FLUSH: 3,
+ Z_FINISH: 4,
+ Z_BLOCK: 5,
+ Z_OK: 0,
+ Z_STREAM_END: 1,
+ Z_NEED_DICT: 2,
+ Z_ERRNO: -1,
+ Z_STREAM_ERROR: -2,
+ Z_DATA_ERROR: -3,
+ Z_MEM_ERROR: -4,
+ Z_BUF_ERROR: -5,
+ Z_VERSION_ERROR: -6,
+ Z_NO_COMPRESSION: 0,
+ Z_BEST_SPEED: 1,
+ Z_BEST_COMPRESSION: 9,
+ Z_DEFAULT_COMPRESSION: -1,
+ Z_FILTERED: 1,
+ Z_HUFFMAN_ONLY: 2,
+ Z_RLE: 3,
+ Z_FIXED: 4,
+ Z_DEFAULT_STRATEGY: 0,
+ DEFLATE: 1,
+ INFLATE: 2,
+ GZIP: 3,
+ GUNZIP: 4,
+ DEFLATERAW: 5,
+ INFLATERAW: 6,
+ UNZIP: 7,
+ BROTLI_DECODE: 8,
+ BROTLI_ENCODE: 9,
+ Z_MIN_WINDOWBITS: 8,
+ Z_MAX_WINDOWBITS: 15,
+ Z_DEFAULT_WINDOWBITS: 15,
+ Z_MIN_CHUNK: 64,
+ Z_MAX_CHUNK: Infinity,
+ Z_DEFAULT_CHUNK: 16384,
+ Z_MIN_MEMLEVEL: 1,
+ Z_MAX_MEMLEVEL: 9,
+ Z_DEFAULT_MEMLEVEL: 8,
+ Z_MIN_LEVEL: -1,
+ Z_MAX_LEVEL: 9,
+ Z_DEFAULT_LEVEL: -1,
+ BROTLI_OPERATION_PROCESS: 0,
+ BROTLI_OPERATION_FLUSH: 1,
+ BROTLI_OPERATION_FINISH: 2,
+ BROTLI_OPERATION_EMIT_METADATA: 3,
+ BROTLI_MODE_GENERIC: 0,
+ BROTLI_MODE_TEXT: 1,
+ BROTLI_MODE_FONT: 2,
+ BROTLI_DEFAULT_MODE: 0,
+ BROTLI_MIN_QUALITY: 0,
+ BROTLI_MAX_QUALITY: 11,
+ BROTLI_DEFAULT_QUALITY: 11,
+ BROTLI_MIN_WINDOW_BITS: 10,
+ BROTLI_MAX_WINDOW_BITS: 24,
+ BROTLI_LARGE_MAX_WINDOW_BITS: 30,
+ BROTLI_DEFAULT_WINDOW: 22,
+ BROTLI_MIN_INPUT_BLOCK_BITS: 16,
+ BROTLI_MAX_INPUT_BLOCK_BITS: 24,
+ BROTLI_PARAM_MODE: 0,
+ BROTLI_PARAM_QUALITY: 1,
+ BROTLI_PARAM_LGWIN: 2,
+ BROTLI_PARAM_LGBLOCK: 3,
+ BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING: 4,
+ BROTLI_PARAM_SIZE_HINT: 5,
+ BROTLI_PARAM_LARGE_WINDOW: 6,
+ BROTLI_PARAM_NPOSTFIX: 7,
+ BROTLI_PARAM_NDIRECT: 8,
+ BROTLI_DECODER_RESULT_ERROR: 0,
+ BROTLI_DECODER_RESULT_SUCCESS: 1,
+ BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT: 2,
+ BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT: 3,
+ BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION: 0,
+ BROTLI_DECODER_PARAM_LARGE_WINDOW: 1,
+ BROTLI_DECODER_NO_ERROR: 0,
+ BROTLI_DECODER_SUCCESS: 1,
+ BROTLI_DECODER_NEEDS_MORE_INPUT: 2,
+ BROTLI_DECODER_NEEDS_MORE_OUTPUT: 3,
+ BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE: -1,
+ BROTLI_DECODER_ERROR_FORMAT_RESERVED: -2,
+ BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE: -3,
+ BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET: -4,
+ BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME: -5,
+ BROTLI_DECODER_ERROR_FORMAT_CL_SPACE: -6,
+ BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE: -7,
+ BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT: -8,
+ BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1: -9,
+ BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2: -10,
+ BROTLI_DECODER_ERROR_FORMAT_TRANSFORM: -11,
+ BROTLI_DECODER_ERROR_FORMAT_DICTIONARY: -12,
+ BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS: -13,
+ BROTLI_DECODER_ERROR_FORMAT_PADDING_1: -14,
+ BROTLI_DECODER_ERROR_FORMAT_PADDING_2: -15,
+ BROTLI_DECODER_ERROR_FORMAT_DISTANCE: -16,
+ BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET: -19,
+ BROTLI_DECODER_ERROR_INVALID_ARGUMENTS: -20,
+ BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES: -21,
+ BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS: -22,
+ BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP: -25,
+ BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1: -26,
+ BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2: -27,
+ BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES: -30,
+ BROTLI_DECODER_ERROR_UNREACHABLE: -31,
+}, realZlibConstants))
diff --git a/temporary_modules/trezor-connect/node_modules/minizlib/index.js b/temporary_modules/trezor-connect/node_modules/minizlib/index.js
new file mode 100644
index 00000000..fbaf69e1
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/minizlib/index.js
@@ -0,0 +1,348 @@
+'use strict'
+
+const assert = require('assert')
+const Buffer = require('buffer').Buffer
+const realZlib = require('zlib')
+
+const constants = exports.constants = require('./constants.js')
+const Minipass = require('minipass')
+
+const OriginalBufferConcat = Buffer.concat
+
+const _superWrite = Symbol('_superWrite')
+class ZlibError extends Error {
+ constructor (err) {
+ super('zlib: ' + err.message)
+ this.code = err.code
+ this.errno = err.errno
+ /* istanbul ignore if */
+ if (!this.code)
+ this.code = 'ZLIB_ERROR'
+
+ this.message = 'zlib: ' + err.message
+ Error.captureStackTrace(this, this.constructor)
+ }
+
+ get name () {
+ return 'ZlibError'
+ }
+}
+
+// the Zlib class they all inherit from
+// This thing manages the queue of requests, and returns
+// true or false if there is anything in the queue when
+// you call the .write() method.
+const _opts = Symbol('opts')
+const _flushFlag = Symbol('flushFlag')
+const _finishFlushFlag = Symbol('finishFlushFlag')
+const _fullFlushFlag = Symbol('fullFlushFlag')
+const _handle = Symbol('handle')
+const _onError = Symbol('onError')
+const _sawError = Symbol('sawError')
+const _level = Symbol('level')
+const _strategy = Symbol('strategy')
+const _ended = Symbol('ended')
+const _defaultFullFlush = Symbol('_defaultFullFlush')
+
+class ZlibBase extends Minipass {
+ constructor (opts, mode) {
+ if (!opts || typeof opts !== 'object')
+ throw new TypeError('invalid options for ZlibBase constructor')
+
+ super(opts)
+ this[_sawError] = false
+ this[_ended] = false
+ this[_opts] = opts
+
+ this[_flushFlag] = opts.flush
+ this[_finishFlushFlag] = opts.finishFlush
+ // this will throw if any options are invalid for the class selected
+ try {
+ this[_handle] = new realZlib[mode](opts)
+ } catch (er) {
+ // make sure that all errors get decorated properly
+ throw new ZlibError(er)
+ }
+
+ this[_onError] = (err) => {
+ // no sense raising multiple errors, since we abort on the first one.
+ if (this[_sawError])
+ return
+
+ this[_sawError] = true
+
+ // there is no way to cleanly recover.
+ // continuing only obscures problems.
+ this.close()
+ this.emit('error', err)
+ }
+
+ this[_handle].on('error', er => this[_onError](new ZlibError(er)))
+ this.once('end', () => this.close)
+ }
+
+ close () {
+ if (this[_handle]) {
+ this[_handle].close()
+ this[_handle] = null
+ this.emit('close')
+ }
+ }
+
+ reset () {
+ if (!this[_sawError]) {
+ assert(this[_handle], 'zlib binding closed')
+ return this[_handle].reset()
+ }
+ }
+
+ flush (flushFlag) {
+ if (this.ended)
+ return
+
+ if (typeof flushFlag !== 'number')
+ flushFlag = this[_fullFlushFlag]
+ this.write(Object.assign(Buffer.alloc(0), { [_flushFlag]: flushFlag }))
+ }
+
+ end (chunk, encoding, cb) {
+ if (chunk)
+ this.write(chunk, encoding)
+ this.flush(this[_finishFlushFlag])
+ this[_ended] = true
+ return super.end(null, null, cb)
+ }
+
+ get ended () {
+ return this[_ended]
+ }
+
+ write (chunk, encoding, cb) {
+ // process the chunk using the sync process
+ // then super.write() all the outputted chunks
+ if (typeof encoding === 'function')
+ cb = encoding, encoding = 'utf8'
+
+ if (typeof chunk === 'string')
+ chunk = Buffer.from(chunk, encoding)
+
+ if (this[_sawError])
+ return
+ assert(this[_handle], 'zlib binding closed')
+
+ // _processChunk tries to .close() the native handle after it's done, so we
+ // intercept that by temporarily making it a no-op.
+ const nativeHandle = this[_handle]._handle
+ const originalNativeClose = nativeHandle.close
+ nativeHandle.close = () => {}
+ const originalClose = this[_handle].close
+ this[_handle].close = () => {}
+ // It also calls `Buffer.concat()` at the end, which may be convenient
+ // for some, but which we are not interested in as it slows us down.
+ Buffer.concat = (args) => args
+ let result
+ try {
+ const flushFlag = typeof chunk[_flushFlag] === 'number'
+ ? chunk[_flushFlag] : this[_flushFlag]
+ result = this[_handle]._processChunk(chunk, flushFlag)
+ // if we don't throw, reset it back how it was
+ Buffer.concat = OriginalBufferConcat
+ } catch (err) {
+ // or if we do, put Buffer.concat() back before we emit error
+ // Error events call into user code, which may call Buffer.concat()
+ Buffer.concat = OriginalBufferConcat
+ this[_onError](new ZlibError(err))
+ } finally {
+ if (this[_handle]) {
+ // Core zlib resets `_handle` to null after attempting to close the
+ // native handle. Our no-op handler prevented actual closure, but we
+ // need to restore the `._handle` property.
+ this[_handle]._handle = nativeHandle
+ nativeHandle.close = originalNativeClose
+ this[_handle].close = originalClose
+ // `_processChunk()` adds an 'error' listener. If we don't remove it
+ // after each call, these handlers start piling up.
+ this[_handle].removeAllListeners('error')
+ // make sure OUR error listener is still attached tho
+ }
+ }
+
+ if (this[_handle])
+ this[_handle].on('error', er => this[_onError](new ZlibError(er)))
+
+ let writeReturn
+ if (result) {
+ if (Array.isArray(result) && result.length > 0) {
+ // The first buffer is always `handle._outBuffer`, which would be
+ // re-used for later invocations; so, we always have to copy that one.
+ writeReturn = this[_superWrite](Buffer.from(result[0]))
+ for (let i = 1; i < result.length; i++) {
+ writeReturn = this[_superWrite](result[i])
+ }
+ } else {
+ writeReturn = this[_superWrite](Buffer.from(result))
+ }
+ }
+
+ if (cb)
+ cb()
+ return writeReturn
+ }
+
+ [_superWrite] (data) {
+ return super.write(data)
+ }
+}
+
+class Zlib extends ZlibBase {
+ constructor (opts, mode) {
+ opts = opts || {}
+
+ opts.flush = opts.flush || constants.Z_NO_FLUSH
+ opts.finishFlush = opts.finishFlush || constants.Z_FINISH
+ super(opts, mode)
+
+ this[_fullFlushFlag] = constants.Z_FULL_FLUSH
+ this[_level] = opts.level
+ this[_strategy] = opts.strategy
+ }
+
+ params (level, strategy) {
+ if (this[_sawError])
+ return
+
+ if (!this[_handle])
+ throw new Error('cannot switch params when binding is closed')
+
+ // no way to test this without also not supporting params at all
+ /* istanbul ignore if */
+ if (!this[_handle].params)
+ throw new Error('not supported in this implementation')
+
+ if (this[_level] !== level || this[_strategy] !== strategy) {
+ this.flush(constants.Z_SYNC_FLUSH)
+ assert(this[_handle], 'zlib binding closed')
+ // .params() calls .flush(), but the latter is always async in the
+ // core zlib. We override .flush() temporarily to intercept that and
+ // flush synchronously.
+ const origFlush = this[_handle].flush
+ this[_handle].flush = (flushFlag, cb) => {
+ this.flush(flushFlag)
+ cb()
+ }
+ try {
+ this[_handle].params(level, strategy)
+ } finally {
+ this[_handle].flush = origFlush
+ }
+ /* istanbul ignore else */
+ if (this[_handle]) {
+ this[_level] = level
+ this[_strategy] = strategy
+ }
+ }
+ }
+}
+
+// minimal 2-byte header
+class Deflate extends Zlib {
+ constructor (opts) {
+ super(opts, 'Deflate')
+ }
+}
+
+class Inflate extends Zlib {
+ constructor (opts) {
+ super(opts, 'Inflate')
+ }
+}
+
+// gzip - bigger header, same deflate compression
+const _portable = Symbol('_portable')
+class Gzip extends Zlib {
+ constructor (opts) {
+ super(opts, 'Gzip')
+ this[_portable] = opts && !!opts.portable
+ }
+
+ [_superWrite] (data) {
+ if (!this[_portable])
+ return super[_superWrite](data)
+
+ // we'll always get the header emitted in one first chunk
+ // overwrite the OS indicator byte with 0xFF
+ this[_portable] = false
+ data[9] = 255
+ return super[_superWrite](data)
+ }
+}
+
+class Gunzip extends Zlib {
+ constructor (opts) {
+ super(opts, 'Gunzip')
+ }
+}
+
+// raw - no header
+class DeflateRaw extends Zlib {
+ constructor (opts) {
+ super(opts, 'DeflateRaw')
+ }
+}
+
+class InflateRaw extends Zlib {
+ constructor (opts) {
+ super(opts, 'InflateRaw')
+ }
+}
+
+// auto-detect header.
+class Unzip extends Zlib {
+ constructor (opts) {
+ super(opts, 'Unzip')
+ }
+}
+
+class Brotli extends ZlibBase {
+ constructor (opts, mode) {
+ opts = opts || {}
+
+ opts.flush = opts.flush || constants.BROTLI_OPERATION_PROCESS
+ opts.finishFlush = opts.finishFlush || constants.BROTLI_OPERATION_FINISH
+
+ super(opts, mode)
+
+ this[_fullFlushFlag] = constants.BROTLI_OPERATION_FLUSH
+ }
+}
+
+class BrotliCompress extends Brotli {
+ constructor (opts) {
+ super(opts, 'BrotliCompress')
+ }
+}
+
+class BrotliDecompress extends Brotli {
+ constructor (opts) {
+ super(opts, 'BrotliDecompress')
+ }
+}
+
+exports.Deflate = Deflate
+exports.Inflate = Inflate
+exports.Gzip = Gzip
+exports.Gunzip = Gunzip
+exports.DeflateRaw = DeflateRaw
+exports.InflateRaw = InflateRaw
+exports.Unzip = Unzip
+/* istanbul ignore else */
+if (typeof realZlib.BrotliCompress === 'function') {
+ exports.BrotliCompress = BrotliCompress
+ exports.BrotliDecompress = BrotliDecompress
+} else {
+ exports.BrotliCompress = exports.BrotliDecompress = class {
+ constructor () {
+ throw new Error('Brotli is not supported in this version of Node.js')
+ }
+ }
+}
diff --git a/temporary_modules/trezor-connect/node_modules/minizlib/package.json b/temporary_modules/trezor-connect/node_modules/minizlib/package.json
new file mode 100644
index 00000000..98825a54
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/minizlib/package.json
@@ -0,0 +1,42 @@
+{
+ "name": "minizlib",
+ "version": "2.1.2",
+ "description": "A small fast zlib stream built on [minipass](http://npm.im/minipass) and Node.js's zlib binding.",
+ "main": "index.js",
+ "dependencies": {
+ "minipass": "^3.0.0",
+ "yallist": "^4.0.0"
+ },
+ "scripts": {
+ "test": "tap test/*.js --100 -J",
+ "preversion": "npm test",
+ "postversion": "npm publish",
+ "postpublish": "git push origin --all; git push origin --tags"
+ },
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/isaacs/minizlib.git"
+ },
+ "keywords": [
+ "zlib",
+ "gzip",
+ "gunzip",
+ "deflate",
+ "inflate",
+ "compression",
+ "zip",
+ "unzip"
+ ],
+ "author": "Isaac Z. Schlueter (http://blog.izs.me/)",
+ "license": "MIT",
+ "devDependencies": {
+ "tap": "^14.6.9"
+ },
+ "files": [
+ "index.js",
+ "constants.js"
+ ],
+ "engines": {
+ "node": ">= 8"
+ }
+}
diff --git a/temporary_modules/trezor-connect/node_modules/mkdirp/CHANGELOG.md b/temporary_modules/trezor-connect/node_modules/mkdirp/CHANGELOG.md
new file mode 100644
index 00000000..81458380
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/mkdirp/CHANGELOG.md
@@ -0,0 +1,15 @@
+# Changers Lorgs!
+
+## 1.0
+
+Full rewrite. Essentially a brand new module.
+
+- Return a promise instead of taking a callback.
+- Use native `fs.mkdir(path, { recursive: true })` when available.
+- Drop support for outdated Node.js versions. (Technically still works on
+ Node.js v8, but only 10 and above are officially supported.)
+
+## 0.x
+
+Original and most widely used recursive directory creation implementation
+in JavaScript, dating back to 2010.
diff --git a/temporary_modules/trezor-connect/node_modules/mkdirp/LICENSE b/temporary_modules/trezor-connect/node_modules/mkdirp/LICENSE
new file mode 100644
index 00000000..13fcd15f
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/mkdirp/LICENSE
@@ -0,0 +1,21 @@
+Copyright James Halliday (mail@substack.net) and Isaac Z. Schlueter (i@izs.me)
+
+This project is free software released under the MIT license:
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
diff --git a/temporary_modules/trezor-connect/node_modules/mkdirp/bin/cmd.js b/temporary_modules/trezor-connect/node_modules/mkdirp/bin/cmd.js
new file mode 100644
index 00000000..6e0aa8dc
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/mkdirp/bin/cmd.js
@@ -0,0 +1,68 @@
+#!/usr/bin/env node
+
+const usage = () => `
+usage: mkdirp [DIR1,DIR2..] {OPTIONS}
+
+ Create each supplied directory including any necessary parent directories
+ that don't yet exist.
+
+ If the directory already exists, do nothing.
+
+OPTIONS are:
+
+ -m If a directory needs to be created, set the mode as an octal
+ --mode= permission string.
+
+ -v --version Print the mkdirp version number
+
+ -h --help Print this helpful banner
+
+ -p --print Print the first directories created for each path provided
+
+ --manual Use manual implementation, even if native is available
+`
+
+const dirs = []
+const opts = {}
+let print = false
+let dashdash = false
+let manual = false
+for (const arg of process.argv.slice(2)) {
+ if (dashdash)
+ dirs.push(arg)
+ else if (arg === '--')
+ dashdash = true
+ else if (arg === '--manual')
+ manual = true
+ else if (/^-h/.test(arg) || /^--help/.test(arg)) {
+ console.log(usage())
+ process.exit(0)
+ } else if (arg === '-v' || arg === '--version') {
+ console.log(require('../package.json').version)
+ process.exit(0)
+ } else if (arg === '-p' || arg === '--print') {
+ print = true
+ } else if (/^-m/.test(arg) || /^--mode=/.test(arg)) {
+ const mode = parseInt(arg.replace(/^(-m|--mode=)/, ''), 8)
+ if (isNaN(mode)) {
+ console.error(`invalid mode argument: ${arg}\nMust be an octal number.`)
+ process.exit(1)
+ }
+ opts.mode = mode
+ } else
+ dirs.push(arg)
+}
+
+const mkdirp = require('../')
+const impl = manual ? mkdirp.manual : mkdirp
+if (dirs.length === 0)
+ console.error(usage())
+
+Promise.all(dirs.map(dir => impl(dir, opts)))
+ .then(made => print ? made.forEach(m => m && console.log(m)) : null)
+ .catch(er => {
+ console.error(er.message)
+ if (er.code)
+ console.error(' code: ' + er.code)
+ process.exit(1)
+ })
diff --git a/temporary_modules/trezor-connect/node_modules/mkdirp/index.js b/temporary_modules/trezor-connect/node_modules/mkdirp/index.js
new file mode 100644
index 00000000..ad7a16c9
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/mkdirp/index.js
@@ -0,0 +1,31 @@
+const optsArg = require('./lib/opts-arg.js')
+const pathArg = require('./lib/path-arg.js')
+
+const {mkdirpNative, mkdirpNativeSync} = require('./lib/mkdirp-native.js')
+const {mkdirpManual, mkdirpManualSync} = require('./lib/mkdirp-manual.js')
+const {useNative, useNativeSync} = require('./lib/use-native.js')
+
+
+const mkdirp = (path, opts) => {
+ path = pathArg(path)
+ opts = optsArg(opts)
+ return useNative(opts)
+ ? mkdirpNative(path, opts)
+ : mkdirpManual(path, opts)
+}
+
+const mkdirpSync = (path, opts) => {
+ path = pathArg(path)
+ opts = optsArg(opts)
+ return useNativeSync(opts)
+ ? mkdirpNativeSync(path, opts)
+ : mkdirpManualSync(path, opts)
+}
+
+mkdirp.sync = mkdirpSync
+mkdirp.native = (path, opts) => mkdirpNative(pathArg(path), optsArg(opts))
+mkdirp.manual = (path, opts) => mkdirpManual(pathArg(path), optsArg(opts))
+mkdirp.nativeSync = (path, opts) => mkdirpNativeSync(pathArg(path), optsArg(opts))
+mkdirp.manualSync = (path, opts) => mkdirpManualSync(pathArg(path), optsArg(opts))
+
+module.exports = mkdirp
diff --git a/temporary_modules/trezor-connect/node_modules/mkdirp/lib/find-made.js b/temporary_modules/trezor-connect/node_modules/mkdirp/lib/find-made.js
new file mode 100644
index 00000000..022e492c
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/mkdirp/lib/find-made.js
@@ -0,0 +1,29 @@
+const {dirname} = require('path')
+
+const findMade = (opts, parent, path = undefined) => {
+ // we never want the 'made' return value to be a root directory
+ if (path === parent)
+ return Promise.resolve()
+
+ return opts.statAsync(parent).then(
+ st => st.isDirectory() ? path : undefined, // will fail later
+ er => er.code === 'ENOENT'
+ ? findMade(opts, dirname(parent), parent)
+ : undefined
+ )
+}
+
+const findMadeSync = (opts, parent, path = undefined) => {
+ if (path === parent)
+ return undefined
+
+ try {
+ return opts.statSync(parent).isDirectory() ? path : undefined
+ } catch (er) {
+ return er.code === 'ENOENT'
+ ? findMadeSync(opts, dirname(parent), parent)
+ : undefined
+ }
+}
+
+module.exports = {findMade, findMadeSync}
diff --git a/temporary_modules/trezor-connect/node_modules/mkdirp/lib/mkdirp-manual.js b/temporary_modules/trezor-connect/node_modules/mkdirp/lib/mkdirp-manual.js
new file mode 100644
index 00000000..2eb18cd6
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/mkdirp/lib/mkdirp-manual.js
@@ -0,0 +1,64 @@
+const {dirname} = require('path')
+
+const mkdirpManual = (path, opts, made) => {
+ opts.recursive = false
+ const parent = dirname(path)
+ if (parent === path) {
+ return opts.mkdirAsync(path, opts).catch(er => {
+ // swallowed by recursive implementation on posix systems
+ // any other error is a failure
+ if (er.code !== 'EISDIR')
+ throw er
+ })
+ }
+
+ return opts.mkdirAsync(path, opts).then(() => made || path, er => {
+ if (er.code === 'ENOENT')
+ return mkdirpManual(parent, opts)
+ .then(made => mkdirpManual(path, opts, made))
+ if (er.code !== 'EEXIST' && er.code !== 'EROFS')
+ throw er
+ return opts.statAsync(path).then(st => {
+ if (st.isDirectory())
+ return made
+ else
+ throw er
+ }, () => { throw er })
+ })
+}
+
+const mkdirpManualSync = (path, opts, made) => {
+ const parent = dirname(path)
+ opts.recursive = false
+
+ if (parent === path) {
+ try {
+ return opts.mkdirSync(path, opts)
+ } catch (er) {
+ // swallowed by recursive implementation on posix systems
+ // any other error is a failure
+ if (er.code !== 'EISDIR')
+ throw er
+ else
+ return
+ }
+ }
+
+ try {
+ opts.mkdirSync(path, opts)
+ return made || path
+ } catch (er) {
+ if (er.code === 'ENOENT')
+ return mkdirpManualSync(path, opts, mkdirpManualSync(parent, opts, made))
+ if (er.code !== 'EEXIST' && er.code !== 'EROFS')
+ throw er
+ try {
+ if (!opts.statSync(path).isDirectory())
+ throw er
+ } catch (_) {
+ throw er
+ }
+ }
+}
+
+module.exports = {mkdirpManual, mkdirpManualSync}
diff --git a/temporary_modules/trezor-connect/node_modules/mkdirp/lib/mkdirp-native.js b/temporary_modules/trezor-connect/node_modules/mkdirp/lib/mkdirp-native.js
new file mode 100644
index 00000000..c7a6b698
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/mkdirp/lib/mkdirp-native.js
@@ -0,0 +1,39 @@
+const {dirname} = require('path')
+const {findMade, findMadeSync} = require('./find-made.js')
+const {mkdirpManual, mkdirpManualSync} = require('./mkdirp-manual.js')
+
+const mkdirpNative = (path, opts) => {
+ opts.recursive = true
+ const parent = dirname(path)
+ if (parent === path)
+ return opts.mkdirAsync(path, opts)
+
+ return findMade(opts, path).then(made =>
+ opts.mkdirAsync(path, opts).then(() => made)
+ .catch(er => {
+ if (er.code === 'ENOENT')
+ return mkdirpManual(path, opts)
+ else
+ throw er
+ }))
+}
+
+const mkdirpNativeSync = (path, opts) => {
+ opts.recursive = true
+ const parent = dirname(path)
+ if (parent === path)
+ return opts.mkdirSync(path, opts)
+
+ const made = findMadeSync(opts, path)
+ try {
+ opts.mkdirSync(path, opts)
+ return made
+ } catch (er) {
+ if (er.code === 'ENOENT')
+ return mkdirpManualSync(path, opts)
+ else
+ throw er
+ }
+}
+
+module.exports = {mkdirpNative, mkdirpNativeSync}
diff --git a/temporary_modules/trezor-connect/node_modules/mkdirp/lib/opts-arg.js b/temporary_modules/trezor-connect/node_modules/mkdirp/lib/opts-arg.js
new file mode 100644
index 00000000..2fa4833f
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/mkdirp/lib/opts-arg.js
@@ -0,0 +1,23 @@
+const { promisify } = require('util')
+const fs = require('fs')
+const optsArg = opts => {
+ if (!opts)
+ opts = { mode: 0o777, fs }
+ else if (typeof opts === 'object')
+ opts = { mode: 0o777, fs, ...opts }
+ else if (typeof opts === 'number')
+ opts = { mode: opts, fs }
+ else if (typeof opts === 'string')
+ opts = { mode: parseInt(opts, 8), fs }
+ else
+ throw new TypeError('invalid options argument')
+
+ opts.mkdir = opts.mkdir || opts.fs.mkdir || fs.mkdir
+ opts.mkdirAsync = promisify(opts.mkdir)
+ opts.stat = opts.stat || opts.fs.stat || fs.stat
+ opts.statAsync = promisify(opts.stat)
+ opts.statSync = opts.statSync || opts.fs.statSync || fs.statSync
+ opts.mkdirSync = opts.mkdirSync || opts.fs.mkdirSync || fs.mkdirSync
+ return opts
+}
+module.exports = optsArg
diff --git a/temporary_modules/trezor-connect/node_modules/mkdirp/lib/path-arg.js b/temporary_modules/trezor-connect/node_modules/mkdirp/lib/path-arg.js
new file mode 100644
index 00000000..cc07de5a
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/mkdirp/lib/path-arg.js
@@ -0,0 +1,29 @@
+const platform = process.env.__TESTING_MKDIRP_PLATFORM__ || process.platform
+const { resolve, parse } = require('path')
+const pathArg = path => {
+ if (/\0/.test(path)) {
+ // simulate same failure that node raises
+ throw Object.assign(
+ new TypeError('path must be a string without null bytes'),
+ {
+ path,
+ code: 'ERR_INVALID_ARG_VALUE',
+ }
+ )
+ }
+
+ path = resolve(path)
+ if (platform === 'win32') {
+ const badWinChars = /[*|"<>?:]/
+ const {root} = parse(path)
+ if (badWinChars.test(path.substr(root.length))) {
+ throw Object.assign(new Error('Illegal characters in path.'), {
+ path,
+ code: 'EINVAL',
+ })
+ }
+ }
+
+ return path
+}
+module.exports = pathArg
diff --git a/temporary_modules/trezor-connect/node_modules/mkdirp/lib/use-native.js b/temporary_modules/trezor-connect/node_modules/mkdirp/lib/use-native.js
new file mode 100644
index 00000000..079361de
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/mkdirp/lib/use-native.js
@@ -0,0 +1,10 @@
+const fs = require('fs')
+
+const version = process.env.__TESTING_MKDIRP_NODE_VERSION__ || process.version
+const versArr = version.replace(/^v/, '').split('.')
+const hasNative = +versArr[0] > 10 || +versArr[0] === 10 && +versArr[1] >= 12
+
+const useNative = !hasNative ? () => false : opts => opts.mkdir === fs.mkdir
+const useNativeSync = !hasNative ? () => false : opts => opts.mkdirSync === fs.mkdirSync
+
+module.exports = {useNative, useNativeSync}
diff --git a/temporary_modules/trezor-connect/node_modules/mkdirp/package.json b/temporary_modules/trezor-connect/node_modules/mkdirp/package.json
new file mode 100644
index 00000000..2913ed09
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/mkdirp/package.json
@@ -0,0 +1,44 @@
+{
+ "name": "mkdirp",
+ "description": "Recursively mkdir, like `mkdir -p`",
+ "version": "1.0.4",
+ "main": "index.js",
+ "keywords": [
+ "mkdir",
+ "directory",
+ "make dir",
+ "make",
+ "dir",
+ "recursive",
+ "native"
+ ],
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/isaacs/node-mkdirp.git"
+ },
+ "scripts": {
+ "test": "tap",
+ "snap": "tap",
+ "preversion": "npm test",
+ "postversion": "npm publish",
+ "postpublish": "git push origin --follow-tags"
+ },
+ "tap": {
+ "check-coverage": true,
+ "coverage-map": "map.js"
+ },
+ "devDependencies": {
+ "require-inject": "^1.4.4",
+ "tap": "^14.10.7"
+ },
+ "bin": "bin/cmd.js",
+ "license": "MIT",
+ "engines": {
+ "node": ">=10"
+ },
+ "files": [
+ "bin",
+ "lib",
+ "index.js"
+ ]
+}
diff --git a/temporary_modules/trezor-connect/node_modules/mkdirp/readme.markdown b/temporary_modules/trezor-connect/node_modules/mkdirp/readme.markdown
new file mode 100644
index 00000000..827de590
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/mkdirp/readme.markdown
@@ -0,0 +1,266 @@
+# mkdirp
+
+Like `mkdir -p`, but in Node.js!
+
+Now with a modern API and no\* bugs!
+
+\* may contain some bugs
+
+# example
+
+## pow.js
+
+```js
+const mkdirp = require('mkdirp')
+
+// return value is a Promise resolving to the first directory created
+mkdirp('/tmp/foo/bar/baz').then(made =>
+ console.log(`made directories, starting with ${made}`))
+```
+
+Output (where `/tmp/foo` already exists)
+
+```
+made directories, starting with /tmp/foo/bar
+```
+
+Or, if you don't have time to wait around for promises:
+
+```js
+const mkdirp = require('mkdirp')
+
+// return value is the first directory created
+const made = mkdirp.sync('/tmp/foo/bar/baz')
+console.log(`made directories, starting with ${made}`)
+```
+
+And now /tmp/foo/bar/baz exists, huzzah!
+
+# methods
+
+```js
+const mkdirp = require('mkdirp')
+```
+
+## mkdirp(dir, [opts]) -> Promise
+
+Create a new directory and any necessary subdirectories at `dir` with octal
+permission string `opts.mode`. If `opts` is a string or number, it will be
+treated as the `opts.mode`.
+
+If `opts.mode` isn't specified, it defaults to `0o777 &
+(~process.umask())`.
+
+Promise resolves to first directory `made` that had to be created, or
+`undefined` if everything already exists. Promise rejects if any errors
+are encountered. Note that, in the case of promise rejection, some
+directories _may_ have been created, as recursive directory creation is not
+an atomic operation.
+
+You can optionally pass in an alternate `fs` implementation by passing in
+`opts.fs`. Your implementation should have `opts.fs.mkdir(path, opts, cb)`
+and `opts.fs.stat(path, cb)`.
+
+You can also override just one or the other of `mkdir` and `stat` by
+passing in `opts.stat` or `opts.mkdir`, or providing an `fs` option that
+only overrides one of these.
+
+## mkdirp.sync(dir, opts) -> String|null
+
+Synchronously create a new directory and any necessary subdirectories at
+`dir` with octal permission string `opts.mode`. If `opts` is a string or
+number, it will be treated as the `opts.mode`.
+
+If `opts.mode` isn't specified, it defaults to `0o777 &
+(~process.umask())`.
+
+Returns the first directory that had to be created, or undefined if
+everything already exists.
+
+You can optionally pass in an alternate `fs` implementation by passing in
+`opts.fs`. Your implementation should have `opts.fs.mkdirSync(path, mode)`
+and `opts.fs.statSync(path)`.
+
+You can also override just one or the other of `mkdirSync` and `statSync`
+by passing in `opts.statSync` or `opts.mkdirSync`, or providing an `fs`
+option that only overrides one of these.
+
+## mkdirp.manual, mkdirp.manualSync
+
+Use the manual implementation (not the native one). This is the default
+when the native implementation is not available or the stat/mkdir
+implementation is overridden.
+
+## mkdirp.native, mkdirp.nativeSync
+
+Use the native implementation (not the manual one). This is the default
+when the native implementation is available and stat/mkdir are not
+overridden.
+
+# implementation
+
+On Node.js v10.12.0 and above, use the native `fs.mkdir(p,
+{recursive:true})` option, unless `fs.mkdir`/`fs.mkdirSync` has been
+overridden by an option.
+
+## native implementation
+
+- If the path is a root directory, then pass it to the underlying
+ implementation and return the result/error. (In this case, it'll either
+ succeed or fail, but we aren't actually creating any dirs.)
+- Walk up the path statting each directory, to find the first path that
+ will be created, `made`.
+- Call `fs.mkdir(path, { recursive: true })` (or `fs.mkdirSync`)
+- If error, raise it to the caller.
+- Return `made`.
+
+## manual implementation
+
+- Call underlying `fs.mkdir` implementation, with `recursive: false`
+- If error:
+ - If path is a root directory, raise to the caller and do not handle it
+ - If ENOENT, mkdirp parent dir, store result as `made`
+ - stat(path)
+ - If error, raise original `mkdir` error
+ - If directory, return `made`
+ - Else, raise original `mkdir` error
+- else
+ - return `undefined` if a root dir, or `made` if set, or `path`
+
+## windows vs unix caveat
+
+On Windows file systems, attempts to create a root directory (ie, a drive
+letter or root UNC path) will fail. If the root directory exists, then it
+will fail with `EPERM`. If the root directory does not exist, then it will
+fail with `ENOENT`.
+
+On posix file systems, attempts to create a root directory (in recursive
+mode) will succeed silently, as it is treated like just another directory
+that already exists. (In non-recursive mode, of course, it fails with
+`EEXIST`.)
+
+In order to preserve this system-specific behavior (and because it's not as
+if we can create the parent of a root directory anyway), attempts to create
+a root directory are passed directly to the `fs` implementation, and any
+errors encountered are not handled.
+
+## native error caveat
+
+The native implementation (as of at least Node.js v13.4.0) does not provide
+appropriate errors in some cases (see
+[nodejs/node#31481](https://github.com/nodejs/node/issues/31481) and
+[nodejs/node#28015](https://github.com/nodejs/node/issues/28015)).
+
+In order to work around this issue, the native implementation will fall
+back to the manual implementation if an `ENOENT` error is encountered.
+
+# choosing a recursive mkdir implementation
+
+There are a few to choose from! Use the one that suits your needs best :D
+
+## use `fs.mkdir(path, {recursive: true}, cb)` if:
+
+- You wish to optimize performance even at the expense of other factors.
+- You don't need to know the first dir created.
+- You are ok with getting `ENOENT` as the error when some other problem is
+ the actual cause.
+- You can limit your platforms to Node.js v10.12 and above.
+- You're ok with using callbacks instead of promises.
+- You don't need/want a CLI.
+- You don't need to override the `fs` methods in use.
+
+## use this module (mkdirp 1.x) if:
+
+- You need to know the first directory that was created.
+- You wish to use the native implementation if available, but fall back
+ when it's not.
+- You prefer promise-returning APIs to callback-taking APIs.
+- You want more useful error messages than the native recursive mkdir
+ provides (at least as of Node.js v13.4), and are ok with re-trying on
+ `ENOENT` to achieve this.
+- You need (or at least, are ok with) a CLI.
+- You need to override the `fs` methods in use.
+
+## use [`make-dir`](http://npm.im/make-dir) if:
+
+- You do not need to know the first dir created (and wish to save a few
+ `stat` calls when using the native implementation for this reason).
+- You wish to use the native implementation if available, but fall back
+ when it's not.
+- You prefer promise-returning APIs to callback-taking APIs.
+- You are ok with occasionally getting `ENOENT` errors for failures that
+ are actually related to something other than a missing file system entry.
+- You don't need/want a CLI.
+- You need to override the `fs` methods in use.
+
+## use mkdirp 0.x if:
+
+- You need to know the first directory that was created.
+- You need (or at least, are ok with) a CLI.
+- You need to override the `fs` methods in use.
+- You're ok with using callbacks instead of promises.
+- You are not running on Windows, where the root-level ENOENT errors can
+ lead to infinite regress.
+- You think vinyl just sounds warmer and richer for some weird reason.
+- You are supporting truly ancient Node.js versions, before even the advent
+ of a `Promise` language primitive. (Please don't. You deserve better.)
+
+# cli
+
+This package also ships with a `mkdirp` command.
+
+```
+$ mkdirp -h
+
+usage: mkdirp [DIR1,DIR2..] {OPTIONS}
+
+ Create each supplied directory including any necessary parent directories
+ that don't yet exist.
+
+ If the directory already exists, do nothing.
+
+OPTIONS are:
+
+ -m If a directory needs to be created, set the mode as an octal
+ --mode= permission string.
+
+ -v --version Print the mkdirp version number
+
+ -h --help Print this helpful banner
+
+ -p --print Print the first directories created for each path provided
+
+ --manual Use manual implementation, even if native is available
+```
+
+# install
+
+With [npm](http://npmjs.org) do:
+
+```
+npm install mkdirp
+```
+
+to get the library locally, or
+
+```
+npm install -g mkdirp
+```
+
+to get the command everywhere, or
+
+```
+npx mkdirp ...
+```
+
+to run the command without installing it globally.
+
+# platform support
+
+This module works on node v8, but only v10 and above are officially
+supported, as Node v8 reached its LTS end of life 2020-01-01, which is in
+the past, as of this writing.
+
+# license
+
+MIT
diff --git a/temporary_modules/trezor-connect/node_modules/ms/index.js b/temporary_modules/trezor-connect/node_modules/ms/index.js
new file mode 100644
index 00000000..c4498bcc
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/ms/index.js
@@ -0,0 +1,162 @@
+/**
+ * Helpers.
+ */
+
+var s = 1000;
+var m = s * 60;
+var h = m * 60;
+var d = h * 24;
+var w = d * 7;
+var y = d * 365.25;
+
+/**
+ * Parse or format the given `val`.
+ *
+ * Options:
+ *
+ * - `long` verbose formatting [false]
+ *
+ * @param {String|Number} val
+ * @param {Object} [options]
+ * @throws {Error} throw an error if val is not a non-empty string or a number
+ * @return {String|Number}
+ * @api public
+ */
+
+module.exports = function(val, options) {
+ options = options || {};
+ var type = typeof val;
+ if (type === 'string' && val.length > 0) {
+ return parse(val);
+ } else if (type === 'number' && isFinite(val)) {
+ return options.long ? fmtLong(val) : fmtShort(val);
+ }
+ throw new Error(
+ 'val is not a non-empty string or a valid number. val=' +
+ JSON.stringify(val)
+ );
+};
+
+/**
+ * Parse the given `str` and return milliseconds.
+ *
+ * @param {String} str
+ * @return {Number}
+ * @api private
+ */
+
+function parse(str) {
+ str = String(str);
+ if (str.length > 100) {
+ return;
+ }
+ var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
+ str
+ );
+ if (!match) {
+ return;
+ }
+ var n = parseFloat(match[1]);
+ var type = (match[2] || 'ms').toLowerCase();
+ switch (type) {
+ case 'years':
+ case 'year':
+ case 'yrs':
+ case 'yr':
+ case 'y':
+ return n * y;
+ case 'weeks':
+ case 'week':
+ case 'w':
+ return n * w;
+ case 'days':
+ case 'day':
+ case 'd':
+ return n * d;
+ case 'hours':
+ case 'hour':
+ case 'hrs':
+ case 'hr':
+ case 'h':
+ return n * h;
+ case 'minutes':
+ case 'minute':
+ case 'mins':
+ case 'min':
+ case 'm':
+ return n * m;
+ case 'seconds':
+ case 'second':
+ case 'secs':
+ case 'sec':
+ case 's':
+ return n * s;
+ case 'milliseconds':
+ case 'millisecond':
+ case 'msecs':
+ case 'msec':
+ case 'ms':
+ return n;
+ default:
+ return undefined;
+ }
+}
+
+/**
+ * Short format for `ms`.
+ *
+ * @param {Number} ms
+ * @return {String}
+ * @api private
+ */
+
+function fmtShort(ms) {
+ var msAbs = Math.abs(ms);
+ if (msAbs >= d) {
+ return Math.round(ms / d) + 'd';
+ }
+ if (msAbs >= h) {
+ return Math.round(ms / h) + 'h';
+ }
+ if (msAbs >= m) {
+ return Math.round(ms / m) + 'm';
+ }
+ if (msAbs >= s) {
+ return Math.round(ms / s) + 's';
+ }
+ return ms + 'ms';
+}
+
+/**
+ * Long format for `ms`.
+ *
+ * @param {Number} ms
+ * @return {String}
+ * @api private
+ */
+
+function fmtLong(ms) {
+ var msAbs = Math.abs(ms);
+ if (msAbs >= d) {
+ return plural(ms, msAbs, d, 'day');
+ }
+ if (msAbs >= h) {
+ return plural(ms, msAbs, h, 'hour');
+ }
+ if (msAbs >= m) {
+ return plural(ms, msAbs, m, 'minute');
+ }
+ if (msAbs >= s) {
+ return plural(ms, msAbs, s, 'second');
+ }
+ return ms + ' ms';
+}
+
+/**
+ * Pluralization helper.
+ */
+
+function plural(ms, msAbs, n, name) {
+ var isPlural = msAbs >= n * 1.5;
+ return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
+}
diff --git a/temporary_modules/trezor-connect/node_modules/ms/license.md b/temporary_modules/trezor-connect/node_modules/ms/license.md
new file mode 100644
index 00000000..69b61253
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/ms/license.md
@@ -0,0 +1,21 @@
+The MIT License (MIT)
+
+Copyright (c) 2016 Zeit, Inc.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/temporary_modules/trezor-connect/node_modules/ms/package.json b/temporary_modules/trezor-connect/node_modules/ms/package.json
new file mode 100644
index 00000000..eea666e1
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/ms/package.json
@@ -0,0 +1,37 @@
+{
+ "name": "ms",
+ "version": "2.1.2",
+ "description": "Tiny millisecond conversion utility",
+ "repository": "zeit/ms",
+ "main": "./index",
+ "files": [
+ "index.js"
+ ],
+ "scripts": {
+ "precommit": "lint-staged",
+ "lint": "eslint lib/* bin/*",
+ "test": "mocha tests.js"
+ },
+ "eslintConfig": {
+ "extends": "eslint:recommended",
+ "env": {
+ "node": true,
+ "es6": true
+ }
+ },
+ "lint-staged": {
+ "*.js": [
+ "npm run lint",
+ "prettier --single-quote --write",
+ "git add"
+ ]
+ },
+ "license": "MIT",
+ "devDependencies": {
+ "eslint": "4.12.1",
+ "expect.js": "0.3.1",
+ "husky": "0.14.3",
+ "lint-staged": "5.0.0",
+ "mocha": "4.0.1"
+ }
+}
diff --git a/temporary_modules/trezor-connect/node_modules/ms/readme.md b/temporary_modules/trezor-connect/node_modules/ms/readme.md
new file mode 100644
index 00000000..9a1996b1
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/ms/readme.md
@@ -0,0 +1,60 @@
+# ms
+
+[](https://travis-ci.org/zeit/ms)
+[](https://spectrum.chat/zeit)
+
+Use this package to easily convert various time formats to milliseconds.
+
+## Examples
+
+```js
+ms('2 days') // 172800000
+ms('1d') // 86400000
+ms('10h') // 36000000
+ms('2.5 hrs') // 9000000
+ms('2h') // 7200000
+ms('1m') // 60000
+ms('5s') // 5000
+ms('1y') // 31557600000
+ms('100') // 100
+ms('-3 days') // -259200000
+ms('-1h') // -3600000
+ms('-200') // -200
+```
+
+### Convert from Milliseconds
+
+```js
+ms(60000) // "1m"
+ms(2 * 60000) // "2m"
+ms(-3 * 60000) // "-3m"
+ms(ms('10 hours')) // "10h"
+```
+
+### Time Format Written-Out
+
+```js
+ms(60000, { long: true }) // "1 minute"
+ms(2 * 60000, { long: true }) // "2 minutes"
+ms(-3 * 60000, { long: true }) // "-3 minutes"
+ms(ms('10 hours'), { long: true }) // "10 hours"
+```
+
+## Features
+
+- Works both in [Node.js](https://nodejs.org) and in the browser
+- If a number is supplied to `ms`, a string with a unit is returned
+- If a string that contains the number is supplied, it returns it as a number (e.g.: it returns `100` for `'100'`)
+- If you pass a string with a number and a valid unit, the number of equivalent milliseconds is returned
+
+## Related Packages
+
+- [ms.macro](https://github.com/knpwrs/ms.macro) - Run `ms` as a macro at build-time.
+
+## Caught a Bug?
+
+1. [Fork](https://help.github.com/articles/fork-a-repo/) this repository to your own GitHub account and then [clone](https://help.github.com/articles/cloning-a-repository/) it to your local device
+2. Link the package to the global module directory: `npm link`
+3. Within the module you want to test your local development instance of ms, just link it to the dependencies: `npm link ms`. Instead of the default one from npm, Node.js will now use your clone of ms!
+
+As always, you can run the tests using: `npm test`
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/LICENSE b/temporary_modules/trezor-connect/node_modules/native-run/LICENSE
new file mode 100644
index 00000000..3fef7e70
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/native-run/LICENSE
@@ -0,0 +1,21 @@
+The MIT License (MIT)
+
+Copyright (c) 2018 Drifty Co
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of
+this software and associated documentation files (the "Software"), to deal in
+the Software without restriction, including without limitation the rights to
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
+of the Software, and to permit persons to whom the Software is furnished to do
+so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/README.md b/temporary_modules/trezor-connect/node_modules/native-run/README.md
new file mode 100644
index 00000000..5230db14
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/native-run/README.md
@@ -0,0 +1,39 @@
+[](https://github.com/ionic-team/native-run/actions?query=workflow%3ACI)
+[](https://github.com/semantic-release/semantic-release)
+[](https://www.npmjs.com/package/native-run)
+
+# native-run
+
+`native-run` is a cross-platform command-line utility for running native app binaries (`.ipa` and `.apk` files) on iOS and Android devices. It can be used for both hardware and virtual devices.
+
+This tool is used by the Ionic CLI, but it can be used standalone as part of a development or testing pipeline for launching apps. It doesn't matter whether the `.apk` or `.ipa` is created with Cordova or native IDEs, `native-run` will be able to deploy it.
+
+## Install
+
+`native-run` is written entirely in TypeScript/NodeJS, so there are no native dependencies.
+
+To install, run:
+
+```
+npm install -g native-run
+```
+
+:memo: Requires NodeJS 10+
+
+## Usage
+
+```
+native-run [options]
+```
+
+See the help documentation with the `--help` flag.
+
+```
+native-run --help
+native-run ios --help
+native-run android --help
+```
+
+### Troubleshooting
+
+Much more information can be printed to the screen with the `--verbose` flag.
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/assets/android/skins/LICENSE b/temporary_modules/trezor-connect/node_modules/native-run/assets/android/skins/LICENSE
new file mode 100644
index 00000000..e7034671
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/native-run/assets/android/skins/LICENSE
@@ -0,0 +1,10 @@
+Copyright (C) 2013 The Android Open Source Project Licensed under the Apache
+License, Version 2.0 (the "License"); you may not use this file except in
+compliance with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software distributed
+under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
+CONDITIONS OF ANY KIND, either express or implied. See the License for the
+specific language governing permissions and limitations under the License.
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/assets/android/skins/README.md b/temporary_modules/trezor-connect/node_modules/native-run/assets/android/skins/README.md
new file mode 100644
index 00000000..2b1f5d7d
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/native-run/assets/android/skins/README.md
@@ -0,0 +1,4 @@
+# Android Skins
+
+These skins are copied from the Android Plugin for IntelliJ IDEA:
+https://github.com/JetBrains/android/tree/master/artwork/resources/device-art-resources
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/assets/android/skins/nexus_5x/land_back.webp b/temporary_modules/trezor-connect/node_modules/native-run/assets/android/skins/nexus_5x/land_back.webp
new file mode 100644
index 00000000..122c8f57
Binary files /dev/null and b/temporary_modules/trezor-connect/node_modules/native-run/assets/android/skins/nexus_5x/land_back.webp differ
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/assets/android/skins/nexus_5x/land_fore.webp b/temporary_modules/trezor-connect/node_modules/native-run/assets/android/skins/nexus_5x/land_fore.webp
new file mode 100644
index 00000000..6c5e6510
Binary files /dev/null and b/temporary_modules/trezor-connect/node_modules/native-run/assets/android/skins/nexus_5x/land_fore.webp differ
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/assets/android/skins/nexus_5x/land_shadow.webp b/temporary_modules/trezor-connect/node_modules/native-run/assets/android/skins/nexus_5x/land_shadow.webp
new file mode 100644
index 00000000..a93b5ff9
Binary files /dev/null and b/temporary_modules/trezor-connect/node_modules/native-run/assets/android/skins/nexus_5x/land_shadow.webp differ
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/assets/android/skins/nexus_5x/layout b/temporary_modules/trezor-connect/node_modules/native-run/assets/android/skins/nexus_5x/layout
new file mode 100644
index 00000000..2e8b0cb8
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/native-run/assets/android/skins/nexus_5x/layout
@@ -0,0 +1,59 @@
+parts {
+ device {
+ display {
+ width 1080
+ height 1920
+ x 0
+ y 0
+ }
+ }
+ portrait {
+ background {
+ image port_back.webp
+ }
+ onion {
+ image port_fore.webp
+ }
+ }
+ landscape {
+ background {
+ image land_back.webp
+ }
+ onion {
+ image land_fore.webp
+ }
+ }
+}
+layouts {
+ portrait {
+ width 1370
+ height 2446
+ event EV_SW:0:1
+ part1 {
+ name portrait
+ x 0
+ y 0
+ }
+ part2 {
+ name device
+ x 147
+ y 233
+ }
+ }
+ landscape {
+ width 2497
+ height 1234
+ event EV_SW:0:0
+ part1 {
+ name landscape
+ x 0
+ y 0
+ }
+ part2 {
+ name device
+ x 278
+ y 1143
+ rotation 3
+ }
+ }
+}
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/assets/android/skins/nexus_5x/port_back.webp b/temporary_modules/trezor-connect/node_modules/native-run/assets/android/skins/nexus_5x/port_back.webp
new file mode 100644
index 00000000..0dccf8ed
Binary files /dev/null and b/temporary_modules/trezor-connect/node_modules/native-run/assets/android/skins/nexus_5x/port_back.webp differ
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/assets/android/skins/nexus_5x/port_fore.webp b/temporary_modules/trezor-connect/node_modules/native-run/assets/android/skins/nexus_5x/port_fore.webp
new file mode 100644
index 00000000..d56ba36a
Binary files /dev/null and b/temporary_modules/trezor-connect/node_modules/native-run/assets/android/skins/nexus_5x/port_fore.webp differ
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/assets/android/skins/nexus_5x/port_shadow.webp b/temporary_modules/trezor-connect/node_modules/native-run/assets/android/skins/nexus_5x/port_shadow.webp
new file mode 100644
index 00000000..ecf15a19
Binary files /dev/null and b/temporary_modules/trezor-connect/node_modules/native-run/assets/android/skins/nexus_5x/port_shadow.webp differ
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/assets/android/skins/pixel/land_back.webp b/temporary_modules/trezor-connect/node_modules/native-run/assets/android/skins/pixel/land_back.webp
new file mode 100644
index 00000000..9f21e144
Binary files /dev/null and b/temporary_modules/trezor-connect/node_modules/native-run/assets/android/skins/pixel/land_back.webp differ
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/assets/android/skins/pixel/land_fore.webp b/temporary_modules/trezor-connect/node_modules/native-run/assets/android/skins/pixel/land_fore.webp
new file mode 100644
index 00000000..578dbfae
Binary files /dev/null and b/temporary_modules/trezor-connect/node_modules/native-run/assets/android/skins/pixel/land_fore.webp differ
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/assets/android/skins/pixel/land_shadow.webp b/temporary_modules/trezor-connect/node_modules/native-run/assets/android/skins/pixel/land_shadow.webp
new file mode 100644
index 00000000..7a13dbd9
Binary files /dev/null and b/temporary_modules/trezor-connect/node_modules/native-run/assets/android/skins/pixel/land_shadow.webp differ
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/assets/android/skins/pixel/layout b/temporary_modules/trezor-connect/node_modules/native-run/assets/android/skins/pixel/layout
new file mode 100644
index 00000000..e4c66b43
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/native-run/assets/android/skins/pixel/layout
@@ -0,0 +1,59 @@
+parts {
+ device {
+ display {
+ width 1080
+ height 1920
+ x 0
+ y 0
+ }
+ }
+ portrait {
+ background {
+ image port_back.webp
+ }
+ onion {
+ image port_fore.webp
+ }
+ }
+ landscape {
+ background {
+ image land_back.webp
+ }
+ onion {
+ image land_fore.webp
+ }
+ }
+}
+layouts {
+ portrait {
+ width 1370
+ height 2534
+ event EV_SW:0:1
+ part1 {
+ name portrait
+ x 0
+ y 0
+ }
+ part2 {
+ name device
+ x 139
+ y 285
+ }
+ }
+ landscape {
+ width 2596
+ height 1258
+ event EV_SW:0:0
+ part1 {
+ name landscape
+ x 0
+ y 0
+ }
+ part2 {
+ name device
+ x 338
+ y 1158
+ rotation 3
+ }
+ }
+}
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/assets/android/skins/pixel/port_back.webp b/temporary_modules/trezor-connect/node_modules/native-run/assets/android/skins/pixel/port_back.webp
new file mode 100644
index 00000000..d964ec8e
Binary files /dev/null and b/temporary_modules/trezor-connect/node_modules/native-run/assets/android/skins/pixel/port_back.webp differ
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/assets/android/skins/pixel/port_fore.webp b/temporary_modules/trezor-connect/node_modules/native-run/assets/android/skins/pixel/port_fore.webp
new file mode 100644
index 00000000..808f8a27
Binary files /dev/null and b/temporary_modules/trezor-connect/node_modules/native-run/assets/android/skins/pixel/port_fore.webp differ
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/assets/android/skins/pixel/port_shadow.webp b/temporary_modules/trezor-connect/node_modules/native-run/assets/android/skins/pixel/port_shadow.webp
new file mode 100644
index 00000000..069fbbb8
Binary files /dev/null and b/temporary_modules/trezor-connect/node_modules/native-run/assets/android/skins/pixel/port_shadow.webp differ
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/assets/android/skins/pixel_2/land_back.webp b/temporary_modules/trezor-connect/node_modules/native-run/assets/android/skins/pixel_2/land_back.webp
new file mode 100644
index 00000000..795077e8
Binary files /dev/null and b/temporary_modules/trezor-connect/node_modules/native-run/assets/android/skins/pixel_2/land_back.webp differ
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/assets/android/skins/pixel_2/land_fore.webp b/temporary_modules/trezor-connect/node_modules/native-run/assets/android/skins/pixel_2/land_fore.webp
new file mode 100644
index 00000000..1d44531b
Binary files /dev/null and b/temporary_modules/trezor-connect/node_modules/native-run/assets/android/skins/pixel_2/land_fore.webp differ
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/assets/android/skins/pixel_2/land_shadow.webp b/temporary_modules/trezor-connect/node_modules/native-run/assets/android/skins/pixel_2/land_shadow.webp
new file mode 100644
index 00000000..71c92bd0
Binary files /dev/null and b/temporary_modules/trezor-connect/node_modules/native-run/assets/android/skins/pixel_2/land_shadow.webp differ
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/assets/android/skins/pixel_2/layout b/temporary_modules/trezor-connect/node_modules/native-run/assets/android/skins/pixel_2/layout
new file mode 100644
index 00000000..7e3a58f7
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/native-run/assets/android/skins/pixel_2/layout
@@ -0,0 +1,59 @@
+parts {
+ device {
+ display {
+ width 1080
+ height 1920
+ x 0
+ y 0
+ }
+ }
+ portrait {
+ background {
+ image port_back.webp
+ }
+ onion {
+ image port_fore.webp
+ }
+ }
+ landscape {
+ background {
+ image land_back.webp
+ }
+ onion {
+ image land_fore.webp
+ }
+ }
+}
+layouts {
+ portrait {
+ width 1370
+ height 2534
+ event EV_SW:0:1
+ part1 {
+ name portrait
+ x 0
+ y 0
+ }
+ part2 {
+ name device
+ x 140
+ y 280
+ }
+ }
+ landscape {
+ width 2596
+ height 1258
+ event EV_SW:0:0
+ part1 {
+ name landscape
+ x 0
+ y 0
+ }
+ part2 {
+ name device
+ x 338
+ y 68
+ rotation 3
+ }
+ }
+}
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/assets/android/skins/pixel_2/port_back.webp b/temporary_modules/trezor-connect/node_modules/native-run/assets/android/skins/pixel_2/port_back.webp
new file mode 100644
index 00000000..b932d0a7
Binary files /dev/null and b/temporary_modules/trezor-connect/node_modules/native-run/assets/android/skins/pixel_2/port_back.webp differ
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/assets/android/skins/pixel_2/port_fore.webp b/temporary_modules/trezor-connect/node_modules/native-run/assets/android/skins/pixel_2/port_fore.webp
new file mode 100644
index 00000000..9a917f14
Binary files /dev/null and b/temporary_modules/trezor-connect/node_modules/native-run/assets/android/skins/pixel_2/port_fore.webp differ
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/assets/android/skins/pixel_2/port_shadow.webp b/temporary_modules/trezor-connect/node_modules/native-run/assets/android/skins/pixel_2/port_shadow.webp
new file mode 100644
index 00000000..66806cc9
Binary files /dev/null and b/temporary_modules/trezor-connect/node_modules/native-run/assets/android/skins/pixel_2/port_shadow.webp differ
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/assets/android/skins/pixel_3/layout b/temporary_modules/trezor-connect/node_modules/native-run/assets/android/skins/pixel_3/layout
new file mode 100644
index 00000000..4615fb58
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/native-run/assets/android/skins/pixel_3/layout
@@ -0,0 +1,38 @@
+parts {
+ device {
+ display {
+ width 1080
+ height 2160
+ x 0
+ y 0
+ }
+ }
+ portrait {
+ background {
+ image port_back.webp
+ }
+ foreground {
+ mask round_corners.webp
+ }
+ onion {
+ image port_fore.webp
+ }
+ }
+}
+layouts {
+ portrait {
+ width 1194
+ height 2532
+ event EV_SW:0:1
+ part1 {
+ name portrait
+ x 0
+ y 0
+ }
+ part2 {
+ name device
+ x 54
+ y 196
+ }
+ }
+}
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/assets/android/skins/pixel_3/port_back.webp b/temporary_modules/trezor-connect/node_modules/native-run/assets/android/skins/pixel_3/port_back.webp
new file mode 100644
index 00000000..6037b796
Binary files /dev/null and b/temporary_modules/trezor-connect/node_modules/native-run/assets/android/skins/pixel_3/port_back.webp differ
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/assets/android/skins/pixel_3/round_corners.webp b/temporary_modules/trezor-connect/node_modules/native-run/assets/android/skins/pixel_3/round_corners.webp
new file mode 100644
index 00000000..9dad9033
Binary files /dev/null and b/temporary_modules/trezor-connect/node_modules/native-run/assets/android/skins/pixel_3/round_corners.webp differ
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/bin/native-run b/temporary_modules/trezor-connect/node_modules/native-run/bin/native-run
new file mode 100644
index 00000000..888f147f
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/native-run/bin/native-run
@@ -0,0 +1,11 @@
+#!/usr/bin/env node
+
+'use strict';
+
+process.title = 'native-run';
+
+if (process.argv.includes('--verbose')) {
+ process.env.DEBUG = '*';
+}
+
+require('../').run();
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/dist/android/data/avds/Nexus_5X_API_24.json b/temporary_modules/trezor-connect/node_modules/native-run/dist/android/data/avds/Nexus_5X_API_24.json
new file mode 100644
index 00000000..9faba513
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/native-run/dist/android/data/avds/Nexus_5X_API_24.json
@@ -0,0 +1,50 @@
+{
+ "id": "Nexus_5X_API_24",
+ "ini": {
+ "avd.ini.encoding": "UTF-8",
+ "target": "android-24"
+ },
+ "configini": {
+ "AvdId": "Nexus_5X_API_24",
+ "PlayStore.enabled": "true",
+ "abi.type": "x86",
+ "avd.ini.displayname": "Nexus 5X API 24",
+ "avd.ini.encoding": "UTF-8",
+ "disk.dataPartition.size": "2G",
+ "fastboot.forceColdBoot": "no",
+ "hw.accelerometer": "yes",
+ "hw.arc": "false",
+ "hw.audioInput": "yes",
+ "hw.battery": "yes",
+ "hw.camera.back": "virtualscene",
+ "hw.camera.front": "emulated",
+ "hw.cpu.arch": "x86",
+ "hw.cpu.ncore": "4",
+ "hw.dPad": "no",
+ "hw.device.hash2": "MD5:bc5032b2a871da511332401af3ac6bb0",
+ "hw.device.manufacturer": "Google",
+ "hw.device.name": "Nexus 5X",
+ "hw.gps": "yes",
+ "hw.gpu.enabled": "yes",
+ "hw.gpu.mode": "auto",
+ "hw.initialOrientation": "Portrait",
+ "hw.keyboard": "yes",
+ "hw.lcd.density": "420",
+ "hw.lcd.height": "1920",
+ "hw.lcd.width": "1080",
+ "hw.mainKeys": "no",
+ "hw.ramSize": "1536",
+ "hw.sdCard": "yes",
+ "hw.sensors.orientation": "yes",
+ "hw.sensors.proximity": "yes",
+ "hw.trackBall": "no",
+ "runtime.network.latency": "none",
+ "runtime.network.speed": "full",
+ "sdcard.size": "100M",
+ "showDeviceFrame": "yes",
+ "skin.dynamic": "yes",
+ "skin.name": "nexus_5x",
+ "tag.display": "Google Play",
+ "vm.heapSize": "256"
+ }
+}
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/dist/android/data/avds/Pixel_2_API_26.json b/temporary_modules/trezor-connect/node_modules/native-run/dist/android/data/avds/Pixel_2_API_26.json
new file mode 100644
index 00000000..179ce2ba
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/native-run/dist/android/data/avds/Pixel_2_API_26.json
@@ -0,0 +1,40 @@
+{
+ "id": "Pixel_2_API_26",
+ "ini": {
+ "avd.ini.encoding": "UTF-8",
+ "target": "android-26"
+ },
+ "configini": {
+ "AvdId": "Pixel_2_API_28",
+ "abi.type": "x86",
+ "avd.ini.displayname": "Pixel 2 API 26",
+ "avd.ini.encoding": "UTF-8",
+ "hw.accelerometer": "yes",
+ "hw.audioInput": "yes",
+ "hw.battery": "yes",
+ "hw.camera.back": "virtualscene",
+ "hw.camera.front": "emulated",
+ "hw.cpu.arch": "x86",
+ "hw.cpu.ncore": "4",
+ "hw.device.hash2": "MD5:bc5032b2a871da511332401af3ac6bb0",
+ "hw.device.manufacturer": "Google",
+ "hw.device.name": "pixel_2",
+ "hw.gps": "yes",
+ "hw.gpu.enabled": "yes",
+ "hw.gpu.mode": "auto",
+ "hw.initialOrientation": "Portrait",
+ "hw.keyboard": "yes",
+ "hw.lcd.density": "420",
+ "hw.lcd.height": "1920",
+ "hw.lcd.width": "1080",
+ "hw.ramSize": "1536",
+ "hw.sdCard": "yes",
+ "hw.sensors.orientation": "yes",
+ "hw.sensors.proximity": "yes",
+ "sdcard.size": "100M",
+ "showDeviceFrame": "yes",
+ "skin.dynamic": "yes",
+ "skin.name": "pixel_2",
+ "tag.display": "Google APIs"
+ }
+}
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/dist/android/data/avds/Pixel_2_API_27.json b/temporary_modules/trezor-connect/node_modules/native-run/dist/android/data/avds/Pixel_2_API_27.json
new file mode 100644
index 00000000..e915478a
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/native-run/dist/android/data/avds/Pixel_2_API_27.json
@@ -0,0 +1,40 @@
+{
+ "id": "Pixel_2_API_27",
+ "ini": {
+ "avd.ini.encoding": "UTF-8",
+ "target": "android-27"
+ },
+ "configini": {
+ "AvdId": "Pixel_2_API_28",
+ "abi.type": "x86",
+ "avd.ini.displayname": "Pixel 2 API 27",
+ "avd.ini.encoding": "UTF-8",
+ "hw.accelerometer": "yes",
+ "hw.audioInput": "yes",
+ "hw.battery": "yes",
+ "hw.camera.back": "virtualscene",
+ "hw.camera.front": "emulated",
+ "hw.cpu.arch": "x86",
+ "hw.cpu.ncore": "4",
+ "hw.device.hash2": "MD5:bc5032b2a871da511332401af3ac6bb0",
+ "hw.device.manufacturer": "Google",
+ "hw.device.name": "pixel_2",
+ "hw.gps": "yes",
+ "hw.gpu.enabled": "yes",
+ "hw.gpu.mode": "auto",
+ "hw.initialOrientation": "Portrait",
+ "hw.keyboard": "yes",
+ "hw.lcd.density": "420",
+ "hw.lcd.height": "1920",
+ "hw.lcd.width": "1080",
+ "hw.ramSize": "1536",
+ "hw.sdCard": "yes",
+ "hw.sensors.orientation": "yes",
+ "hw.sensors.proximity": "yes",
+ "sdcard.size": "100M",
+ "showDeviceFrame": "yes",
+ "skin.dynamic": "yes",
+ "skin.name": "pixel_2",
+ "tag.display": "Google APIs"
+ }
+}
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/dist/android/data/avds/Pixel_2_API_28.json b/temporary_modules/trezor-connect/node_modules/native-run/dist/android/data/avds/Pixel_2_API_28.json
new file mode 100644
index 00000000..6298b916
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/native-run/dist/android/data/avds/Pixel_2_API_28.json
@@ -0,0 +1,40 @@
+{
+ "id": "Pixel_2_API_28",
+ "ini": {
+ "avd.ini.encoding": "UTF-8",
+ "target": "android-28"
+ },
+ "configini": {
+ "AvdId": "Pixel_2_API_28",
+ "abi.type": "x86",
+ "avd.ini.displayname": "Pixel 2 API 28",
+ "avd.ini.encoding": "UTF-8",
+ "hw.accelerometer": "yes",
+ "hw.audioInput": "yes",
+ "hw.battery": "yes",
+ "hw.camera.back": "virtualscene",
+ "hw.camera.front": "emulated",
+ "hw.cpu.arch": "x86",
+ "hw.cpu.ncore": "4",
+ "hw.device.hash2": "MD5:bc5032b2a871da511332401af3ac6bb0",
+ "hw.device.manufacturer": "Google",
+ "hw.device.name": "pixel_2",
+ "hw.gps": "yes",
+ "hw.gpu.enabled": "yes",
+ "hw.gpu.mode": "auto",
+ "hw.initialOrientation": "Portrait",
+ "hw.keyboard": "yes",
+ "hw.lcd.density": "420",
+ "hw.lcd.height": "1920",
+ "hw.lcd.width": "1080",
+ "hw.ramSize": "1536",
+ "hw.sdCard": "yes",
+ "hw.sensors.orientation": "yes",
+ "hw.sensors.proximity": "yes",
+ "sdcard.size": "100M",
+ "showDeviceFrame": "yes",
+ "skin.dynamic": "yes",
+ "skin.name": "pixel_2",
+ "tag.display": "Google APIs"
+ }
+}
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/dist/android/data/avds/Pixel_3_API_29.json b/temporary_modules/trezor-connect/node_modules/native-run/dist/android/data/avds/Pixel_3_API_29.json
new file mode 100644
index 00000000..e7880c2e
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/native-run/dist/android/data/avds/Pixel_3_API_29.json
@@ -0,0 +1,40 @@
+{
+ "id": "Pixel_3_API_29",
+ "ini": {
+ "avd.ini.encoding": "UTF-8",
+ "target": "android-29"
+ },
+ "configini": {
+ "AvdId": "Pixel_3_API_29",
+ "abi.type": "x86",
+ "avd.ini.displayname": "Pixel 3 API 29",
+ "avd.ini.encoding": "UTF-8",
+ "hw.accelerometer": "yes",
+ "hw.audioInput": "yes",
+ "hw.battery": "yes",
+ "hw.camera.back": "virtualscene",
+ "hw.camera.front": "emulated",
+ "hw.cpu.arch": "x86",
+ "hw.cpu.ncore": "4",
+ "hw.device.hash2": "MD5:8a60718609e0741c7c0cc225f49c5590",
+ "hw.device.manufacturer": "Google",
+ "hw.device.name": "pixel_3",
+ "hw.gps": "yes",
+ "hw.gpu.enabled": "yes",
+ "hw.gpu.mode": "auto",
+ "hw.initialOrientation": "Portrait",
+ "hw.keyboard": "yes",
+ "hw.lcd.density": "440",
+ "hw.lcd.height": "2160",
+ "hw.lcd.width": "1080",
+ "hw.ramSize": "1536",
+ "hw.sdCard": "yes",
+ "hw.sensors.orientation": "yes",
+ "hw.sensors.proximity": "yes",
+ "sdcard.size": "512M",
+ "showDeviceFrame": "yes",
+ "skin.dynamic": "yes",
+ "skin.name": "pixel_2",
+ "tag.display": "Google Play"
+ }
+}
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/dist/android/data/avds/Pixel_3_API_30.json b/temporary_modules/trezor-connect/node_modules/native-run/dist/android/data/avds/Pixel_3_API_30.json
new file mode 100644
index 00000000..790869b8
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/native-run/dist/android/data/avds/Pixel_3_API_30.json
@@ -0,0 +1,40 @@
+{
+ "id": "Pixel_3_API_30",
+ "ini": {
+ "avd.ini.encoding": "UTF-8",
+ "target": "android-30"
+ },
+ "configini": {
+ "AvdId": "Pixel_3_API_30",
+ "abi.type": "x86",
+ "avd.ini.displayname": "Pixel 3 API 30",
+ "avd.ini.encoding": "UTF-8",
+ "hw.accelerometer": "yes",
+ "hw.audioInput": "yes",
+ "hw.battery": "yes",
+ "hw.camera.back": "virtualscene",
+ "hw.camera.front": "emulated",
+ "hw.cpu.arch": "x86",
+ "hw.cpu.ncore": "4",
+ "hw.device.hash2": "MD5:8a60718609e0741c7c0cc225f49c5590",
+ "hw.device.manufacturer": "Google",
+ "hw.device.name": "pixel_3",
+ "hw.gps": "yes",
+ "hw.gpu.enabled": "yes",
+ "hw.gpu.mode": "auto",
+ "hw.initialOrientation": "Portrait",
+ "hw.keyboard": "yes",
+ "hw.lcd.density": "440",
+ "hw.lcd.height": "2160",
+ "hw.lcd.width": "1080",
+ "hw.ramSize": "1536",
+ "hw.sdCard": "yes",
+ "hw.sensors.orientation": "yes",
+ "hw.sensors.proximity": "yes",
+ "sdcard.size": "512M",
+ "showDeviceFrame": "yes",
+ "skin.dynamic": "yes",
+ "skin.name": "pixel_2",
+ "tag.display": "Google Play"
+ }
+}
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/dist/android/data/avds/Pixel_3_API_31.json b/temporary_modules/trezor-connect/node_modules/native-run/dist/android/data/avds/Pixel_3_API_31.json
new file mode 100644
index 00000000..239def5b
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/native-run/dist/android/data/avds/Pixel_3_API_31.json
@@ -0,0 +1,40 @@
+{
+ "id": "Pixel_3_API_31",
+ "ini": {
+ "avd.ini.encoding": "UTF-8",
+ "target": "android-31"
+ },
+ "configini": {
+ "AvdId": "Pixel_3_API_31",
+ "abi.type": "x86",
+ "avd.ini.displayname": "Pixel 3 API 31",
+ "avd.ini.encoding": "UTF-8",
+ "hw.accelerometer": "yes",
+ "hw.audioInput": "yes",
+ "hw.battery": "yes",
+ "hw.camera.back": "virtualscene",
+ "hw.camera.front": "emulated",
+ "hw.cpu.arch": "x86",
+ "hw.cpu.ncore": "4",
+ "hw.device.hash2": "MD5:8a60718609e0741c7c0cc225f49c5590",
+ "hw.device.manufacturer": "Google",
+ "hw.device.name": "pixel_3",
+ "hw.gps": "yes",
+ "hw.gpu.enabled": "yes",
+ "hw.gpu.mode": "auto",
+ "hw.initialOrientation": "Portrait",
+ "hw.keyboard": "yes",
+ "hw.lcd.density": "440",
+ "hw.lcd.height": "2160",
+ "hw.lcd.width": "1080",
+ "hw.ramSize": "1536",
+ "hw.sdCard": "yes",
+ "hw.sensors.orientation": "yes",
+ "hw.sensors.proximity": "yes",
+ "sdcard.size": "512M",
+ "showDeviceFrame": "yes",
+ "skin.dynamic": "yes",
+ "skin.name": "pixel_2",
+ "tag.display": "Google Play"
+ }
+}
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/dist/android/data/avds/Pixel_API_25.json b/temporary_modules/trezor-connect/node_modules/native-run/dist/android/data/avds/Pixel_API_25.json
new file mode 100644
index 00000000..04161945
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/native-run/dist/android/data/avds/Pixel_API_25.json
@@ -0,0 +1,50 @@
+{
+ "id": "Pixel_API_25",
+ "ini": {
+ "avd.ini.encoding": "UTF-8",
+ "target": "android-25"
+ },
+ "configini": {
+ "AvdId": "Pixel_API_25",
+ "PlayStore.enabled": "false",
+ "abi.type": "x86",
+ "avd.ini.displayname": "Pixel API 25",
+ "avd.ini.encoding": "UTF-8",
+ "disk.dataPartition.size": "800M",
+ "fastboot.forceColdBoot": "no",
+ "hw.accelerometer": "yes",
+ "hw.arc": "false",
+ "hw.audioInput": "yes",
+ "hw.battery": "yes",
+ "hw.camera.back": "virtualscene",
+ "hw.camera.front": "emulated",
+ "hw.cpu.arch": "x86",
+ "hw.cpu.ncore": "4",
+ "hw.dPad": "no",
+ "hw.device.hash2": "MD5:524882cfa9f421413193056700a29392",
+ "hw.device.manufacturer": "Google",
+ "hw.device.name": "pixel",
+ "hw.gps": "yes",
+ "hw.gpu.enabled": "yes",
+ "hw.gpu.mode": "auto",
+ "hw.initialOrientation": "Portrait",
+ "hw.keyboard": "yes",
+ "hw.lcd.density": "480",
+ "hw.lcd.height": "1920",
+ "hw.lcd.width": "1080",
+ "hw.mainKeys": "no",
+ "hw.ramSize": "1536",
+ "hw.sdCard": "yes",
+ "hw.sensors.orientation": "yes",
+ "hw.sensors.proximity": "yes",
+ "hw.trackBall": "no",
+ "runtime.network.latency": "none",
+ "runtime.network.speed": "full",
+ "sdcard.size": "100M",
+ "showDeviceFrame": "yes",
+ "skin.dynamic": "yes",
+ "skin.name": "pixel",
+ "tag.display": "Google APIs",
+ "vm.heapSize": "256"
+ }
+}
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/dist/android/help.js b/temporary_modules/trezor-connect/node_modules/native-run/dist/android/help.js
new file mode 100644
index 00000000..49534ea4
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/native-run/dist/android/help.js
@@ -0,0 +1,38 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+exports.run = void 0;
+const help = `
+ Usage: native-run android [options]
+
+ Run an .apk on a device or emulator target
+
+ Targets are selected as follows:
+ 1) --target using device/emulator serial number or AVD ID
+ 2) A connected device, unless --virtual is used
+ 3) A running emulator
+
+ If the above criteria are not met, an emulator is started from a default
+ AVD, which is created if it does not exist.
+
+ Use --list to list available targets.
+
+ Options:
+
+ --list .................. Print available targets, then quit
+ --sdk-info .............. Print SDK information, then quit
+ --json .................. Output JSON
+
+
+ --app ............ Deploy specified .apk file
+ --device ................ Use a device if available
+ With --list prints connected devices
+ --virtual ............... Prefer an emulator
+ With --list prints available emulators
+ --target ........... Use a specific target
+ --connect ............... Tie process to app process
+ --forward ... Forward a port from device to host
+`;
+async function run(args) {
+ process.stdout.write(`${help}\n`);
+}
+exports.run = run;
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/dist/android/index.js b/temporary_modules/trezor-connect/node_modules/native-run/dist/android/index.js
new file mode 100644
index 00000000..b10df42d
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/native-run/dist/android/index.js
@@ -0,0 +1,21 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+exports.run = void 0;
+async function run(args) {
+ let cmd;
+ if (args.includes('--help') || args.includes('-h')) {
+ cmd = await Promise.resolve().then(() => require('./help'));
+ return cmd.run(args);
+ }
+ if (args.includes('--list')) {
+ cmd = await Promise.resolve().then(() => require('./list'));
+ return cmd.run(args);
+ }
+ if (args.includes('--sdk-info')) {
+ cmd = await Promise.resolve().then(() => require('./sdk-info'));
+ return cmd.run(args);
+ }
+ cmd = await Promise.resolve().then(() => require('./run'));
+ await cmd.run(args);
+}
+exports.run = run;
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/dist/android/list.js b/temporary_modules/trezor-connect/node_modules/native-run/dist/android/list.js
new file mode 100644
index 00000000..1073785c
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/native-run/dist/android/list.js
@@ -0,0 +1,37 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+exports.list = exports.run = void 0;
+const list_1 = require("../utils/list");
+const list_2 = require("./utils/list");
+const sdk_1 = require("./utils/sdk");
+async function run(args) {
+ const targets = await list(args);
+ process.stdout.write(`\n${list_1.formatTargets(args, targets)}\n`);
+}
+exports.run = run;
+async function list(args) {
+ const sdk = await sdk_1.getSDK();
+ const errors = [];
+ const [devices, virtualDevices] = await Promise.all([
+ (async () => {
+ try {
+ return await list_2.getDeviceTargets(sdk);
+ }
+ catch (e) {
+ errors.push(e);
+ return [];
+ }
+ })(),
+ (async () => {
+ try {
+ return await list_2.getVirtualTargets(sdk);
+ }
+ catch (e) {
+ errors.push(e);
+ return [];
+ }
+ })(),
+ ]);
+ return { devices, virtualDevices, errors };
+}
+exports.list = list;
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/dist/android/run.js b/temporary_modules/trezor-connect/node_modules/native-run/dist/android/run.js
new file mode 100644
index 00000000..db7440cc
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/native-run/dist/android/run.js
@@ -0,0 +1,103 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+exports.selectDevice = exports.run = void 0;
+const Debug = require("debug");
+const errors_1 = require("../errors");
+const cli_1 = require("../utils/cli");
+const log_1 = require("../utils/log");
+const process_1 = require("../utils/process");
+const adb_1 = require("./utils/adb");
+const apk_1 = require("./utils/apk");
+const avd_1 = require("./utils/avd");
+const run_1 = require("./utils/run");
+const sdk_1 = require("./utils/sdk");
+const modulePrefix = 'native-run:android:run';
+async function run(args) {
+ const sdk = await sdk_1.getSDK();
+ const apkPath = cli_1.getOptionValue(args, '--app');
+ const forwardedPorts = cli_1.getOptionValues(args, '--forward');
+ const ports = [];
+ if (forwardedPorts && forwardedPorts.length > 0) {
+ forwardedPorts.forEach((port) => {
+ const [device, host] = port.split(':');
+ if (!device || !host) {
+ throw new errors_1.CLIException(`Invalid --forward value "${port}": expecting , e.g. 8080:8080`);
+ }
+ ports.push({ device, host });
+ });
+ }
+ if (!apkPath) {
+ throw new errors_1.CLIException('--app is required', errors_1.ERR_BAD_INPUT);
+ }
+ const device = await selectDevice(sdk, args);
+ log_1.log(`Selected ${device.type === 'hardware' ? 'hardware device' : 'emulator'} ${device.serial}\n`);
+ const { appId, activityName } = await apk_1.getApkInfo(apkPath);
+ await adb_1.waitForBoot(sdk, device);
+ if (ports) {
+ await Promise.all(ports.map(async (port) => {
+ await adb_1.forwardPorts(sdk, device, port);
+ log_1.log(`Forwarded device port ${port.device} to host port ${port.host}\n`);
+ }));
+ }
+ await run_1.installApkToDevice(sdk, device, apkPath, appId);
+ log_1.log(`Starting application activity ${appId}/${activityName}...\n`);
+ await adb_1.startActivity(sdk, device, appId, activityName);
+ log_1.log(`Run Successful\n`);
+ process_1.onBeforeExit(async () => {
+ if (ports) {
+ await Promise.all(ports.map(async (port) => {
+ await adb_1.unforwardPorts(sdk, device, port);
+ }));
+ }
+ });
+ if (args.includes('--connect')) {
+ process_1.onBeforeExit(async () => {
+ await adb_1.closeApp(sdk, device, appId);
+ });
+ log_1.log(`Waiting for app to close...\n`);
+ await adb_1.waitForClose(sdk, device, appId);
+ }
+}
+exports.run = run;
+async function selectDevice(sdk, args) {
+ const debug = Debug(`${modulePrefix}:${selectDevice.name}`);
+ const devices = await adb_1.getDevices(sdk);
+ const avds = await avd_1.getInstalledAVDs(sdk);
+ const target = cli_1.getOptionValue(args, '--target');
+ const preferEmulator = args.includes('--virtual');
+ if (target) {
+ const targetDevice = await run_1.selectDeviceByTarget(sdk, devices, avds, target);
+ if (targetDevice) {
+ return targetDevice;
+ }
+ else {
+ throw new errors_1.AndroidRunException(`Target not found: ${target}`, errors_1.ERR_TARGET_NOT_FOUND);
+ }
+ }
+ if (!preferEmulator) {
+ const selectedDevice = await run_1.selectHardwareDevice(devices);
+ if (selectedDevice) {
+ return selectedDevice;
+ }
+ else if (args.includes('--device')) {
+ throw new errors_1.AndroidRunException(`No hardware devices found. Not attempting emulator because --device was specified.`, errors_1.ERR_NO_DEVICE);
+ }
+ else {
+ log_1.log('No hardware devices found, attempting emulator...\n');
+ }
+ }
+ try {
+ return await run_1.selectVirtualDevice(sdk, devices, avds);
+ }
+ catch (e) {
+ if (!(e instanceof errors_1.AVDException)) {
+ throw e;
+ }
+ debug('Issue with AVDs: %s', e.message);
+ if (e.code === errors_1.ERR_UNSUITABLE_API_INSTALLATION) {
+ throw new errors_1.AndroidRunException('No targets devices/emulators available. Cannot create AVD because there is no suitable API installation. Use --sdk-info to reveal missing packages and other issues.', errors_1.ERR_NO_TARGET);
+ }
+ }
+ throw new errors_1.AndroidRunException('No target devices/emulators available.', errors_1.ERR_NO_TARGET);
+}
+exports.selectDevice = selectDevice;
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/dist/android/sdk-info.js b/temporary_modules/trezor-connect/node_modules/native-run/dist/android/sdk-info.js
new file mode 100644
index 00000000..f7b336bb
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/native-run/dist/android/sdk-info.js
@@ -0,0 +1,54 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+exports.run = void 0;
+const json_1 = require("../utils/json");
+const sdk_1 = require("./utils/sdk");
+const api_1 = require("./utils/sdk/api");
+async function run(args) {
+ const sdk = await sdk_1.getSDK();
+ const packages = await sdk_1.findAllSDKPackages(sdk);
+ const apis = await api_1.getAPILevels(packages);
+ const platforms = apis.map(api => {
+ const schema = api_1.API_LEVEL_SCHEMAS.find(s => s.apiLevel === api.apiLevel);
+ return { ...api, missingPackages: schema ? schema.validate(packages) : [] };
+ });
+ const sdkinfo = {
+ root: sdk.root,
+ avdHome: sdk.avdHome,
+ platforms,
+ tools: packages.filter(pkg => typeof pkg.apiLevel === 'undefined'),
+ };
+ if (args.includes('--json')) {
+ process.stdout.write(json_1.stringify(sdkinfo));
+ return;
+ }
+ process.stdout.write(`${formatSDKInfo(sdkinfo)}\n\n`);
+}
+exports.run = run;
+function formatSDKInfo(sdk) {
+ return `
+SDK Location: ${sdk.root}
+AVD Home${sdk.avdHome ? `: ${sdk.avdHome}` : ` (!): not found`}
+
+${sdk.platforms.map(platform => `${formatPlatform(platform)}\n\n`).join('\n')}
+Tools:
+
+${sdk.tools.map(tool => formatPackage(tool)).join('\n')}
+ `.trim();
+}
+function formatPlatform(platform) {
+ return `
+API Level: ${platform.apiLevel}
+Packages: ${platform.packages
+ .map(p => formatPackage(p))
+ .join('\n' + ' '.repeat(22))}
+${platform.missingPackages.length > 0
+ ? `(!) Missing Packages: ${platform.missingPackages
+ .map(p => formatPackage(p))
+ .join('\n' + ' '.repeat(22))}`
+ : ''}
+ `.trim();
+}
+function formatPackage(p) {
+ return `${p.name} ${p.path} ${typeof p.version === 'string' ? p.version : ''}`;
+}
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/dist/android/utils/adb.js b/temporary_modules/trezor-connect/node_modules/native-run/dist/android/utils/adb.js
new file mode 100644
index 00000000..0644862a
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/native-run/dist/android/utils/adb.js
@@ -0,0 +1,345 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+exports.execAdb = exports.unforwardPorts = exports.forwardPorts = exports.parseAdbDevices = exports.startActivity = exports.parseAdbInstallOutput = exports.ADBEvent = exports.uninstallApp = exports.closeApp = exports.installApk = exports.waitForClose = exports.waitForBoot = exports.waitForDevice = exports.getDeviceProperties = exports.getDeviceProperty = exports.getDevices = void 0;
+const child_process_1 = require("child_process");
+const Debug = require("debug");
+const os = require("os");
+const path = require("path");
+const split2 = require("split2");
+const through2 = require("through2");
+const errors_1 = require("../../errors");
+const process_1 = require("../../utils/process");
+const sdk_1 = require("./sdk");
+const modulePrefix = 'native-run:android:utils:adb';
+const ADB_GETPROP_MAP = new Map([
+ ['ro.product.manufacturer', 'manufacturer'],
+ ['ro.product.model', 'model'],
+ ['ro.product.name', 'product'],
+ ['ro.build.version.sdk', 'sdkVersion'],
+]);
+async function getDevices(sdk) {
+ const debug = Debug(`${modulePrefix}:${getDevices.name}`);
+ const args = ['devices', '-l'];
+ debug('Invoking adb with args: %O', args);
+ const stdout = await execAdb(sdk, args, { timeout: 5000 });
+ const devices = parseAdbDevices(stdout);
+ await Promise.all(devices.map(async (device) => {
+ const properties = await getDeviceProperties(sdk, device);
+ for (const [prop, deviceProp] of ADB_GETPROP_MAP.entries()) {
+ const value = properties[prop];
+ if (value) {
+ device[deviceProp] = value;
+ }
+ }
+ }));
+ debug('Found adb devices: %O', devices);
+ return devices;
+}
+exports.getDevices = getDevices;
+async function getDeviceProperty(sdk, device, property) {
+ const debug = Debug(`${modulePrefix}:${getDeviceProperty.name}`);
+ const args = ['-s', device.serial, 'shell', 'getprop', property];
+ debug('Invoking adb with args: %O', args);
+ const stdout = await execAdb(sdk, args, { timeout: 5000 });
+ return stdout.trim();
+}
+exports.getDeviceProperty = getDeviceProperty;
+async function getDeviceProperties(sdk, device) {
+ const debug = Debug(`${modulePrefix}:${getDeviceProperties.name}`);
+ const args = ['-s', device.serial, 'shell', 'getprop'];
+ debug('Invoking adb with args: %O', args);
+ const stdout = await execAdb(sdk, args, { timeout: 5000 });
+ const re = /^\[([a-z0-9.]+)\]: \[(.*)\]$/;
+ const propAllowList = [...ADB_GETPROP_MAP.keys()];
+ const properties = {};
+ for (const line of stdout.split(os.EOL)) {
+ const m = line.match(re);
+ if (m) {
+ const [, key, value] = m;
+ if (propAllowList.includes(key)) {
+ properties[key] = value;
+ }
+ }
+ }
+ return properties;
+}
+exports.getDeviceProperties = getDeviceProperties;
+async function waitForDevice(sdk, serial) {
+ const debug = Debug(`${modulePrefix}:${waitForDevice.name}`);
+ const args = ['-s', serial, 'wait-for-any-device'];
+ debug('Invoking adb with args: %O', args);
+ await execAdb(sdk, args);
+ debug('Device %s is connected to ADB!', serial);
+}
+exports.waitForDevice = waitForDevice;
+async function waitForBoot(sdk, device) {
+ const debug = Debug(`${modulePrefix}:${waitForBoot.name}`);
+ return new Promise(resolve => {
+ const interval = setInterval(async () => {
+ const booted = await getDeviceProperty(sdk, device, 'dev.bootcomplete');
+ if (booted) {
+ debug('Device %s is booted!', device.serial);
+ clearInterval(interval);
+ resolve();
+ }
+ }, 100);
+ });
+}
+exports.waitForBoot = waitForBoot;
+async function waitForClose(sdk, device, app) {
+ const debug = Debug(`${modulePrefix}:${waitForClose.name}`);
+ const args = ['-s', device.serial, 'shell', `ps | grep ${app}`];
+ return new Promise(resolve => {
+ const interval = setInterval(async () => {
+ try {
+ debug('Invoking adb with args: %O', args);
+ await execAdb(sdk, args);
+ }
+ catch (e) {
+ debug('Error received from adb: %O', e);
+ debug('App %s no longer found in process list for %s', app, device.serial);
+ clearInterval(interval);
+ resolve();
+ }
+ }, 500);
+ });
+}
+exports.waitForClose = waitForClose;
+async function installApk(sdk, device, apk) {
+ const debug = Debug(`${modulePrefix}:${installApk.name}`);
+ const platformTools = await sdk_1.getSDKPackage(path.join(sdk.root, 'platform-tools'));
+ const adbBin = path.join(platformTools.location, 'adb');
+ const args = ['-s', device.serial, 'install', '-r', '-t', apk];
+ debug('Invoking adb with args: %O', args);
+ const p = child_process_1.spawn(adbBin, args, {
+ stdio: 'pipe',
+ env: sdk_1.supplementProcessEnv(sdk),
+ });
+ return new Promise((resolve, reject) => {
+ p.on('close', code => {
+ if (code === 0) {
+ resolve();
+ }
+ else {
+ reject(new errors_1.ADBException(`Non-zero exit code from adb: ${code}`));
+ }
+ });
+ p.on('error', err => {
+ debug('adb install error: %O', err);
+ reject(err);
+ });
+ p.stderr.pipe(split2()).pipe(through2((chunk, enc, cb) => {
+ const line = chunk.toString();
+ debug('adb install: %O', line);
+ const event = parseAdbInstallOutput(line);
+ if (event === ADBEvent.IncompatibleUpdateFailure) {
+ reject(new errors_1.ADBException(`Encountered adb error: ${ADBEvent[event]}.`, errors_1.ERR_INCOMPATIBLE_UPDATE));
+ }
+ else if (event === ADBEvent.NewerVersionOnDeviceFailure) {
+ reject(new errors_1.ADBException(`Encountered adb error: ${ADBEvent[event]}.`, errors_1.ERR_VERSION_DOWNGRADE));
+ }
+ else if (event === ADBEvent.NewerSdkRequiredOnDeviceFailure) {
+ reject(new errors_1.ADBException(`Encountered adb error: ${ADBEvent[event]}.`, errors_1.ERR_MIN_SDK_VERSION));
+ }
+ else if (event === ADBEvent.NoCertificates) {
+ reject(new errors_1.ADBException(`Encountered adb error: ${ADBEvent[event]}.`, errors_1.ERR_NO_CERTIFICATES));
+ }
+ else if (event === ADBEvent.NotEnoughSpace) {
+ reject(new errors_1.ADBException(`Encountered adb error: ${ADBEvent[event]}.`, errors_1.ERR_NOT_ENOUGH_SPACE));
+ }
+ else if (event === ADBEvent.DeviceOffline) {
+ reject(new errors_1.ADBException(`Encountered adb error: ${ADBEvent[event]}.`, errors_1.ERR_DEVICE_OFFLINE));
+ }
+ cb();
+ }));
+ });
+}
+exports.installApk = installApk;
+async function closeApp(sdk, device, app) {
+ const debug = Debug(`${modulePrefix}:${closeApp.name}`);
+ const args = ['-s', device.serial, 'shell', 'am', 'force-stop', app];
+ debug('Invoking adb with args: %O', args);
+ await execAdb(sdk, args);
+}
+exports.closeApp = closeApp;
+async function uninstallApp(sdk, device, app) {
+ const debug = Debug(`${modulePrefix}:${uninstallApp.name}`);
+ const args = ['-s', device.serial, 'uninstall', app];
+ debug('Invoking adb with args: %O', args);
+ await execAdb(sdk, args);
+}
+exports.uninstallApp = uninstallApp;
+var ADBEvent;
+(function (ADBEvent) {
+ ADBEvent[ADBEvent["IncompatibleUpdateFailure"] = 0] = "IncompatibleUpdateFailure";
+ ADBEvent[ADBEvent["NewerVersionOnDeviceFailure"] = 1] = "NewerVersionOnDeviceFailure";
+ ADBEvent[ADBEvent["NewerSdkRequiredOnDeviceFailure"] = 2] = "NewerSdkRequiredOnDeviceFailure";
+ ADBEvent[ADBEvent["NoCertificates"] = 3] = "NoCertificates";
+ ADBEvent[ADBEvent["NotEnoughSpace"] = 4] = "NotEnoughSpace";
+ ADBEvent[ADBEvent["DeviceOffline"] = 5] = "DeviceOffline";
+})(ADBEvent = exports.ADBEvent || (exports.ADBEvent = {}));
+function parseAdbInstallOutput(line) {
+ const debug = Debug(`${modulePrefix}:${parseAdbInstallOutput.name}`);
+ let event;
+ if (line.includes('INSTALL_FAILED_UPDATE_INCOMPATIBLE')) {
+ event = ADBEvent.IncompatibleUpdateFailure;
+ }
+ else if (line.includes('INSTALL_FAILED_VERSION_DOWNGRADE')) {
+ event = ADBEvent.NewerVersionOnDeviceFailure;
+ }
+ else if (line.includes('INSTALL_FAILED_OLDER_SDK')) {
+ event = ADBEvent.NewerSdkRequiredOnDeviceFailure;
+ }
+ else if (line.includes('INSTALL_PARSE_FAILED_NO_CERTIFICATES')) {
+ event = ADBEvent.NoCertificates;
+ }
+ else if (line.includes('INSTALL_FAILED_INSUFFICIENT_STORAGE') ||
+ line.includes('not enough space')) {
+ event = ADBEvent.NotEnoughSpace;
+ }
+ else if (line.includes('device offline')) {
+ event = ADBEvent.DeviceOffline;
+ }
+ if (typeof event !== 'undefined') {
+ debug('Parsed event from adb install output: %s', ADBEvent[event]);
+ }
+ return event;
+}
+exports.parseAdbInstallOutput = parseAdbInstallOutput;
+async function startActivity(sdk, device, packageName, activityName) {
+ const debug = Debug(`${modulePrefix}:${startActivity.name}`);
+ const args = [
+ '-s',
+ device.serial,
+ 'shell',
+ 'am',
+ 'start',
+ '-W',
+ '-n',
+ `${packageName}/${activityName}`,
+ ];
+ debug('Invoking adb with args: %O', args);
+ await execAdb(sdk, args, { timeout: 5000 });
+}
+exports.startActivity = startActivity;
+function parseAdbDevices(output) {
+ const debug = Debug(`${modulePrefix}:${parseAdbDevices.name}`);
+ const re = /^([\S]+)\s+([a-z\s]+)\s+(.*)$/;
+ const ipRe = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:\d+$/;
+ const lines = output.split(os.EOL);
+ debug('Parsing adb devices from output lines: %O', lines);
+ const devices = [];
+ for (const line of lines) {
+ if (line && !line.startsWith('List')) {
+ const m = line.match(re);
+ if (m) {
+ const [, serial, state, description] = m;
+ const properties = description
+ .split(/\s+/)
+ .map(prop => (prop.includes(':') ? prop.split(':') : undefined))
+ .filter((kv) => typeof kv !== 'undefined' && kv.length >= 2)
+ .reduce((acc, [k, v]) => {
+ if (k && v) {
+ acc[k.trim()] = v.trim();
+ }
+ return acc;
+ }, {});
+ const isIP = !!serial.match(ipRe);
+ const isGenericDevice = (properties['device'] || '').startsWith('generic');
+ const type = 'usb' in properties ||
+ isIP ||
+ !serial.startsWith('emulator') ||
+ !isGenericDevice
+ ? 'hardware'
+ : 'emulator';
+ const connection = 'usb' in properties ? 'usb' : isIP ? 'tcpip' : null;
+ devices.push({
+ serial,
+ state,
+ type,
+ connection,
+ properties,
+ // We might not know these yet
+ manufacturer: '',
+ model: properties['model'] || '',
+ product: properties['product'] || '',
+ sdkVersion: '',
+ });
+ }
+ else {
+ debug('adb devices output line does not match expected regex: %O', line);
+ }
+ }
+ }
+ return devices;
+}
+exports.parseAdbDevices = parseAdbDevices;
+async function forwardPorts(sdk, device, ports) {
+ const debug = Debug(`${modulePrefix}:${forwardPorts.name}`);
+ const args = [
+ '-s',
+ device.serial,
+ 'reverse',
+ `tcp:${ports.device}`,
+ `tcp:${ports.host}`,
+ ];
+ debug('Invoking adb with args: %O', args);
+ await execAdb(sdk, args, { timeout: 5000 });
+}
+exports.forwardPorts = forwardPorts;
+async function unforwardPorts(sdk, device, ports) {
+ const debug = Debug(`${modulePrefix}:${unforwardPorts.name}`);
+ const args = [
+ '-s',
+ device.serial,
+ 'reverse',
+ '--remove',
+ `tcp:${ports.device}`,
+ ];
+ debug('Invoking adb with args: %O', args);
+ await execAdb(sdk, args, { timeout: 5000 });
+}
+exports.unforwardPorts = unforwardPorts;
+async function execAdb(sdk, args, options = {}) {
+ const debug = Debug(`${modulePrefix}:${execAdb.name}`);
+ let timer;
+ const retry = async () => {
+ const msg = `ADBs is unresponsive after ${options.timeout}ms, killing server and retrying...\n`;
+ if (process.argv.includes('--json')) {
+ debug(msg);
+ }
+ else {
+ process.stderr.write(msg);
+ }
+ debug('ADB timeout of %O reached, killing server and retrying...', options.timeout);
+ debug('Invoking adb with args: %O', ['kill-server']);
+ await execAdb(sdk, ['kill-server']);
+ debug('Invoking adb with args: %O', ['start-server']);
+ await execAdb(sdk, ['start-server']);
+ debug('Retrying...');
+ return run();
+ };
+ const run = async () => {
+ const platformTools = await sdk_1.getSDKPackage(path.join(sdk.root, 'platform-tools'));
+ const adbBin = path.join(platformTools.location, 'adb');
+ const { stdout } = await process_1.execFile(adbBin, args, {
+ env: sdk_1.supplementProcessEnv(sdk),
+ });
+ if (timer) {
+ clearTimeout(timer);
+ timer = undefined;
+ }
+ return stdout;
+ };
+ return new Promise((resolve, reject) => {
+ if (options.timeout) {
+ timer = setTimeout(() => retry().then(resolve, reject), options.timeout);
+ }
+ run().then(resolve, err => {
+ if (!timer) {
+ reject(err);
+ }
+ });
+ });
+}
+exports.execAdb = execAdb;
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/dist/android/utils/apk.js b/temporary_modules/trezor-connect/node_modules/native-run/dist/android/utils/apk.js
new file mode 100644
index 00000000..1f68d03c
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/native-run/dist/android/utils/apk.js
@@ -0,0 +1,36 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+exports.getApkInfo = exports.readAndroidManifest = void 0;
+const unzip_1 = require("../../utils/unzip");
+const binary_xml_parser_1 = require("./binary-xml-parser");
+async function readAndroidManifest(apkPath) {
+ let error;
+ const chunks = [];
+ await unzip_1.unzip(apkPath, async (entry, zipfile, openReadStream) => {
+ if (entry.fileName === 'AndroidManifest.xml') {
+ const readStream = await openReadStream(entry);
+ readStream.on('error', (err) => (error = err));
+ readStream.on('data', (chunk) => chunks.push(chunk));
+ readStream.on('end', () => zipfile.close());
+ }
+ else {
+ zipfile.readEntry();
+ }
+ });
+ if (error) {
+ throw error;
+ }
+ const buf = Buffer.concat(chunks);
+ const manifestBuffer = Buffer.from(buf);
+ return new binary_xml_parser_1.BinaryXmlParser(manifestBuffer).parse();
+}
+exports.readAndroidManifest = readAndroidManifest;
+async function getApkInfo(apkPath) {
+ const doc = await readAndroidManifest(apkPath);
+ const appId = doc.attributes.find((a) => a.name === 'package').value;
+ const application = doc.childNodes.find((n) => n.nodeName === 'application');
+ const activity = application.childNodes.find((n) => n.nodeName === 'activity');
+ const activityName = activity.attributes.find((a) => a.name === 'name').value;
+ return { appId, activityName };
+}
+exports.getApkInfo = getApkInfo;
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/dist/android/utils/avd.js b/temporary_modules/trezor-connect/node_modules/native-run/dist/android/utils/avd.js
new file mode 100644
index 00000000..e3f19d4d
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/native-run/dist/android/utils/avd.js
@@ -0,0 +1,235 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+exports.getSkinPathByName = exports.validateSystemImagePath = exports.copySkin = exports.validateSkin = exports.validateAVDSchematic = exports.createAVDSchematic = exports.createAVD = exports.getDefaultAVD = exports.getAVDSchematicFromAPILevel = exports.getDefaultAVDSchematic = exports.getInstalledAVDs = exports.getAVDFromINI = exports.getSDKVersionFromTarget = exports.getAVDFromConfigINI = exports.getAVDINIs = exports.isAVDConfigINI = exports.isAVDINI = void 0;
+const utils_fs_1 = require("@ionic/utils-fs");
+const Debug = require("debug");
+const pathlib = require("path");
+const constants_1 = require("../../constants");
+const errors_1 = require("../../errors");
+const ini_1 = require("../../utils/ini");
+const object_1 = require("../../utils/object");
+const sdk_1 = require("./sdk");
+const api_1 = require("./sdk/api");
+const modulePrefix = 'native-run:android:utils:avd';
+const isAVDINI = (o) => o &&
+ typeof o['avd.ini.encoding'] === 'string' &&
+ typeof o['path'] === 'string' &&
+ typeof o['path.rel'] === 'string' &&
+ typeof o['target'] === 'string';
+exports.isAVDINI = isAVDINI;
+const isAVDConfigINI = (o) => o &&
+ (typeof o['avd.ini.displayname'] === 'undefined' ||
+ typeof o['avd.ini.displayname'] === 'string') &&
+ (typeof o['hw.lcd.density'] === 'undefined' ||
+ typeof o['hw.lcd.density'] === 'string') &&
+ (typeof o['hw.lcd.height'] === 'undefined' ||
+ typeof o['hw.lcd.height'] === 'string') &&
+ (typeof o['hw.lcd.width'] === 'undefined' ||
+ typeof o['hw.lcd.width'] === 'string') &&
+ (typeof o['image.sysdir.1'] === 'undefined' ||
+ typeof o['image.sysdir.1'] === 'string');
+exports.isAVDConfigINI = isAVDConfigINI;
+async function getAVDINIs(sdk) {
+ const debug = Debug(`${modulePrefix}:${getAVDINIs.name}`);
+ const contents = await utils_fs_1.readdir(sdk.avdHome);
+ const iniFilePaths = contents
+ .filter(f => pathlib.extname(f) === '.ini')
+ .map(f => pathlib.resolve(sdk.avdHome, f));
+ debug('Discovered AVD ini files: %O', iniFilePaths);
+ const iniFiles = await Promise.all(iniFilePaths.map(async (f) => [
+ f,
+ await ini_1.readINI(f, exports.isAVDINI),
+ ]));
+ const avdInis = iniFiles.filter((c) => typeof c[1] !== 'undefined');
+ return avdInis;
+}
+exports.getAVDINIs = getAVDINIs;
+function getAVDFromConfigINI(inipath, ini, configini) {
+ const inibasename = pathlib.basename(inipath);
+ const id = inibasename.substring(0, inibasename.length - pathlib.extname(inibasename).length);
+ const name = configini['avd.ini.displayname']
+ ? String(configini['avd.ini.displayname'])
+ : id.replace(/_/g, ' ');
+ const screenDPI = configini['hw.lcd.density']
+ ? Number(configini['hw.lcd.density'])
+ : null;
+ const screenWidth = configini['hw.lcd.width']
+ ? Number(configini['hw.lcd.width'])
+ : null;
+ const screenHeight = configini['hw.lcd.height']
+ ? Number(configini['hw.lcd.height'])
+ : null;
+ return {
+ id,
+ path: ini.path,
+ name,
+ sdkVersion: getSDKVersionFromTarget(ini.target),
+ screenDPI,
+ screenWidth,
+ screenHeight,
+ };
+}
+exports.getAVDFromConfigINI = getAVDFromConfigINI;
+function getSDKVersionFromTarget(target) {
+ return target.replace(/^android-(\d+)/, '$1');
+}
+exports.getSDKVersionFromTarget = getSDKVersionFromTarget;
+async function getAVDFromINI(inipath, ini) {
+ const configini = await ini_1.readINI(pathlib.resolve(ini.path, 'config.ini'), exports.isAVDConfigINI);
+ if (configini) {
+ return getAVDFromConfigINI(inipath, ini, configini);
+ }
+}
+exports.getAVDFromINI = getAVDFromINI;
+async function getInstalledAVDs(sdk) {
+ const avdInis = await getAVDINIs(sdk);
+ const possibleAvds = await Promise.all(avdInis.map(([inipath, ini]) => getAVDFromINI(inipath, ini)));
+ const avds = possibleAvds.filter((avd) => typeof avd !== 'undefined');
+ return avds;
+}
+exports.getInstalledAVDs = getInstalledAVDs;
+async function getDefaultAVDSchematic(sdk) {
+ const debug = Debug(`${modulePrefix}:${getDefaultAVDSchematic.name}`);
+ const packages = await sdk_1.findAllSDKPackages(sdk);
+ const apis = await api_1.getAPILevels(packages);
+ const errors = [];
+ for (const api of apis) {
+ try {
+ const schematic = await getAVDSchematicFromAPILevel(sdk, packages, api);
+ debug('Using schematic %s for default AVD', schematic.id);
+ return schematic;
+ }
+ catch (e) {
+ if (!(e instanceof errors_1.AVDException)) {
+ throw e;
+ }
+ errors.push(e);
+ debug('Issue with API %s: %s', api.apiLevel, e.message);
+ }
+ }
+ if (errors.length > 0) {
+ const unsupportedError = errors.find(e => e.code === errors_1.ERR_UNSUPPORTED_API_LEVEL);
+ if (unsupportedError) {
+ throw unsupportedError;
+ }
+ }
+ throw new errors_1.AVDException('No suitable API installation found. Use --sdk-info to reveal missing packages and other issues.', errors_1.ERR_UNSUITABLE_API_INSTALLATION, 1);
+}
+exports.getDefaultAVDSchematic = getDefaultAVDSchematic;
+async function getAVDSchematicFromAPILevel(sdk, packages, api) {
+ const schema = api_1.API_LEVEL_SCHEMAS.find(s => s.apiLevel === api.apiLevel);
+ if (!schema) {
+ throw new errors_1.AVDException(`Unsupported API level: ${api.apiLevel}`, errors_1.ERR_UNSUPPORTED_API_LEVEL);
+ }
+ const missingPackages = schema.validate(packages);
+ if (missingPackages.length > 0) {
+ throw new errors_1.AVDException(`Unsatisfied packages within API ${api.apiLevel}: ${missingPackages
+ .map(pkg => pkg.path)
+ .join(', ')}`, errors_1.ERR_SDK_UNSATISFIED_PACKAGES, 1);
+ }
+ return createAVDSchematic(sdk, await schema.loadPartialAVDSchematic());
+}
+exports.getAVDSchematicFromAPILevel = getAVDSchematicFromAPILevel;
+async function getDefaultAVD(sdk, avds) {
+ const defaultAvdSchematic = await getDefaultAVDSchematic(sdk);
+ const defaultAvd = avds.find(avd => avd.id === defaultAvdSchematic.id);
+ if (defaultAvd) {
+ return defaultAvd;
+ }
+ return createAVD(sdk, defaultAvdSchematic);
+}
+exports.getDefaultAVD = getDefaultAVD;
+async function createAVD(sdk, schematic) {
+ const { id, ini, configini } = schematic;
+ await utils_fs_1.mkdirp(pathlib.join(sdk.avdHome, `${id}.avd`));
+ await Promise.all([
+ ini_1.writeINI(pathlib.join(sdk.avdHome, `${id}.ini`), ini),
+ ini_1.writeINI(pathlib.join(sdk.avdHome, `${id}.avd`, 'config.ini'), configini),
+ ]);
+ return getAVDFromConfigINI(pathlib.join(sdk.avdHome, `${id}.ini`), ini, configini);
+}
+exports.createAVD = createAVD;
+async function createAVDSchematic(sdk, partialSchematic) {
+ const sysimage = api_1.findPackageBySchemaPath(sdk.packages || [], new RegExp(`^system-images;${partialSchematic.ini.target}`));
+ if (!sysimage) {
+ throw new errors_1.AVDException(`Cannot create AVD schematic for ${partialSchematic.id}: missing system image.`, errors_1.ERR_MISSING_SYSTEM_IMAGE);
+ }
+ const avdpath = pathlib.join(sdk.avdHome, `${partialSchematic.id}.avd`);
+ const skinpath = getSkinPathByName(sdk, partialSchematic.configini['skin.name']);
+ const sysdir = pathlib.relative(sdk.root, sysimage.location);
+ const [, , tagid] = sysimage.path.split(';');
+ const schematic = {
+ id: partialSchematic.id,
+ ini: object_1.sort({
+ ...partialSchematic.ini,
+ 'path': avdpath,
+ 'path.rel': `avd/${partialSchematic.id}.avd`,
+ }),
+ configini: object_1.sort({
+ ...partialSchematic.configini,
+ 'skin.path': skinpath,
+ 'image.sysdir.1': sysdir,
+ 'tag.id': tagid,
+ }),
+ };
+ await validateAVDSchematic(sdk, schematic);
+ return schematic;
+}
+exports.createAVDSchematic = createAVDSchematic;
+async function validateAVDSchematic(sdk, schematic) {
+ const { configini } = schematic;
+ const skin = configini['skin.name'];
+ const skinpath = configini['skin.path'];
+ const sysdir = configini['image.sysdir.1'];
+ if (!skinpath) {
+ throw new errors_1.AVDException(`${schematic.id} does not have a skin defined.`, errors_1.ERR_INVALID_SKIN);
+ }
+ if (!sysdir) {
+ throw new errors_1.AVDException(`${schematic.id} does not have a system image defined.`, errors_1.ERR_INVALID_SYSTEM_IMAGE);
+ }
+ await validateSkin(sdk, skin, skinpath);
+ await validateSystemImagePath(sdk, sysdir);
+}
+exports.validateAVDSchematic = validateAVDSchematic;
+async function validateSkin(sdk, skin, skinpath) {
+ const debug = Debug(`${modulePrefix}:${validateSkin.name}`);
+ const p = pathlib.join(skinpath, 'layout');
+ debug('Checking skin layout file: %s', p);
+ const stat = await utils_fs_1.statSafe(p);
+ if (stat === null || stat === void 0 ? void 0 : stat.isFile()) {
+ return;
+ }
+ await copySkin(sdk, skin, skinpath);
+}
+exports.validateSkin = validateSkin;
+async function copySkin(sdk, skin, skinpath) {
+ const debug = Debug(`${modulePrefix}:${copySkin.name}`);
+ const skinsrc = pathlib.resolve(constants_1.ASSETS_PATH, 'android', 'skins', skin);
+ const stat = await utils_fs_1.statSafe(skinsrc);
+ if (stat === null || stat === void 0 ? void 0 : stat.isDirectory()) {
+ debug('Copying skin from %s to %s', skinsrc, skinpath);
+ try {
+ return await utils_fs_1.copy(skinsrc, skinpath);
+ }
+ catch (e) {
+ debug('Error while copying skin: %O', e);
+ }
+ }
+ throw new errors_1.AVDException(`${skinpath} is an invalid skin.`, errors_1.ERR_INVALID_SKIN);
+}
+exports.copySkin = copySkin;
+async function validateSystemImagePath(sdk, sysdir) {
+ const debug = Debug(`${modulePrefix}:${validateSystemImagePath.name}`);
+ const p = pathlib.join(sdk.root, sysdir, 'package.xml');
+ debug('Checking package.xml file: %s', p);
+ const stat = await utils_fs_1.statSafe(p);
+ if (!stat || !stat.isFile()) {
+ throw new errors_1.AVDException(`${p} is an invalid system image package.`, errors_1.ERR_INVALID_SYSTEM_IMAGE);
+ }
+}
+exports.validateSystemImagePath = validateSystemImagePath;
+function getSkinPathByName(sdk, name) {
+ const path = pathlib.join(sdk.root, 'skins', name);
+ return path;
+}
+exports.getSkinPathByName = getSkinPathByName;
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/dist/android/utils/binary-xml-parser.js b/temporary_modules/trezor-connect/node_modules/native-run/dist/android/utils/binary-xml-parser.js
new file mode 100644
index 00000000..aa8d5dbb
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/native-run/dist/android/utils/binary-xml-parser.js
@@ -0,0 +1,593 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+exports.BinaryXmlParser = void 0;
+/*
+ Copyright © 2013 CyberAgent, Inc.
+ Copyright © 2016 The OpenSTF Project
+ Modifications Copyright © 2018 Drifty Co
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+
+ https://github.com/openstf/adbkit-apkreader/blob/368f6b207c57e82fa7373c1608920ca7f4a8904c/lib/apkreader/parser/binaryxml.js
+*/
+const assert = require("assert");
+// import * as Debug from 'debug';
+const errors_1 = require("../../errors");
+// const debug = Debug('native-run:android:util:binary-xml-parser');
+const NodeType = {
+ ELEMENT_NODE: 1,
+ ATTRIBUTE_NODE: 2,
+ CDATA_SECTION_NODE: 4,
+};
+const ChunkType = {
+ NULL: 0x0000,
+ STRING_POOL: 0x0001,
+ TABLE: 0x0002,
+ XML: 0x0003,
+ XML_FIRST_CHUNK: 0x0100,
+ XML_START_NAMESPACE: 0x0100,
+ XML_END_NAMESPACE: 0x0101,
+ XML_START_ELEMENT: 0x0102,
+ XML_END_ELEMENT: 0x0103,
+ XML_CDATA: 0x0104,
+ XML_LAST_CHUNK: 0x017f,
+ XML_RESOURCE_MAP: 0x0180,
+ TABLE_PACKAGE: 0x0200,
+ TABLE_TYPE: 0x0201,
+ TABLE_TYPE_SPEC: 0x0202,
+};
+const StringFlags = {
+ SORTED: 1 << 0,
+ UTF8: 1 << 8,
+};
+// Taken from android.util.TypedValue
+const TypedValue = {
+ COMPLEX_MANTISSA_MASK: 0x00ffffff,
+ COMPLEX_MANTISSA_SHIFT: 0x00000008,
+ COMPLEX_RADIX_0p23: 0x00000003,
+ COMPLEX_RADIX_16p7: 0x00000001,
+ COMPLEX_RADIX_23p0: 0x00000000,
+ COMPLEX_RADIX_8p15: 0x00000002,
+ COMPLEX_RADIX_MASK: 0x00000003,
+ COMPLEX_RADIX_SHIFT: 0x00000004,
+ COMPLEX_UNIT_DIP: 0x00000001,
+ COMPLEX_UNIT_FRACTION: 0x00000000,
+ COMPLEX_UNIT_FRACTION_PARENT: 0x00000001,
+ COMPLEX_UNIT_IN: 0x00000004,
+ COMPLEX_UNIT_MASK: 0x0000000f,
+ COMPLEX_UNIT_MM: 0x00000005,
+ COMPLEX_UNIT_PT: 0x00000003,
+ COMPLEX_UNIT_PX: 0x00000000,
+ COMPLEX_UNIT_SHIFT: 0x00000000,
+ COMPLEX_UNIT_SP: 0x00000002,
+ DENSITY_DEFAULT: 0x00000000,
+ DENSITY_NONE: 0x0000ffff,
+ TYPE_ATTRIBUTE: 0x00000002,
+ TYPE_DIMENSION: 0x00000005,
+ TYPE_FIRST_COLOR_INT: 0x0000001c,
+ TYPE_FIRST_INT: 0x00000010,
+ TYPE_FLOAT: 0x00000004,
+ TYPE_FRACTION: 0x00000006,
+ TYPE_INT_BOOLEAN: 0x00000012,
+ TYPE_INT_COLOR_ARGB4: 0x0000001e,
+ TYPE_INT_COLOR_ARGB8: 0x0000001c,
+ TYPE_INT_COLOR_RGB4: 0x0000001f,
+ TYPE_INT_COLOR_RGB8: 0x0000001d,
+ TYPE_INT_DEC: 0x00000010,
+ TYPE_INT_HEX: 0x00000011,
+ TYPE_LAST_COLOR_INT: 0x0000001f,
+ TYPE_LAST_INT: 0x0000001f,
+ TYPE_NULL: 0x00000000,
+ TYPE_REFERENCE: 0x00000001,
+ TYPE_STRING: 0x00000003,
+};
+class BinaryXmlParser {
+ constructor(buffer, options = {}) {
+ this.buffer = buffer;
+ this.cursor = 0;
+ this.strings = [];
+ this.resources = [];
+ this.stack = [];
+ this.debug = false;
+ this.debug = options.debug || false;
+ }
+ readU8() {
+ // debug('readU8');
+ // debug('cursor:', this.cursor);
+ const val = this.buffer[this.cursor];
+ // debug('value:', val);
+ this.cursor += 1;
+ return val;
+ }
+ readU16() {
+ // debug('readU16');
+ // debug('cursor:', this.cursor);
+ const val = this.buffer.readUInt16LE(this.cursor);
+ // debug('value:', val);
+ this.cursor += 2;
+ return val;
+ }
+ readS32() {
+ // debug('readS32');
+ // debug('cursor:', this.cursor);
+ const val = this.buffer.readInt32LE(this.cursor);
+ // debug('value:', val);
+ this.cursor += 4;
+ return val;
+ }
+ readU32() {
+ // debug('readU32');
+ // debug('cursor:', this.cursor);
+ const val = this.buffer.readUInt32LE(this.cursor);
+ // debug('value:', val);
+ this.cursor += 4;
+ return val;
+ }
+ readLength8() {
+ // debug('readLength8');
+ let len = this.readU8();
+ if (len & 0x80) {
+ len = (len & 0x7f) << 8;
+ len += this.readU8();
+ }
+ // debug('length:', len);
+ return len;
+ }
+ readLength16() {
+ // debug('readLength16');
+ let len = this.readU16();
+ if (len & 0x8000) {
+ len = (len & 0x7fff) << 16;
+ len += this.readU16();
+ }
+ // debug('length:', len);
+ return len;
+ }
+ readDimension() {
+ // debug('readDimension');
+ const dimension = {
+ value: null,
+ unit: null,
+ rawUnit: null,
+ };
+ const value = this.readU32();
+ const unit = dimension.value & 0xff;
+ dimension.value = value >> 8;
+ dimension.rawUnit = unit;
+ switch (unit) {
+ case TypedValue.COMPLEX_UNIT_MM:
+ dimension.unit = 'mm';
+ break;
+ case TypedValue.COMPLEX_UNIT_PX:
+ dimension.unit = 'px';
+ break;
+ case TypedValue.COMPLEX_UNIT_DIP:
+ dimension.unit = 'dp';
+ break;
+ case TypedValue.COMPLEX_UNIT_SP:
+ dimension.unit = 'sp';
+ break;
+ case TypedValue.COMPLEX_UNIT_PT:
+ dimension.unit = 'pt';
+ break;
+ case TypedValue.COMPLEX_UNIT_IN:
+ dimension.unit = 'in';
+ break;
+ }
+ return dimension;
+ }
+ readFraction() {
+ // debug('readFraction');
+ const fraction = {
+ value: null,
+ type: null,
+ rawType: null,
+ };
+ const value = this.readU32();
+ const type = value & 0xf;
+ fraction.value = this.convertIntToFloat(value >> 4);
+ fraction.rawType = type;
+ switch (type) {
+ case TypedValue.COMPLEX_UNIT_FRACTION:
+ fraction.type = '%';
+ break;
+ case TypedValue.COMPLEX_UNIT_FRACTION_PARENT:
+ fraction.type = '%p';
+ break;
+ }
+ return fraction;
+ }
+ readHex24() {
+ // debug('readHex24');
+ const val = (this.readU32() & 0xffffff).toString(16);
+ return val;
+ }
+ readHex32() {
+ // debug('readHex32');
+ const val = this.readU32().toString(16);
+ return val;
+ }
+ readTypedValue() {
+ // debug('readTypedValue');
+ const typedValue = {
+ value: null,
+ type: null,
+ rawType: null,
+ };
+ const start = this.cursor;
+ let size = this.readU16();
+ /* const zero = */ this.readU8();
+ const dataType = this.readU8();
+ // Yes, there has been a real world APK where the size is malformed.
+ if (size === 0) {
+ size = 8;
+ }
+ typedValue.rawType = dataType;
+ switch (dataType) {
+ case TypedValue.TYPE_INT_DEC:
+ typedValue.value = this.readS32();
+ typedValue.type = 'int_dec';
+ break;
+ case TypedValue.TYPE_INT_HEX:
+ typedValue.value = this.readS32();
+ typedValue.type = 'int_hex';
+ break;
+ case TypedValue.TYPE_STRING: {
+ const ref = this.readS32();
+ typedValue.value = ref > 0 ? this.strings[ref] : '';
+ typedValue.type = 'string';
+ break;
+ }
+ case TypedValue.TYPE_REFERENCE: {
+ const id = this.readU32();
+ typedValue.value = `resourceId:0x${id.toString(16)}`;
+ typedValue.type = 'reference';
+ break;
+ }
+ case TypedValue.TYPE_INT_BOOLEAN:
+ typedValue.value = this.readS32() !== 0;
+ typedValue.type = 'boolean';
+ break;
+ case TypedValue.TYPE_NULL:
+ this.readU32();
+ typedValue.value = null;
+ typedValue.type = 'null';
+ break;
+ case TypedValue.TYPE_INT_COLOR_RGB8:
+ typedValue.value = this.readHex24();
+ typedValue.type = 'rgb8';
+ break;
+ case TypedValue.TYPE_INT_COLOR_RGB4:
+ typedValue.value = this.readHex24();
+ typedValue.type = 'rgb4';
+ break;
+ case TypedValue.TYPE_INT_COLOR_ARGB8:
+ typedValue.value = this.readHex32();
+ typedValue.type = 'argb8';
+ break;
+ case TypedValue.TYPE_INT_COLOR_ARGB4:
+ typedValue.value = this.readHex32();
+ typedValue.type = 'argb4';
+ break;
+ case TypedValue.TYPE_DIMENSION:
+ typedValue.value = this.readDimension();
+ typedValue.type = 'dimension';
+ break;
+ case TypedValue.TYPE_FRACTION:
+ typedValue.value = this.readFraction();
+ typedValue.type = 'fraction';
+ break;
+ default: {
+ // const type = dataType.toString(16);
+ // debug(`Not sure what to do with typed value of type 0x${type}, falling back to reading an uint32.`);
+ typedValue.value = this.readU32();
+ typedValue.type = 'unknown';
+ }
+ }
+ // Ensure we consume the whole value
+ const end = start + size;
+ if (this.cursor !== end) {
+ // const type = dataType.toString(16);
+ // const diff = end - this.cursor;
+ // debug(`Cursor is off by ${diff} bytes at ${this.cursor} at supposed end \
+ // of typed value of type 0x${type}. The typed value started at offset ${start} \
+ // and is supposed to end at offset ${end}. Ignoring the rest of the value.`);
+ this.cursor = end;
+ }
+ return typedValue;
+ }
+ // https://twitter.com/kawasima/status/427730289201139712
+ convertIntToFloat(int) {
+ const buf = new ArrayBuffer(4);
+ new Int32Array(buf)[0] = int;
+ return new Float32Array(buf)[0];
+ }
+ readString(encoding) {
+ // debug('readString', encoding);
+ let stringLength;
+ let byteLength;
+ let value;
+ switch (encoding) {
+ case 'utf-8':
+ stringLength = this.readLength8();
+ // debug('stringLength:', stringLength);
+ byteLength = this.readLength8();
+ // debug('byteLength:', byteLength);
+ value = this.buffer.toString(encoding, this.cursor, (this.cursor += byteLength));
+ // debug('value:', value);
+ assert.equal(this.readU8(), 0, 'String must end with trailing zero');
+ return value;
+ case 'ucs2':
+ stringLength = this.readLength16();
+ // debug('stringLength:', stringLength);
+ byteLength = stringLength * 2;
+ // debug('byteLength:', byteLength);
+ value = this.buffer.toString(encoding, this.cursor, (this.cursor += byteLength));
+ // debug('value:', value);
+ assert.equal(this.readU16(), 0, 'String must end with trailing zero');
+ return value;
+ default:
+ throw new errors_1.Exception(`Unsupported encoding '${encoding}'`);
+ }
+ }
+ readChunkHeader() {
+ // debug('readChunkHeader');
+ const header = {
+ startOffset: this.cursor,
+ chunkType: this.readU16(),
+ headerSize: this.readU16(),
+ chunkSize: this.readU32(),
+ };
+ // debug('startOffset:', header.startOffset);
+ // debug('chunkType:', header.chunkType);
+ // debug('headerSize:', header.headerSize);
+ // debug('chunkSize:', header.chunkSize);
+ return header;
+ }
+ readStringPool(header) {
+ // debug('readStringPool');
+ header.stringCount = this.readU32();
+ // debug('stringCount:', header.stringCount);
+ header.styleCount = this.readU32();
+ // debug('styleCount:', header.styleCount);
+ header.flags = this.readU32();
+ // debug('flags:', header.flags);
+ header.stringsStart = this.readU32();
+ // debug('stringsStart:', header.stringsStart);
+ header.stylesStart = this.readU32();
+ // debug('stylesStart:', header.stylesStart);
+ if (header.chunkType !== ChunkType.STRING_POOL) {
+ throw new errors_1.Exception('Invalid string pool header');
+ }
+ const offsets = [];
+ for (let i = 0, l = header.stringCount; i < l; ++i) {
+ // debug('offset:', i);
+ offsets.push(this.readU32());
+ }
+ // const sorted = (header.flags & StringFlags.SORTED) === StringFlags.SORTED;
+ // debug('sorted:', sorted);
+ const encoding = (header.flags & StringFlags.UTF8) === StringFlags.UTF8 ? 'utf-8' : 'ucs2';
+ // debug('encoding:', encoding);
+ const stringsStart = header.startOffset + header.stringsStart;
+ this.cursor = stringsStart;
+ for (let i = 0, l = header.stringCount; i < l; ++i) {
+ // debug('string:', i);
+ // debug('offset:', offsets[i]);
+ this.cursor = stringsStart + offsets[i];
+ this.strings.push(this.readString(encoding));
+ }
+ // Skip styles
+ this.cursor = header.startOffset + header.chunkSize;
+ return null;
+ }
+ readResourceMap(header) {
+ // debug('readResourceMap');
+ const count = Math.floor((header.chunkSize - header.headerSize) / 4);
+ for (let i = 0; i < count; ++i) {
+ this.resources.push(this.readU32());
+ }
+ return null;
+ }
+ readXmlNamespaceStart( /* header */) {
+ // debug('readXmlNamespaceStart');
+ this.readU32();
+ this.readU32();
+ this.readU32();
+ this.readU32();
+ // const line = this.readU32();
+ // const commentRef = this.readU32();
+ // const prefixRef = this.readS32();
+ // const uriRef = this.readS32();
+ // We don't currently care about the values, but they could
+ // be accessed like so:
+ //
+ // namespaceURI.prefix = this.strings[prefixRef] // if prefixRef > 0
+ // namespaceURI.uri = this.strings[uriRef] // if uriRef > 0
+ return null;
+ }
+ readXmlNamespaceEnd( /* header */) {
+ // debug('readXmlNamespaceEnd');
+ this.readU32();
+ this.readU32();
+ this.readU32();
+ this.readU32();
+ // const line = this.readU32();
+ // const commentRef = this.readU32();
+ // const prefixRef = this.readS32();
+ // const uriRef = this.readS32();
+ // We don't currently care about the values, but they could
+ // be accessed like so:
+ //
+ // namespaceURI.prefix = this.strings[prefixRef] // if prefixRef > 0
+ // namespaceURI.uri = this.strings[uriRef] // if uriRef > 0
+ return null;
+ }
+ readXmlElementStart( /* header */) {
+ // debug('readXmlElementStart');
+ const node = {
+ namespaceURI: null,
+ nodeType: NodeType.ELEMENT_NODE,
+ nodeName: null,
+ attributes: [],
+ childNodes: [],
+ };
+ this.readU32();
+ this.readU32();
+ // const line = this.readU32();
+ // const commentRef = this.readU32();
+ const nsRef = this.readS32();
+ const nameRef = this.readS32();
+ if (nsRef > 0) {
+ node.namespaceURI = this.strings[nsRef];
+ }
+ node.nodeName = this.strings[nameRef];
+ this.readU16();
+ this.readU16();
+ // const attrStart = this.readU16();
+ // const attrSize = this.readU16();
+ const attrCount = this.readU16();
+ // const idIndex = this.readU16();
+ // const classIndex = this.readU16();
+ // const styleIndex = this.readU16();
+ this.readU16();
+ this.readU16();
+ this.readU16();
+ for (let i = 0; i < attrCount; ++i) {
+ node.attributes.push(this.readXmlAttribute());
+ }
+ if (this.document) {
+ this.parent.childNodes.push(node);
+ this.parent = node;
+ }
+ else {
+ this.document = this.parent = node;
+ }
+ this.stack.push(node);
+ return node;
+ }
+ readXmlAttribute() {
+ // debug('readXmlAttribute');
+ const attr = {
+ namespaceURI: null,
+ nodeType: NodeType.ATTRIBUTE_NODE,
+ nodeName: null,
+ name: null,
+ value: null,
+ typedValue: null,
+ };
+ const nsRef = this.readS32();
+ const nameRef = this.readS32();
+ const valueRef = this.readS32();
+ if (nsRef > 0) {
+ attr.namespaceURI = this.strings[nsRef];
+ }
+ attr.nodeName = attr.name = this.strings[nameRef];
+ if (valueRef > 0) {
+ attr.value = this.strings[valueRef];
+ }
+ attr.typedValue = this.readTypedValue();
+ return attr;
+ }
+ readXmlElementEnd( /* header */) {
+ // debug('readXmlCData');
+ this.readU32();
+ this.readU32();
+ this.readU32();
+ this.readU32();
+ // const line = this.readU32();
+ // const commentRef = this.readU32();
+ // const nsRef = this.readS32();
+ // const nameRef = this.readS32();
+ this.stack.pop();
+ this.parent = this.stack[this.stack.length - 1];
+ return null;
+ }
+ readXmlCData( /* header */) {
+ // debug('readXmlCData');
+ const cdata = {
+ namespaceURI: null,
+ nodeType: NodeType.CDATA_SECTION_NODE,
+ nodeName: '#cdata',
+ data: null,
+ typedValue: null,
+ };
+ this.readU32();
+ this.readU32();
+ // const line = this.readU32();
+ // const commentRef = this.readU32();
+ const dataRef = this.readS32();
+ if (dataRef > 0) {
+ cdata.data = this.strings[dataRef];
+ }
+ cdata.typedValue = this.readTypedValue();
+ this.parent.childNodes.push(cdata);
+ return cdata;
+ }
+ readNull(header) {
+ // debug('readNull');
+ this.cursor += header.chunkSize - header.headerSize;
+ return null;
+ }
+ parse() {
+ // debug('parse');
+ const xmlHeader = this.readChunkHeader();
+ if (xmlHeader.chunkType !== ChunkType.XML) {
+ throw new errors_1.Exception('Invalid XML header');
+ }
+ while (this.cursor < this.buffer.length) {
+ // debug('chunk');
+ const start = this.cursor;
+ const header = this.readChunkHeader();
+ switch (header.chunkType) {
+ case ChunkType.STRING_POOL:
+ this.readStringPool(header);
+ break;
+ case ChunkType.XML_RESOURCE_MAP:
+ this.readResourceMap(header);
+ break;
+ case ChunkType.XML_START_NAMESPACE:
+ this.readXmlNamespaceStart();
+ break;
+ case ChunkType.XML_END_NAMESPACE:
+ this.readXmlNamespaceEnd();
+ break;
+ case ChunkType.XML_START_ELEMENT:
+ this.readXmlElementStart();
+ break;
+ case ChunkType.XML_END_ELEMENT:
+ this.readXmlElementEnd();
+ break;
+ case ChunkType.XML_CDATA:
+ this.readXmlCData();
+ break;
+ case ChunkType.NULL:
+ this.readNull(header);
+ break;
+ default:
+ throw new errors_1.Exception(`Unsupported chunk type '${header.chunkType}'`);
+ }
+ // Ensure we consume the whole chunk
+ const end = start + header.chunkSize;
+ if (this.cursor !== end) {
+ // const diff = end - this.cursor;
+ // const type = header.chunkType.toString(16);
+ // debug(`Cursor is off by ${diff} bytes at ${this.cursor} at supposed \
+ // end of chunk of type 0x${type}. The chunk started at offset ${start} and is \
+ // supposed to end at offset ${end}. Ignoring the rest of the chunk.`);
+ // this.cursor = end;
+ }
+ }
+ return this.document;
+ }
+}
+exports.BinaryXmlParser = BinaryXmlParser;
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/dist/android/utils/emulator.js b/temporary_modules/trezor-connect/node_modules/native-run/dist/android/utils/emulator.js
new file mode 100644
index 00000000..c0d11dac
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/native-run/dist/android/utils/emulator.js
@@ -0,0 +1,205 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+exports.parseAndroidConsoleResponse = exports.getAVDFromEmulator = exports.parseEmulatorOutput = exports.EmulatorEvent = exports.spawnEmulator = exports.runEmulator = void 0;
+const utils_fs_1 = require("@ionic/utils-fs");
+const child_process_1 = require("child_process");
+const Debug = require("debug");
+const net = require("net");
+const os = require("os");
+const path = require("path");
+const split2 = require("split2");
+const through2 = require("through2");
+const errors_1 = require("../../errors");
+const fn_1 = require("../../utils/fn");
+const adb_1 = require("./adb");
+const sdk_1 = require("./sdk");
+const modulePrefix = 'native-run:android:utils:emulator';
+/**
+ * Resolves when emulator is ready and running with the specified AVD.
+ */
+async function runEmulator(sdk, avd, port) {
+ try {
+ await spawnEmulator(sdk, avd, port);
+ }
+ catch (e) {
+ if (!(e instanceof errors_1.EmulatorException) || e.code !== errors_1.ERR_ALREADY_RUNNING) {
+ throw e;
+ }
+ }
+ const serial = `emulator-${port}`;
+ const devices = await adb_1.getDevices(sdk);
+ const emulator = devices.find(device => device.serial === serial);
+ if (!emulator) {
+ throw new errors_1.EmulatorException(`Emulator not found: ${serial}`);
+ }
+ return emulator;
+}
+exports.runEmulator = runEmulator;
+async function spawnEmulator(sdk, avd, port) {
+ const debug = Debug(`${modulePrefix}:${spawnEmulator.name}`);
+ const emulator = await sdk_1.getSDKPackage(path.join(sdk.root, 'emulator'));
+ const emulatorBin = path.join(emulator.location, 'emulator');
+ const args = ['-avd', avd.id, '-port', port.toString(), '-verbose'];
+ debug('Invoking emulator: %O %O', emulatorBin, args);
+ const p = child_process_1.spawn(emulatorBin, args, {
+ detached: true,
+ stdio: ['ignore', 'pipe', 'pipe'],
+ env: sdk_1.supplementProcessEnv(sdk),
+ });
+ p.unref();
+ return new Promise((_resolve, _reject) => {
+ const resolve = fn_1.once(() => {
+ _resolve();
+ cleanup();
+ });
+ const reject = fn_1.once(err => {
+ _reject(err);
+ cleanup();
+ });
+ adb_1.waitForDevice(sdk, `emulator-${port}`).then(() => resolve(), err => reject(err));
+ const eventParser = through2((chunk, enc, cb) => {
+ const line = chunk.toString();
+ debug('Android Emulator: %O', line);
+ const event = parseEmulatorOutput(line);
+ if (event === EmulatorEvent.AlreadyRunning) {
+ reject(new errors_1.EmulatorException(`Emulator already running with AVD [${avd.id}]`, errors_1.ERR_ALREADY_RUNNING));
+ }
+ else if (event === EmulatorEvent.UnknownAVD) {
+ reject(new errors_1.EmulatorException(`Unknown AVD name [${avd.id}]`, errors_1.ERR_UNKNOWN_AVD));
+ }
+ else if (event === EmulatorEvent.AVDHomeNotFound) {
+ reject(new errors_1.EmulatorException(`Emulator cannot find AVD home`, errors_1.ERR_AVD_HOME_NOT_FOUND));
+ }
+ cb();
+ });
+ const stdoutStream = p.stdout.pipe(split2());
+ const stderrStream = p.stderr.pipe(split2());
+ stdoutStream.pipe(eventParser);
+ stderrStream.pipe(eventParser);
+ const cleanup = () => {
+ debug('Unhooking stdout/stderr streams from emulator process');
+ p.stdout.push(null);
+ p.stderr.push(null);
+ };
+ p.on('close', code => {
+ debug('Emulator closed, exit code %d', code);
+ if (code > 0) {
+ reject(new errors_1.EmulatorException(`Non-zero exit code from Emulator: ${code}`, errors_1.ERR_NON_ZERO_EXIT));
+ }
+ });
+ p.on('error', err => {
+ debug('Emulator error: %O', err);
+ reject(err);
+ });
+ });
+}
+exports.spawnEmulator = spawnEmulator;
+var EmulatorEvent;
+(function (EmulatorEvent) {
+ EmulatorEvent[EmulatorEvent["UnknownAVD"] = 0] = "UnknownAVD";
+ EmulatorEvent[EmulatorEvent["AlreadyRunning"] = 1] = "AlreadyRunning";
+ EmulatorEvent[EmulatorEvent["AVDHomeNotFound"] = 2] = "AVDHomeNotFound";
+})(EmulatorEvent = exports.EmulatorEvent || (exports.EmulatorEvent = {}));
+function parseEmulatorOutput(line) {
+ const debug = Debug(`${modulePrefix}:${parseEmulatorOutput.name}`);
+ let event;
+ if (line.includes('Unknown AVD name')) {
+ event = EmulatorEvent.UnknownAVD;
+ }
+ else if (line.includes('another emulator instance running with the current AVD')) {
+ event = EmulatorEvent.AlreadyRunning;
+ }
+ else if (line.includes('Cannot find AVD system path')) {
+ event = EmulatorEvent.AVDHomeNotFound;
+ }
+ if (typeof event !== 'undefined') {
+ debug('Parsed event from emulator output: %s', EmulatorEvent[event]);
+ }
+ return event;
+}
+exports.parseEmulatorOutput = parseEmulatorOutput;
+async function getAVDFromEmulator(emulator, avds) {
+ const debug = Debug(`${modulePrefix}:${getAVDFromEmulator.name}`);
+ const emulatorPortRegex = /^emulator-(\d+)$/;
+ const m = emulator.serial.match(emulatorPortRegex);
+ if (!m) {
+ throw new errors_1.EmulatorException(`Emulator ${emulator.serial} does not match expected emulator serial format`);
+ }
+ const port = Number.parseInt(m[1], 10);
+ const host = 'localhost';
+ const sock = net.createConnection({ host, port });
+ sock.setEncoding('utf8');
+ sock.setTimeout(5000);
+ const readAuthFile = new Promise((resolve, reject) => {
+ sock.on('connect', () => {
+ debug('Connected to %s:%d', host, port);
+ utils_fs_1.readFile(path.resolve(os.homedir(), '.emulator_console_auth_token'), {
+ encoding: 'utf8',
+ }).then(contents => resolve(contents.trim()), err => reject(err));
+ });
+ });
+ let Stage;
+ (function (Stage) {
+ Stage[Stage["Initial"] = 0] = "Initial";
+ Stage[Stage["Auth"] = 1] = "Auth";
+ Stage[Stage["AuthSuccess"] = 2] = "AuthSuccess";
+ Stage[Stage["Response"] = 3] = "Response";
+ Stage[Stage["Complete"] = 4] = "Complete";
+ })(Stage || (Stage = {}));
+ return new Promise((resolve, reject) => {
+ let stage = Stage.Initial;
+ const timer = setTimeout(() => {
+ if (stage !== Stage.Complete) {
+ reject(new errors_1.EmulatorException(`Took too long to get AVD name from Android Emulator Console, something went wrong.`));
+ }
+ }, 3000);
+ const cleanup = fn_1.once(() => {
+ clearTimeout(timer);
+ sock.end();
+ });
+ sock.on('timeout', () => {
+ reject(new errors_1.EmulatorException(`Socket timeout on ${host}:${port}`));
+ cleanup();
+ });
+ sock.pipe(split2()).pipe(through2((chunk, enc, cb) => {
+ const line = chunk.toString();
+ debug('Android Console: %O', line);
+ if (stage === Stage.Initial &&
+ line.includes('Authentication required')) {
+ stage = Stage.Auth;
+ }
+ else if (stage === Stage.Auth && line.trim() === 'OK') {
+ readAuthFile.then(token => sock.write(`auth ${token}\n`, 'utf8'), err => reject(err));
+ stage = Stage.AuthSuccess;
+ }
+ else if (stage === Stage.AuthSuccess && line.trim() === 'OK') {
+ sock.write('avd name\n', 'utf8');
+ stage = Stage.Response;
+ }
+ else if (stage === Stage.Response) {
+ const avdId = line.trim();
+ const avd = avds.find(avd => avd.id === avdId);
+ if (avd) {
+ resolve(avd);
+ }
+ else {
+ reject(new errors_1.EmulatorException(`Unknown AVD name [${avdId}]`, errors_1.ERR_UNKNOWN_AVD));
+ }
+ stage = Stage.Complete;
+ cleanup();
+ }
+ cb();
+ }));
+ });
+}
+exports.getAVDFromEmulator = getAVDFromEmulator;
+function parseAndroidConsoleResponse(output) {
+ const debug = Debug(`${modulePrefix}:${parseAndroidConsoleResponse.name}`);
+ const m = /([\s\S]+)OK\r?\n/g.exec(output);
+ if (m) {
+ const [, response] = m;
+ debug('Parsed response data from Android Console output: %O', response);
+ return response;
+ }
+}
+exports.parseAndroidConsoleResponse = parseAndroidConsoleResponse;
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/dist/android/utils/list.js b/temporary_modules/trezor-connect/node_modules/native-run/dist/android/utils/list.js
new file mode 100644
index 00000000..a59aeac8
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/native-run/dist/android/utils/list.js
@@ -0,0 +1,38 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+exports.avdToTarget = exports.deviceToTarget = exports.getVirtualTargets = exports.getDeviceTargets = void 0;
+const adb_1 = require("./adb");
+const avd_1 = require("./avd");
+async function getDeviceTargets(sdk) {
+ return (await adb_1.getDevices(sdk))
+ .filter(device => device.type === 'hardware')
+ .map(deviceToTarget);
+}
+exports.getDeviceTargets = getDeviceTargets;
+async function getVirtualTargets(sdk) {
+ const avds = await avd_1.getInstalledAVDs(sdk);
+ const defaultAvd = await avd_1.getDefaultAVD(sdk, avds);
+ if (!avds.includes(defaultAvd)) {
+ avds.push(defaultAvd);
+ }
+ return avds.map(avdToTarget);
+}
+exports.getVirtualTargets = getVirtualTargets;
+function deviceToTarget(device) {
+ return {
+ platform: 'android',
+ model: `${device.manufacturer} ${device.model}`,
+ sdkVersion: device.sdkVersion,
+ id: device.serial,
+ };
+}
+exports.deviceToTarget = deviceToTarget;
+function avdToTarget(avd) {
+ return {
+ platform: 'android',
+ name: avd.name,
+ sdkVersion: avd.sdkVersion,
+ id: avd.id,
+ };
+}
+exports.avdToTarget = avdToTarget;
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/dist/android/utils/run.js b/temporary_modules/trezor-connect/node_modules/native-run/dist/android/utils/run.js
new file mode 100644
index 00000000..087351b5
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/native-run/dist/android/utils/run.js
@@ -0,0 +1,93 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+exports.installApkToDevice = exports.selectVirtualDevice = exports.selectHardwareDevice = exports.selectDeviceByTarget = void 0;
+const Debug = require("debug");
+const errors_1 = require("../../errors");
+const log_1 = require("../../utils/log");
+const adb_1 = require("./adb");
+const avd_1 = require("./avd");
+const emulator_1 = require("./emulator");
+const modulePrefix = 'native-run:android:utils:run';
+async function selectDeviceByTarget(sdk, devices, avds, target) {
+ const debug = Debug(`${modulePrefix}:${selectDeviceByTarget.name}`);
+ debug('--target %s detected', target);
+ debug('Checking if device can be found by serial: %s', target);
+ const device = devices.find(d => d.serial === target);
+ if (device) {
+ debug('Device found by serial: %s', device.serial);
+ return device;
+ }
+ const emulatorDevices = devices.filter(d => d.type === 'emulator');
+ const pairAVD = async (emulator) => {
+ let avd;
+ try {
+ avd = await emulator_1.getAVDFromEmulator(emulator, avds);
+ debug('Emulator %s is using AVD: %s', emulator.serial, avd.id);
+ }
+ catch (e) {
+ debug('Error with emulator %s: %O', emulator.serial, e);
+ }
+ return [emulator, avd];
+ };
+ debug('Checking if any of %d running emulators are using AVD by ID: %s', emulatorDevices.length, target);
+ const emulatorsAndAVDs = await Promise.all(emulatorDevices.map(emulator => pairAVD(emulator)));
+ const emulators = emulatorsAndAVDs.filter((t) => typeof t[1] !== 'undefined');
+ const emulator = emulators.find(([, avd]) => avd.id === target);
+ if (emulator) {
+ const [device, avd] = emulator;
+ debug('Emulator %s found by AVD: %s', device.serial, avd.id);
+ return device;
+ }
+ debug('Checking if AVD can be found by ID: %s', target);
+ const avd = avds.find(avd => avd.id === target);
+ if (avd) {
+ debug('AVD found by ID: %s', avd.id);
+ const device = await emulator_1.runEmulator(sdk, avd, 5554); // TODO: 5554 will not always be available at this point
+ debug('Emulator ready, running avd: %s on %s', avd.id, device.serial);
+ return device;
+ }
+}
+exports.selectDeviceByTarget = selectDeviceByTarget;
+async function selectHardwareDevice(devices) {
+ const hardwareDevices = devices.filter(d => d.type === 'hardware');
+ // If a hardware device is found, we prefer launching to it instead of in an emulator.
+ if (hardwareDevices.length > 0) {
+ return hardwareDevices[0]; // TODO: can probably do better analysis on which to use?
+ }
+}
+exports.selectHardwareDevice = selectHardwareDevice;
+async function selectVirtualDevice(sdk, devices, avds) {
+ const debug = Debug(`${modulePrefix}:${selectVirtualDevice.name}`);
+ const emulators = devices.filter(d => d.type === 'emulator');
+ // If an emulator is running, use it.
+ if (emulators.length > 0) {
+ const [emulator] = emulators;
+ debug('Found running emulator: %s', emulator.serial);
+ return emulator;
+ }
+ // Spin up an emulator using the AVD we ship with.
+ const defaultAvd = await avd_1.getDefaultAVD(sdk, avds);
+ const device = await emulator_1.runEmulator(sdk, defaultAvd, 5554); // TODO: will 5554 always be available at this point?
+ debug('Emulator ready, running avd: %s on %s', defaultAvd.id, device.serial);
+ return device;
+}
+exports.selectVirtualDevice = selectVirtualDevice;
+async function installApkToDevice(sdk, device, apk, appId) {
+ log_1.log(`Installing ${apk}...\n`);
+ try {
+ await adb_1.installApk(sdk, device, apk);
+ }
+ catch (e) {
+ if (e instanceof errors_1.ADBException) {
+ if (e.code === errors_1.ERR_INCOMPATIBLE_UPDATE ||
+ e.code === errors_1.ERR_VERSION_DOWNGRADE) {
+ log_1.log(`${e.message} Uninstalling and trying again...\n`);
+ await adb_1.uninstallApp(sdk, device, appId);
+ await adb_1.installApk(sdk, device, apk);
+ return;
+ }
+ }
+ throw e;
+ }
+}
+exports.installApkToDevice = installApkToDevice;
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/dist/android/utils/sdk/api.js b/temporary_modules/trezor-connect/node_modules/native-run/dist/android/utils/sdk/api.js
new file mode 100644
index 00000000..40e30c67
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/native-run/dist/android/utils/sdk/api.js
@@ -0,0 +1,243 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+exports.API_LEVEL_SCHEMAS = exports.API_LEVEL_24 = exports.API_LEVEL_25 = exports.API_LEVEL_26 = exports.API_LEVEL_27 = exports.API_LEVEL_28 = exports.API_LEVEL_29 = exports.API_LEVEL_30 = exports.API_LEVEL_31 = exports.findPackageBySchemaPath = exports.findPackageBySchema = exports.findUnsatisfiedPackages = exports.getAPILevels = void 0;
+const Debug = require("debug");
+const modulePrefix = 'native-run:android:utils:sdk:api';
+async function getAPILevels(packages) {
+ const debug = Debug(`${modulePrefix}:${getAPILevels.name}`);
+ const levels = [
+ ...new Set(packages
+ .map(pkg => pkg.apiLevel)
+ .filter((apiLevel) => typeof apiLevel !== 'undefined')),
+ ].sort((a, b) => (a <= b ? 1 : -1));
+ const apis = levels.map(apiLevel => ({
+ apiLevel,
+ packages: packages.filter(pkg => pkg.apiLevel === apiLevel),
+ }));
+ debug('Discovered installed API Levels: %O', apis.map(api => ({ ...api, packages: api.packages.map(pkg => pkg.path) })));
+ return apis;
+}
+exports.getAPILevels = getAPILevels;
+function findUnsatisfiedPackages(packages, schemas) {
+ return schemas.filter(pkg => !findPackageBySchema(packages, pkg));
+}
+exports.findUnsatisfiedPackages = findUnsatisfiedPackages;
+function findPackageBySchema(packages, pkg) {
+ const apiPkg = findPackageBySchemaPath(packages, pkg.path);
+ if (apiPkg) {
+ if (typeof pkg.version === 'string') {
+ if (pkg.version === apiPkg.version) {
+ return apiPkg;
+ }
+ }
+ else {
+ if (apiPkg.version.match(pkg.version)) {
+ return apiPkg;
+ }
+ }
+ }
+}
+exports.findPackageBySchema = findPackageBySchema;
+function findPackageBySchemaPath(packages, path) {
+ return packages.find(pkg => {
+ if (typeof path !== 'string') {
+ return !!pkg.path.match(path);
+ }
+ return path === pkg.path;
+ });
+}
+exports.findPackageBySchemaPath = findPackageBySchemaPath;
+exports.API_LEVEL_31 = Object.freeze({
+ apiLevel: '31',
+ validate: (packages) => {
+ const schemas = [
+ { name: 'Android Emulator', path: 'emulator', version: /.+/ },
+ {
+ name: 'Android SDK Platform 31',
+ path: 'platforms;android-31',
+ version: /.+/,
+ },
+ ];
+ const missingPackages = findUnsatisfiedPackages(packages, schemas);
+ if (!findPackageBySchemaPath(packages, /^system-images;android-31;/)) {
+ missingPackages.push({
+ name: 'Google Play Intel x86 Atom System Image',
+ path: 'system-images;android-31;google_apis_playstore;x86',
+ version: '/.+/',
+ });
+ }
+ return missingPackages;
+ },
+ loadPartialAVDSchematic: async () => Promise.resolve().then(() => require('../../data/avds/Pixel_3_API_31.json')),
+});
+exports.API_LEVEL_30 = Object.freeze({
+ apiLevel: '30',
+ validate: (packages) => {
+ const schemas = [
+ { name: 'Android Emulator', path: 'emulator', version: /.+/ },
+ {
+ name: 'Android SDK Platform 30',
+ path: 'platforms;android-30',
+ version: /.+/,
+ },
+ ];
+ const missingPackages = findUnsatisfiedPackages(packages, schemas);
+ if (!findPackageBySchemaPath(packages, /^system-images;android-30;/)) {
+ missingPackages.push({
+ name: 'Google Play Intel x86 Atom System Image',
+ path: 'system-images;android-30;google_apis_playstore;x86',
+ version: '/.+/',
+ });
+ }
+ return missingPackages;
+ },
+ loadPartialAVDSchematic: async () => Promise.resolve().then(() => require('../../data/avds/Pixel_3_API_30.json')),
+});
+exports.API_LEVEL_29 = Object.freeze({
+ apiLevel: '29',
+ validate: (packages) => {
+ const schemas = [
+ { name: 'Android Emulator', path: 'emulator', version: /.+/ },
+ {
+ name: 'Android SDK Platform 29',
+ path: 'platforms;android-29',
+ version: /.+/,
+ },
+ ];
+ const missingPackages = findUnsatisfiedPackages(packages, schemas);
+ if (!findPackageBySchemaPath(packages, /^system-images;android-29;/)) {
+ missingPackages.push({
+ name: 'Google Play Intel x86 Atom System Image',
+ path: 'system-images;android-29;google_apis_playstore;x86',
+ version: '/.+/',
+ });
+ }
+ return missingPackages;
+ },
+ loadPartialAVDSchematic: async () => Promise.resolve().then(() => require('../../data/avds/Pixel_3_API_29.json')),
+});
+exports.API_LEVEL_28 = Object.freeze({
+ apiLevel: '28',
+ validate: (packages) => {
+ const schemas = [
+ { name: 'Android Emulator', path: 'emulator', version: /.+/ },
+ {
+ name: 'Android SDK Platform 28',
+ path: 'platforms;android-28',
+ version: /.+/,
+ },
+ ];
+ const missingPackages = findUnsatisfiedPackages(packages, schemas);
+ if (!findPackageBySchemaPath(packages, /^system-images;android-28;/)) {
+ missingPackages.push({
+ name: 'Google Play Intel x86 Atom System Image',
+ path: 'system-images;android-28;google_apis_playstore;x86',
+ version: '/.+/',
+ });
+ }
+ return missingPackages;
+ },
+ loadPartialAVDSchematic: async () => Promise.resolve().then(() => require('../../data/avds/Pixel_2_API_28.json')),
+});
+exports.API_LEVEL_27 = Object.freeze({
+ apiLevel: '27',
+ validate: (packages) => {
+ const schemas = [
+ { name: 'Android Emulator', path: 'emulator', version: /.+/ },
+ {
+ name: 'Android SDK Platform 27',
+ path: 'platforms;android-27',
+ version: /.+/,
+ },
+ ];
+ const missingPackages = findUnsatisfiedPackages(packages, schemas);
+ if (!findPackageBySchemaPath(packages, /^system-images;android-27;/)) {
+ missingPackages.push({
+ name: 'Google Play Intel x86 Atom System Image',
+ path: 'system-images;android-27;google_apis_playstore;x86',
+ version: '/.+/',
+ });
+ }
+ return missingPackages;
+ },
+ loadPartialAVDSchematic: async () => Promise.resolve().then(() => require('../../data/avds/Pixel_2_API_27.json')),
+});
+exports.API_LEVEL_26 = Object.freeze({
+ apiLevel: '26',
+ validate: (packages) => {
+ const schemas = [
+ { name: 'Android Emulator', path: 'emulator', version: /.+/ },
+ {
+ name: 'Android SDK Platform 26',
+ path: 'platforms;android-26',
+ version: /.+/,
+ },
+ ];
+ const missingPackages = findUnsatisfiedPackages(packages, schemas);
+ if (!findPackageBySchemaPath(packages, /^system-images;android-26;/)) {
+ missingPackages.push({
+ name: 'Google Play Intel x86 Atom System Image',
+ path: 'system-images;android-26;google_apis_playstore;x86',
+ version: '/.+/',
+ });
+ }
+ return missingPackages;
+ },
+ loadPartialAVDSchematic: async () => Promise.resolve().then(() => require('../../data/avds/Pixel_2_API_26.json')),
+});
+exports.API_LEVEL_25 = Object.freeze({
+ apiLevel: '25',
+ validate: (packages) => {
+ const schemas = [
+ { name: 'Android Emulator', path: 'emulator', version: /.+/ },
+ {
+ name: 'Android SDK Platform 25',
+ path: 'platforms;android-25',
+ version: /.+/,
+ },
+ ];
+ const missingPackages = findUnsatisfiedPackages(packages, schemas);
+ if (!findPackageBySchemaPath(packages, /^system-images;android-25;/)) {
+ missingPackages.push({
+ name: 'Google Play Intel x86 Atom System Image',
+ path: 'system-images;android-25;google_apis_playstore;x86',
+ version: '/.+/',
+ });
+ }
+ return missingPackages;
+ },
+ loadPartialAVDSchematic: async () => Promise.resolve().then(() => require('../../data/avds/Pixel_API_25.json')),
+});
+exports.API_LEVEL_24 = Object.freeze({
+ apiLevel: '24',
+ validate: (packages) => {
+ const schemas = [
+ { name: 'Android Emulator', path: 'emulator', version: /.+/ },
+ {
+ name: 'Android SDK Platform 24',
+ path: 'platforms;android-24',
+ version: /.+/,
+ },
+ ];
+ const missingPackages = findUnsatisfiedPackages(packages, schemas);
+ if (!findPackageBySchemaPath(packages, /^system-images;android-24;/)) {
+ missingPackages.push({
+ name: 'Google Play Intel x86 Atom System Image',
+ path: 'system-images;android-24;google_apis_playstore;x86',
+ version: '/.+/',
+ });
+ }
+ return missingPackages;
+ },
+ loadPartialAVDSchematic: async () => Promise.resolve().then(() => require('../../data/avds/Nexus_5X_API_24.json')),
+});
+exports.API_LEVEL_SCHEMAS = [
+ exports.API_LEVEL_31,
+ exports.API_LEVEL_30,
+ exports.API_LEVEL_29,
+ exports.API_LEVEL_28,
+ exports.API_LEVEL_27,
+ exports.API_LEVEL_26,
+ exports.API_LEVEL_25,
+ exports.API_LEVEL_24,
+];
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/dist/android/utils/sdk/index.js b/temporary_modules/trezor-connect/node_modules/native-run/dist/android/utils/sdk/index.js
new file mode 100644
index 00000000..00828cc4
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/native-run/dist/android/utils/sdk/index.js
@@ -0,0 +1,176 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+exports.supplementProcessEnv = exports.resolveAVDHome = exports.resolveEmulatorHome = exports.resolveSDKRoot = exports.getSDKPackage = exports.findAllSDKPackages = exports.getSDK = exports.SDK_DIRECTORIES = void 0;
+const utils_fs_1 = require("@ionic/utils-fs");
+const Debug = require("debug");
+const os = require("os");
+const pathlib = require("path");
+const errors_1 = require("../../../errors");
+const fs_1 = require("../../../utils/fs");
+const xml_1 = require("./xml");
+const modulePrefix = 'native-run:android:utils:sdk';
+const homedir = os.homedir();
+exports.SDK_DIRECTORIES = new Map([
+ ['darwin', [pathlib.join(homedir, 'Library', 'Android', 'sdk')]],
+ ['linux', [pathlib.join(homedir, 'Android', 'sdk')]],
+ [
+ 'win32',
+ [
+ pathlib.join(process.env.LOCALAPPDATA || pathlib.join(homedir, 'AppData', 'Local'), 'Android', 'Sdk'),
+ ],
+ ],
+]);
+async function getSDK() {
+ const root = await resolveSDKRoot();
+ const emulatorHome = await resolveEmulatorHome();
+ const avdHome = await resolveAVDHome();
+ return { root, emulatorHome, avdHome };
+}
+exports.getSDK = getSDK;
+const pkgcache = new Map();
+async function findAllSDKPackages(sdk) {
+ const debug = Debug(`${modulePrefix}:${findAllSDKPackages.name}`);
+ if (sdk.packages) {
+ return sdk.packages;
+ }
+ const sourcesRe = /^sources\/android-\d+\/.+\/.+/;
+ debug('Walking %s to discover SDK packages', sdk.root);
+ const contents = await utils_fs_1.readdirp(sdk.root, {
+ filter: item => pathlib.basename(item.path) === 'package.xml',
+ onError: err => debug('Error while walking SDK: %O', err),
+ walkerOptions: {
+ pathFilter: p => {
+ if ([
+ 'bin',
+ 'bin64',
+ 'lib',
+ 'lib64',
+ 'include',
+ 'clang-include',
+ 'skins',
+ 'data',
+ 'examples',
+ 'resources',
+ 'systrace',
+ 'extras',
+ ].includes(pathlib.basename(p))) {
+ return false;
+ }
+ if (p.match(sourcesRe)) {
+ return false;
+ }
+ return true;
+ },
+ },
+ });
+ sdk.packages = await Promise.all(contents.map(p => pathlib.dirname(p)).map(p => getSDKPackage(p)));
+ sdk.packages.sort((a, b) => (a.name >= b.name ? 1 : -1));
+ return sdk.packages;
+}
+exports.findAllSDKPackages = findAllSDKPackages;
+async function getSDKPackage(location) {
+ const debug = Debug(`${modulePrefix}:${getSDKPackage.name}`);
+ let pkg = pkgcache.get(location);
+ if (!pkg) {
+ const packageXmlPath = pathlib.join(location, 'package.xml');
+ debug('Parsing %s', packageXmlPath);
+ try {
+ const packageXml = await xml_1.readPackageXml(packageXmlPath);
+ const name = xml_1.getNameFromPackageXml(packageXml);
+ const version = xml_1.getVersionFromPackageXml(packageXml);
+ const path = xml_1.getPathFromPackageXml(packageXml);
+ const apiLevel = xml_1.getAPILevelFromPackageXml(packageXml);
+ pkg = {
+ path,
+ location,
+ version,
+ name,
+ apiLevel,
+ };
+ }
+ catch (e) {
+ debug('Encountered error with %s: %O', packageXmlPath, e);
+ if (e.code === 'ENOENT') {
+ throw new errors_1.SDKException(`SDK package not found by location: ${location}.`, errors_1.ERR_SDK_PACKAGE_NOT_FOUND);
+ }
+ throw e;
+ }
+ pkgcache.set(location, pkg);
+ }
+ return pkg;
+}
+exports.getSDKPackage = getSDKPackage;
+async function resolveSDKRoot() {
+ const debug = Debug(`${modulePrefix}:${resolveSDKRoot.name}`);
+ debug('Looking for $ANDROID_HOME');
+ // $ANDROID_HOME is deprecated, but still overrides $ANDROID_SDK_ROOT if
+ // defined and valid.
+ if (process.env.ANDROID_HOME && (await fs_1.isDir(process.env.ANDROID_HOME))) {
+ debug('Using $ANDROID_HOME at %s', process.env.ANDROID_HOME);
+ return process.env.ANDROID_HOME;
+ }
+ debug('Looking for $ANDROID_SDK_ROOT');
+ // No valid $ANDROID_HOME, try $ANDROID_SDK_ROOT.
+ if (process.env.ANDROID_SDK_ROOT &&
+ (await fs_1.isDir(process.env.ANDROID_SDK_ROOT))) {
+ debug('Using $ANDROID_SDK_ROOT at %s', process.env.ANDROID_SDK_ROOT);
+ return process.env.ANDROID_SDK_ROOT;
+ }
+ const sdkDirs = exports.SDK_DIRECTORIES.get(process.platform);
+ if (!sdkDirs) {
+ throw new errors_1.SDKException(`Unsupported platform: ${process.platform}`);
+ }
+ debug('Looking at following directories: %O', sdkDirs);
+ for (const sdkDir of sdkDirs) {
+ if (await fs_1.isDir(sdkDir)) {
+ debug('Using %s', sdkDir);
+ return sdkDir;
+ }
+ }
+ throw new errors_1.SDKException(`No valid Android SDK root found.`, errors_1.ERR_SDK_NOT_FOUND);
+}
+exports.resolveSDKRoot = resolveSDKRoot;
+async function resolveEmulatorHome() {
+ const debug = Debug(`${modulePrefix}:${resolveEmulatorHome.name}`);
+ debug('Looking for $ANDROID_EMULATOR_HOME');
+ if (process.env.ANDROID_EMULATOR_HOME &&
+ (await fs_1.isDir(process.env.ANDROID_EMULATOR_HOME))) {
+ debug('Using $ANDROID_EMULATOR_HOME at %s', process.env.$ANDROID_EMULATOR_HOME);
+ return process.env.ANDROID_EMULATOR_HOME;
+ }
+ debug('Looking at $HOME/.android');
+ const homeEmulatorHome = pathlib.join(homedir, '.android');
+ if (await fs_1.isDir(homeEmulatorHome)) {
+ debug('Using $HOME/.android/ at %s', homeEmulatorHome);
+ return homeEmulatorHome;
+ }
+ throw new errors_1.SDKException(`No valid Android Emulator home found.`, errors_1.ERR_EMULATOR_HOME_NOT_FOUND);
+}
+exports.resolveEmulatorHome = resolveEmulatorHome;
+async function resolveAVDHome() {
+ const debug = Debug(`${modulePrefix}:${resolveAVDHome.name}`);
+ debug('Looking for $ANDROID_AVD_HOME');
+ if (process.env.ANDROID_AVD_HOME &&
+ (await fs_1.isDir(process.env.ANDROID_AVD_HOME))) {
+ debug('Using $ANDROID_AVD_HOME at %s', process.env.$ANDROID_AVD_HOME);
+ return process.env.ANDROID_AVD_HOME;
+ }
+ debug('Looking at $HOME/.android/avd');
+ const homeAvdHome = pathlib.join(homedir, '.android', 'avd');
+ if (!(await fs_1.isDir(homeAvdHome))) {
+ debug('Creating directory: %s', homeAvdHome);
+ await utils_fs_1.mkdirp(homeAvdHome);
+ }
+ debug('Using $HOME/.android/avd/ at %s', homeAvdHome);
+ return homeAvdHome;
+}
+exports.resolveAVDHome = resolveAVDHome;
+function supplementProcessEnv(sdk) {
+ return {
+ ...process.env,
+ ANDROID_SDK_ROOT: sdk.root,
+ ANDROID_EMULATOR_HOME: sdk.emulatorHome,
+ ANDROID_AVD_HOME: sdk.avdHome,
+ };
+}
+exports.supplementProcessEnv = supplementProcessEnv;
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/dist/android/utils/sdk/xml.js b/temporary_modules/trezor-connect/node_modules/native-run/dist/android/utils/sdk/xml.js
new file mode 100644
index 00000000..7c8f65bc
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/native-run/dist/android/utils/sdk/xml.js
@@ -0,0 +1,58 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+exports.getVersionFromPackageXml = exports.getNameFromPackageXml = exports.getPathFromPackageXml = exports.readPackageXml = exports.getAPILevelFromPackageXml = void 0;
+const utils_fs_1 = require("@ionic/utils-fs");
+const errors_1 = require("../../../errors");
+function getAPILevelFromPackageXml(packageXml) {
+ var _a;
+ const apiLevel = packageXml.find('./localPackage/type-details/api-level');
+ return (_a = apiLevel === null || apiLevel === void 0 ? void 0 : apiLevel.text) === null || _a === void 0 ? void 0 : _a.toString();
+}
+exports.getAPILevelFromPackageXml = getAPILevelFromPackageXml;
+async function readPackageXml(path) {
+ const et = await Promise.resolve().then(() => require('elementtree'));
+ const contents = await utils_fs_1.readFile(path, { encoding: 'utf8' });
+ const etree = et.parse(contents);
+ return etree;
+}
+exports.readPackageXml = readPackageXml;
+function getPathFromPackageXml(packageXml) {
+ const localPackage = packageXml.find('./localPackage');
+ if (!localPackage) {
+ throw new errors_1.SDKException(`Invalid SDK package.`, errors_1.ERR_INVALID_SDK_PACKAGE);
+ }
+ const path = localPackage.get('path');
+ if (!path) {
+ throw new errors_1.SDKException(`Invalid SDK package path.`, errors_1.ERR_INVALID_SDK_PACKAGE);
+ }
+ return path.toString();
+}
+exports.getPathFromPackageXml = getPathFromPackageXml;
+function getNameFromPackageXml(packageXml) {
+ const name = packageXml.find('./localPackage/display-name');
+ if (!name || !name.text) {
+ throw new errors_1.SDKException(`Invalid SDK package name.`, errors_1.ERR_INVALID_SDK_PACKAGE);
+ }
+ return name.text.toString();
+}
+exports.getNameFromPackageXml = getNameFromPackageXml;
+function getVersionFromPackageXml(packageXml) {
+ const versionElements = [
+ packageXml.find('./localPackage/revision/major'),
+ packageXml.find('./localPackage/revision/minor'),
+ packageXml.find('./localPackage/revision/micro'),
+ ];
+ const textFromElement = (e) => (e === null || e === void 0 ? void 0 : e.text) ? e.text.toString() : '';
+ const versions = [];
+ for (const version of versionElements.map(textFromElement)) {
+ if (!version) {
+ break;
+ }
+ versions.push(version);
+ }
+ if (versions.length === 0) {
+ throw new errors_1.SDKException(`Invalid SDK package version.`, errors_1.ERR_INVALID_SDK_PACKAGE);
+ }
+ return versions.join('.');
+}
+exports.getVersionFromPackageXml = getVersionFromPackageXml;
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/dist/constants.js b/temporary_modules/trezor-connect/node_modules/native-run/dist/constants.js
new file mode 100644
index 00000000..ecf85e1c
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/native-run/dist/constants.js
@@ -0,0 +1,5 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+exports.ASSETS_PATH = void 0;
+const pathlib = require("path");
+exports.ASSETS_PATH = pathlib.resolve(__dirname, '..', 'assets');
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/dist/errors.js b/temporary_modules/trezor-connect/node_modules/native-run/dist/errors.js
new file mode 100644
index 00000000..4e948960
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/native-run/dist/errors.js
@@ -0,0 +1,88 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+exports.serializeError = exports.IOSRunException = exports.SDKException = exports.AndroidRunException = exports.EmulatorException = exports.AVDException = exports.ADBException = exports.CLIException = exports.ERR_UNSUPPORTED_API_LEVEL = exports.ERR_UNKNOWN_AVD = exports.ERR_DEVICE_LOCKED = exports.ERR_NO_TARGET = exports.ERR_NO_DEVICE = exports.ERR_TARGET_NOT_FOUND = exports.ERR_SDK_UNSATISFIED_PACKAGES = exports.ERR_SDK_PACKAGE_NOT_FOUND = exports.ERR_SDK_NOT_FOUND = exports.ERR_UNSUITABLE_API_INSTALLATION = exports.ERR_MISSING_SYSTEM_IMAGE = exports.ERR_NO_AVDS_FOUND = exports.ERR_NON_ZERO_EXIT = exports.ERR_INVALID_SYSTEM_IMAGE = exports.ERR_INVALID_SKIN = exports.ERR_INVALID_SERIAL = exports.ERR_INVALID_SDK_PACKAGE = exports.ERR_DEVICE_OFFLINE = exports.ERR_NOT_ENOUGH_SPACE = exports.ERR_NO_CERTIFICATES = exports.ERR_MIN_SDK_VERSION = exports.ERR_VERSION_DOWNGRADE = exports.ERR_INCOMPATIBLE_UPDATE = exports.ERR_EMULATOR_HOME_NOT_FOUND = exports.ERR_AVD_HOME_NOT_FOUND = exports.ERR_ALREADY_RUNNING = exports.ERR_BAD_INPUT = exports.AndroidException = exports.Exception = void 0;
+const json_1 = require("./utils/json");
+class Exception extends Error {
+ constructor(message, code, exitCode = 1 /* GENERAL */, data) {
+ super(message);
+ this.message = message;
+ this.code = code;
+ this.exitCode = exitCode;
+ this.data = data;
+ }
+ serialize() {
+ return `${this.code ? this.code : 'ERR_UNKNOWN'}: ${this.message}`;
+ }
+ toJSON() {
+ return {
+ error: this.message,
+ code: this.code,
+ ...this.data,
+ };
+ }
+}
+exports.Exception = Exception;
+class AndroidException extends Exception {
+ serialize() {
+ return (`${super.serialize()}\n\n` +
+ `\tMore details for this error may be available online:\n\n` +
+ `\thttps://github.com/ionic-team/native-run/wiki/Android-Errors`);
+ }
+}
+exports.AndroidException = AndroidException;
+exports.ERR_BAD_INPUT = 'ERR_BAD_INPUT';
+exports.ERR_ALREADY_RUNNING = 'ERR_ALREADY_RUNNING ';
+exports.ERR_AVD_HOME_NOT_FOUND = 'ERR_AVD_HOME_NOT_FOUND';
+exports.ERR_EMULATOR_HOME_NOT_FOUND = 'ERR_EMULATOR_HOME_NOT_FOUND';
+exports.ERR_INCOMPATIBLE_UPDATE = 'ERR_INCOMPATIBLE_UPDATE';
+exports.ERR_VERSION_DOWNGRADE = 'ERR_VERSION_DOWNGRADE';
+exports.ERR_MIN_SDK_VERSION = 'ERR_MIN_SDK_VERSION';
+exports.ERR_NO_CERTIFICATES = 'ERR_NO_CERTIFICATES';
+exports.ERR_NOT_ENOUGH_SPACE = 'ERR_NOT_ENOUGH_SPACE';
+exports.ERR_DEVICE_OFFLINE = 'ERR_DEVICE_OFFLINE';
+exports.ERR_INVALID_SDK_PACKAGE = 'ERR_INVALID_SDK_PACKAGE';
+exports.ERR_INVALID_SERIAL = 'ERR_INVALID_SERIAL';
+exports.ERR_INVALID_SKIN = 'ERR_INVALID_SKIN';
+exports.ERR_INVALID_SYSTEM_IMAGE = 'ERR_INVALID_SYSTEM_IMAGE';
+exports.ERR_NON_ZERO_EXIT = 'ERR_NON_ZERO_EXIT';
+exports.ERR_NO_AVDS_FOUND = 'ERR_NO_AVDS_FOUND';
+exports.ERR_MISSING_SYSTEM_IMAGE = 'ERR_MISSING_SYSTEM_IMAGE';
+exports.ERR_UNSUITABLE_API_INSTALLATION = 'ERR_UNSUITABLE_API_INSTALLATION';
+exports.ERR_SDK_NOT_FOUND = 'ERR_SDK_NOT_FOUND';
+exports.ERR_SDK_PACKAGE_NOT_FOUND = 'ERR_SDK_PACKAGE_NOT_FOUND';
+exports.ERR_SDK_UNSATISFIED_PACKAGES = 'ERR_SDK_UNSATISFIED_PACKAGES';
+exports.ERR_TARGET_NOT_FOUND = 'ERR_TARGET_NOT_FOUND';
+exports.ERR_NO_DEVICE = 'ERR_NO_DEVICE';
+exports.ERR_NO_TARGET = 'ERR_NO_TARGET';
+exports.ERR_DEVICE_LOCKED = 'ERR_DEVICE_LOCKED';
+exports.ERR_UNKNOWN_AVD = 'ERR_UNKNOWN_AVD';
+exports.ERR_UNSUPPORTED_API_LEVEL = 'ERR_UNSUPPORTED_API_LEVEL';
+class CLIException extends Exception {
+}
+exports.CLIException = CLIException;
+class ADBException extends AndroidException {
+}
+exports.ADBException = ADBException;
+class AVDException extends AndroidException {
+}
+exports.AVDException = AVDException;
+class EmulatorException extends AndroidException {
+}
+exports.EmulatorException = EmulatorException;
+class AndroidRunException extends AndroidException {
+}
+exports.AndroidRunException = AndroidRunException;
+class SDKException extends AndroidException {
+}
+exports.SDKException = SDKException;
+class IOSRunException extends Exception {
+}
+exports.IOSRunException = IOSRunException;
+function serializeError(e = new Error()) {
+ const stack = String(e.stack ? e.stack : e);
+ if (process.argv.includes('--json')) {
+ return json_1.stringify(e instanceof Exception ? e : { error: stack });
+ }
+ return (e instanceof Exception ? e.serialize() : stack) + '\n';
+}
+exports.serializeError = serializeError;
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/dist/help.js b/temporary_modules/trezor-connect/node_modules/native-run/dist/help.js
new file mode 100644
index 00000000..093acc8a
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/native-run/dist/help.js
@@ -0,0 +1,18 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+exports.run = void 0;
+const help = `
+ Usage: native-run [ios|android] [options]
+
+ Options:
+
+ -h, --help ........... Print help for the platform, then quit
+ --version ............ Print version, then quit
+ --verbose ............ Print verbose output to stderr
+ --list ............... Print connected devices and virtual devices
+
+`;
+async function run(args) {
+ process.stdout.write(help);
+}
+exports.run = run;
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/dist/index.js b/temporary_modules/trezor-connect/node_modules/native-run/dist/index.js
new file mode 100644
index 00000000..1e262133
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/native-run/dist/index.js
@@ -0,0 +1,48 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+exports.run = void 0;
+const Debug = require("debug");
+const path = require("path");
+const errors_1 = require("./errors");
+const debug = Debug('native-run');
+async function run() {
+ const args = process.argv.slice(2);
+ if (args.includes('--version')) {
+ const pkg = await Promise.resolve().then(() => require(path.resolve(__dirname, '../package.json')));
+ process.stdout.write(pkg.version + '\n');
+ return;
+ }
+ let cmd;
+ const [platform, ...platformArgs] = args;
+ try {
+ if (platform === 'android') {
+ cmd = await Promise.resolve().then(() => require('./android'));
+ await cmd.run(platformArgs);
+ }
+ else if (platform === 'ios') {
+ cmd = await Promise.resolve().then(() => require('./ios'));
+ await cmd.run(platformArgs);
+ }
+ else if (platform === '--list') {
+ cmd = await Promise.resolve().then(() => require('./list'));
+ await cmd.run(args);
+ }
+ else {
+ if (!platform ||
+ platform === 'help' ||
+ args.includes('--help') ||
+ args.includes('-h') ||
+ platform.startsWith('-')) {
+ cmd = await Promise.resolve().then(() => require('./help'));
+ return cmd.run(args);
+ }
+ throw new errors_1.CLIException(`Unsupported platform: "${platform}"`, errors_1.ERR_BAD_INPUT);
+ }
+ }
+ catch (e) {
+ debug('Caught fatal error: %O', e);
+ process.exitCode = e instanceof errors_1.Exception ? e.exitCode : 1 /* GENERAL */;
+ process.stdout.write(errors_1.serializeError(e));
+ }
+}
+exports.run = run;
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/dist/ios/help.js b/temporary_modules/trezor-connect/node_modules/native-run/dist/ios/help.js
new file mode 100644
index 00000000..25a65155
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/native-run/dist/ios/help.js
@@ -0,0 +1,35 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+exports.run = void 0;
+const help = `
+ Usage: native-run ios [options]
+
+ Run an .app or .ipa on a device or simulator target
+
+ Targets are selected as follows:
+ 1) --target using device/simulator UUID
+ 2) A connected device, unless --virtual is used
+ 3) A running simulator
+
+ If the above criteria are not met, the app is run on the default simulator
+ (the last simulator in the list).
+
+ Use --list to list available targets.
+
+ Options:
+
+ --list ............... Print available targets, then quit
+ --json ............... Output JSON
+
+ --app ......... Deploy specified .app or .ipa file
+ --device ............. Use a device if available
+ With --list prints connected devices
+ --virtual ............ Prefer a simulator
+ With --list prints available simulators
+ --target ........ Use a specific target
+ --connect ............ Tie process to app process
+`;
+async function run() {
+ process.stdout.write(`${help}\n`);
+}
+exports.run = run;
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/dist/ios/index.js b/temporary_modules/trezor-connect/node_modules/native-run/dist/ios/index.js
new file mode 100644
index 00000000..23d3af19
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/native-run/dist/ios/index.js
@@ -0,0 +1,17 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+exports.run = void 0;
+async function run(args) {
+ let cmd;
+ if (args.includes('--help') || args.includes('-h')) {
+ cmd = await Promise.resolve().then(() => require('./help'));
+ return cmd.run(args);
+ }
+ if (args.includes('--list') || args.includes('-l')) {
+ cmd = await Promise.resolve().then(() => require('./list'));
+ return cmd.run(args);
+ }
+ cmd = await Promise.resolve().then(() => require('./run'));
+ await cmd.run(args);
+}
+exports.run = run;
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/dist/ios/lib/client/afc.js b/temporary_modules/trezor-connect/node_modules/native-run/dist/ios/lib/client/afc.js
new file mode 100644
index 00000000..afb1c3fe
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/native-run/dist/ios/lib/client/afc.js
@@ -0,0 +1,164 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+exports.AFCClient = void 0;
+const Debug = require("debug");
+const fs = require("fs");
+const path = require("path");
+const util_1 = require("util");
+const afc_1 = require("../protocol/afc");
+const client_1 = require("./client");
+const debug = Debug('native-run:ios:lib:client:afc');
+const MAX_OPEN_FILES = 240;
+class AFCClient extends client_1.ServiceClient {
+ constructor(socket) {
+ super(socket, new afc_1.AFCProtocolClient(socket));
+ this.socket = socket;
+ }
+ async getFileInfo(path) {
+ debug(`getFileInfo: ${path}`);
+ const resp = await this.protocolClient.sendMessage({
+ operation: afc_1.AFC_OPS.GET_FILE_INFO,
+ data: toCString(path),
+ });
+ const strings = [];
+ let currentString = '';
+ const tokens = resp.data;
+ tokens.forEach(token => {
+ if (token === 0) {
+ strings.push(currentString);
+ currentString = '';
+ }
+ else {
+ currentString += String.fromCharCode(token);
+ }
+ });
+ return strings;
+ }
+ async writeFile(fd, data) {
+ debug(`writeFile: ${Array.prototype.toString.call(fd)}`);
+ return this.protocolClient.sendMessage({
+ operation: afc_1.AFC_OPS.FILE_WRITE,
+ data: fd,
+ payload: data,
+ });
+ }
+ async openFile(path) {
+ debug(`openFile: ${path}`);
+ // mode + path + null terminator
+ const data = Buffer.alloc(8 + path.length + 1);
+ // write mode
+ data.writeUInt32LE(afc_1.AFC_FILE_OPEN_FLAGS.WRONLY, 0);
+ // then path to file
+ toCString(path).copy(data, 8);
+ const resp = await this.protocolClient.sendMessage({
+ operation: afc_1.AFC_OPS.FILE_OPEN,
+ data,
+ });
+ if (resp.operation === afc_1.AFC_OPS.FILE_OPEN_RES) {
+ return resp.data;
+ }
+ throw new Error(`There was an unknown error opening file ${path}, response: ${Array.prototype.toString.call(resp.data)}`);
+ }
+ async closeFile(fd) {
+ debug(`closeFile fd: ${Array.prototype.toString.call(fd)}`);
+ return this.protocolClient.sendMessage({
+ operation: afc_1.AFC_OPS.FILE_CLOSE,
+ data: fd,
+ });
+ }
+ async uploadFile(srcPath, destPath) {
+ debug(`uploadFile: ${srcPath}`);
+ // read local file and get fd of destination
+ const [srcFile, destFile] = await Promise.all([
+ await util_1.promisify(fs.readFile)(srcPath),
+ await this.openFile(destPath),
+ ]);
+ try {
+ await this.writeFile(destFile, srcFile);
+ await this.closeFile(destFile);
+ }
+ catch (err) {
+ await this.closeFile(destFile);
+ throw err;
+ }
+ }
+ async makeDirectory(path) {
+ debug(`makeDirectory: ${path}`);
+ return this.protocolClient.sendMessage({
+ operation: afc_1.AFC_OPS.MAKE_DIR,
+ data: toCString(path),
+ });
+ }
+ async uploadDirectory(srcPath, destPath) {
+ debug(`uploadDirectory: ${srcPath}`);
+ await this.makeDirectory(destPath);
+ // AFC doesn't seem to give out more than 240 file handles,
+ // so we delay any requests that would push us over until more open up
+ let numOpenFiles = 0;
+ const pendingFileUploads = [];
+ const _this = this;
+ return uploadDir(srcPath);
+ async function uploadDir(dirPath) {
+ const promises = [];
+ for (const file of fs.readdirSync(dirPath)) {
+ const filePath = path.join(dirPath, file);
+ const remotePath = path.join(destPath, path.relative(srcPath, filePath));
+ if (fs.lstatSync(filePath).isDirectory()) {
+ promises.push(_this.makeDirectory(remotePath).then(() => uploadDir(filePath)));
+ }
+ else {
+ // Create promise to add to promises array
+ // this way it can be resolved once a pending upload has finished
+ let resolve;
+ let reject;
+ const promise = new Promise((res, rej) => {
+ resolve = res;
+ reject = rej;
+ });
+ promises.push(promise);
+ // wrap upload in a function in case we need to save it for later
+ const uploadFile = (tries = 0) => {
+ numOpenFiles++;
+ _this
+ .uploadFile(filePath, remotePath)
+ .then(() => {
+ resolve();
+ numOpenFiles--;
+ const fn = pendingFileUploads.pop();
+ if (fn) {
+ fn();
+ }
+ })
+ .catch((err) => {
+ // Couldn't get fd for whatever reason, try again
+ // # of retries is arbitrary and can be adjusted
+ if (err.status === afc_1.AFC_STATUS.NO_RESOURCES && tries < 10) {
+ debug(`Received NO_RESOURCES from AFC, retrying ${filePath} upload. ${tries}`);
+ uploadFile(tries++);
+ }
+ else {
+ numOpenFiles--;
+ reject(err);
+ }
+ });
+ };
+ if (numOpenFiles < MAX_OPEN_FILES) {
+ uploadFile();
+ }
+ else {
+ debug(`numOpenFiles >= ${MAX_OPEN_FILES}, adding to pending queue. Length: ${pendingFileUploads.length}`);
+ pendingFileUploads.push(uploadFile);
+ }
+ }
+ }
+ await Promise.all(promises);
+ }
+ }
+}
+exports.AFCClient = AFCClient;
+function toCString(s) {
+ const buf = Buffer.alloc(s.length + 1);
+ const len = buf.write(s);
+ buf.writeUInt8(0, len);
+ return buf;
+}
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/dist/ios/lib/client/client.js b/temporary_modules/trezor-connect/node_modules/native-run/dist/ios/lib/client/client.js
new file mode 100644
index 00000000..9ac2d42d
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/native-run/dist/ios/lib/client/client.js
@@ -0,0 +1,17 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+exports.ResponseError = exports.ServiceClient = void 0;
+class ServiceClient {
+ constructor(socket, protocolClient) {
+ this.socket = socket;
+ this.protocolClient = protocolClient;
+ }
+}
+exports.ServiceClient = ServiceClient;
+class ResponseError extends Error {
+ constructor(msg, response) {
+ super(msg);
+ this.response = response;
+ }
+}
+exports.ResponseError = ResponseError;
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/dist/ios/lib/client/debugserver.js b/temporary_modules/trezor-connect/node_modules/native-run/dist/ios/lib/client/debugserver.js
new file mode 100644
index 00000000..14bbf71d
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/native-run/dist/ios/lib/client/debugserver.js
@@ -0,0 +1,66 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+exports.DebugserverClient = void 0;
+const Debug = require("debug");
+const path = require("path");
+const gdb_1 = require("../protocol/gdb");
+const client_1 = require("./client");
+const debug = Debug('native-run:ios:lib:client:debugserver');
+class DebugserverClient extends client_1.ServiceClient {
+ constructor(socket) {
+ super(socket, new gdb_1.GDBProtocolClient(socket));
+ this.socket = socket;
+ }
+ async setMaxPacketSize(size) {
+ return this.sendCommand('QSetMaxPacketSize:', [size.toString()]);
+ }
+ async setWorkingDir(workingDir) {
+ return this.sendCommand('QSetWorkingDir:', [workingDir]);
+ }
+ async checkLaunchSuccess() {
+ return this.sendCommand('qLaunchSuccess', []);
+ }
+ async attachByName(name) {
+ const hexName = Buffer.from(name).toString('hex');
+ return this.sendCommand(`vAttachName;${hexName}`, []);
+ }
+ async continue() {
+ return this.sendCommand('c', []);
+ }
+ halt() {
+ // ^C
+ debug('Sending ^C to debugserver');
+ return this.protocolClient.socket.write('\u0003');
+ }
+ async kill() {
+ const msg = { cmd: 'k', args: [] };
+ return this.protocolClient.sendMessage(msg, (resp, resolve, reject) => {
+ this.protocolClient.socket.write('+');
+ const parts = resp.split(';');
+ for (const part of parts) {
+ if (part.includes('description')) {
+ // description:{hex encoded message like: "Terminated with signal 9"}
+ resolve(Buffer.from(part.split(':')[1], 'hex').toString('ascii'));
+ }
+ }
+ });
+ }
+ // TODO support app args
+ // https://sourceware.org/gdb/onlinedocs/gdb/Packets.html#Packets
+ // A arglen,argnum,arg,
+ async launchApp(appPath, executableName) {
+ const fullPath = path.join(appPath, executableName);
+ const hexAppPath = Buffer.from(fullPath).toString('hex');
+ const appCommand = `A${hexAppPath.length},0,${hexAppPath}`;
+ return this.sendCommand(appCommand, []);
+ }
+ async sendCommand(cmd, args) {
+ const msg = { cmd, args };
+ debug(`Sending command: ${cmd}, args: ${args}`);
+ const resp = await this.protocolClient.sendMessage(msg);
+ // we need to ACK as well
+ this.protocolClient.socket.write('+');
+ return resp;
+ }
+}
+exports.DebugserverClient = DebugserverClient;
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/dist/ios/lib/client/index.js b/temporary_modules/trezor-connect/node_modules/native-run/dist/ios/lib/client/index.js
new file mode 100644
index 00000000..f1803808
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/native-run/dist/ios/lib/client/index.js
@@ -0,0 +1,10 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+const tslib_1 = require("tslib");
+tslib_1.__exportStar(require("./client"), exports);
+tslib_1.__exportStar(require("./afc"), exports);
+tslib_1.__exportStar(require("./debugserver"), exports);
+tslib_1.__exportStar(require("./installation_proxy"), exports);
+tslib_1.__exportStar(require("./lockdownd"), exports);
+tslib_1.__exportStar(require("./mobile_image_mounter"), exports);
+tslib_1.__exportStar(require("./usbmuxd"), exports);
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/dist/ios/lib/client/installation_proxy.js b/temporary_modules/trezor-connect/node_modules/native-run/dist/ios/lib/client/installation_proxy.js
new file mode 100644
index 00000000..9ec54336
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/native-run/dist/ios/lib/client/installation_proxy.js
@@ -0,0 +1,77 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+exports.InstallationProxyClient = void 0;
+const Debug = require("debug");
+const lockdown_1 = require("../protocol/lockdown");
+const client_1 = require("./client");
+const debug = Debug('native-run:ios:lib:client:installation_proxy');
+function isIPLookupResponse(resp) {
+ return resp.length && resp[0].LookupResult !== undefined;
+}
+function isIPInstallPercentCompleteResponse(resp) {
+ return resp.length && resp[0].PercentComplete !== undefined;
+}
+function isIPInstallCFBundleIdentifierResponse(resp) {
+ return resp.length && resp[0].CFBundleIdentifier !== undefined;
+}
+function isIPInstallCompleteResponse(resp) {
+ return resp.length && resp[0].Status === 'Complete';
+}
+class InstallationProxyClient extends client_1.ServiceClient {
+ constructor(socket) {
+ super(socket, new lockdown_1.LockdownProtocolClient(socket));
+ this.socket = socket;
+ }
+ async lookupApp(bundleIds, options = {
+ ReturnAttributes: [
+ 'Path',
+ 'Container',
+ 'CFBundleExecutable',
+ 'CFBundleIdentifier',
+ ],
+ ApplicationsType: 'Any',
+ }) {
+ debug(`lookupApp, options: ${JSON.stringify(options)}`);
+ const resp = await this.protocolClient.sendMessage({
+ Command: 'Lookup',
+ ClientOptions: {
+ BundleIDs: bundleIds,
+ ...options,
+ },
+ });
+ if (isIPLookupResponse(resp)) {
+ return resp[0].LookupResult;
+ }
+ else {
+ throw new client_1.ResponseError(`There was an error looking up app`, resp);
+ }
+ }
+ async installApp(packagePath, bundleId, options = {
+ ApplicationsType: 'Any',
+ PackageType: 'Developer',
+ }) {
+ debug(`installApp, packagePath: ${packagePath}, bundleId: ${bundleId}`);
+ return this.protocolClient.sendMessage({
+ Command: 'Install',
+ PackagePath: packagePath,
+ ClientOptions: {
+ CFBundleIdentifier: bundleId,
+ ...options,
+ },
+ }, (resp, resolve, reject) => {
+ if (isIPInstallCompleteResponse(resp)) {
+ resolve();
+ }
+ else if (isIPInstallPercentCompleteResponse(resp)) {
+ debug(`Installation status: ${resp[0].Status}, %${resp[0].PercentComplete}`);
+ }
+ else if (isIPInstallCFBundleIdentifierResponse(resp)) {
+ debug(`Installed app: ${resp[0].CFBundleIdentifier}`);
+ }
+ else {
+ reject(new client_1.ResponseError('There was an error installing app', resp));
+ }
+ });
+ }
+}
+exports.InstallationProxyClient = InstallationProxyClient;
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/dist/ios/lib/client/lockdownd.js b/temporary_modules/trezor-connect/node_modules/native-run/dist/ios/lib/client/lockdownd.js
new file mode 100644
index 00000000..dc20470d
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/native-run/dist/ios/lib/client/lockdownd.js
@@ -0,0 +1,115 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+exports.LockdowndClient = void 0;
+const Debug = require("debug");
+const tls = require("tls");
+const lockdown_1 = require("../protocol/lockdown");
+const client_1 = require("./client");
+const debug = Debug('native-run:ios:lib:client:lockdownd');
+function isLockdowndServiceResponse(resp) {
+ return (resp.Request === 'StartService' &&
+ resp.Service !== undefined &&
+ resp.Port !== undefined);
+}
+function isLockdowndSessionResponse(resp) {
+ return resp.Request === 'StartSession';
+}
+function isLockdowndAllValuesResponse(resp) {
+ return resp.Request === 'GetValue' && resp.Value !== undefined;
+}
+function isLockdowndValueResponse(resp) {
+ return (resp.Request === 'GetValue' &&
+ resp.Key !== undefined &&
+ typeof resp.Value === 'string');
+}
+function isLockdowndQueryTypeResponse(resp) {
+ return resp.Request === 'QueryType' && resp.Type !== undefined;
+}
+class LockdowndClient extends client_1.ServiceClient {
+ constructor(socket) {
+ super(socket, new lockdown_1.LockdownProtocolClient(socket));
+ this.socket = socket;
+ }
+ async startService(name) {
+ debug(`startService: ${name}`);
+ const resp = await this.protocolClient.sendMessage({
+ Request: 'StartService',
+ Service: name,
+ });
+ if (isLockdowndServiceResponse(resp)) {
+ return { port: resp.Port, enableServiceSSL: !!resp.EnableServiceSSL };
+ }
+ else {
+ throw new client_1.ResponseError(`Error starting service ${name}`, resp);
+ }
+ }
+ async startSession(pairRecord) {
+ debug(`startSession: ${pairRecord}`);
+ const resp = await this.protocolClient.sendMessage({
+ Request: 'StartSession',
+ HostID: pairRecord.HostID,
+ SystemBUID: pairRecord.SystemBUID,
+ });
+ if (isLockdowndSessionResponse(resp)) {
+ if (resp.EnableSessionSSL) {
+ this.protocolClient.socket = new tls.TLSSocket(this.protocolClient.socket, {
+ secureContext: tls.createSecureContext({
+ secureProtocol: 'TLSv1_method',
+ cert: pairRecord.RootCertificate,
+ key: pairRecord.RootPrivateKey,
+ }),
+ });
+ debug(`Socket upgraded to TLS connection`);
+ }
+ // TODO: save sessionID for StopSession?
+ }
+ else {
+ throw new client_1.ResponseError('Error starting session', resp);
+ }
+ }
+ async getAllValues() {
+ debug(`getAllValues`);
+ const resp = await this.protocolClient.sendMessage({ Request: 'GetValue' });
+ if (isLockdowndAllValuesResponse(resp)) {
+ return resp.Value;
+ }
+ else {
+ throw new client_1.ResponseError('Error getting lockdown value', resp);
+ }
+ }
+ async getValue(val) {
+ debug(`getValue: ${val}`);
+ const resp = await this.protocolClient.sendMessage({
+ Request: 'GetValue',
+ Key: val,
+ });
+ if (isLockdowndValueResponse(resp)) {
+ return resp.Value;
+ }
+ else {
+ throw new client_1.ResponseError('Error getting lockdown value', resp);
+ }
+ }
+ async queryType() {
+ debug('queryType');
+ const resp = await this.protocolClient.sendMessage({
+ Request: 'QueryType',
+ });
+ if (isLockdowndQueryTypeResponse(resp)) {
+ return resp.Type;
+ }
+ else {
+ throw new client_1.ResponseError('Error getting lockdown query type', resp);
+ }
+ }
+ async doHandshake(pairRecord) {
+ debug('doHandshake');
+ // if (await this.lockdownQueryType() !== 'com.apple.mobile.lockdown') {
+ // throw new Error('Invalid type received from lockdown handshake');
+ // }
+ // await this.getLockdownValue('ProductVersion');
+ // TODO: validate pair and pair
+ await this.startSession(pairRecord);
+ }
+}
+exports.LockdowndClient = LockdowndClient;
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/dist/ios/lib/client/mobile_image_mounter.js b/temporary_modules/trezor-connect/node_modules/native-run/dist/ios/lib/client/mobile_image_mounter.js
new file mode 100644
index 00000000..483dfbec
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/native-run/dist/ios/lib/client/mobile_image_mounter.js
@@ -0,0 +1,61 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+exports.MobileImageMounterClient = void 0;
+const Debug = require("debug");
+const fs = require("fs");
+const lockdown_1 = require("../protocol/lockdown");
+const client_1 = require("./client");
+const debug = Debug('native-run:ios:lib:client:mobile_image_mounter');
+function isMIMUploadCompleteResponse(resp) {
+ return resp.Status === 'Complete';
+}
+function isMIMUploadReceiveBytesResponse(resp) {
+ return resp.Status === 'ReceiveBytesAck';
+}
+class MobileImageMounterClient extends client_1.ServiceClient {
+ constructor(socket) {
+ super(socket, new lockdown_1.LockdownProtocolClient(socket));
+ }
+ async mountImage(imagePath, imageSig) {
+ debug(`mountImage: ${imagePath}`);
+ const resp = await this.protocolClient.sendMessage({
+ Command: 'MountImage',
+ ImagePath: imagePath,
+ ImageSignature: imageSig,
+ ImageType: 'Developer',
+ });
+ if (!lockdown_1.isLockdownResponse(resp) || resp.Status !== 'Complete') {
+ throw new client_1.ResponseError(`There was an error mounting ${imagePath} on device`, resp);
+ }
+ }
+ async uploadImage(imagePath, imageSig) {
+ debug(`uploadImage: ${imagePath}`);
+ const imageSize = fs.statSync(imagePath).size;
+ return this.protocolClient.sendMessage({
+ Command: 'ReceiveBytes',
+ ImageSize: imageSize,
+ ImageSignature: imageSig,
+ ImageType: 'Developer',
+ }, (resp, resolve, reject) => {
+ if (isMIMUploadReceiveBytesResponse(resp)) {
+ const imageStream = fs.createReadStream(imagePath);
+ imageStream.pipe(this.protocolClient.socket, { end: false });
+ imageStream.on('error', err => reject(err));
+ }
+ else if (isMIMUploadCompleteResponse(resp)) {
+ resolve();
+ }
+ else {
+ reject(new client_1.ResponseError(`There was an error uploading image ${imagePath} to the device`, resp));
+ }
+ });
+ }
+ async lookupImage() {
+ debug('lookupImage');
+ return this.protocolClient.sendMessage({
+ Command: 'LookupImage',
+ ImageType: 'Developer',
+ });
+ }
+}
+exports.MobileImageMounterClient = MobileImageMounterClient;
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/dist/ios/lib/client/usbmuxd.js b/temporary_modules/trezor-connect/node_modules/native-run/dist/ios/lib/client/usbmuxd.js
new file mode 100644
index 00000000..b7eccd12
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/native-run/dist/ios/lib/client/usbmuxd.js
@@ -0,0 +1,103 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+exports.UsbmuxdClient = void 0;
+const Debug = require("debug");
+const net = require("net");
+const plist = require("plist");
+const usbmux_1 = require("../protocol/usbmux");
+const client_1 = require("./client");
+const debug = Debug('native-run:ios:lib:client:usbmuxd');
+function isUsbmuxdConnectResponse(resp) {
+ return resp.MessageType === 'Result' && resp.Number !== undefined;
+}
+function isUsbmuxdDeviceResponse(resp) {
+ return resp.DeviceList !== undefined;
+}
+function isUsbmuxdPairRecordResponse(resp) {
+ return resp.PairRecordData !== undefined;
+}
+class UsbmuxdClient extends client_1.ServiceClient {
+ constructor(socket) {
+ super(socket, new usbmux_1.UsbmuxProtocolClient(socket));
+ this.socket = socket;
+ }
+ static connectUsbmuxdSocket() {
+ debug('connectUsbmuxdSocket');
+ if ('win32' === process.platform) {
+ return net.connect({ port: 27015, host: 'localhost' });
+ }
+ else {
+ return net.connect({ path: '/var/run/usbmuxd' });
+ }
+ }
+ async connect(device, port) {
+ debug(`connect: ${device.DeviceID} on port ${port}`);
+ const resp = await this.protocolClient.sendMessage({
+ messageType: 'Connect',
+ extraFields: {
+ DeviceID: device.DeviceID,
+ PortNumber: htons(port),
+ },
+ });
+ if (isUsbmuxdConnectResponse(resp) && resp.Number === 0) {
+ return this.protocolClient.socket;
+ }
+ else {
+ throw new client_1.ResponseError(`There was an error connecting to ${device.DeviceID} on port ${port}`, resp);
+ }
+ }
+ async getDevices() {
+ debug('getDevices');
+ const resp = await this.protocolClient.sendMessage({
+ messageType: 'ListDevices',
+ });
+ if (isUsbmuxdDeviceResponse(resp)) {
+ return resp.DeviceList;
+ }
+ else {
+ throw new client_1.ResponseError('Invalid response from getDevices', resp);
+ }
+ }
+ async getDevice(udid) {
+ debug(`getDevice ${udid ? 'udid: ' + udid : ''}`);
+ const devices = await this.getDevices();
+ if (!devices.length) {
+ throw new Error('No devices found');
+ }
+ if (!udid) {
+ return devices[0];
+ }
+ for (const device of devices) {
+ if (device.Properties && device.Properties.SerialNumber === udid) {
+ return device;
+ }
+ }
+ throw new Error(`No device with udid ${udid} found`);
+ }
+ async readPairRecord(udid) {
+ debug(`readPairRecord: ${udid}`);
+ const resp = await this.protocolClient.sendMessage({
+ messageType: 'ReadPairRecord',
+ extraFields: { PairRecordID: udid },
+ });
+ if (isUsbmuxdPairRecordResponse(resp)) {
+ // the pair record can be created as a binary plist
+ const BPLIST_MAGIC = Buffer.from('bplist00');
+ if (BPLIST_MAGIC.compare(resp.PairRecordData, 0, 8) === 0) {
+ debug('Binary plist pair record detected.');
+ const bplistParser = await Promise.resolve().then(() => require('bplist-parser'));
+ return bplistParser.parseBuffer(resp.PairRecordData)[0];
+ }
+ else {
+ return plist.parse(resp.PairRecordData.toString()); // TODO: type guard
+ }
+ }
+ else {
+ throw new client_1.ResponseError(`There was an error reading pair record for udid: ${udid}`, resp);
+ }
+ }
+}
+exports.UsbmuxdClient = UsbmuxdClient;
+function htons(n) {
+ return ((n & 0xff) << 8) | ((n >> 8) & 0xff);
+}
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/dist/ios/lib/index.js b/temporary_modules/trezor-connect/node_modules/native-run/dist/ios/lib/index.js
new file mode 100644
index 00000000..cb7d0c68
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/native-run/dist/ios/lib/index.js
@@ -0,0 +1,6 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+const tslib_1 = require("tslib");
+tslib_1.__exportStar(require("./client"), exports);
+tslib_1.__exportStar(require("./protocol"), exports);
+tslib_1.__exportStar(require("./manager"), exports);
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/dist/ios/lib/lib-errors.js b/temporary_modules/trezor-connect/node_modules/native-run/dist/ios/lib/lib-errors.js
new file mode 100644
index 00000000..40551ed0
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/native-run/dist/ios/lib/lib-errors.js
@@ -0,0 +1,10 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+exports.IOSLibError = void 0;
+class IOSLibError extends Error {
+ constructor(message, code) {
+ super(message);
+ this.code = code;
+ }
+}
+exports.IOSLibError = IOSLibError;
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/dist/ios/lib/manager.js b/temporary_modules/trezor-connect/node_modules/native-run/dist/ios/lib/manager.js
new file mode 100644
index 00000000..b953aa0d
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/native-run/dist/ios/lib/manager.js
@@ -0,0 +1,139 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+exports.ClientManager = void 0;
+const stream_1 = require("stream");
+const tls = require("tls");
+const afc_1 = require("./client/afc");
+const debugserver_1 = require("./client/debugserver");
+const installation_proxy_1 = require("./client/installation_proxy");
+const lockdownd_1 = require("./client/lockdownd");
+const mobile_image_mounter_1 = require("./client/mobile_image_mounter");
+const usbmuxd_1 = require("./client/usbmuxd");
+class ClientManager {
+ constructor(pairRecord, device, lockdowndClient) {
+ this.pairRecord = pairRecord;
+ this.device = device;
+ this.lockdowndClient = lockdowndClient;
+ this.connections = [lockdowndClient.socket];
+ }
+ static async create(udid) {
+ const usbmuxClient = new usbmuxd_1.UsbmuxdClient(usbmuxd_1.UsbmuxdClient.connectUsbmuxdSocket());
+ const device = await usbmuxClient.getDevice(udid);
+ const pairRecord = await usbmuxClient.readPairRecord(device.Properties.SerialNumber);
+ const lockdownSocket = await usbmuxClient.connect(device, 62078);
+ const lockdownClient = new lockdownd_1.LockdowndClient(lockdownSocket);
+ await lockdownClient.doHandshake(pairRecord);
+ return new ClientManager(pairRecord, device, lockdownClient);
+ }
+ async getUsbmuxdClient() {
+ const usbmuxClient = new usbmuxd_1.UsbmuxdClient(usbmuxd_1.UsbmuxdClient.connectUsbmuxdSocket());
+ this.connections.push(usbmuxClient.socket);
+ return usbmuxClient;
+ }
+ async getLockdowndClient() {
+ const usbmuxClient = new usbmuxd_1.UsbmuxdClient(usbmuxd_1.UsbmuxdClient.connectUsbmuxdSocket());
+ const lockdownSocket = await usbmuxClient.connect(this.device, 62078);
+ const lockdownClient = new lockdownd_1.LockdowndClient(lockdownSocket);
+ this.connections.push(lockdownClient.socket);
+ return lockdownClient;
+ }
+ async getLockdowndClientWithHandshake() {
+ const lockdownClient = await this.getLockdowndClient();
+ await lockdownClient.doHandshake(this.pairRecord);
+ return lockdownClient;
+ }
+ async getAFCClient() {
+ return this.getServiceClient('com.apple.afc', afc_1.AFCClient);
+ }
+ async getInstallationProxyClient() {
+ return this.getServiceClient('com.apple.mobile.installation_proxy', installation_proxy_1.InstallationProxyClient);
+ }
+ async getMobileImageMounterClient() {
+ return this.getServiceClient('com.apple.mobile.mobile_image_mounter', mobile_image_mounter_1.MobileImageMounterClient);
+ }
+ async getDebugserverClient() {
+ try {
+ // iOS 14 added support for a secure debug service so try to connect to that first
+ return await this.getServiceClient('com.apple.debugserver.DVTSecureSocketProxy', debugserver_1.DebugserverClient);
+ }
+ catch {
+ // otherwise, fall back to the previous implementation
+ return this.getServiceClient('com.apple.debugserver', debugserver_1.DebugserverClient, true);
+ }
+ }
+ async getServiceClient(name, ServiceType, disableSSL = false) {
+ const { port: servicePort, enableServiceSSL } = await this.lockdowndClient.startService(name);
+ const usbmuxClient = new usbmuxd_1.UsbmuxdClient(usbmuxd_1.UsbmuxdClient.connectUsbmuxdSocket());
+ let usbmuxdSocket = await usbmuxClient.connect(this.device, servicePort);
+ if (enableServiceSSL) {
+ const tlsOptions = {
+ rejectUnauthorized: false,
+ secureContext: tls.createSecureContext({
+ secureProtocol: 'TLSv1_method',
+ cert: this.pairRecord.RootCertificate,
+ key: this.pairRecord.RootPrivateKey,
+ }),
+ };
+ // Some services seem to not support TLS/SSL after the initial handshake
+ // More info: https://github.com/libimobiledevice/libimobiledevice/issues/793
+ if (disableSSL) {
+ // According to https://nodejs.org/api/tls.html#tls_tls_connect_options_callback we can
+ // pass any Duplex in to tls.connect instead of a Socket. So we'll use our proxy to keep
+ // the TLS wrapper and underlying usbmuxd socket separate.
+ const proxy = new UsbmuxdProxy(usbmuxdSocket);
+ tlsOptions.socket = proxy;
+ await new Promise((res, rej) => {
+ const timeoutId = setTimeout(() => {
+ rej('The TLS handshake failed to complete after 5s.');
+ }, 5000);
+ tls.connect(tlsOptions, function () {
+ clearTimeout(timeoutId);
+ // After the handshake, we don't need TLS or the proxy anymore,
+ // since we'll just pass in the naked usbmuxd socket to the service client
+ this.destroy();
+ res();
+ });
+ });
+ }
+ else {
+ tlsOptions.socket = usbmuxdSocket;
+ usbmuxdSocket = tls.connect(tlsOptions);
+ }
+ }
+ const client = new ServiceType(usbmuxdSocket);
+ this.connections.push(client.socket);
+ return client;
+ }
+ end() {
+ for (const socket of this.connections) {
+ // may already be closed
+ try {
+ socket.end();
+ }
+ catch (err) {
+ // ignore
+ }
+ }
+ }
+}
+exports.ClientManager = ClientManager;
+class UsbmuxdProxy extends stream_1.Duplex {
+ constructor(usbmuxdSock) {
+ super();
+ this.usbmuxdSock = usbmuxdSock;
+ this.usbmuxdSock.on('data', data => {
+ this.push(data);
+ });
+ }
+ _write(chunk, encoding, callback) {
+ this.usbmuxdSock.write(chunk);
+ callback();
+ }
+ _read(size) {
+ // Stub so we don't error, since we push everything we get from usbmuxd as it comes in.
+ // TODO: better way to do this?
+ }
+ _destroy() {
+ this.usbmuxdSock.removeAllListeners();
+ }
+}
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/dist/ios/lib/protocol/afc.js b/temporary_modules/trezor-connect/node_modules/native-run/dist/ios/lib/protocol/afc.js
new file mode 100644
index 00000000..9506cd35
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/native-run/dist/ios/lib/protocol/afc.js
@@ -0,0 +1,375 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+exports.AFCProtocolWriter = exports.AFCProtocolReader = exports.AFCProtocolClient = exports.AFCError = exports.AFC_FILE_OPEN_FLAGS = exports.AFC_STATUS = exports.AFC_OPS = exports.AFC_HEADER_SIZE = exports.AFC_MAGIC = void 0;
+const Debug = require("debug");
+const protocol_1 = require("./protocol");
+const debug = Debug('native-run:ios:lib:protocol:afc');
+exports.AFC_MAGIC = 'CFA6LPAA';
+exports.AFC_HEADER_SIZE = 40;
+/**
+ * AFC Operations
+ */
+var AFC_OPS;
+(function (AFC_OPS) {
+ /**
+ * Invalid
+ */
+ AFC_OPS[AFC_OPS["INVALID"] = 0] = "INVALID";
+ /**
+ * Status
+ */
+ AFC_OPS[AFC_OPS["STATUS"] = 1] = "STATUS";
+ /**
+ * Data
+ */
+ AFC_OPS[AFC_OPS["DATA"] = 2] = "DATA";
+ /**
+ * ReadDir
+ */
+ AFC_OPS[AFC_OPS["READ_DIR"] = 3] = "READ_DIR";
+ /**
+ * ReadFile
+ */
+ AFC_OPS[AFC_OPS["READ_FILE"] = 4] = "READ_FILE";
+ /**
+ * WriteFile
+ */
+ AFC_OPS[AFC_OPS["WRITE_FILE"] = 5] = "WRITE_FILE";
+ /**
+ * WritePart
+ */
+ AFC_OPS[AFC_OPS["WRITE_PART"] = 6] = "WRITE_PART";
+ /**
+ * TruncateFile
+ */
+ AFC_OPS[AFC_OPS["TRUNCATE"] = 7] = "TRUNCATE";
+ /**
+ * RemovePath
+ */
+ AFC_OPS[AFC_OPS["REMOVE_PATH"] = 8] = "REMOVE_PATH";
+ /**
+ * MakeDir
+ */
+ AFC_OPS[AFC_OPS["MAKE_DIR"] = 9] = "MAKE_DIR";
+ /**
+ * GetFileInfo
+ */
+ AFC_OPS[AFC_OPS["GET_FILE_INFO"] = 10] = "GET_FILE_INFO";
+ /**
+ * GetDeviceInfo
+ */
+ AFC_OPS[AFC_OPS["GET_DEVINFO"] = 11] = "GET_DEVINFO";
+ /**
+ * WriteFileAtomic (tmp file+rename)
+ */
+ AFC_OPS[AFC_OPS["WRITE_FILE_ATOM"] = 12] = "WRITE_FILE_ATOM";
+ /**
+ * FileRefOpen
+ */
+ AFC_OPS[AFC_OPS["FILE_OPEN"] = 13] = "FILE_OPEN";
+ /**
+ * FileRefOpenResult
+ */
+ AFC_OPS[AFC_OPS["FILE_OPEN_RES"] = 14] = "FILE_OPEN_RES";
+ /**
+ * FileRefRead
+ */
+ AFC_OPS[AFC_OPS["FILE_READ"] = 15] = "FILE_READ";
+ /**
+ * FileRefWrite
+ */
+ AFC_OPS[AFC_OPS["FILE_WRITE"] = 16] = "FILE_WRITE";
+ /**
+ * FileRefSeek
+ */
+ AFC_OPS[AFC_OPS["FILE_SEEK"] = 17] = "FILE_SEEK";
+ /**
+ * FileRefTell
+ */
+ AFC_OPS[AFC_OPS["FILE_TELL"] = 18] = "FILE_TELL";
+ /**
+ * FileRefTellResult
+ */
+ AFC_OPS[AFC_OPS["FILE_TELL_RES"] = 19] = "FILE_TELL_RES";
+ /**
+ * FileRefClose
+ */
+ AFC_OPS[AFC_OPS["FILE_CLOSE"] = 20] = "FILE_CLOSE";
+ /**
+ * FileRefSetFileSize (ftruncate)
+ */
+ AFC_OPS[AFC_OPS["FILE_SET_SIZE"] = 21] = "FILE_SET_SIZE";
+ /**
+ * GetConnectionInfo
+ */
+ AFC_OPS[AFC_OPS["GET_CON_INFO"] = 22] = "GET_CON_INFO";
+ /**
+ * SetConnectionOptions
+ */
+ AFC_OPS[AFC_OPS["SET_CON_OPTIONS"] = 23] = "SET_CON_OPTIONS";
+ /**
+ * RenamePath
+ */
+ AFC_OPS[AFC_OPS["RENAME_PATH"] = 24] = "RENAME_PATH";
+ /**
+ * SetFSBlockSize (0x800000)
+ */
+ AFC_OPS[AFC_OPS["SET_FS_BS"] = 25] = "SET_FS_BS";
+ /**
+ * SetSocketBlockSize (0x800000)
+ */
+ AFC_OPS[AFC_OPS["SET_SOCKET_BS"] = 26] = "SET_SOCKET_BS";
+ /**
+ * FileRefLock
+ */
+ AFC_OPS[AFC_OPS["FILE_LOCK"] = 27] = "FILE_LOCK";
+ /**
+ * MakeLink
+ */
+ AFC_OPS[AFC_OPS["MAKE_LINK"] = 28] = "MAKE_LINK";
+ /**
+ * GetFileHash
+ */
+ AFC_OPS[AFC_OPS["GET_FILE_HASH"] = 29] = "GET_FILE_HASH";
+ /**
+ * SetModTime
+ */
+ AFC_OPS[AFC_OPS["SET_FILE_MOD_TIME"] = 30] = "SET_FILE_MOD_TIME";
+ /**
+ * GetFileHashWithRange
+ */
+ AFC_OPS[AFC_OPS["GET_FILE_HASH_RANGE"] = 31] = "GET_FILE_HASH_RANGE";
+ // iOS 6+
+ /**
+ * FileRefSetImmutableHint
+ */
+ AFC_OPS[AFC_OPS["FILE_SET_IMMUTABLE_HINT"] = 32] = "FILE_SET_IMMUTABLE_HINT";
+ /**
+ * GetSizeOfPathContents
+ */
+ AFC_OPS[AFC_OPS["GET_SIZE_OF_PATH_CONTENTS"] = 33] = "GET_SIZE_OF_PATH_CONTENTS";
+ /**
+ * RemovePathAndContents
+ */
+ AFC_OPS[AFC_OPS["REMOVE_PATH_AND_CONTENTS"] = 34] = "REMOVE_PATH_AND_CONTENTS";
+ /**
+ * DirectoryEnumeratorRefOpen
+ */
+ AFC_OPS[AFC_OPS["DIR_OPEN"] = 35] = "DIR_OPEN";
+ /**
+ * DirectoryEnumeratorRefOpenResult
+ */
+ AFC_OPS[AFC_OPS["DIR_OPEN_RESULT"] = 36] = "DIR_OPEN_RESULT";
+ /**
+ * DirectoryEnumeratorRefRead
+ */
+ AFC_OPS[AFC_OPS["DIR_READ"] = 37] = "DIR_READ";
+ /**
+ * DirectoryEnumeratorRefClose
+ */
+ AFC_OPS[AFC_OPS["DIR_CLOSE"] = 38] = "DIR_CLOSE";
+ // iOS 7+
+ /**
+ * FileRefReadWithOffset
+ */
+ AFC_OPS[AFC_OPS["FILE_READ_OFFSET"] = 39] = "FILE_READ_OFFSET";
+ /**
+ * FileRefWriteWithOffset
+ */
+ AFC_OPS[AFC_OPS["FILE_WRITE_OFFSET"] = 40] = "FILE_WRITE_OFFSET";
+})(AFC_OPS = exports.AFC_OPS || (exports.AFC_OPS = {}));
+/**
+ * Error Codes
+ */
+var AFC_STATUS;
+(function (AFC_STATUS) {
+ AFC_STATUS[AFC_STATUS["SUCCESS"] = 0] = "SUCCESS";
+ AFC_STATUS[AFC_STATUS["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
+ AFC_STATUS[AFC_STATUS["OP_HEADER_INVALID"] = 2] = "OP_HEADER_INVALID";
+ AFC_STATUS[AFC_STATUS["NO_RESOURCES"] = 3] = "NO_RESOURCES";
+ AFC_STATUS[AFC_STATUS["READ_ERROR"] = 4] = "READ_ERROR";
+ AFC_STATUS[AFC_STATUS["WRITE_ERROR"] = 5] = "WRITE_ERROR";
+ AFC_STATUS[AFC_STATUS["UNKNOWN_PACKET_TYPE"] = 6] = "UNKNOWN_PACKET_TYPE";
+ AFC_STATUS[AFC_STATUS["INVALID_ARG"] = 7] = "INVALID_ARG";
+ AFC_STATUS[AFC_STATUS["OBJECT_NOT_FOUND"] = 8] = "OBJECT_NOT_FOUND";
+ AFC_STATUS[AFC_STATUS["OBJECT_IS_DIR"] = 9] = "OBJECT_IS_DIR";
+ AFC_STATUS[AFC_STATUS["PERM_DENIED"] = 10] = "PERM_DENIED";
+ AFC_STATUS[AFC_STATUS["SERVICE_NOT_CONNECTED"] = 11] = "SERVICE_NOT_CONNECTED";
+ AFC_STATUS[AFC_STATUS["OP_TIMEOUT"] = 12] = "OP_TIMEOUT";
+ AFC_STATUS[AFC_STATUS["TOO_MUCH_DATA"] = 13] = "TOO_MUCH_DATA";
+ AFC_STATUS[AFC_STATUS["END_OF_DATA"] = 14] = "END_OF_DATA";
+ AFC_STATUS[AFC_STATUS["OP_NOT_SUPPORTED"] = 15] = "OP_NOT_SUPPORTED";
+ AFC_STATUS[AFC_STATUS["OBJECT_EXISTS"] = 16] = "OBJECT_EXISTS";
+ AFC_STATUS[AFC_STATUS["OBJECT_BUSY"] = 17] = "OBJECT_BUSY";
+ AFC_STATUS[AFC_STATUS["NO_SPACE_LEFT"] = 18] = "NO_SPACE_LEFT";
+ AFC_STATUS[AFC_STATUS["OP_WOULD_BLOCK"] = 19] = "OP_WOULD_BLOCK";
+ AFC_STATUS[AFC_STATUS["IO_ERROR"] = 20] = "IO_ERROR";
+ AFC_STATUS[AFC_STATUS["OP_INTERRUPTED"] = 21] = "OP_INTERRUPTED";
+ AFC_STATUS[AFC_STATUS["OP_IN_PROGRESS"] = 22] = "OP_IN_PROGRESS";
+ AFC_STATUS[AFC_STATUS["INTERNAL_ERROR"] = 23] = "INTERNAL_ERROR";
+ AFC_STATUS[AFC_STATUS["MUX_ERROR"] = 30] = "MUX_ERROR";
+ AFC_STATUS[AFC_STATUS["NO_MEM"] = 31] = "NO_MEM";
+ AFC_STATUS[AFC_STATUS["NOT_ENOUGH_DATA"] = 32] = "NOT_ENOUGH_DATA";
+ AFC_STATUS[AFC_STATUS["DIR_NOT_EMPTY"] = 33] = "DIR_NOT_EMPTY";
+ AFC_STATUS[AFC_STATUS["FORCE_SIGNED_TYPE"] = -1] = "FORCE_SIGNED_TYPE";
+})(AFC_STATUS = exports.AFC_STATUS || (exports.AFC_STATUS = {}));
+var AFC_FILE_OPEN_FLAGS;
+(function (AFC_FILE_OPEN_FLAGS) {
+ /**
+ * r (O_RDONLY)
+ */
+ AFC_FILE_OPEN_FLAGS[AFC_FILE_OPEN_FLAGS["RDONLY"] = 1] = "RDONLY";
+ /**
+ * r+ (O_RDWR | O_CREAT)
+ */
+ AFC_FILE_OPEN_FLAGS[AFC_FILE_OPEN_FLAGS["RW"] = 2] = "RW";
+ /**
+ * w (O_WRONLY | O_CREAT | O_TRUNC)
+ */
+ AFC_FILE_OPEN_FLAGS[AFC_FILE_OPEN_FLAGS["WRONLY"] = 3] = "WRONLY";
+ /**
+ * w+ (O_RDWR | O_CREAT | O_TRUNC)
+ */
+ AFC_FILE_OPEN_FLAGS[AFC_FILE_OPEN_FLAGS["WR"] = 4] = "WR";
+ /**
+ * a (O_WRONLY | O_APPEND | O_CREAT)
+ */
+ AFC_FILE_OPEN_FLAGS[AFC_FILE_OPEN_FLAGS["APPEND"] = 5] = "APPEND";
+ /**
+ * a+ (O_RDWR | O_APPEND | O_CREAT)
+ */
+ AFC_FILE_OPEN_FLAGS[AFC_FILE_OPEN_FLAGS["RDAPPEND"] = 6] = "RDAPPEND";
+})(AFC_FILE_OPEN_FLAGS = exports.AFC_FILE_OPEN_FLAGS || (exports.AFC_FILE_OPEN_FLAGS = {}));
+function isAFCResponse(resp) {
+ return (AFC_OPS[resp.operation] !== undefined &&
+ resp.id !== undefined &&
+ resp.data !== undefined);
+}
+function isStatusResponse(resp) {
+ return isAFCResponse(resp) && resp.operation === AFC_OPS.STATUS;
+}
+function isErrorStatusResponse(resp) {
+ return isStatusResponse(resp) && resp.data !== AFC_STATUS.SUCCESS;
+}
+class AFCInternalError extends Error {
+ constructor(msg, requestId) {
+ super(msg);
+ this.requestId = requestId;
+ }
+}
+class AFCError extends Error {
+ constructor(msg, status) {
+ super(msg);
+ this.status = status;
+ }
+}
+exports.AFCError = AFCError;
+class AFCProtocolClient extends protocol_1.ProtocolClient {
+ constructor(socket) {
+ super(socket, new protocol_1.ProtocolReaderFactory(AFCProtocolReader), new AFCProtocolWriter());
+ this.requestId = 0;
+ this.requestCallbacks = {};
+ const reader = this.readerFactory.create((resp, err) => {
+ if (err && err instanceof AFCInternalError) {
+ this.requestCallbacks[err.requestId](resp, err);
+ }
+ else if (isErrorStatusResponse(resp)) {
+ this.requestCallbacks[resp.id](resp, new AFCError(AFC_STATUS[resp.data], resp.data));
+ }
+ else {
+ this.requestCallbacks[resp.id](resp);
+ }
+ });
+ socket.on('data', reader.onData);
+ }
+ sendMessage(msg) {
+ return new Promise((resolve, reject) => {
+ const requestId = this.requestId++;
+ this.requestCallbacks[requestId] = async (resp, err) => {
+ if (err) {
+ reject(err);
+ return;
+ }
+ if (isAFCResponse(resp)) {
+ resolve(resp);
+ }
+ else {
+ reject(new Error('Malformed AFC response'));
+ }
+ };
+ this.writer.write(this.socket, { ...msg, requestId });
+ });
+ }
+}
+exports.AFCProtocolClient = AFCProtocolClient;
+class AFCProtocolReader extends protocol_1.ProtocolReader {
+ constructor(callback) {
+ super(exports.AFC_HEADER_SIZE, callback);
+ }
+ parseHeader(data) {
+ const magic = data.slice(0, 8).toString('ascii');
+ if (magic !== exports.AFC_MAGIC) {
+ throw new AFCInternalError(`Invalid AFC packet received (magic != ${exports.AFC_MAGIC})`, data.readUInt32LE(24));
+ }
+ // technically these are uint64
+ this.header = {
+ magic,
+ totalLength: data.readUInt32LE(8),
+ headerLength: data.readUInt32LE(16),
+ requestId: data.readUInt32LE(24),
+ operation: data.readUInt32LE(32),
+ };
+ debug(`parse header: ${JSON.stringify(this.header)}`);
+ if (this.header.headerLength < exports.AFC_HEADER_SIZE) {
+ throw new AFCInternalError('Invalid AFC header', this.header.requestId);
+ }
+ return this.header.totalLength - exports.AFC_HEADER_SIZE;
+ }
+ parseBody(data) {
+ const body = {
+ operation: this.header.operation,
+ id: this.header.requestId,
+ data,
+ };
+ if (isStatusResponse(body)) {
+ const status = data.readUInt32LE(0);
+ debug(`${AFC_OPS[this.header.operation]} response: ${AFC_STATUS[status]}`);
+ body.data = status;
+ }
+ else if (data.length <= 8) {
+ debug(`${AFC_OPS[this.header.operation]} response: ${Array.prototype.toString.call(body)}`);
+ }
+ else {
+ debug(`${AFC_OPS[this.header.operation]} response length: ${data.length} bytes`);
+ }
+ return body;
+ }
+}
+exports.AFCProtocolReader = AFCProtocolReader;
+class AFCProtocolWriter {
+ write(socket, msg) {
+ const { data, payload, operation, requestId } = msg;
+ const dataLength = data ? data.length : 0;
+ const payloadLength = payload ? payload.length : 0;
+ const header = Buffer.alloc(exports.AFC_HEADER_SIZE);
+ const magic = Buffer.from(exports.AFC_MAGIC);
+ magic.copy(header);
+ header.writeUInt32LE(exports.AFC_HEADER_SIZE + dataLength + payloadLength, 8);
+ header.writeUInt32LE(exports.AFC_HEADER_SIZE + dataLength, 16);
+ header.writeUInt32LE(requestId, 24);
+ header.writeUInt32LE(operation, 32);
+ socket.write(header);
+ socket.write(data);
+ if (data.length <= 8) {
+ debug(`socket write, header: { requestId: ${requestId}, operation: ${AFC_OPS[operation]}}, body: ${Array.prototype.toString.call(data)}`);
+ }
+ else {
+ debug(`socket write, header: { requestId: ${requestId}, operation: ${AFC_OPS[operation]}}, body: ${data.length} bytes`);
+ }
+ debug(`socket write, bytes written ${header.length} (header), ${data.length} (body)`);
+ if (payload) {
+ socket.write(payload);
+ }
+ }
+}
+exports.AFCProtocolWriter = AFCProtocolWriter;
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/dist/ios/lib/protocol/gdb.js b/temporary_modules/trezor-connect/node_modules/native-run/dist/ios/lib/protocol/gdb.js
new file mode 100644
index 00000000..af85b7ae
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/native-run/dist/ios/lib/protocol/gdb.js
@@ -0,0 +1,112 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+exports.GDBProtocolWriter = exports.GDBProtocolReader = exports.GDBProtocolClient = void 0;
+const Debug = require("debug");
+const protocol_1 = require("./protocol");
+const debug = Debug('native-run:ios:lib:protocol:gdb');
+const ACK_SUCCESS = '+'.charCodeAt(0);
+class GDBProtocolClient extends protocol_1.ProtocolClient {
+ constructor(socket) {
+ super(socket, new protocol_1.ProtocolReaderFactory(GDBProtocolReader), new GDBProtocolWriter());
+ }
+}
+exports.GDBProtocolClient = GDBProtocolClient;
+class GDBProtocolReader extends protocol_1.ProtocolReader {
+ constructor(callback) {
+ super(1 /* "Header" is '+' or '-' */, callback);
+ }
+ onData(data) {
+ // the GDB protocol does not support body length in its header so we cannot rely on
+ // the parent implementation to determine when a payload is complete
+ try {
+ // if there's data, add it to the existing buffer
+ this.buffer = data ? Buffer.concat([this.buffer, data]) : this.buffer;
+ // do we have enough bytes to proceed
+ if (this.buffer.length < this.headerSize) {
+ return; // incomplete header, wait for more
+ }
+ // first, check the header
+ if (this.parseHeader(this.buffer) === -1) {
+ // we have a valid header so check the body. GDB packets will always be a leading '$', data bytes,
+ // a trailing '#', and a two digit checksum. minimum valid body is the empty response '$#00'
+ // https://developer.apple.com/library/archive/documentation/DeveloperTools/gdb/gdb/gdb_33.html
+ const packetData = this.buffer.toString().match('\\$.*#[0-9a-f]{2}');
+ if (packetData == null) {
+ return; // incomplete body, wait for more
+ }
+ // extract the body and update the buffer
+ const body = Buffer.from(packetData[0]);
+ this.buffer = this.buffer.slice(this.headerSize + body.length);
+ // parse the payload and recurse if there is more data to process
+ this.callback(this.parseBody(body));
+ if (this.buffer.length) {
+ this.onData();
+ }
+ }
+ }
+ catch (err) {
+ this.callback(null, err);
+ }
+ }
+ parseHeader(data) {
+ if (data[0] !== ACK_SUCCESS) {
+ throw new Error('Unsuccessful debugserver response');
+ } // TODO: retry?
+ return -1;
+ }
+ parseBody(buffer) {
+ debug(`Response body: ${buffer.toString()}`);
+ // check for checksum
+ const checksum = buffer.slice(-3).toString();
+ if (checksum.match(/#[0-9a-f]{2}/)) {
+ // remove '$' prefix and checksum
+ const msg = buffer.slice(1, -3).toString();
+ if (validateChecksum(checksum, msg)) {
+ return msg;
+ }
+ else {
+ throw new Error('Invalid checksum received from debugserver');
+ }
+ }
+ else {
+ throw new Error("Didn't receive checksum");
+ }
+ }
+}
+exports.GDBProtocolReader = GDBProtocolReader;
+class GDBProtocolWriter {
+ write(socket, msg) {
+ const { cmd, args } = msg;
+ debug(`Socket write: ${cmd}, args: ${args}`);
+ // hex encode and concat all args
+ const encodedArgs = args
+ .map(arg => Buffer.from(arg).toString('hex'))
+ .join()
+ .toUpperCase();
+ const checksumStr = calculateChecksum(cmd + encodedArgs);
+ const formattedCmd = `$${cmd}${encodedArgs}#${checksumStr}`;
+ socket.write(formattedCmd);
+ }
+}
+exports.GDBProtocolWriter = GDBProtocolWriter;
+// hex value of (sum of cmd chars mod 256)
+function calculateChecksum(cmdStr) {
+ let checksum = 0;
+ for (let i = 0; i < cmdStr.length; i++) {
+ checksum += cmdStr.charCodeAt(i);
+ }
+ let result = (checksum % 256).toString(16);
+ // pad if necessary
+ if (result.length === 1) {
+ result = `0${result}`;
+ }
+ return result;
+}
+function validateChecksum(checksum, msg) {
+ // remove '#' from checksum
+ const checksumVal = checksum.slice(1);
+ // remove '$' from msg and calculate its checksum
+ const computedChecksum = calculateChecksum(msg);
+ debug(`Checksum: ${checksumVal}, computed checksum: ${computedChecksum}`);
+ return checksumVal === computedChecksum;
+}
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/dist/ios/lib/protocol/index.js b/temporary_modules/trezor-connect/node_modules/native-run/dist/ios/lib/protocol/index.js
new file mode 100644
index 00000000..7f4a5670
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/native-run/dist/ios/lib/protocol/index.js
@@ -0,0 +1,8 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+const tslib_1 = require("tslib");
+tslib_1.__exportStar(require("./protocol"), exports);
+tslib_1.__exportStar(require("./afc"), exports);
+tslib_1.__exportStar(require("./gdb"), exports);
+tslib_1.__exportStar(require("./lockdown"), exports);
+tslib_1.__exportStar(require("./usbmux"), exports);
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/dist/ios/lib/protocol/lockdown.js b/temporary_modules/trezor-connect/node_modules/native-run/dist/ios/lib/protocol/lockdown.js
new file mode 100644
index 00000000..92ed98ff
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/native-run/dist/ios/lib/protocol/lockdown.js
@@ -0,0 +1,57 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+exports.LockdownProtocolWriter = exports.LockdownProtocolReader = exports.LockdownProtocolClient = exports.isLockdownErrorResponse = exports.isLockdownResponse = exports.LOCKDOWN_HEADER_SIZE = void 0;
+const Debug = require("debug");
+const plist = require("plist");
+const lib_errors_1 = require("../lib-errors");
+const protocol_1 = require("./protocol");
+const debug = Debug('native-run:ios:lib:protocol:lockdown');
+exports.LOCKDOWN_HEADER_SIZE = 4;
+function isDefined(val) {
+ return typeof val !== 'undefined';
+}
+function isLockdownResponse(resp) {
+ return isDefined(resp.Status);
+}
+exports.isLockdownResponse = isLockdownResponse;
+function isLockdownErrorResponse(resp) {
+ return isDefined(resp.Error);
+}
+exports.isLockdownErrorResponse = isLockdownErrorResponse;
+class LockdownProtocolClient extends protocol_1.ProtocolClient {
+ constructor(socket) {
+ super(socket, new protocol_1.ProtocolReaderFactory(LockdownProtocolReader), new LockdownProtocolWriter());
+ }
+}
+exports.LockdownProtocolClient = LockdownProtocolClient;
+class LockdownProtocolReader extends protocol_1.PlistProtocolReader {
+ constructor(callback) {
+ super(exports.LOCKDOWN_HEADER_SIZE, callback);
+ }
+ parseHeader(data) {
+ return data.readUInt32BE(0);
+ }
+ parseBody(data) {
+ const resp = super.parseBody(data);
+ debug(`Response: ${JSON.stringify(resp)}`);
+ if (isLockdownErrorResponse(resp)) {
+ if (resp.Error === 'DeviceLocked') {
+ throw new lib_errors_1.IOSLibError('Device is currently locked.', 'DeviceLocked');
+ }
+ throw new Error(resp.Error);
+ }
+ return resp;
+ }
+}
+exports.LockdownProtocolReader = LockdownProtocolReader;
+class LockdownProtocolWriter {
+ write(socket, plistData) {
+ debug(`socket write: ${JSON.stringify(plistData)}`);
+ const plistMessage = plist.build(plistData);
+ const header = Buffer.alloc(exports.LOCKDOWN_HEADER_SIZE);
+ header.writeUInt32BE(plistMessage.length, 0);
+ socket.write(header);
+ socket.write(plistMessage);
+ }
+}
+exports.LockdownProtocolWriter = LockdownProtocolWriter;
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/dist/ios/lib/protocol/protocol.js b/temporary_modules/trezor-connect/node_modules/native-run/dist/ios/lib/protocol/protocol.js
new file mode 100644
index 00000000..fd202997
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/native-run/dist/ios/lib/protocol/protocol.js
@@ -0,0 +1,108 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+exports.ProtocolClient = exports.PlistProtocolReader = exports.ProtocolReader = exports.ProtocolReaderFactory = void 0;
+const bplistParser = require("bplist-parser");
+const plist = require("plist");
+const BPLIST_MAGIC = Buffer.from('bplist00');
+class ProtocolReaderFactory {
+ constructor(ProtocolReader) {
+ this.ProtocolReader = ProtocolReader;
+ }
+ create(callback) {
+ return new this.ProtocolReader(callback);
+ }
+}
+exports.ProtocolReaderFactory = ProtocolReaderFactory;
+class ProtocolReader {
+ constructor(headerSize, callback) {
+ this.headerSize = headerSize;
+ this.callback = callback;
+ this.buffer = Buffer.alloc(0);
+ this.onData = this.onData.bind(this);
+ }
+ onData(data) {
+ try {
+ // if there's data, add it on to existing buffer
+ this.buffer = data ? Buffer.concat([this.buffer, data]) : this.buffer;
+ // we haven't gotten the body length from the header yet
+ if (!this.bodyLength) {
+ if (this.buffer.length < this.headerSize) {
+ // partial header, wait for rest
+ return;
+ }
+ this.bodyLength = this.parseHeader(this.buffer);
+ // move on to body
+ this.buffer = this.buffer.slice(this.headerSize);
+ if (!this.buffer.length) {
+ // only got header, wait for body
+ return;
+ }
+ }
+ if (this.buffer.length < this.bodyLength) {
+ // wait for rest of body
+ return;
+ }
+ if (this.bodyLength === -1) {
+ this.callback(this.parseBody(this.buffer));
+ this.buffer = Buffer.alloc(0);
+ }
+ else {
+ this.body = this.buffer.slice(0, this.bodyLength);
+ this.bodyLength -= this.body.length;
+ if (!this.bodyLength) {
+ this.callback(this.parseBody(this.body));
+ }
+ this.buffer = this.buffer.slice(this.body.length);
+ // There are multiple messages here, call parse again
+ if (this.buffer.length) {
+ this.onData();
+ }
+ }
+ }
+ catch (err) {
+ this.callback(null, err);
+ }
+ }
+}
+exports.ProtocolReader = ProtocolReader;
+class PlistProtocolReader extends ProtocolReader {
+ parseBody(body) {
+ if (BPLIST_MAGIC.compare(body, 0, 8) === 0) {
+ return bplistParser.parseBuffer(body);
+ }
+ else {
+ return plist.parse(body.toString('utf8'));
+ }
+ }
+}
+exports.PlistProtocolReader = PlistProtocolReader;
+class ProtocolClient {
+ constructor(socket, readerFactory, writer) {
+ this.socket = socket;
+ this.readerFactory = readerFactory;
+ this.writer = writer;
+ }
+ sendMessage(msg, callback) {
+ return new Promise((resolve, reject) => {
+ const reader = this.readerFactory.create(async (resp, err) => {
+ if (err) {
+ reject(err);
+ return;
+ }
+ if (callback) {
+ callback(resp, (value) => {
+ this.socket.removeListener('data', reader.onData);
+ resolve(value);
+ }, reject);
+ }
+ else {
+ this.socket.removeListener('data', reader.onData);
+ resolve(resp);
+ }
+ });
+ this.socket.on('data', reader.onData);
+ this.writer.write(this.socket, msg);
+ });
+ }
+}
+exports.ProtocolClient = ProtocolClient;
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/dist/ios/lib/protocol/usbmux.js b/temporary_modules/trezor-connect/node_modules/native-run/dist/ios/lib/protocol/usbmux.js
new file mode 100644
index 00000000..9d08877e
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/native-run/dist/ios/lib/protocol/usbmux.js
@@ -0,0 +1,57 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+exports.UsbmuxProtocolWriter = exports.UsbmuxProtocolReader = exports.UsbmuxProtocolClient = exports.USBMUXD_HEADER_SIZE = void 0;
+const Debug = require("debug");
+const plist = require("plist");
+const protocol_1 = require("./protocol");
+const debug = Debug('native-run:ios:lib:protocol:usbmux');
+exports.USBMUXD_HEADER_SIZE = 16;
+class UsbmuxProtocolClient extends protocol_1.ProtocolClient {
+ constructor(socket) {
+ super(socket, new protocol_1.ProtocolReaderFactory(UsbmuxProtocolReader), new UsbmuxProtocolWriter());
+ }
+}
+exports.UsbmuxProtocolClient = UsbmuxProtocolClient;
+class UsbmuxProtocolReader extends protocol_1.PlistProtocolReader {
+ constructor(callback) {
+ super(exports.USBMUXD_HEADER_SIZE, callback);
+ }
+ parseHeader(data) {
+ return data.readUInt32LE(0) - exports.USBMUXD_HEADER_SIZE;
+ }
+ parseBody(data) {
+ const resp = super.parseBody(data);
+ debug(`Response: ${JSON.stringify(resp)}`);
+ return resp;
+ }
+}
+exports.UsbmuxProtocolReader = UsbmuxProtocolReader;
+class UsbmuxProtocolWriter {
+ constructor() {
+ this.useTag = 0;
+ }
+ write(socket, msg) {
+ // TODO Usbmux message type
+ debug(`socket write: ${JSON.stringify(msg)}`);
+ const { messageType, extraFields } = msg;
+ const plistMessage = plist.build({
+ BundleID: 'io.ionic.native-run',
+ ClientVersionString: 'usbmux.js',
+ MessageType: messageType,
+ ProgName: 'native-run',
+ kLibUSBMuxVersion: 3,
+ ...extraFields,
+ });
+ const dataSize = plistMessage ? plistMessage.length : 0;
+ const protocolVersion = 1;
+ const messageCode = 8;
+ const header = Buffer.alloc(exports.USBMUXD_HEADER_SIZE);
+ header.writeUInt32LE(exports.USBMUXD_HEADER_SIZE + dataSize, 0);
+ header.writeUInt32LE(protocolVersion, 4);
+ header.writeUInt32LE(messageCode, 8);
+ header.writeUInt32LE(this.useTag++, 12); // TODO
+ socket.write(header);
+ socket.write(plistMessage);
+ }
+}
+exports.UsbmuxProtocolWriter = UsbmuxProtocolWriter;
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/dist/ios/list.js b/temporary_modules/trezor-connect/node_modules/native-run/dist/ios/list.js
new file mode 100644
index 00000000..bab6c498
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/native-run/dist/ios/list.js
@@ -0,0 +1,55 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+exports.list = exports.run = void 0;
+const list_1 = require("../utils/list");
+const device_1 = require("./utils/device");
+const simulator_1 = require("./utils/simulator");
+async function run(args) {
+ const targets = await list(args);
+ process.stdout.write(`\n${list_1.formatTargets(args, targets)}\n`);
+}
+exports.run = run;
+async function list(args) {
+ const errors = [];
+ const [devices, virtualDevices] = await Promise.all([
+ (async () => {
+ try {
+ const devices = await device_1.getConnectedDevices();
+ return devices.map(deviceToTarget);
+ }
+ catch (e) {
+ errors.push(e);
+ return [];
+ }
+ })(),
+ (async () => {
+ try {
+ const simulators = await simulator_1.getSimulators();
+ return simulators.map(simulatorToTarget);
+ }
+ catch (e) {
+ errors.push(e);
+ return [];
+ }
+ })(),
+ ]);
+ return { devices, virtualDevices, errors };
+}
+exports.list = list;
+function deviceToTarget(device) {
+ return {
+ platform: 'ios',
+ name: device.DeviceName,
+ model: device.ProductType,
+ sdkVersion: device.ProductVersion,
+ id: device.UniqueDeviceID,
+ };
+}
+function simulatorToTarget(simulator) {
+ return {
+ platform: 'ios',
+ name: simulator.name,
+ sdkVersion: simulator.runtime.version,
+ id: simulator.udid,
+ };
+}
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/dist/ios/run.js b/temporary_modules/trezor-connect/node_modules/native-run/dist/ios/run.js
new file mode 100644
index 00000000..b5f2c568
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/native-run/dist/ios/run.js
@@ -0,0 +1,121 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+exports.run = void 0;
+const utils_fs_1 = require("@ionic/utils-fs");
+const Debug = require("debug");
+const fs_1 = require("fs");
+const path = require("path");
+const errors_1 = require("../errors");
+const cli_1 = require("../utils/cli");
+const process_1 = require("../utils/process");
+const lib_errors_1 = require("./lib/lib-errors");
+const app_1 = require("./utils/app");
+const device_1 = require("./utils/device");
+const simulator_1 = require("./utils/simulator");
+const debug = Debug('native-run:ios:run');
+async function runIpaOrAppFile({ udid, devices, simulators, appPath, bundleId, waitForApp, preferSimulator, }) {
+ if (udid) {
+ if (devices.find(d => d.UniqueDeviceID === udid)) {
+ await device_1.runOnDevice(udid, appPath, bundleId, waitForApp);
+ }
+ else if (simulators.find(s => s.udid === udid)) {
+ await simulator_1.runOnSimulator(udid, appPath, bundleId, waitForApp);
+ }
+ else {
+ throw new errors_1.IOSRunException(`No device or simulator with UDID "${udid}" found`, errors_1.ERR_TARGET_NOT_FOUND);
+ }
+ }
+ else if (devices.length && !preferSimulator) {
+ // no udid, use first connected device
+ await device_1.runOnDevice(devices[0].UniqueDeviceID, appPath, bundleId, waitForApp);
+ }
+ else {
+ // use default sim
+ await simulator_1.runOnSimulator(simulators[simulators.length - 1].udid, appPath, bundleId, waitForApp);
+ }
+}
+async function runIpaOrAppFileOnInterval(config) {
+ const maxRetryCount = 12; // 1 minute
+ const retryInterval = 5000; // 5 seconds
+ let error;
+ let retryCount = 0;
+ const retry = async () => {
+ process.stderr.write('Please unlock your device. Waiting 5 seconds...\n');
+ retryCount++;
+ await process_1.wait(retryInterval);
+ await run();
+ };
+ const run = async () => {
+ try {
+ await runIpaOrAppFile(config);
+ }
+ catch (err) {
+ if (err instanceof lib_errors_1.IOSLibError &&
+ err.code == 'DeviceLocked' &&
+ retryCount < maxRetryCount) {
+ await retry();
+ }
+ else {
+ if (retryCount >= maxRetryCount) {
+ error = new errors_1.IOSRunException(`Device still locked after 1 minute. Aborting.`, errors_1.ERR_DEVICE_LOCKED);
+ }
+ else {
+ error = err;
+ }
+ }
+ }
+ };
+ await run();
+ if (error) {
+ throw error;
+ }
+}
+async function run(args) {
+ let appPath = cli_1.getOptionValue(args, '--app');
+ if (!appPath) {
+ throw new errors_1.CLIException('--app is required', errors_1.ERR_BAD_INPUT);
+ }
+ const udid = cli_1.getOptionValue(args, '--target');
+ const preferSimulator = args.includes('--virtual');
+ const waitForApp = args.includes('--connect');
+ const isIPA = appPath.endsWith('.ipa');
+ if (!fs_1.existsSync(appPath)) {
+ throw new errors_1.IOSRunException(`Path '${appPath}' not found`);
+ }
+ try {
+ if (isIPA) {
+ const { tmpdir } = await Promise.resolve().then(() => require('os'));
+ const tempDir = fs_1.mkdtempSync(`${tmpdir()}${path.sep}`);
+ debug(`Unzipping .ipa to ${tempDir}`);
+ const appDir = await app_1.unzipIPA(appPath, tempDir);
+ appPath = path.join(tempDir, appDir);
+ }
+ const bundleId = await app_1.getBundleId(appPath);
+ const [devices, simulators] = await Promise.all([
+ device_1.getConnectedDevices(),
+ simulator_1.getSimulators(),
+ ]);
+ // try to run on device or simulator with udid
+ const config = {
+ udid,
+ devices,
+ simulators,
+ appPath,
+ bundleId,
+ waitForApp,
+ preferSimulator,
+ };
+ await runIpaOrAppFileOnInterval(config);
+ }
+ finally {
+ if (isIPA) {
+ try {
+ await utils_fs_1.remove(appPath);
+ }
+ catch {
+ // ignore
+ }
+ }
+ }
+}
+exports.run = run;
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/dist/ios/utils/app.js b/temporary_modules/trezor-connect/node_modules/native-run/dist/ios/utils/app.js
new file mode 100644
index 00000000..f05271ba
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/native-run/dist/ios/utils/app.js
@@ -0,0 +1,58 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+exports.unzipIPA = exports.getBundleId = void 0;
+const utils_fs_1 = require("@ionic/utils-fs");
+const Debug = require("debug");
+const fs_1 = require("fs");
+const path = require("path");
+const errors_1 = require("../../errors");
+const process_1 = require("../../utils/process");
+const unzip_1 = require("../../utils/unzip");
+const debug = Debug('native-run:ios:utils:app');
+// TODO: cross platform? Use plist/bplist
+async function getBundleId(appPath) {
+ const plistPath = path.resolve(appPath, 'Info.plist');
+ try {
+ const { stdout } = await process_1.execFile('/usr/libexec/PlistBuddy', ['-c', 'Print :CFBundleIdentifier', plistPath], { encoding: 'utf8' });
+ if (stdout) {
+ return stdout.trim();
+ }
+ }
+ catch {
+ // ignore
+ }
+ throw new errors_1.Exception('Unable to get app bundle identifier');
+}
+exports.getBundleId = getBundleId;
+async function unzipIPA(ipaPath, destPath) {
+ let error;
+ let appPath = '';
+ await unzip_1.unzip(ipaPath, async (entry, zipfile, openReadStream) => {
+ debug(`Unzip: ${entry.fileName}`);
+ const dest = path.join(destPath, entry.fileName);
+ if (entry.fileName.endsWith('/')) {
+ await utils_fs_1.mkdirp(dest);
+ if (entry.fileName.endsWith('.app/')) {
+ appPath = entry.fileName;
+ }
+ zipfile.readEntry();
+ }
+ else {
+ await utils_fs_1.mkdirp(path.dirname(dest));
+ const readStream = await openReadStream(entry);
+ readStream.on('error', (err) => (error = err));
+ readStream.on('end', () => {
+ zipfile.readEntry();
+ });
+ readStream.pipe(fs_1.createWriteStream(dest));
+ }
+ });
+ if (error) {
+ throw error;
+ }
+ if (!appPath) {
+ throw new errors_1.Exception('Unable to determine .app directory from .ipa');
+ }
+ return appPath;
+}
+exports.unzipIPA = unzipIPA;
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/dist/ios/utils/device.js b/temporary_modules/trezor-connect/node_modules/native-run/dist/ios/utils/device.js
new file mode 100644
index 00000000..6e17c50a
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/native-run/dist/ios/utils/device.js
@@ -0,0 +1,108 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+exports.runOnDevice = exports.getConnectedDevices = void 0;
+const Debug = require("debug");
+const fs_1 = require("fs");
+const path = require("path");
+const errors_1 = require("../../errors");
+const process_1 = require("../../utils/process");
+const lib_1 = require("../lib");
+const xcode_1 = require("./xcode");
+const debug = Debug('native-run:ios:utils:device');
+async function getConnectedDevices() {
+ const usbmuxClient = new lib_1.UsbmuxdClient(lib_1.UsbmuxdClient.connectUsbmuxdSocket());
+ const usbmuxDevices = await usbmuxClient.getDevices();
+ usbmuxClient.socket.end();
+ return Promise.all(usbmuxDevices.map(async (d) => {
+ const socket = await new lib_1.UsbmuxdClient(lib_1.UsbmuxdClient.connectUsbmuxdSocket()).connect(d, 62078);
+ const device = await new lib_1.LockdowndClient(socket).getAllValues();
+ socket.end();
+ return device;
+ }));
+}
+exports.getConnectedDevices = getConnectedDevices;
+async function runOnDevice(udid, appPath, bundleId, waitForApp) {
+ const clientManager = await lib_1.ClientManager.create(udid);
+ try {
+ await mountDeveloperDiskImage(clientManager);
+ const packageName = path.basename(appPath);
+ const destPackagePath = path.join('PublicStaging', packageName);
+ await uploadApp(clientManager, appPath, destPackagePath);
+ const installer = await clientManager.getInstallationProxyClient();
+ await installer.installApp(destPackagePath, bundleId);
+ const { [bundleId]: appInfo } = await installer.lookupApp([bundleId]);
+ // launch fails with EBusy or ENotFound if you try to launch immediately after install
+ await process_1.wait(200);
+ const debugServerClient = await launchApp(clientManager, appInfo);
+ if (waitForApp) {
+ process_1.onBeforeExit(async () => {
+ // causes continue() to return
+ debugServerClient.halt();
+ // give continue() time to return response
+ await process_1.wait(64);
+ });
+ debug(`Waiting for app to close...\n`);
+ const result = await debugServerClient.continue();
+ // TODO: I have no idea what this packet means yet (successful close?)
+ // if not a close (ie, most likely due to halt from onBeforeExit), then kill the app
+ if (result !== 'W00') {
+ await debugServerClient.kill();
+ }
+ }
+ }
+ finally {
+ clientManager.end();
+ }
+}
+exports.runOnDevice = runOnDevice;
+async function mountDeveloperDiskImage(clientManager) {
+ const imageMounter = await clientManager.getMobileImageMounterClient();
+ // Check if already mounted. If not, mount.
+ if (!(await imageMounter.lookupImage()).ImageSignature) {
+ // verify DeveloperDiskImage exists (TODO: how does this work on Windows/Linux?)
+ // TODO: if windows/linux, download?
+ const version = await (await clientManager.getLockdowndClient()).getValue('ProductVersion');
+ const developerDiskImagePath = await xcode_1.getDeveloperDiskImagePath(version);
+ const developerDiskImageSig = fs_1.readFileSync(`${developerDiskImagePath}.signature`);
+ await imageMounter.uploadImage(developerDiskImagePath, developerDiskImageSig);
+ await imageMounter.mountImage(developerDiskImagePath, developerDiskImageSig);
+ }
+}
+async function uploadApp(clientManager, srcPath, destinationPath) {
+ const afcClient = await clientManager.getAFCClient();
+ try {
+ await afcClient.getFileInfo('PublicStaging');
+ }
+ catch (err) {
+ if (err instanceof lib_1.AFCError && err.status === lib_1.AFC_STATUS.OBJECT_NOT_FOUND) {
+ await afcClient.makeDirectory('PublicStaging');
+ }
+ else {
+ throw err;
+ }
+ }
+ await afcClient.uploadDirectory(srcPath, destinationPath);
+}
+async function launchApp(clientManager, appInfo) {
+ let tries = 0;
+ while (tries < 3) {
+ const debugServerClient = await clientManager.getDebugserverClient();
+ await debugServerClient.setMaxPacketSize(1024);
+ await debugServerClient.setWorkingDir(appInfo.Container);
+ await debugServerClient.launchApp(appInfo.Path, appInfo.CFBundleExecutable);
+ const result = await debugServerClient.checkLaunchSuccess();
+ if (result === 'OK') {
+ return debugServerClient;
+ }
+ else if (result === 'EBusy' || result === 'ENotFound') {
+ debug('Device busy or app not found, trying to launch again in .5s...');
+ tries++;
+ debugServerClient.socket.end();
+ await process_1.wait(500);
+ }
+ else {
+ throw new errors_1.Exception(`There was an error launching app: ${result}`);
+ }
+ }
+ throw new errors_1.Exception('Unable to launch app, number of tries exceeded');
+}
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/dist/ios/utils/simulator.js b/temporary_modules/trezor-connect/node_modules/native-run/dist/ios/utils/simulator.js
new file mode 100644
index 00000000..e984b7dd
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/native-run/dist/ios/utils/simulator.js
@@ -0,0 +1,101 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+exports.runOnSimulator = exports.getSimulators = void 0;
+const child_process_1 = require("child_process"); // TODO: need cross-spawn for windows?
+const Debug = require("debug");
+const errors_1 = require("../../errors");
+const log_1 = require("../../utils/log");
+const process_1 = require("../../utils/process");
+const xcode_1 = require("./xcode");
+const debug = Debug('native-run:ios:utils:simulator');
+async function getSimulators() {
+ const simctl = child_process_1.spawnSync('xcrun', ['simctl', 'list', '--json'], {
+ encoding: 'utf8',
+ });
+ if (simctl.status) {
+ throw new errors_1.Exception(`Unable to retrieve simulator list: ${simctl.stderr}`);
+ }
+ const [xcodeVersion] = xcode_1.getXcodeVersionInfo();
+ if (Number(xcodeVersion) < 10) {
+ throw new errors_1.Exception('native-run only supports Xcode 10 and later');
+ }
+ try {
+ const output = JSON.parse(simctl.stdout);
+ return output.runtimes
+ .filter(runtime => runtime.name.indexOf('watch') === -1 &&
+ runtime.name.indexOf('tv') === -1)
+ .map(runtime => (output.devices[runtime.identifier] || output.devices[runtime.name])
+ .filter(device => device.isAvailable)
+ .map(device => ({ ...device, runtime })))
+ .reduce((prev, next) => prev.concat(next)) // flatten
+ .sort((a, b) => (a.name < b.name ? -1 : 1));
+ }
+ catch (err) {
+ throw new errors_1.Exception(`Unable to retrieve simulator list: ${err.message}`);
+ }
+}
+exports.getSimulators = getSimulators;
+async function runOnSimulator(udid, appPath, bundleId, waitForApp) {
+ debug(`Booting simulator ${udid}`);
+ const bootResult = child_process_1.spawnSync('xcrun', ['simctl', 'boot', udid], {
+ encoding: 'utf8',
+ });
+ // TODO: is there a better way to check this?
+ if (bootResult.status &&
+ !bootResult.stderr.includes('Unable to boot device in current state: Booted')) {
+ throw new errors_1.Exception(`There was an error booting simulator: ${bootResult.stderr}`);
+ }
+ debug(`Installing ${appPath} on ${udid}`);
+ const installResult = child_process_1.spawnSync('xcrun', ['simctl', 'install', udid, appPath], { encoding: 'utf8' });
+ if (installResult.status) {
+ throw new errors_1.Exception(`There was an error installing app on simulator: ${installResult.stderr}`);
+ }
+ const xCodePath = await xcode_1.getXCodePath();
+ debug(`Running simulator ${udid}`);
+ const openResult = child_process_1.spawnSync('open', [
+ `${xCodePath}/Applications/Simulator.app`,
+ '--args',
+ '-CurrentDeviceUDID',
+ udid,
+ ], { encoding: 'utf8' });
+ if (openResult.status) {
+ throw new errors_1.Exception(`There was an error opening simulator: ${openResult.stderr}`);
+ }
+ debug(`Launching ${appPath} on ${udid}`);
+ const launchResult = child_process_1.spawnSync('xcrun', ['simctl', 'launch', udid, bundleId], { encoding: 'utf8' });
+ if (launchResult.status) {
+ throw new errors_1.Exception(`There was an error launching app on simulator: ${launchResult.stderr}`);
+ }
+ if (waitForApp) {
+ process_1.onBeforeExit(async () => {
+ const terminateResult = child_process_1.spawnSync('xcrun', ['simctl', 'terminate', udid, bundleId], { encoding: 'utf8' });
+ if (terminateResult.status) {
+ debug('Unable to terminate app on simulator');
+ }
+ });
+ log_1.log(`Waiting for app to close...\n`);
+ await waitForSimulatorClose(udid, bundleId);
+ }
+}
+exports.runOnSimulator = runOnSimulator;
+async function waitForSimulatorClose(udid, bundleId) {
+ return new Promise(resolve => {
+ // poll service list for bundle id
+ const interval = setInterval(async () => {
+ try {
+ const data = child_process_1.spawnSync('xcrun', ['simctl', 'spawn', udid, 'launchctl', 'list'], { encoding: 'utf8' });
+ // if bundle id isn't in list, app isn't running
+ if (data.stdout.indexOf(bundleId) === -1) {
+ clearInterval(interval);
+ resolve();
+ }
+ }
+ catch (e) {
+ debug('Error received from launchctl: %O', e);
+ debug('App %s no longer found in process list for %s', bundleId, udid);
+ clearInterval(interval);
+ resolve();
+ }
+ }, 500);
+ });
+}
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/dist/ios/utils/xcode.js b/temporary_modules/trezor-connect/node_modules/native-run/dist/ios/utils/xcode.js
new file mode 100644
index 00000000..a8407884
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/native-run/dist/ios/utils/xcode.js
@@ -0,0 +1,54 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+exports.getDeveloperDiskImagePath = exports.getXCodePath = exports.getXcodeVersionInfo = void 0;
+const utils_fs_1 = require("@ionic/utils-fs");
+const child_process_1 = require("child_process");
+const errors_1 = require("../../errors");
+const process_1 = require("../../utils/process");
+function getXcodeVersionInfo() {
+ const xcodeVersionInfo = child_process_1.spawnSync('xcodebuild', ['-version'], {
+ encoding: 'utf8',
+ });
+ if (xcodeVersionInfo.error) {
+ throw xcodeVersionInfo.error;
+ }
+ try {
+ const trimmed = xcodeVersionInfo.stdout.trim().split('\n');
+ return ['Xcode ', 'Build version'].map((s, i) => trimmed[i].replace(s, ''));
+ }
+ catch (error) {
+ throw new errors_1.Exception(`There was an error trying to retrieve the Xcode version: ${xcodeVersionInfo.stderr}`);
+ }
+}
+exports.getXcodeVersionInfo = getXcodeVersionInfo;
+async function getXCodePath() {
+ try {
+ const { stdout } = await process_1.execFile('xcode-select', ['-p'], {
+ encoding: 'utf8',
+ });
+ if (stdout) {
+ return stdout.trim();
+ }
+ }
+ catch {
+ // ignore
+ }
+ throw new errors_1.Exception('Unable to get Xcode location. Is Xcode installed?');
+}
+exports.getXCodePath = getXCodePath;
+async function getDeveloperDiskImagePath(version) {
+ const xCodePath = await getXCodePath();
+ const versionDirs = await utils_fs_1.readdir(`${xCodePath}/Platforms/iPhoneOS.platform/DeviceSupport/`);
+ const versionPrefix = version.match(/\d+\.\d+/);
+ if (versionPrefix === null) {
+ throw new errors_1.Exception(`Invalid iOS version: ${version}`);
+ }
+ // Can look like "11.2 (15C107)"
+ for (const dir of versionDirs) {
+ if (dir.includes(versionPrefix[0])) {
+ return `${xCodePath}/Platforms/iPhoneOS.platform/DeviceSupport/${dir}/DeveloperDiskImage.dmg`;
+ }
+ }
+ throw new errors_1.Exception(`Unable to find Developer Disk Image path for SDK ${version}. Do you have the right version of Xcode?`);
+}
+exports.getDeveloperDiskImagePath = getDeveloperDiskImagePath;
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/dist/list.js b/temporary_modules/trezor-connect/node_modules/native-run/dist/list.js
new file mode 100644
index 00000000..49d00917
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/native-run/dist/list.js
@@ -0,0 +1,35 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+exports.run = void 0;
+const json_1 = require("./utils/json");
+const list_1 = require("./utils/list");
+async function run(args) {
+ const [ios, android] = await Promise.all([
+ (async () => {
+ const cmd = await Promise.resolve().then(() => require('./ios/list'));
+ return cmd.list(args);
+ })(),
+ (async () => {
+ const cmd = await Promise.resolve().then(() => require('./android/list'));
+ return cmd.list(args);
+ })(),
+ ]);
+ if (args.includes('--json')) {
+ process.stdout.write(json_1.stringify({ ios, android }));
+ }
+ else {
+ process.stdout.write(`
+iOS
+---
+
+${list_1.formatTargets(args, ios)}
+
+Android
+-------
+
+${list_1.formatTargets(args, android)}
+
+ `);
+ }
+}
+exports.run = run;
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/dist/utils/cli.js b/temporary_modules/trezor-connect/node_modules/native-run/dist/utils/cli.js
new file mode 100644
index 00000000..77a521f7
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/native-run/dist/utils/cli.js
@@ -0,0 +1,21 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+exports.getOptionValues = exports.getOptionValue = void 0;
+function getOptionValue(args, arg, defaultValue) {
+ const i = args.indexOf(arg);
+ if (i >= 0) {
+ return args[i + 1];
+ }
+ return defaultValue;
+}
+exports.getOptionValue = getOptionValue;
+function getOptionValues(args, arg) {
+ const returnVal = [];
+ args.map((entry, idx) => {
+ if (entry === arg) {
+ returnVal.push(args[idx + 1]);
+ }
+ });
+ return returnVal;
+}
+exports.getOptionValues = getOptionValues;
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/dist/utils/fn.js b/temporary_modules/trezor-connect/node_modules/native-run/dist/utils/fn.js
new file mode 100644
index 00000000..d7263225
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/native-run/dist/utils/fn.js
@@ -0,0 +1,16 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+exports.once = void 0;
+function once(fn) {
+ let called = false;
+ let r;
+ const wrapper = (...args) => {
+ if (!called) {
+ called = true;
+ r = fn(...args);
+ }
+ return r;
+ };
+ return wrapper;
+}
+exports.once = once;
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/dist/utils/fs.js b/temporary_modules/trezor-connect/node_modules/native-run/dist/utils/fs.js
new file mode 100644
index 00000000..50c88c48
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/native-run/dist/utils/fs.js
@@ -0,0 +1,12 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+exports.isDir = void 0;
+const utils_fs_1 = require("@ionic/utils-fs");
+async function isDir(p) {
+ const stats = await utils_fs_1.statSafe(p);
+ if (stats === null || stats === void 0 ? void 0 : stats.isDirectory()) {
+ return true;
+ }
+ return false;
+}
+exports.isDir = isDir;
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/dist/utils/ini.js b/temporary_modules/trezor-connect/node_modules/native-run/dist/utils/ini.js
new file mode 100644
index 00000000..e689642d
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/native-run/dist/utils/ini.js
@@ -0,0 +1,30 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+exports.writeINI = exports.readINI = void 0;
+const utils_fs_1 = require("@ionic/utils-fs");
+const Debug = require("debug");
+const util = require("util");
+const debug = Debug('native-run:android:utils:ini');
+async function readINI(p, guard = (o) => true) {
+ const ini = await Promise.resolve().then(() => require('ini'));
+ try {
+ const contents = await utils_fs_1.readFile(p, { encoding: 'utf8' });
+ const config = ini.decode(contents);
+ if (!guard(config)) {
+ throw new Error(`Invalid ini configuration file: ${p}\n` +
+ `The following guard was used: ${guard.toString()}\n` +
+ `INI config parsed as: ${util.inspect(config)}`);
+ }
+ return { __filename: p, ...config };
+ }
+ catch (e) {
+ debug(e);
+ }
+}
+exports.readINI = readINI;
+async function writeINI(p, o) {
+ const ini = await Promise.resolve().then(() => require('ini'));
+ const contents = ini.encode(o);
+ await utils_fs_1.writeFile(p, contents, { encoding: 'utf8' });
+}
+exports.writeINI = writeINI;
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/dist/utils/json.js b/temporary_modules/trezor-connect/node_modules/native-run/dist/utils/json.js
new file mode 100644
index 00000000..21117a5f
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/native-run/dist/utils/json.js
@@ -0,0 +1,7 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+exports.stringify = void 0;
+function stringify(obj) {
+ return JSON.stringify(obj, (k, v) => (v instanceof RegExp ? v.toString() : v), '\t');
+}
+exports.stringify = stringify;
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/dist/utils/list.js b/temporary_modules/trezor-connect/node_modules/native-run/dist/utils/list.js
new file mode 100644
index 00000000..463d29d3
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/native-run/dist/utils/list.js
@@ -0,0 +1,69 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+exports.formatTargets = void 0;
+const utils_terminal_1 = require("@ionic/utils-terminal");
+const errors_1 = require("../errors");
+const json_1 = require("./json");
+function formatTargets(args, targets) {
+ const { devices, virtualDevices, errors } = targets;
+ const virtualOnly = args.includes('--virtual');
+ const devicesOnly = args.includes('--device');
+ if (virtualOnly && devicesOnly) {
+ throw new errors_1.CLIException('Only one of --device or --virtual may be specified', errors_1.ERR_BAD_INPUT);
+ }
+ if (args.includes('--json')) {
+ let result;
+ if (virtualOnly) {
+ result = { virtualDevices, errors };
+ }
+ else if (devicesOnly) {
+ result = { devices, errors };
+ }
+ else {
+ result = { devices, virtualDevices, errors };
+ }
+ return json_1.stringify(result);
+ }
+ let output = '';
+ if (errors.length > 0) {
+ output += `Errors (!):\n\n${errors.map(e => ` ${errors_1.serializeError(e)}`)}\n`;
+ }
+ if (!virtualOnly) {
+ output += printTargets('Connected Device', devices);
+ if (devicesOnly) {
+ return output;
+ }
+ output += '\n';
+ }
+ output += printTargets('Virtual Device', virtualDevices);
+ return output;
+}
+exports.formatTargets = formatTargets;
+function printTargets(name, targets) {
+ let output = `${name}s:\n\n`;
+ if (targets.length === 0) {
+ output += ` No ${name.toLowerCase()}s found\n`;
+ }
+ else {
+ output += formatTargetTable(targets) + '\n';
+ }
+ return output;
+}
+function formatTargetTable(targets) {
+ const spacer = utils_terminal_1.indent(2);
+ return (spacer +
+ utils_terminal_1.columnar(targets.map(targetToRow), {
+ headers: ['Name', 'API', 'Target ID'],
+ vsep: ' ',
+ })
+ .split('\n')
+ .join(`\n${spacer}`));
+}
+function targetToRow(target) {
+ var _a, _b, _c, _d;
+ return [
+ (_c = (_b = (_a = target.name) !== null && _a !== void 0 ? _a : target.model) !== null && _b !== void 0 ? _b : target.id) !== null && _c !== void 0 ? _c : '?',
+ `${target.platform === 'ios' ? 'iOS' : 'API'} ${target.sdkVersion}`,
+ (_d = target.id) !== null && _d !== void 0 ? _d : '?',
+ ];
+}
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/dist/utils/log.js b/temporary_modules/trezor-connect/node_modules/native-run/dist/utils/log.js
new file mode 100644
index 00000000..aa146fcf
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/native-run/dist/utils/log.js
@@ -0,0 +1,11 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+exports.log = void 0;
+const json_1 = require("./json");
+function log(message) {
+ if (process.argv.includes('--json')) {
+ message = json_1.stringify({ message });
+ }
+ process.stdout.write(message);
+}
+exports.log = log;
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/dist/utils/object.js b/temporary_modules/trezor-connect/node_modules/native-run/dist/utils/object.js
new file mode 100644
index 00000000..7edd0b9d
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/native-run/dist/utils/object.js
@@ -0,0 +1,15 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+exports.sort = void 0;
+function sort(obj) {
+ const entries = [...Object.entries(obj)];
+ entries.sort(([k1], [k2]) => k1.localeCompare(k2));
+ for (const [key] of entries) {
+ delete obj[key];
+ }
+ for (const [key, value] of entries) {
+ obj[key] = value;
+ }
+ return obj;
+}
+exports.sort = sort;
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/dist/utils/process.js b/temporary_modules/trezor-connect/node_modules/native-run/dist/utils/process.js
new file mode 100644
index 00000000..17062752
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/native-run/dist/utils/process.js
@@ -0,0 +1,39 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+exports.onBeforeExit = exports.wait = exports.execFile = exports.exec = void 0;
+const cp = require("child_process");
+const Debug = require("debug");
+const util = require("util");
+const fn_1 = require("./fn");
+const debug = Debug('native-run:utils:process');
+exports.exec = util.promisify(cp.exec);
+exports.execFile = util.promisify(cp.execFile);
+exports.wait = util.promisify(setTimeout);
+const exitQueue = [];
+function onBeforeExit(fn) {
+ exitQueue.push(fn);
+}
+exports.onBeforeExit = onBeforeExit;
+const BEFORE_EXIT_SIGNALS = [
+ 'SIGINT',
+ 'SIGTERM',
+ 'SIGHUP',
+ 'SIGBREAK',
+];
+const beforeExitHandlerWrapper = (signal) => fn_1.once(async () => {
+ debug('onBeforeExit handler: %s received', signal);
+ debug('onBeforeExit handler: running %s queued functions', exitQueue.length);
+ for (const [i, fn] of exitQueue.entries()) {
+ try {
+ await fn();
+ }
+ catch (e) {
+ debug('Error from function %d in exit queue: %O', i, e);
+ }
+ }
+ debug('onBeforeExit handler: exiting (exit code %s)', process.exitCode ? process.exitCode : 0);
+ process.exit();
+});
+for (const signal of BEFORE_EXIT_SIGNALS) {
+ process.on(signal, beforeExitHandlerWrapper(signal));
+}
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/dist/utils/unzip.js b/temporary_modules/trezor-connect/node_modules/native-run/dist/utils/unzip.js
new file mode 100644
index 00000000..d30ff7cc
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/native-run/dist/utils/unzip.js
@@ -0,0 +1,22 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+exports.unzip = void 0;
+const util_1 = require("util");
+async function unzip(srcPath, onEntry) {
+ const yauzl = await Promise.resolve().then(() => require('yauzl'));
+ return new Promise((resolve, reject) => {
+ yauzl.open(srcPath, { lazyEntries: true }, (err, zipfile) => {
+ if (!zipfile || err) {
+ return reject(err);
+ }
+ const openReadStream = util_1.promisify(zipfile.openReadStream.bind(zipfile));
+ zipfile.once('error', reject);
+ // resolve when either one happens
+ zipfile.once('close', resolve); // fd of zip closed
+ zipfile.once('end', resolve); // last entry read
+ zipfile.on('entry', entry => onEntry(entry, zipfile, openReadStream));
+ zipfile.readEntry();
+ });
+ });
+}
+exports.unzip = unzip;
diff --git a/temporary_modules/trezor-connect/node_modules/native-run/package.json b/temporary_modules/trezor-connect/node_modules/native-run/package.json
new file mode 100644
index 00000000..a2e2b02a
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/native-run/package.json
@@ -0,0 +1,110 @@
+{
+ "name": "native-run",
+ "version": "1.5.0",
+ "description": "A CLI for running apps on iOS/Android devices and simulators/emulators",
+ "bin": {
+ "native-run": "bin/native-run"
+ },
+ "scripts": {
+ "clean": "rm -rf dist",
+ "build": "npm run clean && tsc",
+ "watch": "tsc -w",
+ "test": "jest --maxWorkers=4",
+ "lint": "npm run eslint && npm run prettier -- --check",
+ "fmt": "npm run eslint -- --fix && npm run prettier -- --write",
+ "prettier": "prettier \"**/*.ts\"",
+ "eslint": "eslint . --ext .ts",
+ "publish:ci": "semantic-release",
+ "publish:testing": "npm version prerelease --preid=testing --no-git-tag-version && npm publish --tag=testing && git stash",
+ "prepublishOnly": "npm run build",
+ "setup": "husky install"
+ },
+ "main": "dist/index.js",
+ "files": [
+ "assets",
+ "bin",
+ "dist"
+ ],
+ "engines": {
+ "node": ">=10.3.0"
+ },
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/ionic-team/native-run.git"
+ },
+ "dependencies": {
+ "@ionic/utils-fs": "^3.1.5",
+ "@ionic/utils-terminal": "^2.3.1",
+ "bplist-parser": "^0.3.0",
+ "debug": "^4.3.2",
+ "elementtree": "^0.1.7",
+ "ini": "^1.3.5",
+ "plist": "^3.0.4",
+ "split2": "^3.2.2",
+ "through2": "^4.0.2",
+ "tslib": "^2.3.1",
+ "yauzl": "^2.10.0"
+ },
+ "devDependencies": {
+ "@ionic/eslint-config": "^0.3.0",
+ "@ionic/prettier-config": "^1.0.1",
+ "@semantic-release/changelog": "^5.0.0",
+ "@semantic-release/git": "^9.0.0",
+ "@types/debug": "4.1.5",
+ "@types/elementtree": "^0.1.0",
+ "@types/fs-extra": "^8.1.1",
+ "@types/ini": "^1.3.30",
+ "@types/jest": "^26.0.13",
+ "@types/node": "^10.17.14",
+ "@types/plist": "^3.0.2",
+ "@types/slice-ansi": "^4.0.0",
+ "@types/split2": "^2.1.6",
+ "@types/through2": "^2.0.34",
+ "@types/yauzl": "^2.9.1",
+ "eslint": "^7.8.1",
+ "husky": "^5.0.4",
+ "jest": "^26.4.2",
+ "prettier": "^2.2.1",
+ "semantic-release": "^17.1.1",
+ "ts-jest": "^26.3.0",
+ "typescript": "~4.1.2"
+ },
+ "prettier": "@ionic/prettier-config",
+ "eslintConfig": {
+ "extends": "@ionic/eslint-config/recommended",
+ "rules": {
+ "@typescript-eslint/explicit-module-boundary-types": [
+ "warn",
+ {
+ "allowArgumentsExplicitlyTypedAsAny": true
+ }
+ ]
+ }
+ },
+ "release": {
+ "branches": "stable",
+ "plugins": [
+ "@semantic-release/commit-analyzer",
+ "@semantic-release/release-notes-generator",
+ "@semantic-release/changelog",
+ "@semantic-release/npm",
+ "@semantic-release/github",
+ "@semantic-release/git"
+ ]
+ },
+ "keywords": [
+ "android",
+ "ios",
+ "cli",
+ "mobile",
+ "app",
+ "hybrid",
+ "native"
+ ],
+ "author": "Ionic Team (https://ionicframework.com)",
+ "license": "MIT",
+ "bugs": {
+ "url": "https://github.com/ionic-team/native-run/issues"
+ },
+ "homepage": "https://github.com/ionic-team/native-run#readme"
+}
diff --git a/temporary_modules/trezor-connect/node_modules/open/index.d.ts b/temporary_modules/trezor-connect/node_modules/open/index.d.ts
new file mode 100644
index 00000000..4365e1f6
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/open/index.d.ts
@@ -0,0 +1,88 @@
+///
+import {ChildProcess} from 'child_process';
+
+declare namespace open {
+ interface Options {
+ /**
+ Wait for the opened app to exit before fulfilling the promise. If `false` it's fulfilled immediately when opening the app.
+
+ Note that it waits for the app to exit, not just for the window to close.
+
+ On Windows, you have to explicitly specify an app for it to be able to wait.
+
+ @default false
+ */
+ readonly wait?: boolean;
+
+ /**
+ __macOS only__
+
+ Do not bring the app to the foreground.
+
+ @default false
+ */
+ readonly background?: boolean;
+
+ /**
+ Specify the app to open the `target` with, or an array with the app and app arguments.
+
+ The app name is platform dependent. Don't hard code it in reusable modules. For example, Chrome is `google chrome` on macOS, `google-chrome` on Linux and `chrome` on Windows.
+
+ You may also pass in the app's full path. For example on WSL, this can be `/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe` for the Windows installation of Chrome.
+ */
+ readonly app?: string | readonly string[];
+
+ /**
+ __deprecated__
+
+ This option will be removed in the next major release.
+ */
+ readonly url?: boolean;
+
+ /**
+ Allow the opened app to exit with nonzero exit code when the `wait` option is `true`.
+
+ We do not recommend setting this option. The convention for success is exit code zero.
+
+ @default false
+ */
+ readonly allowNonzeroExitCode?: boolean;
+ }
+}
+
+/**
+Open stuff like URLs, files, executables. Cross-platform.
+
+Uses the command `open` on OS X, `start` on Windows and `xdg-open` on other platforms.
+
+There is a caveat for [double-quotes on Windows](https://github.com/sindresorhus/open#double-quotes-on-windows) where all double-quotes are stripped from the `target`.
+
+@param target - The thing you want to open. Can be a URL, file, or executable. Opens in the default app for the file type. For example, URLs open in your default browser.
+@returns The [spawned child process](https://nodejs.org/api/child_process.html#child_process_class_childprocess). You would normally not need to use this for anything, but it can be useful if you'd like to attach custom event listeners or perform other operations directly on the spawned process.
+
+@example
+```
+import open = require('open');
+
+// Opens the image in the default image viewer
+(async () => {
+ await open('unicorn.png', {wait: true});
+ console.log('The image viewer app closed');
+
+ // Opens the url in the default browser
+ await open('https://sindresorhus.com');
+
+ // Specify the app to open in
+ await open('https://sindresorhus.com', {app: 'firefox'});
+
+ // Specify app arguments
+ await open('https://sindresorhus.com', {app: ['google chrome', '--incognito']});
+})();
+```
+*/
+declare function open(
+ target: string,
+ options?: open.Options
+): Promise;
+
+export = open;
diff --git a/temporary_modules/trezor-connect/node_modules/open/index.js b/temporary_modules/trezor-connect/node_modules/open/index.js
new file mode 100644
index 00000000..13147d09
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/open/index.js
@@ -0,0 +1,195 @@
+'use strict';
+const {promisify} = require('util');
+const path = require('path');
+const childProcess = require('child_process');
+const fs = require('fs');
+const isWsl = require('is-wsl');
+const isDocker = require('is-docker');
+
+const pAccess = promisify(fs.access);
+const pReadFile = promisify(fs.readFile);
+
+// Path to included `xdg-open`.
+const localXdgOpenPath = path.join(__dirname, 'xdg-open');
+
+/**
+Get the mount point for fixed drives in WSL.
+
+@inner
+@returns {string} The mount point.
+*/
+const getWslDrivesMountPoint = (() => {
+ // Default value for "root" param
+ // according to https://docs.microsoft.com/en-us/windows/wsl/wsl-config
+ const defaultMountPoint = '/mnt/';
+
+ let mountPoint;
+
+ return async function () {
+ if (mountPoint) {
+ // Return memoized mount point value
+ return mountPoint;
+ }
+
+ const configFilePath = '/etc/wsl.conf';
+
+ let isConfigFileExists = false;
+ try {
+ await pAccess(configFilePath, fs.constants.F_OK);
+ isConfigFileExists = true;
+ } catch (_) {}
+
+ if (!isConfigFileExists) {
+ return defaultMountPoint;
+ }
+
+ const configContent = await pReadFile(configFilePath, {encoding: 'utf8'});
+ const configMountPoint = /root\s*=\s*(.*)/g.exec(configContent);
+
+ if (!configMountPoint) {
+ return defaultMountPoint;
+ }
+
+ mountPoint = configMountPoint[1].trim();
+ mountPoint = mountPoint.endsWith('/') ? mountPoint : mountPoint + '/';
+
+ return mountPoint;
+ };
+})();
+
+module.exports = async (target, options) => {
+ if (typeof target !== 'string') {
+ throw new TypeError('Expected a `target`');
+ }
+
+ options = {
+ wait: false,
+ background: false,
+ allowNonzeroExitCode: false,
+ ...options
+ };
+
+ let command;
+ let {app} = options;
+ let appArguments = [];
+ const cliArguments = [];
+ const childProcessOptions = {};
+
+ if (Array.isArray(app)) {
+ appArguments = app.slice(1);
+ app = app[0];
+ }
+
+ if (process.platform === 'darwin') {
+ command = 'open';
+
+ if (options.wait) {
+ cliArguments.push('--wait-apps');
+ }
+
+ if (options.background) {
+ cliArguments.push('--background');
+ }
+
+ if (app) {
+ cliArguments.push('-a', app);
+ }
+ } else if (process.platform === 'win32' || (isWsl && !isDocker())) {
+ const mountPoint = await getWslDrivesMountPoint();
+
+ command = isWsl ?
+ `${mountPoint}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe` :
+ `${process.env.SYSTEMROOT}\\System32\\WindowsPowerShell\\v1.0\\powershell`;
+
+ cliArguments.push(
+ '-NoProfile',
+ '-NonInteractive',
+ '–ExecutionPolicy',
+ 'Bypass',
+ '-EncodedCommand'
+ );
+
+ if (!isWsl) {
+ childProcessOptions.windowsVerbatimArguments = true;
+ }
+
+ const encodedArguments = ['Start'];
+
+ if (options.wait) {
+ encodedArguments.push('-Wait');
+ }
+
+ if (app) {
+ // Double quote with double quotes to ensure the inner quotes are passed through.
+ // Inner quotes are delimited for PowerShell interpretation with backticks.
+ encodedArguments.push(`"\`"${app}\`""`, '-ArgumentList');
+ appArguments.unshift(target);
+ } else {
+ encodedArguments.push(`"${target}"`);
+ }
+
+ if (appArguments.length > 0) {
+ appArguments = appArguments.map(arg => `"\`"${arg}\`""`);
+ encodedArguments.push(appArguments.join(','));
+ }
+
+ // Using Base64-encoded command, accepted by PowerShell, to allow special characters.
+ target = Buffer.from(encodedArguments.join(' '), 'utf16le').toString('base64');
+ } else {
+ if (app) {
+ command = app;
+ } else {
+ // When bundled by Webpack, there's no actual package file path and no local `xdg-open`.
+ const isBundled = !__dirname || __dirname === '/';
+
+ // Check if local `xdg-open` exists and is executable.
+ let exeLocalXdgOpen = false;
+ try {
+ await pAccess(localXdgOpenPath, fs.constants.X_OK);
+ exeLocalXdgOpen = true;
+ } catch (_) {}
+
+ const useSystemXdgOpen = process.versions.electron ||
+ process.platform === 'android' || isBundled || !exeLocalXdgOpen;
+ command = useSystemXdgOpen ? 'xdg-open' : localXdgOpenPath;
+ }
+
+ if (appArguments.length > 0) {
+ cliArguments.push(...appArguments);
+ }
+
+ if (!options.wait) {
+ // `xdg-open` will block the process unless stdio is ignored
+ // and it's detached from the parent even if it's unref'd.
+ childProcessOptions.stdio = 'ignore';
+ childProcessOptions.detached = true;
+ }
+ }
+
+ cliArguments.push(target);
+
+ if (process.platform === 'darwin' && appArguments.length > 0) {
+ cliArguments.push('--args', ...appArguments);
+ }
+
+ const subprocess = childProcess.spawn(command, cliArguments, childProcessOptions);
+
+ if (options.wait) {
+ return new Promise((resolve, reject) => {
+ subprocess.once('error', reject);
+
+ subprocess.once('close', exitCode => {
+ if (options.allowNonzeroExitCode && exitCode > 0) {
+ reject(new Error(`Exited with code ${exitCode}`));
+ return;
+ }
+
+ resolve(subprocess);
+ });
+ });
+ }
+
+ subprocess.unref();
+
+ return subprocess;
+};
diff --git a/temporary_modules/trezor-connect/node_modules/open/license b/temporary_modules/trezor-connect/node_modules/open/license
new file mode 100644
index 00000000..fa7ceba3
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/open/license
@@ -0,0 +1,9 @@
+MIT License
+
+Copyright (c) Sindre Sorhus (https://sindresorhus.com)
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/temporary_modules/trezor-connect/node_modules/open/package.json b/temporary_modules/trezor-connect/node_modules/open/package.json
new file mode 100644
index 00000000..1800b42b
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/open/package.json
@@ -0,0 +1,60 @@
+{
+ "name": "open",
+ "version": "7.4.2",
+ "description": "Open stuff like URLs, files, executables. Cross-platform.",
+ "license": "MIT",
+ "repository": "sindresorhus/open",
+ "funding": "https://github.com/sponsors/sindresorhus",
+ "author": {
+ "name": "Sindre Sorhus",
+ "email": "sindresorhus@gmail.com",
+ "url": "https://sindresorhus.com"
+ },
+ "engines": {
+ "node": ">=8"
+ },
+ "scripts": {
+ "test": "xo && tsd"
+ },
+ "files": [
+ "index.js",
+ "index.d.ts",
+ "xdg-open"
+ ],
+ "keywords": [
+ "app",
+ "open",
+ "opener",
+ "opens",
+ "launch",
+ "start",
+ "xdg-open",
+ "xdg",
+ "default",
+ "cmd",
+ "browser",
+ "editor",
+ "executable",
+ "exe",
+ "url",
+ "urls",
+ "arguments",
+ "args",
+ "spawn",
+ "exec",
+ "child",
+ "process",
+ "website",
+ "file"
+ ],
+ "dependencies": {
+ "is-docker": "^2.0.0",
+ "is-wsl": "^2.1.1"
+ },
+ "devDependencies": {
+ "@types/node": "^12.7.5",
+ "ava": "^2.3.0",
+ "tsd": "^0.11.0",
+ "xo": "^0.25.3"
+ }
+}
diff --git a/temporary_modules/trezor-connect/node_modules/open/readme.md b/temporary_modules/trezor-connect/node_modules/open/readme.md
new file mode 100644
index 00000000..c4560a7a
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/open/readme.md
@@ -0,0 +1,154 @@
+# open
+
+> Open stuff like URLs, files, executables. Cross-platform.
+
+This is meant to be used in command-line tools and scripts, not in the browser.
+
+If you need this for Electron, use [`shell.openPath()`](https://www.electronjs.org/docs/api/shell#shellopenpathpath) instead.
+
+Note: The original [`open` package](https://github.com/pwnall/node-open) was previously deprecated in favor of this package, and we got the name, so this package is now named `open` instead of `opn`. If you're upgrading from the original `open` package (`open@0.0.5` or lower), keep in mind that the API is different.
+
+#### Why?
+
+- Actively maintained.
+- Supports app arguments.
+- Safer as it uses `spawn` instead of `exec`.
+- Fixes most of the open original `node-open` issues.
+- Includes the latest [`xdg-open` script](https://cgit.freedesktop.org/xdg/xdg-utils/commit/?id=c55122295c2a480fa721a9614f0e2d42b2949c18) for Linux.
+- Supports WSL paths to Windows apps.
+
+## Install
+
+```
+$ npm install open
+```
+
+## Usage
+
+```js
+const open = require('open');
+
+(async () => {
+ // Opens the image in the default image viewer and waits for the opened app to quit.
+ await open('unicorn.png', {wait: true});
+ console.log('The image viewer app quit');
+
+ // Opens the URL in the default browser.
+ await open('https://sindresorhus.com');
+
+ // Opens the URL in a specified browser.
+ await open('https://sindresorhus.com', {app: 'firefox'});
+
+ // Specify app arguments.
+ await open('https://sindresorhus.com', {app: ['google chrome', '--incognito']});
+})();
+```
+
+## API
+
+It uses the command `open` on macOS, `start` on Windows and `xdg-open` on other platforms.
+
+### open(target, options?)
+
+Returns a promise for the [spawned child process](https://nodejs.org/api/child_process.html#child_process_class_childprocess). You would normally not need to use this for anything, but it can be useful if you'd like to attach custom event listeners or perform other operations directly on the spawned process.
+
+#### target
+
+Type: `string`
+
+The thing you want to open. Can be a URL, file, or executable.
+
+Opens in the default app for the file type. For example, URLs opens in your default browser.
+
+#### options
+
+Type: `object`
+
+##### wait
+
+Type: `boolean`\
+Default: `false`
+
+Wait for the opened app to exit before fulfilling the promise. If `false` it's fulfilled immediately when opening the app.
+
+Note that it waits for the app to exit, not just for the window to close.
+
+On Windows, you have to explicitly specify an app for it to be able to wait.
+
+##### background (macOS only)
+
+Type: `boolean`\
+Default: `false`
+
+Do not bring the app to the foreground.
+
+##### app
+
+Type: `string | string[]`
+
+Specify the app to open the `target` with, or an array with the app and app arguments.
+
+The app name is platform dependent. Don't hard code it in reusable modules. For example, Chrome is `google chrome` on macOS, `google-chrome` on Linux and `chrome` on Windows.
+
+You may also pass in the app's full path. For example on WSL, this can be `/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe` for the Windows installation of Chrome.
+
+##### url
+
+Type: `boolean`\
+Default: `false`
+
+Uses `URL` to encode the target before executing it.
+We do not recommend using it on targets that are not URLs.
+
+Especially useful when dealing with the [double-quotes on Windows](#double-quotes-on-windows) caveat.
+
+##### allowNonzeroExitCode
+
+Type: `boolean`\
+Default: `false`
+
+Allow the opened app to exit with nonzero exit code when the `wait` option is `true`.
+
+We do not recommend setting this option. The convention for success is exit code zero.
+
+## Caveats
+
+### Double-quotes on Windows
+
+TL;DR: All double-quotes are stripped from the `target` and do not get to your desired destination (on Windows!).
+
+Due to specific behaviors of Window's Command Prompt (`cmd.exe`) regarding ampersand (`&`) characters breaking commands and URLs, double-quotes are now a special case.
+
+The solution ([#146](https://github.com/sindresorhus/open/pull/146)) to this and other problems was to leverage the fact that `cmd.exe` interprets a double-quoted argument as a plain text argument just by quoting it (like Node.js already does). Unfortunately, `cmd.exe` can only do **one** of two things: handle them all **OR** not handle them at all. As per its own documentation:
+
+>*If /C or /K is specified, then the remainder of the command line after the switch is processed as a command line, where the following logic is used to process quote (") characters:*
+>
+> 1. *If all of the following conditions are met, then quote characters on the command line are preserved:*
+> - *no /S switch*
+> - *exactly two quote characters*
+> - *no special characters between the two quote characters, where special is one of: &<>()@^|*
+> - *there are one or more whitespace characters between the two quote characters*
+> - *the string between the two quote characters is the name of an executable file.*
+>
+> 2. *Otherwise, old behavior is to see if the first character is a quote character and if so, strip the leading character and remove the last quote character on the command line, preserving any text after the last quote character.*
+
+The option that solved all of the problems was the second one, and for additional behavior consistency we're also now using the `/S` switch, so we **always** get the second option. The caveat is that this built-in double-quotes handling ends up stripping all of them from the command line and so far we weren't able to find an escaping method that works (if you do, please feel free to contribute!).
+
+To make this caveat somewhat less impactful (at least for URLs), check out the [url option](#url). Double-quotes will be "preserved" when using it with an URL.
+
+## Related
+
+- [open-cli](https://github.com/sindresorhus/open-cli) - CLI for this module
+- [open-editor](https://github.com/sindresorhus/open-editor) - Open files in your editor at a specific line and column
+
+---
+
+
diff --git a/temporary_modules/trezor-connect/node_modules/open/xdg-open b/temporary_modules/trezor-connect/node_modules/open/xdg-open
new file mode 100644
index 00000000..faaea7ff
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/open/xdg-open
@@ -0,0 +1,1066 @@
+#!/bin/sh
+#---------------------------------------------
+# xdg-open
+#
+# Utility script to open a URL in the registered default application.
+#
+# Refer to the usage() function below for usage.
+#
+# Copyright 2009-2010, Fathi Boudra
+# Copyright 2009-2010, Rex Dieter
+# Copyright 2006, Kevin Krammer
+# Copyright 2006, Jeremy White
+#
+# LICENSE:
+#
+# Permission is hereby granted, free of charge, to any person obtaining a
+# copy of this software and associated documentation files (the "Software"),
+# to deal in the Software without restriction, including without limitation
+# the rights to use, copy, modify, merge, publish, distribute, sublicense,
+# and/or sell copies of the Software, and to permit persons to whom the
+# Software is furnished to do so, subject to the following conditions:
+#
+# The above copyright notice and this permission notice shall be included
+# in all copies or substantial portions of the Software.
+#
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
+# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
+# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+# OTHER DEALINGS IN THE SOFTWARE.
+#
+#---------------------------------------------
+
+manualpage()
+{
+cat << _MANUALPAGE
+Name
+
+ xdg-open -- opens a file or URL in the user's preferred
+ application
+
+Synopsis
+
+ xdg-open { file | URL }
+
+ xdg-open { --help | --manual | --version }
+
+Description
+
+ xdg-open opens a file or URL in the user's preferred
+ application. If a URL is provided the URL will be opened in the
+ user's preferred web browser. If a file is provided the file
+ will be opened in the preferred application for files of that
+ type. xdg-open supports file, ftp, http and https URLs.
+
+ xdg-open is for use inside a desktop session only. It is not
+ recommended to use xdg-open as root.
+
+Options
+
+ --help
+ Show command synopsis.
+
+ --manual
+ Show this manual page.
+
+ --version
+ Show the xdg-utils version information.
+
+Exit Codes
+
+ An exit code of 0 indicates success while a non-zero exit code
+ indicates failure. The following failure codes can be returned:
+
+ 1
+ Error in command line syntax.
+
+ 2
+ One of the files passed on the command line did not
+ exist.
+
+ 3
+ A required tool could not be found.
+
+ 4
+ The action failed.
+
+See Also
+
+ xdg-mime(1), xdg-settings(1), MIME applications associations
+ specification
+
+Examples
+
+xdg-open 'http://www.freedesktop.org/'
+
+ Opens the freedesktop.org website in the user's default
+ browser.
+
+xdg-open /tmp/foobar.png
+
+ Opens the PNG image file /tmp/foobar.png in the user's default
+ image viewing application.
+_MANUALPAGE
+}
+
+usage()
+{
+cat << _USAGE
+ xdg-open -- opens a file or URL in the user's preferred
+ application
+
+Synopsis
+
+ xdg-open { file | URL }
+
+ xdg-open { --help | --manual | --version }
+
+_USAGE
+}
+
+#@xdg-utils-common@
+
+#----------------------------------------------------------------------------
+# Common utility functions included in all XDG wrapper scripts
+#----------------------------------------------------------------------------
+
+DEBUG()
+{
+ [ -z "${XDG_UTILS_DEBUG_LEVEL}" ] && return 0;
+ [ ${XDG_UTILS_DEBUG_LEVEL} -lt $1 ] && return 0;
+ shift
+ echo "$@" >&2
+}
+
+# This handles backslashes but not quote marks.
+first_word()
+{
+ read first rest
+ echo "$first"
+}
+
+#-------------------------------------------------------------
+# map a binary to a .desktop file
+binary_to_desktop_file()
+{
+ search="${XDG_DATA_HOME:-$HOME/.local/share}:${XDG_DATA_DIRS:-/usr/local/share:/usr/share}"
+ binary="`which "$1"`"
+ binary="`readlink -f "$binary"`"
+ base="`basename "$binary"`"
+ IFS=:
+ for dir in $search; do
+ unset IFS
+ [ "$dir" ] || continue
+ [ -d "$dir/applications" ] || [ -d "$dir/applnk" ] || continue
+ for file in "$dir"/applications/*.desktop "$dir"/applications/*/*.desktop "$dir"/applnk/*.desktop "$dir"/applnk/*/*.desktop; do
+ [ -r "$file" ] || continue
+ # Check to make sure it's worth the processing.
+ grep -q "^Exec.*$base" "$file" || continue
+ # Make sure it's a visible desktop file (e.g. not "preferred-web-browser.desktop").
+ grep -Eq "^(NoDisplay|Hidden)=true" "$file" && continue
+ command="`grep -E "^Exec(\[[^]=]*])?=" "$file" | cut -d= -f 2- | first_word`"
+ command="`which "$command"`"
+ if [ x"`readlink -f "$command"`" = x"$binary" ]; then
+ # Fix any double slashes that got added path composition
+ echo "$file" | sed -e 's,//*,/,g'
+ return
+ fi
+ done
+ done
+}
+
+#-------------------------------------------------------------
+# map a .desktop file to a binary
+desktop_file_to_binary()
+{
+ search="${XDG_DATA_HOME:-$HOME/.local/share}:${XDG_DATA_DIRS:-/usr/local/share:/usr/share}"
+ desktop="`basename "$1"`"
+ IFS=:
+ for dir in $search; do
+ unset IFS
+ [ "$dir" ] && [ -d "$dir/applications" ] || [ -d "$dir/applnk" ] || continue
+ # Check if desktop file contains -
+ if [ "${desktop#*-}" != "$desktop" ]; then
+ vendor=${desktop%-*}
+ app=${desktop#*-}
+ if [ -r $dir/applications/$vendor/$app ]; then
+ file_path=$dir/applications/$vendor/$app
+ elif [ -r $dir/applnk/$vendor/$app ]; then
+ file_path=$dir/applnk/$vendor/$app
+ fi
+ fi
+ if test -z "$file_path" ; then
+ for indir in "$dir"/applications/ "$dir"/applications/*/ "$dir"/applnk/ "$dir"/applnk/*/; do
+ file="$indir/$desktop"
+ if [ -r "$file" ]; then
+ file_path=$file
+ break
+ fi
+ done
+ fi
+ if [ -r "$file_path" ]; then
+ # Remove any arguments (%F, %f, %U, %u, etc.).
+ command="`grep -E "^Exec(\[[^]=]*])?=" "$file_path" | cut -d= -f 2- | first_word`"
+ command="`which "$command"`"
+ readlink -f "$command"
+ return
+ fi
+ done
+}
+
+#-------------------------------------------------------------
+# Exit script on successfully completing the desired operation
+
+exit_success()
+{
+ if [ $# -gt 0 ]; then
+ echo "$@"
+ echo
+ fi
+
+ exit 0
+}
+
+
+#-----------------------------------------
+# Exit script on malformed arguments, not enough arguments
+# or missing required option.
+# prints usage information
+
+exit_failure_syntax()
+{
+ if [ $# -gt 0 ]; then
+ echo "xdg-open: $@" >&2
+ echo "Try 'xdg-open --help' for more information." >&2
+ else
+ usage
+ echo "Use 'man xdg-open' or 'xdg-open --manual' for additional info."
+ fi
+
+ exit 1
+}
+
+#-------------------------------------------------------------
+# Exit script on missing file specified on command line
+
+exit_failure_file_missing()
+{
+ if [ $# -gt 0 ]; then
+ echo "xdg-open: $@" >&2
+ fi
+
+ exit 2
+}
+
+#-------------------------------------------------------------
+# Exit script on failure to locate necessary tool applications
+
+exit_failure_operation_impossible()
+{
+ if [ $# -gt 0 ]; then
+ echo "xdg-open: $@" >&2
+ fi
+
+ exit 3
+}
+
+#-------------------------------------------------------------
+# Exit script on failure returned by a tool application
+
+exit_failure_operation_failed()
+{
+ if [ $# -gt 0 ]; then
+ echo "xdg-open: $@" >&2
+ fi
+
+ exit 4
+}
+
+#------------------------------------------------------------
+# Exit script on insufficient permission to read a specified file
+
+exit_failure_file_permission_read()
+{
+ if [ $# -gt 0 ]; then
+ echo "xdg-open: $@" >&2
+ fi
+
+ exit 5
+}
+
+#------------------------------------------------------------
+# Exit script on insufficient permission to write a specified file
+
+exit_failure_file_permission_write()
+{
+ if [ $# -gt 0 ]; then
+ echo "xdg-open: $@" >&2
+ fi
+
+ exit 6
+}
+
+check_input_file()
+{
+ if [ ! -e "$1" ]; then
+ exit_failure_file_missing "file '$1' does not exist"
+ fi
+ if [ ! -r "$1" ]; then
+ exit_failure_file_permission_read "no permission to read file '$1'"
+ fi
+}
+
+check_vendor_prefix()
+{
+ file_label="$2"
+ [ -n "$file_label" ] || file_label="filename"
+ file=`basename "$1"`
+ case "$file" in
+ [[:alpha:]]*-*)
+ return
+ ;;
+ esac
+
+ echo "xdg-open: $file_label '$file' does not have a proper vendor prefix" >&2
+ echo 'A vendor prefix consists of alpha characters ([a-zA-Z]) and is terminated' >&2
+ echo 'with a dash ("-"). An example '"$file_label"' is '"'example-$file'" >&2
+ echo "Use --novendor to override or 'xdg-open --manual' for additional info." >&2
+ exit 1
+}
+
+check_output_file()
+{
+ # if the file exists, check if it is writeable
+ # if it does not exists, check if we are allowed to write on the directory
+ if [ -e "$1" ]; then
+ if [ ! -w "$1" ]; then
+ exit_failure_file_permission_write "no permission to write to file '$1'"
+ fi
+ else
+ DIR=`dirname "$1"`
+ if [ ! -w "$DIR" ] || [ ! -x "$DIR" ]; then
+ exit_failure_file_permission_write "no permission to create file '$1'"
+ fi
+ fi
+}
+
+#----------------------------------------
+# Checks for shared commands, e.g. --help
+
+check_common_commands()
+{
+ while [ $# -gt 0 ] ; do
+ parm="$1"
+ shift
+
+ case "$parm" in
+ --help)
+ usage
+ echo "Use 'man xdg-open' or 'xdg-open --manual' for additional info."
+ exit_success
+ ;;
+
+ --manual)
+ manualpage
+ exit_success
+ ;;
+
+ --version)
+ echo "xdg-open 1.1.3"
+ exit_success
+ ;;
+ esac
+ done
+}
+
+check_common_commands "$@"
+
+[ -z "${XDG_UTILS_DEBUG_LEVEL}" ] && unset XDG_UTILS_DEBUG_LEVEL;
+if [ ${XDG_UTILS_DEBUG_LEVEL-0} -lt 1 ]; then
+ # Be silent
+ xdg_redirect_output=" > /dev/null 2> /dev/null"
+else
+ # All output to stderr
+ xdg_redirect_output=" >&2"
+fi
+
+#--------------------------------------
+# Checks for known desktop environments
+# set variable DE to the desktop environments name, lowercase
+
+detectDE()
+{
+ # see https://bugs.freedesktop.org/show_bug.cgi?id=34164
+ unset GREP_OPTIONS
+
+ if [ -n "${XDG_CURRENT_DESKTOP}" ]; then
+ case "${XDG_CURRENT_DESKTOP}" in
+ # only recently added to menu-spec, pre-spec X- still in use
+ Cinnamon|X-Cinnamon)
+ DE=cinnamon;
+ ;;
+ ENLIGHTENMENT)
+ DE=enlightenment;
+ ;;
+ # GNOME, GNOME-Classic:GNOME, or GNOME-Flashback:GNOME
+ GNOME*)
+ DE=gnome;
+ ;;
+ KDE)
+ DE=kde;
+ ;;
+ # Deepin Desktop Environments
+ DEEPIN|Deepin|deepin)
+ DE=dde;
+ ;;
+ LXDE)
+ DE=lxde;
+ ;;
+ LXQt)
+ DE=lxqt;
+ ;;
+ MATE)
+ DE=mate;
+ ;;
+ XFCE)
+ DE=xfce
+ ;;
+ X-Generic)
+ DE=generic
+ ;;
+ esac
+ fi
+
+ if [ x"$DE" = x"" ]; then
+ # classic fallbacks
+ if [ x"$KDE_FULL_SESSION" != x"" ]; then DE=kde;
+ elif [ x"$GNOME_DESKTOP_SESSION_ID" != x"" ]; then DE=gnome;
+ elif [ x"$MATE_DESKTOP_SESSION_ID" != x"" ]; then DE=mate;
+ elif `dbus-send --print-reply --dest=org.freedesktop.DBus /org/freedesktop/DBus org.freedesktop.DBus.GetNameOwner string:org.gnome.SessionManager > /dev/null 2>&1` ; then DE=gnome;
+ elif xprop -root _DT_SAVE_MODE 2> /dev/null | grep ' = \"xfce4\"$' >/dev/null 2>&1; then DE=xfce;
+ elif xprop -root 2> /dev/null | grep -i '^xfce_desktop_window' >/dev/null 2>&1; then DE=xfce
+ elif echo $DESKTOP | grep -q '^Enlightenment'; then DE=enlightenment;
+ elif [ x"$LXQT_SESSION_CONFIG" != x"" ]; then DE=lxqt;
+ fi
+ fi
+
+ if [ x"$DE" = x"" ]; then
+ # fallback to checking $DESKTOP_SESSION
+ case "$DESKTOP_SESSION" in
+ gnome)
+ DE=gnome;
+ ;;
+ LXDE|Lubuntu)
+ DE=lxde;
+ ;;
+ MATE)
+ DE=mate;
+ ;;
+ xfce|xfce4|'Xfce Session')
+ DE=xfce;
+ ;;
+ esac
+ fi
+
+ if [ x"$DE" = x"" ]; then
+ # fallback to uname output for other platforms
+ case "$(uname 2>/dev/null)" in
+ CYGWIN*)
+ DE=cygwin;
+ ;;
+ Darwin)
+ DE=darwin;
+ ;;
+ esac
+ fi
+
+ if [ x"$DE" = x"gnome" ]; then
+ # gnome-default-applications-properties is only available in GNOME 2.x
+ # but not in GNOME 3.x
+ which gnome-default-applications-properties > /dev/null 2>&1 || DE="gnome3"
+ fi
+
+ if [ -f "$XDG_RUNTIME_DIR/flatpak-info" ]; then
+ DE="flatpak"
+ fi
+}
+
+#----------------------------------------------------------------------------
+# kfmclient exec/openURL can give bogus exit value in KDE <= 3.5.4
+# It also always returns 1 in KDE 3.4 and earlier
+# Simply return 0 in such case
+
+kfmclient_fix_exit_code()
+{
+ version=`LC_ALL=C.UTF-8 kde-config --version 2>/dev/null | grep '^KDE'`
+ major=`echo $version | sed 's/KDE.*: \([0-9]\).*/\1/'`
+ minor=`echo $version | sed 's/KDE.*: [0-9]*\.\([0-9]\).*/\1/'`
+ release=`echo $version | sed 's/KDE.*: [0-9]*\.[0-9]*\.\([0-9]\).*/\1/'`
+ test "$major" -gt 3 && return $1
+ test "$minor" -gt 5 && return $1
+ test "$release" -gt 4 && return $1
+ return 0
+}
+
+#----------------------------------------------------------------------------
+# Returns true if there is a graphical display attached.
+
+has_display()
+{
+ if [ -n "$DISPLAY" ] || [ -n "$WAYLAND_DISPLAY" ]; then
+ return 0
+ else
+ return 1
+ fi
+}
+
+# This handles backslashes but not quote marks.
+last_word()
+{
+ read first rest
+ echo "$rest"
+}
+
+# Get the value of a key in a desktop file's Desktop Entry group.
+# Example: Use get_key foo.desktop Exec
+# to get the values of the Exec= key for the Desktop Entry group.
+get_key()
+{
+ local file="${1}"
+ local key="${2}"
+ local desktop_entry=""
+
+ IFS_="${IFS}"
+ IFS=""
+ while read line
+ do
+ case "$line" in
+ "[Desktop Entry]")
+ desktop_entry="y"
+ ;;
+ # Reset match flag for other groups
+ "["*)
+ desktop_entry=""
+ ;;
+ "${key}="*)
+ # Only match Desktop Entry group
+ if [ -n "${desktop_entry}" ]
+ then
+ echo "${line}" | cut -d= -f 2-
+ fi
+ esac
+ done < "${file}"
+ IFS="${IFS_}"
+}
+
+# Returns true if argument is a file:// URL or path
+is_file_url_or_path()
+{
+ if echo "$1" | grep -q '^file://' \
+ || ! echo "$1" | egrep -q '^[[:alpha:]+\.\-]+:'; then
+ return 0
+ else
+ return 1
+ fi
+}
+
+# If argument is a file URL, convert it to a (percent-decoded) path.
+# If not, leave it as it is.
+file_url_to_path()
+{
+ local file="$1"
+ if echo "$file" | grep -q '^file:///'; then
+ file=${file#file://}
+ file=${file%%#*}
+ file=$(echo "$file" | sed -r 's/\?.*$//')
+ local printf=printf
+ if [ -x /usr/bin/printf ]; then
+ printf=/usr/bin/printf
+ fi
+ file=$($printf "$(echo "$file" | sed -e 's@%\([a-f0-9A-F]\{2\}\)@\\x\1@g')")
+ fi
+ echo "$file"
+}
+
+open_cygwin()
+{
+ cygstart "$1"
+
+ if [ $? -eq 0 ]; then
+ exit_success
+ else
+ exit_failure_operation_failed
+ fi
+}
+
+open_darwin()
+{
+ open "$1"
+
+ if [ $? -eq 0 ]; then
+ exit_success
+ else
+ exit_failure_operation_failed
+ fi
+}
+
+open_kde()
+{
+ if [ -n "${KDE_SESSION_VERSION}" ]; then
+ case "${KDE_SESSION_VERSION}" in
+ 4)
+ kde-open "$1"
+ ;;
+ 5)
+ kde-open${KDE_SESSION_VERSION} "$1"
+ ;;
+ esac
+ else
+ kfmclient exec "$1"
+ kfmclient_fix_exit_code $?
+ fi
+
+ if [ $? -eq 0 ]; then
+ exit_success
+ else
+ exit_failure_operation_failed
+ fi
+}
+
+open_dde()
+{
+ if dde-open -version >/dev/null 2>&1; then
+ dde-open "$1"
+ else
+ open_generic "$1"
+ fi
+
+ if [ $? -eq 0 ]; then
+ exit_success
+ else
+ exit_failure_operation_failed
+ fi
+}
+
+open_gnome3()
+{
+ if gio help open 2>/dev/null 1>&2; then
+ gio open "$1"
+ elif gvfs-open --help 2>/dev/null 1>&2; then
+ gvfs-open "$1"
+ else
+ open_generic "$1"
+ fi
+
+ if [ $? -eq 0 ]; then
+ exit_success
+ else
+ exit_failure_operation_failed
+ fi
+}
+
+open_gnome()
+{
+ if gio help open 2>/dev/null 1>&2; then
+ gio open "$1"
+ elif gvfs-open --help 2>/dev/null 1>&2; then
+ gvfs-open "$1"
+ elif gnome-open --help 2>/dev/null 1>&2; then
+ gnome-open "$1"
+ else
+ open_generic "$1"
+ fi
+
+ if [ $? -eq 0 ]; then
+ exit_success
+ else
+ exit_failure_operation_failed
+ fi
+}
+
+open_mate()
+{
+ if gio help open 2>/dev/null 1>&2; then
+ gio open "$1"
+ elif gvfs-open --help 2>/dev/null 1>&2; then
+ gvfs-open "$1"
+ elif mate-open --help 2>/dev/null 1>&2; then
+ mate-open "$1"
+ else
+ open_generic "$1"
+ fi
+
+ if [ $? -eq 0 ]; then
+ exit_success
+ else
+ exit_failure_operation_failed
+ fi
+}
+
+open_xfce()
+{
+ if exo-open --help 2>/dev/null 1>&2; then
+ exo-open "$1"
+ elif gio help open 2>/dev/null 1>&2; then
+ gio open "$1"
+ elif gvfs-open --help 2>/dev/null 1>&2; then
+ gvfs-open "$1"
+ else
+ open_generic "$1"
+ fi
+
+ if [ $? -eq 0 ]; then
+ exit_success
+ else
+ exit_failure_operation_failed
+ fi
+}
+
+open_enlightenment()
+{
+ if enlightenment_open --help 2>/dev/null 1>&2; then
+ enlightenment_open "$1"
+ else
+ open_generic "$1"
+ fi
+
+ if [ $? -eq 0 ]; then
+ exit_success
+ else
+ exit_failure_operation_failed
+ fi
+}
+
+open_flatpak()
+{
+ gdbus call --session \
+ --dest org.freedesktop.portal.Desktop \
+ --object-path /org/freedesktop/portal/desktop \
+ --method org.freedesktop.portal.OpenURI.OpenURI \
+ "" "$1" {}
+
+ if [ $? -eq 0 ]; then
+ exit_success
+ else
+ exit_failure_operation_failed
+ fi
+}
+
+#-----------------------------------------
+# Recursively search .desktop file
+
+search_desktop_file()
+{
+ local default="$1"
+ local dir="$2"
+ local target="$3"
+
+ local file=""
+ # look for both vendor-app.desktop, vendor/app.desktop
+ if [ -r "$dir/$default" ]; then
+ file="$dir/$default"
+ elif [ -r "$dir/`echo $default | sed -e 's|-|/|'`" ]; then
+ file="$dir/`echo $default | sed -e 's|-|/|'`"
+ fi
+
+ if [ -r "$file" ] ; then
+ command="$(get_key "${file}" "Exec" | first_word)"
+ command_exec=`which $command 2>/dev/null`
+ icon="$(get_key "${file}" "Icon")"
+ # FIXME: Actually LC_MESSAGES should be used as described in
+ # http://standards.freedesktop.org/desktop-entry-spec/latest/ar01s04.html
+ localised_name="$(get_key "${file}" "Name")"
+ set -- $(get_key "${file}" "Exec" | last_word)
+ # We need to replace any occurrence of "%f", "%F" and
+ # the like by the target file. We examine each
+ # argument and append the modified argument to the
+ # end then shift.
+ local args=$#
+ local replaced=0
+ while [ $args -gt 0 ]; do
+ case $1 in
+ %[c])
+ replaced=1
+ arg="${localised_name}"
+ shift
+ set -- "$@" "$arg"
+ ;;
+ %[fFuU])
+ replaced=1
+ arg="$target"
+ shift
+ set -- "$@" "$arg"
+ ;;
+ %[i])
+ replaced=1
+ shift
+ set -- "$@" "--icon" "$icon"
+ ;;
+ *)
+ arg="$1"
+ shift
+ set -- "$@" "$arg"
+ ;;
+ esac
+ args=$(( $args - 1 ))
+ done
+ [ $replaced -eq 1 ] || set -- "$@" "$target"
+ "$command_exec" "$@"
+
+ if [ $? -eq 0 ]; then
+ exit_success
+ fi
+ fi
+
+ for d in $dir/*/; do
+ [ -d "$d" ] && search_desktop_file "$default" "$d" "$target"
+ done
+}
+
+
+open_generic_xdg_mime()
+{
+ filetype="$2"
+ default=`xdg-mime query default "$filetype"`
+ if [ -n "$default" ] ; then
+ xdg_user_dir="$XDG_DATA_HOME"
+ [ -n "$xdg_user_dir" ] || xdg_user_dir="$HOME/.local/share"
+
+ xdg_system_dirs="$XDG_DATA_DIRS"
+ [ -n "$xdg_system_dirs" ] || xdg_system_dirs=/usr/local/share/:/usr/share/
+
+DEBUG 3 "$xdg_user_dir:$xdg_system_dirs"
+ for x in `echo "$xdg_user_dir:$xdg_system_dirs" | sed 's/:/ /g'`; do
+ search_desktop_file "$default" "$x/applications/" "$1"
+ done
+ fi
+}
+
+open_generic_xdg_file_mime()
+{
+ filetype=`xdg-mime query filetype "$1" | sed "s/;.*//"`
+ open_generic_xdg_mime "$1" "$filetype"
+}
+
+open_generic_xdg_x_scheme_handler()
+{
+ scheme="`echo $1 | sed -n 's/\(^[[:alnum:]+\.-]*\):.*$/\1/p'`"
+ if [ -n $scheme ]; then
+ filetype="x-scheme-handler/$scheme"
+ open_generic_xdg_mime "$1" "$filetype"
+ fi
+}
+
+has_single_argument()
+{
+ test $# = 1
+}
+
+open_envvar()
+{
+ local oldifs="$IFS"
+ local browser browser_with_arg
+
+ IFS=":"
+ for browser in $BROWSER; do
+ IFS="$oldifs"
+
+ if [ -z "$browser" ]; then
+ continue
+ fi
+
+ if echo "$browser" | grep -q %s; then
+ # Avoid argument injection.
+ # See https://bugs.freedesktop.org/show_bug.cgi?id=103807
+ # URIs don't have IFS characters spaces anyway.
+ has_single_argument $1 && $(printf "$browser" "$1")
+ else
+ $browser "$1"
+ fi
+
+ if [ $? -eq 0 ]; then
+ exit_success
+ fi
+ done
+}
+
+open_generic()
+{
+ if is_file_url_or_path "$1"; then
+ local file="$(file_url_to_path "$1")"
+
+ check_input_file "$file"
+
+ if has_display; then
+ filetype=`xdg-mime query filetype "$file" | sed "s/;.*//"`
+ open_generic_xdg_mime "$file" "$filetype"
+ fi
+
+ if which run-mailcap 2>/dev/null 1>&2; then
+ run-mailcap --action=view "$file"
+ if [ $? -eq 0 ]; then
+ exit_success
+ fi
+ fi
+
+ if has_display && mimeopen -v 2>/dev/null 1>&2; then
+ mimeopen -L -n "$file"
+ if [ $? -eq 0 ]; then
+ exit_success
+ fi
+ fi
+ fi
+
+ if has_display; then
+ open_generic_xdg_x_scheme_handler "$1"
+ fi
+
+ if [ -n "$BROWSER" ]; then
+ open_envvar "$1"
+ fi
+
+ # if BROWSER variable is not set, check some well known browsers instead
+ if [ x"$BROWSER" = x"" ]; then
+ BROWSER=www-browser:links2:elinks:links:lynx:w3m
+ if has_display; then
+ BROWSER=x-www-browser:firefox:iceweasel:seamonkey:mozilla:epiphany:konqueror:chromium:chromium-browser:google-chrome:$BROWSER
+ fi
+ fi
+
+ open_envvar "$1"
+
+ exit_failure_operation_impossible "no method available for opening '$1'"
+}
+
+open_lxde()
+{
+
+ # pcmanfm only knows how to handle file:// urls and filepaths, it seems.
+ if pcmanfm --help >/dev/null 2>&1 && is_file_url_or_path "$1"; then
+ local file="$(file_url_to_path "$1")"
+
+ # handle relative paths
+ if ! echo "$file" | grep -q ^/; then
+ file="$(pwd)/$file"
+ fi
+
+ pcmanfm "$file"
+ else
+ open_generic "$1"
+ fi
+
+ if [ $? -eq 0 ]; then
+ exit_success
+ else
+ exit_failure_operation_failed
+ fi
+}
+
+open_lxqt()
+{
+ open_generic "$1"
+}
+
+[ x"$1" != x"" ] || exit_failure_syntax
+
+url=
+while [ $# -gt 0 ] ; do
+ parm="$1"
+ shift
+
+ case "$parm" in
+ -*)
+ exit_failure_syntax "unexpected option '$parm'"
+ ;;
+
+ *)
+ if [ -n "$url" ] ; then
+ exit_failure_syntax "unexpected argument '$parm'"
+ fi
+ url="$parm"
+ ;;
+ esac
+done
+
+if [ -z "${url}" ] ; then
+ exit_failure_syntax "file or URL argument missing"
+fi
+
+detectDE
+
+if [ x"$DE" = x"" ]; then
+ DE=generic
+fi
+
+DEBUG 2 "Selected DE $DE"
+
+# sanitize BROWSER (avoid caling ourselves in particular)
+case "${BROWSER}" in
+ *:"xdg-open"|"xdg-open":*)
+ BROWSER=$(echo $BROWSER | sed -e 's|:xdg-open||g' -e 's|xdg-open:||g')
+ ;;
+ "xdg-open")
+ BROWSER=
+ ;;
+esac
+
+case "$DE" in
+ kde)
+ open_kde "$url"
+ ;;
+
+ dde)
+ open_dde "$url"
+ ;;
+
+ gnome3|cinnamon)
+ open_gnome3 "$url"
+ ;;
+
+ gnome)
+ open_gnome "$url"
+ ;;
+
+ mate)
+ open_mate "$url"
+ ;;
+
+ xfce)
+ open_xfce "$url"
+ ;;
+
+ lxde)
+ open_lxde "$url"
+ ;;
+
+ lxqt)
+ open_lxqt "$url"
+ ;;
+
+ enlightenment)
+ open_enlightenment "$url"
+ ;;
+
+ cygwin)
+ open_cygwin "$url"
+ ;;
+
+ darwin)
+ open_darwin "$url"
+ ;;
+
+ flatpak)
+ open_flatpak "$url"
+ ;;
+
+ generic)
+ open_generic "$url"
+ ;;
+
+ *)
+ exit_failure_operation_impossible "no method available for opening '$url'"
+ ;;
+esac
diff --git a/temporary_modules/trezor-connect/node_modules/path-key/index.d.ts b/temporary_modules/trezor-connect/node_modules/path-key/index.d.ts
new file mode 100644
index 00000000..7c575d19
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/path-key/index.d.ts
@@ -0,0 +1,40 @@
+///
+
+declare namespace pathKey {
+ interface Options {
+ /**
+ Use a custom environment variables object. Default: [`process.env`](https://nodejs.org/api/process.html#process_process_env).
+ */
+ readonly env?: {[key: string]: string | undefined};
+
+ /**
+ Get the PATH key for a specific platform. Default: [`process.platform`](https://nodejs.org/api/process.html#process_process_platform).
+ */
+ readonly platform?: NodeJS.Platform;
+ }
+}
+
+declare const pathKey: {
+ /**
+ Get the [PATH](https://en.wikipedia.org/wiki/PATH_(variable)) environment variable key cross-platform.
+
+ @example
+ ```
+ import pathKey = require('path-key');
+
+ const key = pathKey();
+ //=> 'PATH'
+
+ const PATH = process.env[key];
+ //=> '/usr/local/bin:/usr/bin:/bin'
+ ```
+ */
+ (options?: pathKey.Options): string;
+
+ // TODO: Remove this for the next major release, refactor the whole definition to:
+ // declare function pathKey(options?: pathKey.Options): string;
+ // export = pathKey;
+ default: typeof pathKey;
+};
+
+export = pathKey;
diff --git a/temporary_modules/trezor-connect/node_modules/path-key/index.js b/temporary_modules/trezor-connect/node_modules/path-key/index.js
new file mode 100644
index 00000000..0cf6415d
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/path-key/index.js
@@ -0,0 +1,16 @@
+'use strict';
+
+const pathKey = (options = {}) => {
+ const environment = options.env || process.env;
+ const platform = options.platform || process.platform;
+
+ if (platform !== 'win32') {
+ return 'PATH';
+ }
+
+ return Object.keys(environment).reverse().find(key => key.toUpperCase() === 'PATH') || 'Path';
+};
+
+module.exports = pathKey;
+// TODO: Remove this for the next major release
+module.exports.default = pathKey;
diff --git a/temporary_modules/trezor-connect/node_modules/path-key/license b/temporary_modules/trezor-connect/node_modules/path-key/license
new file mode 100644
index 00000000..e7af2f77
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/path-key/license
@@ -0,0 +1,9 @@
+MIT License
+
+Copyright (c) Sindre Sorhus (sindresorhus.com)
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/temporary_modules/trezor-connect/node_modules/path-key/package.json b/temporary_modules/trezor-connect/node_modules/path-key/package.json
new file mode 100644
index 00000000..c8cbd383
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/path-key/package.json
@@ -0,0 +1,39 @@
+{
+ "name": "path-key",
+ "version": "3.1.1",
+ "description": "Get the PATH environment variable key cross-platform",
+ "license": "MIT",
+ "repository": "sindresorhus/path-key",
+ "author": {
+ "name": "Sindre Sorhus",
+ "email": "sindresorhus@gmail.com",
+ "url": "sindresorhus.com"
+ },
+ "engines": {
+ "node": ">=8"
+ },
+ "scripts": {
+ "test": "xo && ava && tsd"
+ },
+ "files": [
+ "index.js",
+ "index.d.ts"
+ ],
+ "keywords": [
+ "path",
+ "key",
+ "environment",
+ "env",
+ "variable",
+ "var",
+ "get",
+ "cross-platform",
+ "windows"
+ ],
+ "devDependencies": {
+ "@types/node": "^11.13.0",
+ "ava": "^1.4.1",
+ "tsd": "^0.7.2",
+ "xo": "^0.24.0"
+ }
+}
diff --git a/temporary_modules/trezor-connect/node_modules/path-key/readme.md b/temporary_modules/trezor-connect/node_modules/path-key/readme.md
new file mode 100644
index 00000000..a9052d7a
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/path-key/readme.md
@@ -0,0 +1,61 @@
+# path-key [](https://travis-ci.org/sindresorhus/path-key)
+
+> Get the [PATH](https://en.wikipedia.org/wiki/PATH_(variable)) environment variable key cross-platform
+
+It's usually `PATH`, but on Windows it can be any casing like `Path`...
+
+
+## Install
+
+```
+$ npm install path-key
+```
+
+
+## Usage
+
+```js
+const pathKey = require('path-key');
+
+const key = pathKey();
+//=> 'PATH'
+
+const PATH = process.env[key];
+//=> '/usr/local/bin:/usr/bin:/bin'
+```
+
+
+## API
+
+### pathKey(options?)
+
+#### options
+
+Type: `object`
+
+##### env
+
+Type: `object`
+Default: [`process.env`](https://nodejs.org/api/process.html#process_process_env)
+
+Use a custom environment variables object.
+
+#### platform
+
+Type: `string`
+Default: [`process.platform`](https://nodejs.org/api/process.html#process_process_platform)
+
+Get the PATH key for a specific platform.
+
+
+---
+
+
diff --git a/temporary_modules/trezor-connect/node_modules/pend/LICENSE b/temporary_modules/trezor-connect/node_modules/pend/LICENSE
new file mode 100644
index 00000000..0bbb53ed
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/pend/LICENSE
@@ -0,0 +1,23 @@
+The MIT License (Expat)
+
+Copyright (c) 2014 Andrew Kelley
+
+Permission is hereby granted, free of charge, to any person
+obtaining a copy of this software and associated documentation files
+(the "Software"), to deal in the Software without restriction,
+including without limitation the rights to use, copy, modify, merge,
+publish, distribute, sublicense, and/or sell copies of the Software,
+and to permit persons to whom the Software is furnished to do so,
+subject to the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
+BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
+ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/temporary_modules/trezor-connect/node_modules/pend/README.md b/temporary_modules/trezor-connect/node_modules/pend/README.md
new file mode 100644
index 00000000..bb40a07c
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/pend/README.md
@@ -0,0 +1,41 @@
+# Pend
+
+Dead-simple optimistic async helper.
+
+## Usage
+
+```js
+var Pend = require('pend');
+var pend = new Pend();
+pend.max = 10; // defaults to Infinity
+setTimeout(pend.hold(), 1000); // pend.wait will have to wait for this hold to finish
+pend.go(function(cb) {
+ console.log("this function is immediately executed");
+ setTimeout(function() {
+ console.log("calling cb 1");
+ cb();
+ }, 500);
+});
+pend.go(function(cb) {
+ console.log("this function is also immediately executed");
+ setTimeout(function() {
+ console.log("calling cb 2");
+ cb();
+ }, 1000);
+});
+pend.wait(function(err) {
+ console.log("this is excuted when the first 2 have returned.");
+ console.log("err is a possible error in the standard callback style.");
+});
+```
+
+Output:
+
+```
+this function is immediately executed
+this function is also immediately executed
+calling cb 1
+calling cb 2
+this is excuted when the first 2 have returned.
+err is a possible error in the standard callback style.
+```
diff --git a/temporary_modules/trezor-connect/node_modules/pend/index.js b/temporary_modules/trezor-connect/node_modules/pend/index.js
new file mode 100644
index 00000000..3bf485ed
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/pend/index.js
@@ -0,0 +1,55 @@
+module.exports = Pend;
+
+function Pend() {
+ this.pending = 0;
+ this.max = Infinity;
+ this.listeners = [];
+ this.waiting = [];
+ this.error = null;
+}
+
+Pend.prototype.go = function(fn) {
+ if (this.pending < this.max) {
+ pendGo(this, fn);
+ } else {
+ this.waiting.push(fn);
+ }
+};
+
+Pend.prototype.wait = function(cb) {
+ if (this.pending === 0) {
+ cb(this.error);
+ } else {
+ this.listeners.push(cb);
+ }
+};
+
+Pend.prototype.hold = function() {
+ return pendHold(this);
+};
+
+function pendHold(self) {
+ self.pending += 1;
+ var called = false;
+ return onCb;
+ function onCb(err) {
+ if (called) throw new Error("callback called twice");
+ called = true;
+ self.error = self.error || err;
+ self.pending -= 1;
+ if (self.waiting.length > 0 && self.pending < self.max) {
+ pendGo(self, self.waiting.shift());
+ } else if (self.pending === 0) {
+ var listeners = self.listeners;
+ self.listeners = [];
+ listeners.forEach(cbListener);
+ }
+ }
+ function cbListener(listener) {
+ listener(self.error);
+ }
+}
+
+function pendGo(self, fn) {
+ fn(pendHold(self));
+}
diff --git a/temporary_modules/trezor-connect/node_modules/pend/package.json b/temporary_modules/trezor-connect/node_modules/pend/package.json
new file mode 100644
index 00000000..8181f8b6
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/pend/package.json
@@ -0,0 +1,18 @@
+{
+ "name": "pend",
+ "version": "1.2.0",
+ "description": "dead-simple optimistic async helper",
+ "main": "index.js",
+ "scripts": {
+ "test": "node test.js"
+ },
+ "author": "Andrew Kelley ",
+ "license": "MIT",
+ "repository": {
+ "type": "git",
+ "url": "git://github.com/andrewrk/node-pend.git"
+ },
+ "bugs": {
+ "url": "https://github.com/andrewrk/node-pend/issues"
+ }
+}
diff --git a/temporary_modules/trezor-connect/node_modules/pend/test.js b/temporary_modules/trezor-connect/node_modules/pend/test.js
new file mode 100644
index 00000000..75c0f2ac
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/pend/test.js
@@ -0,0 +1,137 @@
+var assert = require('assert');
+var Pend = require('./');
+
+var tests = [
+ {
+ name: "basic",
+ fn: testBasic,
+ },
+ {
+ name: "max",
+ fn: testWithMax,
+ },
+ {
+ name: "callback twice",
+ fn: testCallbackTwice,
+ },
+ {
+ name: "calling wait twice",
+ fn: testCallingWaitTwice,
+ },
+ {
+ name: "hold()",
+ fn: testHoldFn,
+ },
+];
+var testCount = tests.length;
+
+doOneTest();
+
+function doOneTest() {
+ var test = tests.shift();
+ if (!test) {
+ console.log(testCount + " tests passed.");
+ return;
+ }
+ process.stdout.write(test.name + "...");
+ test.fn(function() {
+ process.stdout.write("OK\n");
+ doOneTest();
+ });
+}
+
+function testBasic(cb) {
+ var pend = new Pend();
+ var results = [];
+ pend.go(function(cb) {
+ results.push(1);
+ setTimeout(function() {
+ results.push(3);
+ cb();
+ }, 500);
+ });
+ pend.go(function(cb) {
+ results.push(2);
+ setTimeout(function() {
+ results.push(4);
+ cb();
+ }, 1000);
+ });
+ pend.wait(function(err) {
+ assert.deepEqual(results, [1,2,3,4]);
+ cb();
+ });
+ assert.deepEqual(results, [1, 2]);
+}
+
+function testWithMax(cb) {
+ var pend = new Pend();
+ var results = [];
+ pend.max = 2;
+ pend.go(function(cb) {
+ results.push('a');
+ setTimeout(function() {
+ results.push(1);
+ cb();
+ }, 500);
+ });
+ pend.go(function(cb) {
+ results.push('b');
+ setTimeout(function() {
+ results.push(1);
+ cb();
+ }, 500);
+ });
+ pend.go(function(cb) {
+ results.push('c');
+ setTimeout(function() {
+ results.push(2);
+ cb();
+ }, 100);
+ });
+ pend.wait(function(err) {
+ assert.deepEqual(results, ['a', 'b', 1, 'c', 1, 2]);
+ cb();
+ });
+ assert.deepEqual(results, ['a', 'b']);
+}
+
+function testCallbackTwice(cb) {
+ var pend = new Pend();
+ pend.go(function(cb) {
+ setTimeout(cb, 100);
+ });
+ pend.go(function(cb) {
+ cb();
+ assert.throws(cb, /callback called twice/);
+ });
+ pend.wait(cb);
+}
+
+function testCallingWaitTwice(cb) {
+ var pend = new Pend();
+ pend.go(function(cb) {
+ setTimeout(cb, 100);
+ });
+ pend.wait(function() {
+ pend.go(function(cb) {
+ setTimeout(cb, 50);
+ });
+ pend.go(function(cb) {
+ setTimeout(cb, 10);
+ });
+ pend.go(function(cb) {
+ setTimeout(cb, 20);
+ });
+ pend.wait(cb);
+ });
+}
+
+function testHoldFn(cb) {
+ var pend = new Pend();
+ setTimeout(pend.hold(), 100);
+ pend.go(function(cb) {
+ cb();
+ });
+ pend.wait(cb);
+}
diff --git a/temporary_modules/trezor-connect/node_modules/plist/.jshintrc b/temporary_modules/trezor-connect/node_modules/plist/.jshintrc
new file mode 100644
index 00000000..3f426220
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/plist/.jshintrc
@@ -0,0 +1,4 @@
+{
+ "laxbreak": true,
+ "laxcomma": true
+}
diff --git a/temporary_modules/trezor-connect/node_modules/plist/.travis.yml b/temporary_modules/trezor-connect/node_modules/plist/.travis.yml
new file mode 100644
index 00000000..3121bc68
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/plist/.travis.yml
@@ -0,0 +1,22 @@
+dist: xenial
+os: linux
+language: node_js
+node_js:
+- '6'
+- '7'
+- '8'
+- '9'
+
+env:
+ global:
+ - secure: R4tCAipsC0KdBPin8+rWedqptn0RXksLM20yZ0w8En0hhaglWCiIxA5uKt/6njXp9Q8FEKkVOyWF+yjq74jB6+KUu0dSK30pbmaAHhlXsL5kTWmY9vd7rxwcn1Hdf1sW15NqRX4hvWuIC32cA7vDr+58VPyum+A+yvPJICvgIlw=
+ - secure: sfEwCcmUrfFPIRPV8UwdJymRZ8YY20fuJiAlWfOUQSOccNGWB4RbUsD+iyc9XW5qB1kdOqxVkvZ0sKrYo3Uc4k8mhar7+yhP04hfNj4CWAigG3rtTugbar9kSQjwi/yEaTrb4kdP8HRYs5yjrEX/CGwjm3iHGOSyUw5du0PQfbk=
+
+jobs:
+ include:
+ - node_js: '8'
+ env: BROWSER_NAME=chrome BROWSER_VERSION=latest
+ - node_js: '8'
+ env: BROWSER_NAME=firefox BROWSER_VERSION=latest
+ - node_js: '8'
+ env: BROWSER_NAME=ie BROWSER_VERSION=11
diff --git a/temporary_modules/trezor-connect/node_modules/plist/History.md b/temporary_modules/trezor-connect/node_modules/plist/History.md
new file mode 100644
index 00000000..de034471
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/plist/History.md
@@ -0,0 +1,191 @@
+3.0.5 / 2022-03-23
+==================
+* [[`96e2303d05`]](https://github.com/TooTallNate/plist.js/commit/96e2303d059e6be0c9e0c4773226d14b4758de52) Prototype Pollution using .parse() #114 (mario-canva)
+* update browserify from 16 to 17
+
+
+3.0.4 / 2021-08-27
+==================
+* inline xmldom@0.6.0 to eliminate security warning false positive (Mike Reinstein)
+
+
+3.0.3 / 2021-08-04
+==================
+* update xmldom to 0.6.0 to patch critical vulnerability (Mike Reinstein)
+* remove flaky saucelabs teseting badge (Mike Reinstein)
+
+
+3.0.2 / 2021-03-25
+==================
+* update xmldom to 0.5.0 to patch critical vulnerability (Mike Reinstein)
+* update saucelab credentials to point at mreinstein's saucelabs account (Mike Reinstein)
+* remove a bunch of test versions from the matrix because they weren't working in zuul + sauce (Mike Reinstein)
+
+
+3.0.1 / 2018-03-21
+==================
+* avoid using Buffer constructor nodejs/node#19079
+
+
+3.0.0 / 2018-03-18
+==================
+* [[`cb0d8f1bc6`]](https://github.com/TooTallNate/plist.js/commit/cb0d8f1bc60dee423f8fc2cfcac427452dfaddb0) update Makefile, rebuild dist/ (Mike Reinstein)
+* [[`9dfeffe73f`]](https://github.com/TooTallNate/plist.js/commit/9dfeffe73fdb447ac5a87ee364a1472975f12adf) remove unsupported browser versions from travis (Mike Reinstein)
+* [[`c962bfe1ea`]](https://github.com/TooTallNate/plist.js/commit/c962bfe1ea04dd87966250253d33738bceecab61) update module deps, remove support for node < 6 (Mike Reinstein)
+
+
+2.1.0 / 2017-05-04
+==================
+
+* [[`e4f06669bb`]](https://github.com/TooTallNate/plist.js/commit/e4f06669bb51d2e65654df7c39aab52bc3bf4e8a) - update license (extend copyright term) (Mike Reinstein)
+* [[`edc6e41035`]](https://github.com/TooTallNate/plist.js/commit/edc6e4103546b1d7518a577e7c202c305a8abec0) - update module deps (Mike Reinstein)
+* [[`85d11c48ef`](https://github.com/TooTallNate/plist.js/commit/85d11c48eff02312cbdd67f46fd8e74b0d372ca1)] - Harden test-cases and implementation to align with other implementations (Björn Brauer)
+* [[`7619537eaa`]](https://github.com/TooTallNate/plist.js/commit/7619537eaa9e3e5a80829e759c004d2e017a07d2) review feedback: early returns and constants for nodeTypes (Björn Brauer)
+
+
+2.0.1 / 2016-08-16
+==================
+
+* [[`de136c8388`](https://github.com/TooTallNate/plist/commit/de136c8388)] - bad npm release… (Nathan Rajlich)
+
+
+2.0.0 / 2016-08-16
+==================
+
+* [[`90deef5d43`](https://github.com/TooTallNate/plist/commit/90deef5d43)] - remove deprecated functions (Nathan Rajlich)
+* [[`d475cd8ce9`](https://github.com/TooTallNate/plist/commit/d475cd8ce9)] - Added travis ci support for node 6 (Amila Welihinda)
+* [[`04c8ee7646`](https://github.com/TooTallNate/plist/commit/04c8ee7646)] - update dependencies (Mitchell Hentges)
+* [[`97c02b3f05`](https://github.com/TooTallNate/plist/commit/97c02b3f05)] - **travis**: add `sudo: false` and test more node versions (Nathan Rajlich)
+* [[`54c821ec29`](https://github.com/TooTallNate/plist/commit/54c821ec29)] - #71 - fixed and added test (Andrew Goldis)
+* [[`4afb7c5079`](https://github.com/TooTallNate/plist/commit/4afb7c5079)] - fix `Cannot read property 'nodeValue' of undefined exception` that is thrown when a `` construct appears in plist (Chris Kinsman)
+* [[`f360d7d685`](https://github.com/TooTallNate/plist/commit/f360d7d685)] - #66 - fixed empty keys and added tests (Andrew Goldis)
+* [[`421c7f26e9`](https://github.com/TooTallNate/plist/commit/421c7f26e9)] - #66 - fixed empty key (Andrew Goldis)
+* [[`a88aa4dca7`](https://github.com/TooTallNate/plist/commit/a88aa4dca7)] - add verbose examples (mrzmyr)
+
+
+1.2.0 / 2015-11-10
+==================
+
+ * package: update "browserify" to v12.0.1
+ * package: update "zuul" to v3.7.2
+ * package: update "xmlbuilder" to v4.0.0
+ * package: update "util-deprecate" to v1.0.2
+ * package: update "mocha" to v2.3.3
+ * package: update "base64-js" to v0.0.8
+ * build: omit undefined values
+ * travis: add node 4.0 and 4.1 to test matrix
+
+
+1.1.0 / 2014-08-27
+==================
+
+ * package: update "browserify" to v5.10.1
+ * package: update "zuul" to v1.10.2
+ * README: add "Sauce Test Status" build badge
+ * travis: use new "plistjs" sauce credentials
+ * travis: set up zuul saucelabs automated testing
+
+
+1.0.1 / 2014-06-25
+==================
+
+ * add .zuul.yml file for browser testing
+ * remove Testling stuff
+ * build: fix global variable `val` leak
+ * package: use --check-leaks when running mocha tests
+ * README: update examples to use preferred API
+ * package: add "browser" keyword
+
+
+1.0.0 / 2014-05-20
+==================
+
+ * package: remove "android-browser"
+ * test: add build() test
+ * test: re-add the empty string build() test
+ * test: remove "fixtures" and legacy "tests" dir
+ * test: add some more build() tests
+ * test: add a parse() CDATA test
+ * test: starting on build() tests
+ * test: more parse() tests
+ * package: attempt to fix "android-browser" testling
+ * parse: better with newline handling
+ * README: add Testling badge
+ * test: add node tests
+ * test: add a parse() test
+ * travis: don't test node v0.6 or v0.8
+ * test: some more parse() tests
+ * test: add simple parsing test
+ * build: add support for an optional "opts" object
+ * package: test mobile devices
+ * test: use multiline to inline the XML
+ * package: beautify
+ * package: fix "mocha" harness
+ * package: more testling browsers
+ * build: add the "version=1.0" attribute
+ * beginnings of "mocha" tests
+ * build: more JSDocs
+ * tests: add test that ensures that empty string conversion works
+ * build: update "xmlbuilder" to v2.2.1
+ * parse: ignore comment and cdata nodes
+ * tests: make the "Newlines" test actually contain a newline
+ * parse: lint
+ * test travis
+ * README: add Travis CI badge
+ * add .travis.yml file
+ * build: updated DTD to reflect name change
+ * parse: return falsey values in an Array plist
+ * build: fix encoding a typed array in the browser
+ * build: add support for Typed Arrays and ArrayBuffers
+ * build: more lint
+ * build: slight cleanup and optimizations
+ * build: use .txt() for the "date" value
+ * parse: always return a Buffer for nodes
+ * build: don't interpret Strings as base64
+ * dist: commit prebuilt plist*.js files
+ * parse: fix typo in deprecate message
+ * parse: fix parse() return value
+ * parse: add jsdoc comments for the deprecated APIs
+ * parse: add `parse()` function
+ * node, parse: use `util-deprecate` module
+ * re-implemented parseFile to be asynchronous
+ * node: fix jsdoc comment
+ * Makefile: fix "node" require stubbing
+ * examples: add "browser" example
+ * package: tweak "main"
+ * package: remove "engines" field
+ * Makefile: fix --exclude command for browserify
+ * package: update "description"
+ * lib: more styling
+ * Makefile: add -build.js and -parse.js dist files
+ * lib: separate out the parse and build logic into their own files
+ * Makefile: add makefile with browserify build rules
+ * package: add "browserify" as a dev dependency
+ * plist: tabs to spaces (again)
+ * add a .jshintrc file
+ * LICENSE: update
+ * node-webkit support
+ * Ignore tests/ in .npmignore file
+ * Remove duplicate devDependencies key
+ * Remove trailing whitespace
+ * adding recent contributors. Bumping npm package number (patch release)
+ * Fixed node.js string handling
+ * bumping version number
+ * Fixed global variable plist leak
+ * patch release 0.4.1
+ * removed temporary debug output file
+ * flipping the cases for writing data and string elements in build(). removed the 125 length check. Added validation of base64 encoding for data fields when parsing. added unit tests.
+ * fixed syntax errors in README examples (issue #20)
+ * added Sync versions of calls. added deprecation warnings for old method calls. updated documentation. If the resulting object from parseStringSync is an array with 1 element, return just the element. If a plist string or file doesnt have a tag as the document root element, fail noisily (issue #15)
+ * incrementing package version
+ * added cross platform base64 encode/decode for data elements (issue #17.) Comments and hygiene.
+ * refactored the code to use a DOM parser instead of SAX. closes issues #5 and #16
+ * rolling up package version
+ * updated base64 detection regexp. updated README. hygiene.
+ * refactored the build function. Fixes issue #14
+ * refactored tests. Modified tests from issue #9. thanks @sylvinus
+ * upgrade xmlbuilder package version. this is why .end() was needed in last commit; breaking change to xmlbuilder lib. :/
+ * bug fix in build function, forgot to call .end() Refactored tests to use nodeunit
+ * Implemented support for real, identity tests
+ * Refactored base64 detection - still sloppy, fixed date building. Passing tests OK.
+ * Implemented basic plist builder that turns an existing JS object into plist XML. date, real and data types still need to be implemented.
diff --git a/temporary_modules/trezor-connect/node_modules/plist/LICENSE b/temporary_modules/trezor-connect/node_modules/plist/LICENSE
new file mode 100644
index 00000000..92e3423a
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/plist/LICENSE
@@ -0,0 +1,24 @@
+(The MIT License)
+
+Copyright (c) 2010-2017 Nathan Rajlich
+
+Permission is hereby granted, free of charge, to any person
+obtaining a copy of this software and associated documentation
+files (the "Software"), to deal in the Software without
+restriction, including without limitation the rights to use,
+copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the
+Software is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
+OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+OTHER DEALINGS IN THE SOFTWARE.
diff --git a/temporary_modules/trezor-connect/node_modules/plist/Makefile b/temporary_modules/trezor-connect/node_modules/plist/Makefile
new file mode 100644
index 00000000..7a918b55
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/plist/Makefile
@@ -0,0 +1,75 @@
+
+# get Makefile directory name: http://stackoverflow.com/a/5982798/376773
+THIS_MAKEFILE_PATH:=$(word $(words $(MAKEFILE_LIST)),$(MAKEFILE_LIST))
+THIS_DIR:=$(shell cd $(dir $(THIS_MAKEFILE_PATH));pwd)
+
+# BIN directory
+BIN := $(THIS_DIR)/node_modules/.bin
+
+# applications
+NODE ?= node
+NPM ?= $(NODE) $(shell which npm)
+BROWSERIFY ?= $(NODE) $(BIN)/browserify
+MOCHA ?= $(NODE) $(BIN)/mocha
+ZUUL ?= $(NODE) $(BIN)/zuul
+
+REPORTER ?= spec
+
+all: dist/plist.js dist/plist-build.js dist/plist-parse.js
+
+install: node_modules
+
+clean:
+ @rm -rf node_modules dist
+
+dist:
+ @mkdir -p $@
+
+dist/plist-build.js: node_modules lib/build.js dist
+ @$(BROWSERIFY) \
+ --standalone plist \
+ lib/build.js > $@
+
+dist/plist-parse.js: node_modules lib/parse.js dist
+ @$(BROWSERIFY) \
+ --standalone plist \
+ lib/parse.js > $@
+
+dist/plist.js: node_modules lib/*.js dist
+ @$(BROWSERIFY) \
+ --standalone plist \
+ index.js > $@
+
+node_modules: package.json
+ @NODE_ENV= $(NPM) install
+ @touch node_modules
+
+test:
+ @if [ "x$(BROWSER_NAME)" = "x" ]; then \
+ $(MAKE) test-node; \
+ else \
+ $(MAKE) test-zuul; \
+ fi
+
+test-node:
+ @$(MOCHA) \
+ --reporter $(REPORTER) \
+ test/*.js
+
+test-zuul:
+ @if [ "x$(BROWSER_PLATFORM)" = "x" ]; then \
+ $(ZUUL) \
+ --ui mocha-bdd \
+ --browser-name $(BROWSER_NAME) \
+ --browser-version $(BROWSER_VERSION) \
+ test/*.js; \
+ else \
+ $(ZUUL) \
+ --ui mocha-bdd \
+ --browser-name $(BROWSER_NAME) \
+ --browser-version $(BROWSER_VERSION) \
+ --browser-platform "$(BROWSER_PLATFORM)" \
+ test/*.js; \
+ fi
+
+.PHONY: all install clean test test-node test-zuul
diff --git a/temporary_modules/trezor-connect/node_modules/plist/README.md b/temporary_modules/trezor-connect/node_modules/plist/README.md
new file mode 100644
index 00000000..62374953
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/plist/README.md
@@ -0,0 +1,146 @@
+plist.js
+========
+### Mac OS X Plist parser/builder for Node.js and browsers
+
+[](https://travis-ci.org/TooTallNate/plist.js)
+
+Provides facilities for reading and writing Mac OS X Plist (property list)
+files. These are often used in programming OS X and iOS applications, as
+well as the iTunes configuration XML file.
+
+Plist files represent stored programming "object"s. They are very similar
+to JSON. A valid Plist file is representable as a native JavaScript Object
+and vice-versa.
+
+
+## Usage
+
+### Node.js
+
+Install using `npm`:
+
+``` bash
+$ npm install --save plist
+```
+
+Then `require()` the _plist_ module in your file:
+
+``` js
+var plist = require('plist');
+
+// now use the `parse()` and `build()` functions
+var val = plist.parse('Hello World!');
+console.log(val); // "Hello World!"
+```
+
+
+### Browser
+
+Include the `dist/plist.js` in a `
+
+```
+
+
+## API
+
+### Parsing
+
+Parsing a plist from filename:
+
+``` javascript
+var fs = require('fs');
+var plist = require('plist');
+
+var obj = plist.parse(fs.readFileSync('myPlist.plist', 'utf8'));
+console.log(JSON.stringify(obj));
+```
+
+Parsing a plist from string payload:
+
+``` javascript
+var plist = require('plist');
+
+var xml =
+ '' +
+ '' +
+ '' +
+ 'metadata' +
+ '' +
+ 'bundle-identifier' +
+ 'com.company.app' +
+ 'bundle-version' +
+ '0.1.1' +
+ 'kind' +
+ 'software' +
+ 'title' +
+ 'AppName' +
+ '' +
+ '';
+
+console.log(plist.parse(xml));
+
+// [
+// "metadata",
+// {
+// "bundle-identifier": "com.company.app",
+// "bundle-version": "0.1.1",
+// "kind": "software",
+// "title": "AppName"
+// }
+// ]
+```
+
+### Building
+
+Given an existing JavaScript Object, you can turn it into an XML document
+that complies with the plist DTD:
+
+``` javascript
+var plist = require('plist');
+
+var json = [
+ "metadata",
+ {
+ "bundle-identifier": "com.company.app",
+ "bundle-version": "0.1.1",
+ "kind": "software",
+ "title": "AppName"
+ }
+];
+
+console.log(plist.build(json));
+
+//
+//
+//
+// metadata
+//
+// bundle-identifier
+// com.company.app
+// bundle-version
+// 0.1.1
+// kind
+// software
+// title
+// AppName
+//
+//
+```
+
+## Cross Platform Testing Credits
+
+Much thanks to Sauce Labs for providing free resources that enable cross-browser testing on this project!
+
+[](https://saucelabs.com)
+
+
+## License
+
+[(The MIT License)](LICENSE)
diff --git a/temporary_modules/trezor-connect/node_modules/plist/dist/plist-build.js b/temporary_modules/trezor-connect/node_modules/plist/dist/plist-build.js
new file mode 100644
index 00000000..11ec8e63
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/plist/dist/plist-build.js
@@ -0,0 +1,2866 @@
+(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.plist = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i 0) {
+ throw new Error('Invalid string. Length must be a multiple of 4')
+ }
+
+ // Trim off extra bytes after placeholder bytes are found
+ // See: https://github.com/beatgammit/base64-js/issues/42
+ var validLen = b64.indexOf('=')
+ if (validLen === -1) validLen = len
+
+ var placeHoldersLen = validLen === len
+ ? 0
+ : 4 - (validLen % 4)
+
+ return [validLen, placeHoldersLen]
+}
+
+// base64 is 4/3 + up to two characters of the original data
+function byteLength (b64) {
+ var lens = getLens(b64)
+ var validLen = lens[0]
+ var placeHoldersLen = lens[1]
+ return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
+}
+
+function _byteLength (b64, validLen, placeHoldersLen) {
+ return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
+}
+
+function toByteArray (b64) {
+ var tmp
+ var lens = getLens(b64)
+ var validLen = lens[0]
+ var placeHoldersLen = lens[1]
+
+ var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))
+
+ var curByte = 0
+
+ // if there are placeholders, only get up to the last complete 4 chars
+ var len = placeHoldersLen > 0
+ ? validLen - 4
+ : validLen
+
+ var i
+ for (i = 0; i < len; i += 4) {
+ tmp =
+ (revLookup[b64.charCodeAt(i)] << 18) |
+ (revLookup[b64.charCodeAt(i + 1)] << 12) |
+ (revLookup[b64.charCodeAt(i + 2)] << 6) |
+ revLookup[b64.charCodeAt(i + 3)]
+ arr[curByte++] = (tmp >> 16) & 0xFF
+ arr[curByte++] = (tmp >> 8) & 0xFF
+ arr[curByte++] = tmp & 0xFF
+ }
+
+ if (placeHoldersLen === 2) {
+ tmp =
+ (revLookup[b64.charCodeAt(i)] << 2) |
+ (revLookup[b64.charCodeAt(i + 1)] >> 4)
+ arr[curByte++] = tmp & 0xFF
+ }
+
+ if (placeHoldersLen === 1) {
+ tmp =
+ (revLookup[b64.charCodeAt(i)] << 10) |
+ (revLookup[b64.charCodeAt(i + 1)] << 4) |
+ (revLookup[b64.charCodeAt(i + 2)] >> 2)
+ arr[curByte++] = (tmp >> 8) & 0xFF
+ arr[curByte++] = tmp & 0xFF
+ }
+
+ return arr
+}
+
+function tripletToBase64 (num) {
+ return lookup[num >> 18 & 0x3F] +
+ lookup[num >> 12 & 0x3F] +
+ lookup[num >> 6 & 0x3F] +
+ lookup[num & 0x3F]
+}
+
+function encodeChunk (uint8, start, end) {
+ var tmp
+ var output = []
+ for (var i = start; i < end; i += 3) {
+ tmp =
+ ((uint8[i] << 16) & 0xFF0000) +
+ ((uint8[i + 1] << 8) & 0xFF00) +
+ (uint8[i + 2] & 0xFF)
+ output.push(tripletToBase64(tmp))
+ }
+ return output.join('')
+}
+
+function fromByteArray (uint8) {
+ var tmp
+ var len = uint8.length
+ var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
+ var parts = []
+ var maxChunkLength = 16383 // must be multiple of 3
+
+ // go through the array every three bytes, we'll deal with trailing stuff later
+ for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
+ parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
+ }
+
+ // pad the end with zeros, but make sure to not forget the extra bytes
+ if (extraBytes === 1) {
+ tmp = uint8[len - 1]
+ parts.push(
+ lookup[tmp >> 2] +
+ lookup[(tmp << 4) & 0x3F] +
+ '=='
+ )
+ } else if (extraBytes === 2) {
+ tmp = (uint8[len - 2] << 8) + uint8[len - 1]
+ parts.push(
+ lookup[tmp >> 10] +
+ lookup[(tmp >> 4) & 0x3F] +
+ lookup[(tmp << 2) & 0x3F] +
+ '='
+ )
+ }
+
+ return parts.join('')
+}
+
+},{}],3:[function(require,module,exports){
+/*!
+ * Determine if an object is a Buffer
+ *
+ * @author Feross Aboukhadijeh
+ * @license MIT
+ */
+
+// The _isBuffer check is for Safari 5-7 support, because it's missing
+// Object.prototype.constructor. Remove this eventually
+module.exports = function (obj) {
+ return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
+}
+
+function isBuffer (obj) {
+ return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
+}
+
+// For Node v0.10 support. Remove this eventually.
+function isSlowBuffer (obj) {
+ return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
+}
+
+},{}],4:[function(require,module,exports){
+// Generated by CoffeeScript 1.12.7
+(function() {
+ var assign, isArray, isEmpty, isFunction, isObject, isPlainObject,
+ slice = [].slice,
+ hasProp = {}.hasOwnProperty;
+
+ assign = function() {
+ var i, key, len, source, sources, target;
+ target = arguments[0], sources = 2 <= arguments.length ? slice.call(arguments, 1) : [];
+ if (isFunction(Object.assign)) {
+ Object.assign.apply(null, arguments);
+ } else {
+ for (i = 0, len = sources.length; i < len; i++) {
+ source = sources[i];
+ if (source != null) {
+ for (key in source) {
+ if (!hasProp.call(source, key)) continue;
+ target[key] = source[key];
+ }
+ }
+ }
+ }
+ return target;
+ };
+
+ isFunction = function(val) {
+ return !!val && Object.prototype.toString.call(val) === '[object Function]';
+ };
+
+ isObject = function(val) {
+ var ref;
+ return !!val && ((ref = typeof val) === 'function' || ref === 'object');
+ };
+
+ isArray = function(val) {
+ if (isFunction(Array.isArray)) {
+ return Array.isArray(val);
+ } else {
+ return Object.prototype.toString.call(val) === '[object Array]';
+ }
+ };
+
+ isEmpty = function(val) {
+ var key;
+ if (isArray(val)) {
+ return !val.length;
+ } else {
+ for (key in val) {
+ if (!hasProp.call(val, key)) continue;
+ return false;
+ }
+ return true;
+ }
+ };
+
+ isPlainObject = function(val) {
+ var ctor, proto;
+ return isObject(val) && (proto = Object.getPrototypeOf(val)) && (ctor = proto.constructor) && (typeof ctor === 'function') && (ctor instanceof ctor) && (Function.prototype.toString.call(ctor) === Function.prototype.toString.call(Object));
+ };
+
+ module.exports.assign = assign;
+
+ module.exports.isFunction = isFunction;
+
+ module.exports.isObject = isObject;
+
+ module.exports.isArray = isArray;
+
+ module.exports.isEmpty = isEmpty;
+
+ module.exports.isPlainObject = isPlainObject;
+
+}).call(this);
+
+},{}],5:[function(require,module,exports){
+// Generated by CoffeeScript 1.12.7
+(function() {
+ var XMLAttribute;
+
+ module.exports = XMLAttribute = (function() {
+ function XMLAttribute(parent, name, value) {
+ this.options = parent.options;
+ this.stringify = parent.stringify;
+ if (name == null) {
+ throw new Error("Missing attribute name of element " + parent.name);
+ }
+ if (value == null) {
+ throw new Error("Missing attribute value for attribute " + name + " of element " + parent.name);
+ }
+ this.name = this.stringify.attName(name);
+ this.value = this.stringify.attValue(value);
+ }
+
+ XMLAttribute.prototype.clone = function() {
+ return Object.create(this);
+ };
+
+ XMLAttribute.prototype.toString = function(options) {
+ return this.options.writer.set(options).attribute(this);
+ };
+
+ return XMLAttribute;
+
+ })();
+
+}).call(this);
+
+},{}],6:[function(require,module,exports){
+// Generated by CoffeeScript 1.12.7
+(function() {
+ var XMLCData, XMLNode,
+ extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
+ hasProp = {}.hasOwnProperty;
+
+ XMLNode = require('./XMLNode');
+
+ module.exports = XMLCData = (function(superClass) {
+ extend(XMLCData, superClass);
+
+ function XMLCData(parent, text) {
+ XMLCData.__super__.constructor.call(this, parent);
+ if (text == null) {
+ throw new Error("Missing CDATA text");
+ }
+ this.text = this.stringify.cdata(text);
+ }
+
+ XMLCData.prototype.clone = function() {
+ return Object.create(this);
+ };
+
+ XMLCData.prototype.toString = function(options) {
+ return this.options.writer.set(options).cdata(this);
+ };
+
+ return XMLCData;
+
+ })(XMLNode);
+
+}).call(this);
+
+},{"./XMLNode":17}],7:[function(require,module,exports){
+// Generated by CoffeeScript 1.12.7
+(function() {
+ var XMLComment, XMLNode,
+ extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
+ hasProp = {}.hasOwnProperty;
+
+ XMLNode = require('./XMLNode');
+
+ module.exports = XMLComment = (function(superClass) {
+ extend(XMLComment, superClass);
+
+ function XMLComment(parent, text) {
+ XMLComment.__super__.constructor.call(this, parent);
+ if (text == null) {
+ throw new Error("Missing comment text");
+ }
+ this.text = this.stringify.comment(text);
+ }
+
+ XMLComment.prototype.clone = function() {
+ return Object.create(this);
+ };
+
+ XMLComment.prototype.toString = function(options) {
+ return this.options.writer.set(options).comment(this);
+ };
+
+ return XMLComment;
+
+ })(XMLNode);
+
+}).call(this);
+
+},{"./XMLNode":17}],8:[function(require,module,exports){
+// Generated by CoffeeScript 1.12.7
+(function() {
+ var XMLDTDAttList, XMLNode,
+ extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
+ hasProp = {}.hasOwnProperty;
+
+ XMLNode = require('./XMLNode');
+
+ module.exports = XMLDTDAttList = (function(superClass) {
+ extend(XMLDTDAttList, superClass);
+
+ function XMLDTDAttList(parent, elementName, attributeName, attributeType, defaultValueType, defaultValue) {
+ XMLDTDAttList.__super__.constructor.call(this, parent);
+ if (elementName == null) {
+ throw new Error("Missing DTD element name");
+ }
+ if (attributeName == null) {
+ throw new Error("Missing DTD attribute name");
+ }
+ if (!attributeType) {
+ throw new Error("Missing DTD attribute type");
+ }
+ if (!defaultValueType) {
+ throw new Error("Missing DTD attribute default");
+ }
+ if (defaultValueType.indexOf('#') !== 0) {
+ defaultValueType = '#' + defaultValueType;
+ }
+ if (!defaultValueType.match(/^(#REQUIRED|#IMPLIED|#FIXED|#DEFAULT)$/)) {
+ throw new Error("Invalid default value type; expected: #REQUIRED, #IMPLIED, #FIXED or #DEFAULT");
+ }
+ if (defaultValue && !defaultValueType.match(/^(#FIXED|#DEFAULT)$/)) {
+ throw new Error("Default value only applies to #FIXED or #DEFAULT");
+ }
+ this.elementName = this.stringify.eleName(elementName);
+ this.attributeName = this.stringify.attName(attributeName);
+ this.attributeType = this.stringify.dtdAttType(attributeType);
+ this.defaultValue = this.stringify.dtdAttDefault(defaultValue);
+ this.defaultValueType = defaultValueType;
+ }
+
+ XMLDTDAttList.prototype.toString = function(options) {
+ return this.options.writer.set(options).dtdAttList(this);
+ };
+
+ return XMLDTDAttList;
+
+ })(XMLNode);
+
+}).call(this);
+
+},{"./XMLNode":17}],9:[function(require,module,exports){
+// Generated by CoffeeScript 1.12.7
+(function() {
+ var XMLDTDElement, XMLNode,
+ extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
+ hasProp = {}.hasOwnProperty;
+
+ XMLNode = require('./XMLNode');
+
+ module.exports = XMLDTDElement = (function(superClass) {
+ extend(XMLDTDElement, superClass);
+
+ function XMLDTDElement(parent, name, value) {
+ XMLDTDElement.__super__.constructor.call(this, parent);
+ if (name == null) {
+ throw new Error("Missing DTD element name");
+ }
+ if (!value) {
+ value = '(#PCDATA)';
+ }
+ if (Array.isArray(value)) {
+ value = '(' + value.join(',') + ')';
+ }
+ this.name = this.stringify.eleName(name);
+ this.value = this.stringify.dtdElementValue(value);
+ }
+
+ XMLDTDElement.prototype.toString = function(options) {
+ return this.options.writer.set(options).dtdElement(this);
+ };
+
+ return XMLDTDElement;
+
+ })(XMLNode);
+
+}).call(this);
+
+},{"./XMLNode":17}],10:[function(require,module,exports){
+// Generated by CoffeeScript 1.12.7
+(function() {
+ var XMLDTDEntity, XMLNode, isObject,
+ extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
+ hasProp = {}.hasOwnProperty;
+
+ isObject = require('./Utility').isObject;
+
+ XMLNode = require('./XMLNode');
+
+ module.exports = XMLDTDEntity = (function(superClass) {
+ extend(XMLDTDEntity, superClass);
+
+ function XMLDTDEntity(parent, pe, name, value) {
+ XMLDTDEntity.__super__.constructor.call(this, parent);
+ if (name == null) {
+ throw new Error("Missing entity name");
+ }
+ if (value == null) {
+ throw new Error("Missing entity value");
+ }
+ this.pe = !!pe;
+ this.name = this.stringify.eleName(name);
+ if (!isObject(value)) {
+ this.value = this.stringify.dtdEntityValue(value);
+ } else {
+ if (!value.pubID && !value.sysID) {
+ throw new Error("Public and/or system identifiers are required for an external entity");
+ }
+ if (value.pubID && !value.sysID) {
+ throw new Error("System identifier is required for a public external entity");
+ }
+ if (value.pubID != null) {
+ this.pubID = this.stringify.dtdPubID(value.pubID);
+ }
+ if (value.sysID != null) {
+ this.sysID = this.stringify.dtdSysID(value.sysID);
+ }
+ if (value.nData != null) {
+ this.nData = this.stringify.dtdNData(value.nData);
+ }
+ if (this.pe && this.nData) {
+ throw new Error("Notation declaration is not allowed in a parameter entity");
+ }
+ }
+ }
+
+ XMLDTDEntity.prototype.toString = function(options) {
+ return this.options.writer.set(options).dtdEntity(this);
+ };
+
+ return XMLDTDEntity;
+
+ })(XMLNode);
+
+}).call(this);
+
+},{"./Utility":4,"./XMLNode":17}],11:[function(require,module,exports){
+// Generated by CoffeeScript 1.12.7
+(function() {
+ var XMLDTDNotation, XMLNode,
+ extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
+ hasProp = {}.hasOwnProperty;
+
+ XMLNode = require('./XMLNode');
+
+ module.exports = XMLDTDNotation = (function(superClass) {
+ extend(XMLDTDNotation, superClass);
+
+ function XMLDTDNotation(parent, name, value) {
+ XMLDTDNotation.__super__.constructor.call(this, parent);
+ if (name == null) {
+ throw new Error("Missing notation name");
+ }
+ if (!value.pubID && !value.sysID) {
+ throw new Error("Public or system identifiers are required for an external entity");
+ }
+ this.name = this.stringify.eleName(name);
+ if (value.pubID != null) {
+ this.pubID = this.stringify.dtdPubID(value.pubID);
+ }
+ if (value.sysID != null) {
+ this.sysID = this.stringify.dtdSysID(value.sysID);
+ }
+ }
+
+ XMLDTDNotation.prototype.toString = function(options) {
+ return this.options.writer.set(options).dtdNotation(this);
+ };
+
+ return XMLDTDNotation;
+
+ })(XMLNode);
+
+}).call(this);
+
+},{"./XMLNode":17}],12:[function(require,module,exports){
+// Generated by CoffeeScript 1.12.7
+(function() {
+ var XMLDeclaration, XMLNode, isObject,
+ extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
+ hasProp = {}.hasOwnProperty;
+
+ isObject = require('./Utility').isObject;
+
+ XMLNode = require('./XMLNode');
+
+ module.exports = XMLDeclaration = (function(superClass) {
+ extend(XMLDeclaration, superClass);
+
+ function XMLDeclaration(parent, version, encoding, standalone) {
+ var ref;
+ XMLDeclaration.__super__.constructor.call(this, parent);
+ if (isObject(version)) {
+ ref = version, version = ref.version, encoding = ref.encoding, standalone = ref.standalone;
+ }
+ if (!version) {
+ version = '1.0';
+ }
+ this.version = this.stringify.xmlVersion(version);
+ if (encoding != null) {
+ this.encoding = this.stringify.xmlEncoding(encoding);
+ }
+ if (standalone != null) {
+ this.standalone = this.stringify.xmlStandalone(standalone);
+ }
+ }
+
+ XMLDeclaration.prototype.toString = function(options) {
+ return this.options.writer.set(options).declaration(this);
+ };
+
+ return XMLDeclaration;
+
+ })(XMLNode);
+
+}).call(this);
+
+},{"./Utility":4,"./XMLNode":17}],13:[function(require,module,exports){
+// Generated by CoffeeScript 1.12.7
+(function() {
+ var XMLDTDAttList, XMLDTDElement, XMLDTDEntity, XMLDTDNotation, XMLDocType, XMLNode, isObject,
+ extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
+ hasProp = {}.hasOwnProperty;
+
+ isObject = require('./Utility').isObject;
+
+ XMLNode = require('./XMLNode');
+
+ XMLDTDAttList = require('./XMLDTDAttList');
+
+ XMLDTDEntity = require('./XMLDTDEntity');
+
+ XMLDTDElement = require('./XMLDTDElement');
+
+ XMLDTDNotation = require('./XMLDTDNotation');
+
+ module.exports = XMLDocType = (function(superClass) {
+ extend(XMLDocType, superClass);
+
+ function XMLDocType(parent, pubID, sysID) {
+ var ref, ref1;
+ XMLDocType.__super__.constructor.call(this, parent);
+ this.documentObject = parent;
+ if (isObject(pubID)) {
+ ref = pubID, pubID = ref.pubID, sysID = ref.sysID;
+ }
+ if (sysID == null) {
+ ref1 = [pubID, sysID], sysID = ref1[0], pubID = ref1[1];
+ }
+ if (pubID != null) {
+ this.pubID = this.stringify.dtdPubID(pubID);
+ }
+ if (sysID != null) {
+ this.sysID = this.stringify.dtdSysID(sysID);
+ }
+ }
+
+ XMLDocType.prototype.element = function(name, value) {
+ var child;
+ child = new XMLDTDElement(this, name, value);
+ this.children.push(child);
+ return this;
+ };
+
+ XMLDocType.prototype.attList = function(elementName, attributeName, attributeType, defaultValueType, defaultValue) {
+ var child;
+ child = new XMLDTDAttList(this, elementName, attributeName, attributeType, defaultValueType, defaultValue);
+ this.children.push(child);
+ return this;
+ };
+
+ XMLDocType.prototype.entity = function(name, value) {
+ var child;
+ child = new XMLDTDEntity(this, false, name, value);
+ this.children.push(child);
+ return this;
+ };
+
+ XMLDocType.prototype.pEntity = function(name, value) {
+ var child;
+ child = new XMLDTDEntity(this, true, name, value);
+ this.children.push(child);
+ return this;
+ };
+
+ XMLDocType.prototype.notation = function(name, value) {
+ var child;
+ child = new XMLDTDNotation(this, name, value);
+ this.children.push(child);
+ return this;
+ };
+
+ XMLDocType.prototype.toString = function(options) {
+ return this.options.writer.set(options).docType(this);
+ };
+
+ XMLDocType.prototype.ele = function(name, value) {
+ return this.element(name, value);
+ };
+
+ XMLDocType.prototype.att = function(elementName, attributeName, attributeType, defaultValueType, defaultValue) {
+ return this.attList(elementName, attributeName, attributeType, defaultValueType, defaultValue);
+ };
+
+ XMLDocType.prototype.ent = function(name, value) {
+ return this.entity(name, value);
+ };
+
+ XMLDocType.prototype.pent = function(name, value) {
+ return this.pEntity(name, value);
+ };
+
+ XMLDocType.prototype.not = function(name, value) {
+ return this.notation(name, value);
+ };
+
+ XMLDocType.prototype.up = function() {
+ return this.root() || this.documentObject;
+ };
+
+ return XMLDocType;
+
+ })(XMLNode);
+
+}).call(this);
+
+},{"./Utility":4,"./XMLDTDAttList":8,"./XMLDTDElement":9,"./XMLDTDEntity":10,"./XMLDTDNotation":11,"./XMLNode":17}],14:[function(require,module,exports){
+// Generated by CoffeeScript 1.12.7
+(function() {
+ var XMLDocument, XMLNode, XMLStringWriter, XMLStringifier, isPlainObject,
+ extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
+ hasProp = {}.hasOwnProperty;
+
+ isPlainObject = require('./Utility').isPlainObject;
+
+ XMLNode = require('./XMLNode');
+
+ XMLStringifier = require('./XMLStringifier');
+
+ XMLStringWriter = require('./XMLStringWriter');
+
+ module.exports = XMLDocument = (function(superClass) {
+ extend(XMLDocument, superClass);
+
+ function XMLDocument(options) {
+ XMLDocument.__super__.constructor.call(this, null);
+ options || (options = {});
+ if (!options.writer) {
+ options.writer = new XMLStringWriter();
+ }
+ this.options = options;
+ this.stringify = new XMLStringifier(options);
+ this.isDocument = true;
+ }
+
+ XMLDocument.prototype.end = function(writer) {
+ var writerOptions;
+ if (!writer) {
+ writer = this.options.writer;
+ } else if (isPlainObject(writer)) {
+ writerOptions = writer;
+ writer = this.options.writer.set(writerOptions);
+ }
+ return writer.document(this);
+ };
+
+ XMLDocument.prototype.toString = function(options) {
+ return this.options.writer.set(options).document(this);
+ };
+
+ return XMLDocument;
+
+ })(XMLNode);
+
+}).call(this);
+
+},{"./Utility":4,"./XMLNode":17,"./XMLStringWriter":21,"./XMLStringifier":22}],15:[function(require,module,exports){
+// Generated by CoffeeScript 1.12.7
+(function() {
+ var XMLAttribute, XMLCData, XMLComment, XMLDTDAttList, XMLDTDElement, XMLDTDEntity, XMLDTDNotation, XMLDeclaration, XMLDocType, XMLDocumentCB, XMLElement, XMLProcessingInstruction, XMLRaw, XMLStringWriter, XMLStringifier, XMLText, isFunction, isObject, isPlainObject, ref,
+ hasProp = {}.hasOwnProperty;
+
+ ref = require('./Utility'), isObject = ref.isObject, isFunction = ref.isFunction, isPlainObject = ref.isPlainObject;
+
+ XMLElement = require('./XMLElement');
+
+ XMLCData = require('./XMLCData');
+
+ XMLComment = require('./XMLComment');
+
+ XMLRaw = require('./XMLRaw');
+
+ XMLText = require('./XMLText');
+
+ XMLProcessingInstruction = require('./XMLProcessingInstruction');
+
+ XMLDeclaration = require('./XMLDeclaration');
+
+ XMLDocType = require('./XMLDocType');
+
+ XMLDTDAttList = require('./XMLDTDAttList');
+
+ XMLDTDEntity = require('./XMLDTDEntity');
+
+ XMLDTDElement = require('./XMLDTDElement');
+
+ XMLDTDNotation = require('./XMLDTDNotation');
+
+ XMLAttribute = require('./XMLAttribute');
+
+ XMLStringifier = require('./XMLStringifier');
+
+ XMLStringWriter = require('./XMLStringWriter');
+
+ module.exports = XMLDocumentCB = (function() {
+ function XMLDocumentCB(options, onData, onEnd) {
+ var writerOptions;
+ options || (options = {});
+ if (!options.writer) {
+ options.writer = new XMLStringWriter(options);
+ } else if (isPlainObject(options.writer)) {
+ writerOptions = options.writer;
+ options.writer = new XMLStringWriter(writerOptions);
+ }
+ this.options = options;
+ this.writer = options.writer;
+ this.stringify = new XMLStringifier(options);
+ this.onDataCallback = onData || function() {};
+ this.onEndCallback = onEnd || function() {};
+ this.currentNode = null;
+ this.currentLevel = -1;
+ this.openTags = {};
+ this.documentStarted = false;
+ this.documentCompleted = false;
+ this.root = null;
+ }
+
+ XMLDocumentCB.prototype.node = function(name, attributes, text) {
+ var ref1;
+ if (name == null) {
+ throw new Error("Missing node name");
+ }
+ if (this.root && this.currentLevel === -1) {
+ throw new Error("Document can only have one root node");
+ }
+ this.openCurrent();
+ name = name.valueOf();
+ if (attributes == null) {
+ attributes = {};
+ }
+ attributes = attributes.valueOf();
+ if (!isObject(attributes)) {
+ ref1 = [attributes, text], text = ref1[0], attributes = ref1[1];
+ }
+ this.currentNode = new XMLElement(this, name, attributes);
+ this.currentNode.children = false;
+ this.currentLevel++;
+ this.openTags[this.currentLevel] = this.currentNode;
+ if (text != null) {
+ this.text(text);
+ }
+ return this;
+ };
+
+ XMLDocumentCB.prototype.element = function(name, attributes, text) {
+ if (this.currentNode && this.currentNode instanceof XMLDocType) {
+ return this.dtdElement.apply(this, arguments);
+ } else {
+ return this.node(name, attributes, text);
+ }
+ };
+
+ XMLDocumentCB.prototype.attribute = function(name, value) {
+ var attName, attValue;
+ if (!this.currentNode || this.currentNode.children) {
+ throw new Error("att() can only be used immediately after an ele() call in callback mode");
+ }
+ if (name != null) {
+ name = name.valueOf();
+ }
+ if (isObject(name)) {
+ for (attName in name) {
+ if (!hasProp.call(name, attName)) continue;
+ attValue = name[attName];
+ this.attribute(attName, attValue);
+ }
+ } else {
+ if (isFunction(value)) {
+ value = value.apply();
+ }
+ if (!this.options.skipNullAttributes || (value != null)) {
+ this.currentNode.attributes[name] = new XMLAttribute(this, name, value);
+ }
+ }
+ return this;
+ };
+
+ XMLDocumentCB.prototype.text = function(value) {
+ var node;
+ this.openCurrent();
+ node = new XMLText(this, value);
+ this.onData(this.writer.text(node, this.currentLevel + 1));
+ return this;
+ };
+
+ XMLDocumentCB.prototype.cdata = function(value) {
+ var node;
+ this.openCurrent();
+ node = new XMLCData(this, value);
+ this.onData(this.writer.cdata(node, this.currentLevel + 1));
+ return this;
+ };
+
+ XMLDocumentCB.prototype.comment = function(value) {
+ var node;
+ this.openCurrent();
+ node = new XMLComment(this, value);
+ this.onData(this.writer.comment(node, this.currentLevel + 1));
+ return this;
+ };
+
+ XMLDocumentCB.prototype.raw = function(value) {
+ var node;
+ this.openCurrent();
+ node = new XMLRaw(this, value);
+ this.onData(this.writer.raw(node, this.currentLevel + 1));
+ return this;
+ };
+
+ XMLDocumentCB.prototype.instruction = function(target, value) {
+ var i, insTarget, insValue, len, node;
+ this.openCurrent();
+ if (target != null) {
+ target = target.valueOf();
+ }
+ if (value != null) {
+ value = value.valueOf();
+ }
+ if (Array.isArray(target)) {
+ for (i = 0, len = target.length; i < len; i++) {
+ insTarget = target[i];
+ this.instruction(insTarget);
+ }
+ } else if (isObject(target)) {
+ for (insTarget in target) {
+ if (!hasProp.call(target, insTarget)) continue;
+ insValue = target[insTarget];
+ this.instruction(insTarget, insValue);
+ }
+ } else {
+ if (isFunction(value)) {
+ value = value.apply();
+ }
+ node = new XMLProcessingInstruction(this, target, value);
+ this.onData(this.writer.processingInstruction(node, this.currentLevel + 1));
+ }
+ return this;
+ };
+
+ XMLDocumentCB.prototype.declaration = function(version, encoding, standalone) {
+ var node;
+ this.openCurrent();
+ if (this.documentStarted) {
+ throw new Error("declaration() must be the first node");
+ }
+ node = new XMLDeclaration(this, version, encoding, standalone);
+ this.onData(this.writer.declaration(node, this.currentLevel + 1));
+ return this;
+ };
+
+ XMLDocumentCB.prototype.doctype = function(root, pubID, sysID) {
+ this.openCurrent();
+ if (root == null) {
+ throw new Error("Missing root node name");
+ }
+ if (this.root) {
+ throw new Error("dtd() must come before the root node");
+ }
+ this.currentNode = new XMLDocType(this, pubID, sysID);
+ this.currentNode.rootNodeName = root;
+ this.currentNode.children = false;
+ this.currentLevel++;
+ this.openTags[this.currentLevel] = this.currentNode;
+ return this;
+ };
+
+ XMLDocumentCB.prototype.dtdElement = function(name, value) {
+ var node;
+ this.openCurrent();
+ node = new XMLDTDElement(this, name, value);
+ this.onData(this.writer.dtdElement(node, this.currentLevel + 1));
+ return this;
+ };
+
+ XMLDocumentCB.prototype.attList = function(elementName, attributeName, attributeType, defaultValueType, defaultValue) {
+ var node;
+ this.openCurrent();
+ node = new XMLDTDAttList(this, elementName, attributeName, attributeType, defaultValueType, defaultValue);
+ this.onData(this.writer.dtdAttList(node, this.currentLevel + 1));
+ return this;
+ };
+
+ XMLDocumentCB.prototype.entity = function(name, value) {
+ var node;
+ this.openCurrent();
+ node = new XMLDTDEntity(this, false, name, value);
+ this.onData(this.writer.dtdEntity(node, this.currentLevel + 1));
+ return this;
+ };
+
+ XMLDocumentCB.prototype.pEntity = function(name, value) {
+ var node;
+ this.openCurrent();
+ node = new XMLDTDEntity(this, true, name, value);
+ this.onData(this.writer.dtdEntity(node, this.currentLevel + 1));
+ return this;
+ };
+
+ XMLDocumentCB.prototype.notation = function(name, value) {
+ var node;
+ this.openCurrent();
+ node = new XMLDTDNotation(this, name, value);
+ this.onData(this.writer.dtdNotation(node, this.currentLevel + 1));
+ return this;
+ };
+
+ XMLDocumentCB.prototype.up = function() {
+ if (this.currentLevel < 0) {
+ throw new Error("The document node has no parent");
+ }
+ if (this.currentNode) {
+ if (this.currentNode.children) {
+ this.closeNode(this.currentNode);
+ } else {
+ this.openNode(this.currentNode);
+ }
+ this.currentNode = null;
+ } else {
+ this.closeNode(this.openTags[this.currentLevel]);
+ }
+ delete this.openTags[this.currentLevel];
+ this.currentLevel--;
+ return this;
+ };
+
+ XMLDocumentCB.prototype.end = function() {
+ while (this.currentLevel >= 0) {
+ this.up();
+ }
+ return this.onEnd();
+ };
+
+ XMLDocumentCB.prototype.openCurrent = function() {
+ if (this.currentNode) {
+ this.currentNode.children = true;
+ return this.openNode(this.currentNode);
+ }
+ };
+
+ XMLDocumentCB.prototype.openNode = function(node) {
+ if (!node.isOpen) {
+ if (!this.root && this.currentLevel === 0 && node instanceof XMLElement) {
+ this.root = node;
+ }
+ this.onData(this.writer.openNode(node, this.currentLevel));
+ return node.isOpen = true;
+ }
+ };
+
+ XMLDocumentCB.prototype.closeNode = function(node) {
+ if (!node.isClosed) {
+ this.onData(this.writer.closeNode(node, this.currentLevel));
+ return node.isClosed = true;
+ }
+ };
+
+ XMLDocumentCB.prototype.onData = function(chunk) {
+ this.documentStarted = true;
+ return this.onDataCallback(chunk);
+ };
+
+ XMLDocumentCB.prototype.onEnd = function() {
+ this.documentCompleted = true;
+ return this.onEndCallback();
+ };
+
+ XMLDocumentCB.prototype.ele = function() {
+ return this.element.apply(this, arguments);
+ };
+
+ XMLDocumentCB.prototype.nod = function(name, attributes, text) {
+ return this.node(name, attributes, text);
+ };
+
+ XMLDocumentCB.prototype.txt = function(value) {
+ return this.text(value);
+ };
+
+ XMLDocumentCB.prototype.dat = function(value) {
+ return this.cdata(value);
+ };
+
+ XMLDocumentCB.prototype.com = function(value) {
+ return this.comment(value);
+ };
+
+ XMLDocumentCB.prototype.ins = function(target, value) {
+ return this.instruction(target, value);
+ };
+
+ XMLDocumentCB.prototype.dec = function(version, encoding, standalone) {
+ return this.declaration(version, encoding, standalone);
+ };
+
+ XMLDocumentCB.prototype.dtd = function(root, pubID, sysID) {
+ return this.doctype(root, pubID, sysID);
+ };
+
+ XMLDocumentCB.prototype.e = function(name, attributes, text) {
+ return this.element(name, attributes, text);
+ };
+
+ XMLDocumentCB.prototype.n = function(name, attributes, text) {
+ return this.node(name, attributes, text);
+ };
+
+ XMLDocumentCB.prototype.t = function(value) {
+ return this.text(value);
+ };
+
+ XMLDocumentCB.prototype.d = function(value) {
+ return this.cdata(value);
+ };
+
+ XMLDocumentCB.prototype.c = function(value) {
+ return this.comment(value);
+ };
+
+ XMLDocumentCB.prototype.r = function(value) {
+ return this.raw(value);
+ };
+
+ XMLDocumentCB.prototype.i = function(target, value) {
+ return this.instruction(target, value);
+ };
+
+ XMLDocumentCB.prototype.att = function() {
+ if (this.currentNode && this.currentNode instanceof XMLDocType) {
+ return this.attList.apply(this, arguments);
+ } else {
+ return this.attribute.apply(this, arguments);
+ }
+ };
+
+ XMLDocumentCB.prototype.a = function() {
+ if (this.currentNode && this.currentNode instanceof XMLDocType) {
+ return this.attList.apply(this, arguments);
+ } else {
+ return this.attribute.apply(this, arguments);
+ }
+ };
+
+ XMLDocumentCB.prototype.ent = function(name, value) {
+ return this.entity(name, value);
+ };
+
+ XMLDocumentCB.prototype.pent = function(name, value) {
+ return this.pEntity(name, value);
+ };
+
+ XMLDocumentCB.prototype.not = function(name, value) {
+ return this.notation(name, value);
+ };
+
+ return XMLDocumentCB;
+
+ })();
+
+}).call(this);
+
+},{"./Utility":4,"./XMLAttribute":5,"./XMLCData":6,"./XMLComment":7,"./XMLDTDAttList":8,"./XMLDTDElement":9,"./XMLDTDEntity":10,"./XMLDTDNotation":11,"./XMLDeclaration":12,"./XMLDocType":13,"./XMLElement":16,"./XMLProcessingInstruction":18,"./XMLRaw":19,"./XMLStringWriter":21,"./XMLStringifier":22,"./XMLText":23}],16:[function(require,module,exports){
+// Generated by CoffeeScript 1.12.7
+(function() {
+ var XMLAttribute, XMLElement, XMLNode, isFunction, isObject, ref,
+ extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
+ hasProp = {}.hasOwnProperty;
+
+ ref = require('./Utility'), isObject = ref.isObject, isFunction = ref.isFunction;
+
+ XMLNode = require('./XMLNode');
+
+ XMLAttribute = require('./XMLAttribute');
+
+ module.exports = XMLElement = (function(superClass) {
+ extend(XMLElement, superClass);
+
+ function XMLElement(parent, name, attributes) {
+ XMLElement.__super__.constructor.call(this, parent);
+ if (name == null) {
+ throw new Error("Missing element name");
+ }
+ this.name = this.stringify.eleName(name);
+ this.attributes = {};
+ if (attributes != null) {
+ this.attribute(attributes);
+ }
+ if (parent.isDocument) {
+ this.isRoot = true;
+ this.documentObject = parent;
+ parent.rootObject = this;
+ }
+ }
+
+ XMLElement.prototype.clone = function() {
+ var att, attName, clonedSelf, ref1;
+ clonedSelf = Object.create(this);
+ if (clonedSelf.isRoot) {
+ clonedSelf.documentObject = null;
+ }
+ clonedSelf.attributes = {};
+ ref1 = this.attributes;
+ for (attName in ref1) {
+ if (!hasProp.call(ref1, attName)) continue;
+ att = ref1[attName];
+ clonedSelf.attributes[attName] = att.clone();
+ }
+ clonedSelf.children = [];
+ this.children.forEach(function(child) {
+ var clonedChild;
+ clonedChild = child.clone();
+ clonedChild.parent = clonedSelf;
+ return clonedSelf.children.push(clonedChild);
+ });
+ return clonedSelf;
+ };
+
+ XMLElement.prototype.attribute = function(name, value) {
+ var attName, attValue;
+ if (name != null) {
+ name = name.valueOf();
+ }
+ if (isObject(name)) {
+ for (attName in name) {
+ if (!hasProp.call(name, attName)) continue;
+ attValue = name[attName];
+ this.attribute(attName, attValue);
+ }
+ } else {
+ if (isFunction(value)) {
+ value = value.apply();
+ }
+ if (!this.options.skipNullAttributes || (value != null)) {
+ this.attributes[name] = new XMLAttribute(this, name, value);
+ }
+ }
+ return this;
+ };
+
+ XMLElement.prototype.removeAttribute = function(name) {
+ var attName, i, len;
+ if (name == null) {
+ throw new Error("Missing attribute name");
+ }
+ name = name.valueOf();
+ if (Array.isArray(name)) {
+ for (i = 0, len = name.length; i < len; i++) {
+ attName = name[i];
+ delete this.attributes[attName];
+ }
+ } else {
+ delete this.attributes[name];
+ }
+ return this;
+ };
+
+ XMLElement.prototype.toString = function(options) {
+ return this.options.writer.set(options).element(this);
+ };
+
+ XMLElement.prototype.att = function(name, value) {
+ return this.attribute(name, value);
+ };
+
+ XMLElement.prototype.a = function(name, value) {
+ return this.attribute(name, value);
+ };
+
+ return XMLElement;
+
+ })(XMLNode);
+
+}).call(this);
+
+},{"./Utility":4,"./XMLAttribute":5,"./XMLNode":17}],17:[function(require,module,exports){
+// Generated by CoffeeScript 1.12.7
+(function() {
+ var XMLCData, XMLComment, XMLDeclaration, XMLDocType, XMLElement, XMLNode, XMLProcessingInstruction, XMLRaw, XMLText, isEmpty, isFunction, isObject, ref,
+ hasProp = {}.hasOwnProperty;
+
+ ref = require('./Utility'), isObject = ref.isObject, isFunction = ref.isFunction, isEmpty = ref.isEmpty;
+
+ XMLElement = null;
+
+ XMLCData = null;
+
+ XMLComment = null;
+
+ XMLDeclaration = null;
+
+ XMLDocType = null;
+
+ XMLRaw = null;
+
+ XMLText = null;
+
+ XMLProcessingInstruction = null;
+
+ module.exports = XMLNode = (function() {
+ function XMLNode(parent) {
+ this.parent = parent;
+ if (this.parent) {
+ this.options = this.parent.options;
+ this.stringify = this.parent.stringify;
+ }
+ this.children = [];
+ if (!XMLElement) {
+ XMLElement = require('./XMLElement');
+ XMLCData = require('./XMLCData');
+ XMLComment = require('./XMLComment');
+ XMLDeclaration = require('./XMLDeclaration');
+ XMLDocType = require('./XMLDocType');
+ XMLRaw = require('./XMLRaw');
+ XMLText = require('./XMLText');
+ XMLProcessingInstruction = require('./XMLProcessingInstruction');
+ }
+ }
+
+ XMLNode.prototype.element = function(name, attributes, text) {
+ var childNode, item, j, k, key, lastChild, len, len1, ref1, val;
+ lastChild = null;
+ if (attributes == null) {
+ attributes = {};
+ }
+ attributes = attributes.valueOf();
+ if (!isObject(attributes)) {
+ ref1 = [attributes, text], text = ref1[0], attributes = ref1[1];
+ }
+ if (name != null) {
+ name = name.valueOf();
+ }
+ if (Array.isArray(name)) {
+ for (j = 0, len = name.length; j < len; j++) {
+ item = name[j];
+ lastChild = this.element(item);
+ }
+ } else if (isFunction(name)) {
+ lastChild = this.element(name.apply());
+ } else if (isObject(name)) {
+ for (key in name) {
+ if (!hasProp.call(name, key)) continue;
+ val = name[key];
+ if (isFunction(val)) {
+ val = val.apply();
+ }
+ if ((isObject(val)) && (isEmpty(val))) {
+ val = null;
+ }
+ if (!this.options.ignoreDecorators && this.stringify.convertAttKey && key.indexOf(this.stringify.convertAttKey) === 0) {
+ lastChild = this.attribute(key.substr(this.stringify.convertAttKey.length), val);
+ } else if (!this.options.separateArrayItems && Array.isArray(val)) {
+ for (k = 0, len1 = val.length; k < len1; k++) {
+ item = val[k];
+ childNode = {};
+ childNode[key] = item;
+ lastChild = this.element(childNode);
+ }
+ } else if (isObject(val)) {
+ lastChild = this.element(key);
+ lastChild.element(val);
+ } else {
+ lastChild = this.element(key, val);
+ }
+ }
+ } else {
+ if (!this.options.ignoreDecorators && this.stringify.convertTextKey && name.indexOf(this.stringify.convertTextKey) === 0) {
+ lastChild = this.text(text);
+ } else if (!this.options.ignoreDecorators && this.stringify.convertCDataKey && name.indexOf(this.stringify.convertCDataKey) === 0) {
+ lastChild = this.cdata(text);
+ } else if (!this.options.ignoreDecorators && this.stringify.convertCommentKey && name.indexOf(this.stringify.convertCommentKey) === 0) {
+ lastChild = this.comment(text);
+ } else if (!this.options.ignoreDecorators && this.stringify.convertRawKey && name.indexOf(this.stringify.convertRawKey) === 0) {
+ lastChild = this.raw(text);
+ } else if (!this.options.ignoreDecorators && this.stringify.convertPIKey && name.indexOf(this.stringify.convertPIKey) === 0) {
+ lastChild = this.instruction(name.substr(this.stringify.convertPIKey.length), text);
+ } else {
+ lastChild = this.node(name, attributes, text);
+ }
+ }
+ if (lastChild == null) {
+ throw new Error("Could not create any elements with: " + name);
+ }
+ return lastChild;
+ };
+
+ XMLNode.prototype.insertBefore = function(name, attributes, text) {
+ var child, i, removed;
+ if (this.isRoot) {
+ throw new Error("Cannot insert elements at root level");
+ }
+ i = this.parent.children.indexOf(this);
+ removed = this.parent.children.splice(i);
+ child = this.parent.element(name, attributes, text);
+ Array.prototype.push.apply(this.parent.children, removed);
+ return child;
+ };
+
+ XMLNode.prototype.insertAfter = function(name, attributes, text) {
+ var child, i, removed;
+ if (this.isRoot) {
+ throw new Error("Cannot insert elements at root level");
+ }
+ i = this.parent.children.indexOf(this);
+ removed = this.parent.children.splice(i + 1);
+ child = this.parent.element(name, attributes, text);
+ Array.prototype.push.apply(this.parent.children, removed);
+ return child;
+ };
+
+ XMLNode.prototype.remove = function() {
+ var i, ref1;
+ if (this.isRoot) {
+ throw new Error("Cannot remove the root element");
+ }
+ i = this.parent.children.indexOf(this);
+ [].splice.apply(this.parent.children, [i, i - i + 1].concat(ref1 = [])), ref1;
+ return this.parent;
+ };
+
+ XMLNode.prototype.node = function(name, attributes, text) {
+ var child, ref1;
+ if (name != null) {
+ name = name.valueOf();
+ }
+ attributes || (attributes = {});
+ attributes = attributes.valueOf();
+ if (!isObject(attributes)) {
+ ref1 = [attributes, text], text = ref1[0], attributes = ref1[1];
+ }
+ child = new XMLElement(this, name, attributes);
+ if (text != null) {
+ child.text(text);
+ }
+ this.children.push(child);
+ return child;
+ };
+
+ XMLNode.prototype.text = function(value) {
+ var child;
+ child = new XMLText(this, value);
+ this.children.push(child);
+ return this;
+ };
+
+ XMLNode.prototype.cdata = function(value) {
+ var child;
+ child = new XMLCData(this, value);
+ this.children.push(child);
+ return this;
+ };
+
+ XMLNode.prototype.comment = function(value) {
+ var child;
+ child = new XMLComment(this, value);
+ this.children.push(child);
+ return this;
+ };
+
+ XMLNode.prototype.commentBefore = function(value) {
+ var child, i, removed;
+ i = this.parent.children.indexOf(this);
+ removed = this.parent.children.splice(i);
+ child = this.parent.comment(value);
+ Array.prototype.push.apply(this.parent.children, removed);
+ return this;
+ };
+
+ XMLNode.prototype.commentAfter = function(value) {
+ var child, i, removed;
+ i = this.parent.children.indexOf(this);
+ removed = this.parent.children.splice(i + 1);
+ child = this.parent.comment(value);
+ Array.prototype.push.apply(this.parent.children, removed);
+ return this;
+ };
+
+ XMLNode.prototype.raw = function(value) {
+ var child;
+ child = new XMLRaw(this, value);
+ this.children.push(child);
+ return this;
+ };
+
+ XMLNode.prototype.instruction = function(target, value) {
+ var insTarget, insValue, instruction, j, len;
+ if (target != null) {
+ target = target.valueOf();
+ }
+ if (value != null) {
+ value = value.valueOf();
+ }
+ if (Array.isArray(target)) {
+ for (j = 0, len = target.length; j < len; j++) {
+ insTarget = target[j];
+ this.instruction(insTarget);
+ }
+ } else if (isObject(target)) {
+ for (insTarget in target) {
+ if (!hasProp.call(target, insTarget)) continue;
+ insValue = target[insTarget];
+ this.instruction(insTarget, insValue);
+ }
+ } else {
+ if (isFunction(value)) {
+ value = value.apply();
+ }
+ instruction = new XMLProcessingInstruction(this, target, value);
+ this.children.push(instruction);
+ }
+ return this;
+ };
+
+ XMLNode.prototype.instructionBefore = function(target, value) {
+ var child, i, removed;
+ i = this.parent.children.indexOf(this);
+ removed = this.parent.children.splice(i);
+ child = this.parent.instruction(target, value);
+ Array.prototype.push.apply(this.parent.children, removed);
+ return this;
+ };
+
+ XMLNode.prototype.instructionAfter = function(target, value) {
+ var child, i, removed;
+ i = this.parent.children.indexOf(this);
+ removed = this.parent.children.splice(i + 1);
+ child = this.parent.instruction(target, value);
+ Array.prototype.push.apply(this.parent.children, removed);
+ return this;
+ };
+
+ XMLNode.prototype.declaration = function(version, encoding, standalone) {
+ var doc, xmldec;
+ doc = this.document();
+ xmldec = new XMLDeclaration(doc, version, encoding, standalone);
+ if (doc.children[0] instanceof XMLDeclaration) {
+ doc.children[0] = xmldec;
+ } else {
+ doc.children.unshift(xmldec);
+ }
+ return doc.root() || doc;
+ };
+
+ XMLNode.prototype.doctype = function(pubID, sysID) {
+ var child, doc, doctype, i, j, k, len, len1, ref1, ref2;
+ doc = this.document();
+ doctype = new XMLDocType(doc, pubID, sysID);
+ ref1 = doc.children;
+ for (i = j = 0, len = ref1.length; j < len; i = ++j) {
+ child = ref1[i];
+ if (child instanceof XMLDocType) {
+ doc.children[i] = doctype;
+ return doctype;
+ }
+ }
+ ref2 = doc.children;
+ for (i = k = 0, len1 = ref2.length; k < len1; i = ++k) {
+ child = ref2[i];
+ if (child.isRoot) {
+ doc.children.splice(i, 0, doctype);
+ return doctype;
+ }
+ }
+ doc.children.push(doctype);
+ return doctype;
+ };
+
+ XMLNode.prototype.up = function() {
+ if (this.isRoot) {
+ throw new Error("The root node has no parent. Use doc() if you need to get the document object.");
+ }
+ return this.parent;
+ };
+
+ XMLNode.prototype.root = function() {
+ var node;
+ node = this;
+ while (node) {
+ if (node.isDocument) {
+ return node.rootObject;
+ } else if (node.isRoot) {
+ return node;
+ } else {
+ node = node.parent;
+ }
+ }
+ };
+
+ XMLNode.prototype.document = function() {
+ var node;
+ node = this;
+ while (node) {
+ if (node.isDocument) {
+ return node;
+ } else {
+ node = node.parent;
+ }
+ }
+ };
+
+ XMLNode.prototype.end = function(options) {
+ return this.document().end(options);
+ };
+
+ XMLNode.prototype.prev = function() {
+ var i;
+ i = this.parent.children.indexOf(this);
+ if (i < 1) {
+ throw new Error("Already at the first node");
+ }
+ return this.parent.children[i - 1];
+ };
+
+ XMLNode.prototype.next = function() {
+ var i;
+ i = this.parent.children.indexOf(this);
+ if (i === -1 || i === this.parent.children.length - 1) {
+ throw new Error("Already at the last node");
+ }
+ return this.parent.children[i + 1];
+ };
+
+ XMLNode.prototype.importDocument = function(doc) {
+ var clonedRoot;
+ clonedRoot = doc.root().clone();
+ clonedRoot.parent = this;
+ clonedRoot.isRoot = false;
+ this.children.push(clonedRoot);
+ return this;
+ };
+
+ XMLNode.prototype.ele = function(name, attributes, text) {
+ return this.element(name, attributes, text);
+ };
+
+ XMLNode.prototype.nod = function(name, attributes, text) {
+ return this.node(name, attributes, text);
+ };
+
+ XMLNode.prototype.txt = function(value) {
+ return this.text(value);
+ };
+
+ XMLNode.prototype.dat = function(value) {
+ return this.cdata(value);
+ };
+
+ XMLNode.prototype.com = function(value) {
+ return this.comment(value);
+ };
+
+ XMLNode.prototype.ins = function(target, value) {
+ return this.instruction(target, value);
+ };
+
+ XMLNode.prototype.doc = function() {
+ return this.document();
+ };
+
+ XMLNode.prototype.dec = function(version, encoding, standalone) {
+ return this.declaration(version, encoding, standalone);
+ };
+
+ XMLNode.prototype.dtd = function(pubID, sysID) {
+ return this.doctype(pubID, sysID);
+ };
+
+ XMLNode.prototype.e = function(name, attributes, text) {
+ return this.element(name, attributes, text);
+ };
+
+ XMLNode.prototype.n = function(name, attributes, text) {
+ return this.node(name, attributes, text);
+ };
+
+ XMLNode.prototype.t = function(value) {
+ return this.text(value);
+ };
+
+ XMLNode.prototype.d = function(value) {
+ return this.cdata(value);
+ };
+
+ XMLNode.prototype.c = function(value) {
+ return this.comment(value);
+ };
+
+ XMLNode.prototype.r = function(value) {
+ return this.raw(value);
+ };
+
+ XMLNode.prototype.i = function(target, value) {
+ return this.instruction(target, value);
+ };
+
+ XMLNode.prototype.u = function() {
+ return this.up();
+ };
+
+ XMLNode.prototype.importXMLBuilder = function(doc) {
+ return this.importDocument(doc);
+ };
+
+ return XMLNode;
+
+ })();
+
+}).call(this);
+
+},{"./Utility":4,"./XMLCData":6,"./XMLComment":7,"./XMLDeclaration":12,"./XMLDocType":13,"./XMLElement":16,"./XMLProcessingInstruction":18,"./XMLRaw":19,"./XMLText":23}],18:[function(require,module,exports){
+// Generated by CoffeeScript 1.12.7
+(function() {
+ var XMLNode, XMLProcessingInstruction,
+ extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
+ hasProp = {}.hasOwnProperty;
+
+ XMLNode = require('./XMLNode');
+
+ module.exports = XMLProcessingInstruction = (function(superClass) {
+ extend(XMLProcessingInstruction, superClass);
+
+ function XMLProcessingInstruction(parent, target, value) {
+ XMLProcessingInstruction.__super__.constructor.call(this, parent);
+ if (target == null) {
+ throw new Error("Missing instruction target");
+ }
+ this.target = this.stringify.insTarget(target);
+ if (value) {
+ this.value = this.stringify.insValue(value);
+ }
+ }
+
+ XMLProcessingInstruction.prototype.clone = function() {
+ return Object.create(this);
+ };
+
+ XMLProcessingInstruction.prototype.toString = function(options) {
+ return this.options.writer.set(options).processingInstruction(this);
+ };
+
+ return XMLProcessingInstruction;
+
+ })(XMLNode);
+
+}).call(this);
+
+},{"./XMLNode":17}],19:[function(require,module,exports){
+// Generated by CoffeeScript 1.12.7
+(function() {
+ var XMLNode, XMLRaw,
+ extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
+ hasProp = {}.hasOwnProperty;
+
+ XMLNode = require('./XMLNode');
+
+ module.exports = XMLRaw = (function(superClass) {
+ extend(XMLRaw, superClass);
+
+ function XMLRaw(parent, text) {
+ XMLRaw.__super__.constructor.call(this, parent);
+ if (text == null) {
+ throw new Error("Missing raw text");
+ }
+ this.value = this.stringify.raw(text);
+ }
+
+ XMLRaw.prototype.clone = function() {
+ return Object.create(this);
+ };
+
+ XMLRaw.prototype.toString = function(options) {
+ return this.options.writer.set(options).raw(this);
+ };
+
+ return XMLRaw;
+
+ })(XMLNode);
+
+}).call(this);
+
+},{"./XMLNode":17}],20:[function(require,module,exports){
+// Generated by CoffeeScript 1.12.7
+(function() {
+ var XMLCData, XMLComment, XMLDTDAttList, XMLDTDElement, XMLDTDEntity, XMLDTDNotation, XMLDeclaration, XMLDocType, XMLElement, XMLProcessingInstruction, XMLRaw, XMLStreamWriter, XMLText, XMLWriterBase,
+ extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
+ hasProp = {}.hasOwnProperty;
+
+ XMLDeclaration = require('./XMLDeclaration');
+
+ XMLDocType = require('./XMLDocType');
+
+ XMLCData = require('./XMLCData');
+
+ XMLComment = require('./XMLComment');
+
+ XMLElement = require('./XMLElement');
+
+ XMLRaw = require('./XMLRaw');
+
+ XMLText = require('./XMLText');
+
+ XMLProcessingInstruction = require('./XMLProcessingInstruction');
+
+ XMLDTDAttList = require('./XMLDTDAttList');
+
+ XMLDTDElement = require('./XMLDTDElement');
+
+ XMLDTDEntity = require('./XMLDTDEntity');
+
+ XMLDTDNotation = require('./XMLDTDNotation');
+
+ XMLWriterBase = require('./XMLWriterBase');
+
+ module.exports = XMLStreamWriter = (function(superClass) {
+ extend(XMLStreamWriter, superClass);
+
+ function XMLStreamWriter(stream, options) {
+ XMLStreamWriter.__super__.constructor.call(this, options);
+ this.stream = stream;
+ }
+
+ XMLStreamWriter.prototype.document = function(doc) {
+ var child, i, j, len, len1, ref, ref1, results;
+ ref = doc.children;
+ for (i = 0, len = ref.length; i < len; i++) {
+ child = ref[i];
+ child.isLastRootNode = false;
+ }
+ doc.children[doc.children.length - 1].isLastRootNode = true;
+ ref1 = doc.children;
+ results = [];
+ for (j = 0, len1 = ref1.length; j < len1; j++) {
+ child = ref1[j];
+ switch (false) {
+ case !(child instanceof XMLDeclaration):
+ results.push(this.declaration(child));
+ break;
+ case !(child instanceof XMLDocType):
+ results.push(this.docType(child));
+ break;
+ case !(child instanceof XMLComment):
+ results.push(this.comment(child));
+ break;
+ case !(child instanceof XMLProcessingInstruction):
+ results.push(this.processingInstruction(child));
+ break;
+ default:
+ results.push(this.element(child));
+ }
+ }
+ return results;
+ };
+
+ XMLStreamWriter.prototype.attribute = function(att) {
+ return this.stream.write(' ' + att.name + '="' + att.value + '"');
+ };
+
+ XMLStreamWriter.prototype.cdata = function(node, level) {
+ return this.stream.write(this.space(level) + '' + this.endline(node));
+ };
+
+ XMLStreamWriter.prototype.comment = function(node, level) {
+ return this.stream.write(this.space(level) + '' + this.endline(node));
+ };
+
+ XMLStreamWriter.prototype.declaration = function(node, level) {
+ this.stream.write(this.space(level));
+ this.stream.write('');
+ return this.stream.write(this.endline(node));
+ };
+
+ XMLStreamWriter.prototype.docType = function(node, level) {
+ var child, i, len, ref;
+ level || (level = 0);
+ this.stream.write(this.space(level));
+ this.stream.write(' 0) {
+ this.stream.write(' [');
+ this.stream.write(this.endline(node));
+ ref = node.children;
+ for (i = 0, len = ref.length; i < len; i++) {
+ child = ref[i];
+ switch (false) {
+ case !(child instanceof XMLDTDAttList):
+ this.dtdAttList(child, level + 1);
+ break;
+ case !(child instanceof XMLDTDElement):
+ this.dtdElement(child, level + 1);
+ break;
+ case !(child instanceof XMLDTDEntity):
+ this.dtdEntity(child, level + 1);
+ break;
+ case !(child instanceof XMLDTDNotation):
+ this.dtdNotation(child, level + 1);
+ break;
+ case !(child instanceof XMLCData):
+ this.cdata(child, level + 1);
+ break;
+ case !(child instanceof XMLComment):
+ this.comment(child, level + 1);
+ break;
+ case !(child instanceof XMLProcessingInstruction):
+ this.processingInstruction(child, level + 1);
+ break;
+ default:
+ throw new Error("Unknown DTD node type: " + child.constructor.name);
+ }
+ }
+ this.stream.write(']');
+ }
+ this.stream.write(this.spacebeforeslash + '>');
+ return this.stream.write(this.endline(node));
+ };
+
+ XMLStreamWriter.prototype.element = function(node, level) {
+ var att, child, i, len, name, ref, ref1, space;
+ level || (level = 0);
+ space = this.space(level);
+ this.stream.write(space + '<' + node.name);
+ ref = node.attributes;
+ for (name in ref) {
+ if (!hasProp.call(ref, name)) continue;
+ att = ref[name];
+ this.attribute(att);
+ }
+ if (node.children.length === 0 || node.children.every(function(e) {
+ return e.value === '';
+ })) {
+ if (this.allowEmpty) {
+ this.stream.write('>' + node.name + '>');
+ } else {
+ this.stream.write(this.spacebeforeslash + '/>');
+ }
+ } else if (this.pretty && node.children.length === 1 && (node.children[0].value != null)) {
+ this.stream.write('>');
+ this.stream.write(node.children[0].value);
+ this.stream.write('' + node.name + '>');
+ } else {
+ this.stream.write('>' + this.newline);
+ ref1 = node.children;
+ for (i = 0, len = ref1.length; i < len; i++) {
+ child = ref1[i];
+ switch (false) {
+ case !(child instanceof XMLCData):
+ this.cdata(child, level + 1);
+ break;
+ case !(child instanceof XMLComment):
+ this.comment(child, level + 1);
+ break;
+ case !(child instanceof XMLElement):
+ this.element(child, level + 1);
+ break;
+ case !(child instanceof XMLRaw):
+ this.raw(child, level + 1);
+ break;
+ case !(child instanceof XMLText):
+ this.text(child, level + 1);
+ break;
+ case !(child instanceof XMLProcessingInstruction):
+ this.processingInstruction(child, level + 1);
+ break;
+ default:
+ throw new Error("Unknown XML node type: " + child.constructor.name);
+ }
+ }
+ this.stream.write(space + '' + node.name + '>');
+ }
+ return this.stream.write(this.endline(node));
+ };
+
+ XMLStreamWriter.prototype.processingInstruction = function(node, level) {
+ this.stream.write(this.space(level) + '' + node.target);
+ if (node.value) {
+ this.stream.write(' ' + node.value);
+ }
+ return this.stream.write(this.spacebeforeslash + '?>' + this.endline(node));
+ };
+
+ XMLStreamWriter.prototype.raw = function(node, level) {
+ return this.stream.write(this.space(level) + node.value + this.endline(node));
+ };
+
+ XMLStreamWriter.prototype.text = function(node, level) {
+ return this.stream.write(this.space(level) + node.value + this.endline(node));
+ };
+
+ XMLStreamWriter.prototype.dtdAttList = function(node, level) {
+ this.stream.write(this.space(level) + '' + this.endline(node));
+ };
+
+ XMLStreamWriter.prototype.dtdElement = function(node, level) {
+ this.stream.write(this.space(level) + '' + this.endline(node));
+ };
+
+ XMLStreamWriter.prototype.dtdEntity = function(node, level) {
+ this.stream.write(this.space(level) + '' + this.endline(node));
+ };
+
+ XMLStreamWriter.prototype.dtdNotation = function(node, level) {
+ this.stream.write(this.space(level) + '' + this.endline(node));
+ };
+
+ XMLStreamWriter.prototype.endline = function(node) {
+ if (!node.isLastRootNode) {
+ return this.newline;
+ } else {
+ return '';
+ }
+ };
+
+ return XMLStreamWriter;
+
+ })(XMLWriterBase);
+
+}).call(this);
+
+},{"./XMLCData":6,"./XMLComment":7,"./XMLDTDAttList":8,"./XMLDTDElement":9,"./XMLDTDEntity":10,"./XMLDTDNotation":11,"./XMLDeclaration":12,"./XMLDocType":13,"./XMLElement":16,"./XMLProcessingInstruction":18,"./XMLRaw":19,"./XMLText":23,"./XMLWriterBase":24}],21:[function(require,module,exports){
+// Generated by CoffeeScript 1.12.7
+(function() {
+ var XMLCData, XMLComment, XMLDTDAttList, XMLDTDElement, XMLDTDEntity, XMLDTDNotation, XMLDeclaration, XMLDocType, XMLElement, XMLProcessingInstruction, XMLRaw, XMLStringWriter, XMLText, XMLWriterBase,
+ extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
+ hasProp = {}.hasOwnProperty;
+
+ XMLDeclaration = require('./XMLDeclaration');
+
+ XMLDocType = require('./XMLDocType');
+
+ XMLCData = require('./XMLCData');
+
+ XMLComment = require('./XMLComment');
+
+ XMLElement = require('./XMLElement');
+
+ XMLRaw = require('./XMLRaw');
+
+ XMLText = require('./XMLText');
+
+ XMLProcessingInstruction = require('./XMLProcessingInstruction');
+
+ XMLDTDAttList = require('./XMLDTDAttList');
+
+ XMLDTDElement = require('./XMLDTDElement');
+
+ XMLDTDEntity = require('./XMLDTDEntity');
+
+ XMLDTDNotation = require('./XMLDTDNotation');
+
+ XMLWriterBase = require('./XMLWriterBase');
+
+ module.exports = XMLStringWriter = (function(superClass) {
+ extend(XMLStringWriter, superClass);
+
+ function XMLStringWriter(options) {
+ XMLStringWriter.__super__.constructor.call(this, options);
+ }
+
+ XMLStringWriter.prototype.document = function(doc) {
+ var child, i, len, r, ref;
+ this.textispresent = false;
+ r = '';
+ ref = doc.children;
+ for (i = 0, len = ref.length; i < len; i++) {
+ child = ref[i];
+ r += (function() {
+ switch (false) {
+ case !(child instanceof XMLDeclaration):
+ return this.declaration(child);
+ case !(child instanceof XMLDocType):
+ return this.docType(child);
+ case !(child instanceof XMLComment):
+ return this.comment(child);
+ case !(child instanceof XMLProcessingInstruction):
+ return this.processingInstruction(child);
+ default:
+ return this.element(child, 0);
+ }
+ }).call(this);
+ }
+ if (this.pretty && r.slice(-this.newline.length) === this.newline) {
+ r = r.slice(0, -this.newline.length);
+ }
+ return r;
+ };
+
+ XMLStringWriter.prototype.attribute = function(att) {
+ return ' ' + att.name + '="' + att.value + '"';
+ };
+
+ XMLStringWriter.prototype.cdata = function(node, level) {
+ return this.space(level) + '' + this.newline;
+ };
+
+ XMLStringWriter.prototype.comment = function(node, level) {
+ return this.space(level) + '' + this.newline;
+ };
+
+ XMLStringWriter.prototype.declaration = function(node, level) {
+ var r;
+ r = this.space(level);
+ r += '';
+ r += this.newline;
+ return r;
+ };
+
+ XMLStringWriter.prototype.docType = function(node, level) {
+ var child, i, len, r, ref;
+ level || (level = 0);
+ r = this.space(level);
+ r += ' 0) {
+ r += ' [';
+ r += this.newline;
+ ref = node.children;
+ for (i = 0, len = ref.length; i < len; i++) {
+ child = ref[i];
+ r += (function() {
+ switch (false) {
+ case !(child instanceof XMLDTDAttList):
+ return this.dtdAttList(child, level + 1);
+ case !(child instanceof XMLDTDElement):
+ return this.dtdElement(child, level + 1);
+ case !(child instanceof XMLDTDEntity):
+ return this.dtdEntity(child, level + 1);
+ case !(child instanceof XMLDTDNotation):
+ return this.dtdNotation(child, level + 1);
+ case !(child instanceof XMLCData):
+ return this.cdata(child, level + 1);
+ case !(child instanceof XMLComment):
+ return this.comment(child, level + 1);
+ case !(child instanceof XMLProcessingInstruction):
+ return this.processingInstruction(child, level + 1);
+ default:
+ throw new Error("Unknown DTD node type: " + child.constructor.name);
+ }
+ }).call(this);
+ }
+ r += ']';
+ }
+ r += this.spacebeforeslash + '>';
+ r += this.newline;
+ return r;
+ };
+
+ XMLStringWriter.prototype.element = function(node, level) {
+ var att, child, i, j, len, len1, name, r, ref, ref1, ref2, space, textispresentwasset;
+ level || (level = 0);
+ textispresentwasset = false;
+ if (this.textispresent) {
+ this.newline = '';
+ this.pretty = false;
+ } else {
+ this.newline = this.newlinedefault;
+ this.pretty = this.prettydefault;
+ }
+ space = this.space(level);
+ r = '';
+ r += space + '<' + node.name;
+ ref = node.attributes;
+ for (name in ref) {
+ if (!hasProp.call(ref, name)) continue;
+ att = ref[name];
+ r += this.attribute(att);
+ }
+ if (node.children.length === 0 || node.children.every(function(e) {
+ return e.value === '';
+ })) {
+ if (this.allowEmpty) {
+ r += '>' + node.name + '>' + this.newline;
+ } else {
+ r += this.spacebeforeslash + '/>' + this.newline;
+ }
+ } else if (this.pretty && node.children.length === 1 && (node.children[0].value != null)) {
+ r += '>';
+ r += node.children[0].value;
+ r += '' + node.name + '>' + this.newline;
+ } else {
+ if (this.dontprettytextnodes) {
+ ref1 = node.children;
+ for (i = 0, len = ref1.length; i < len; i++) {
+ child = ref1[i];
+ if (child.value != null) {
+ this.textispresent++;
+ textispresentwasset = true;
+ break;
+ }
+ }
+ }
+ if (this.textispresent) {
+ this.newline = '';
+ this.pretty = false;
+ space = this.space(level);
+ }
+ r += '>' + this.newline;
+ ref2 = node.children;
+ for (j = 0, len1 = ref2.length; j < len1; j++) {
+ child = ref2[j];
+ r += (function() {
+ switch (false) {
+ case !(child instanceof XMLCData):
+ return this.cdata(child, level + 1);
+ case !(child instanceof XMLComment):
+ return this.comment(child, level + 1);
+ case !(child instanceof XMLElement):
+ return this.element(child, level + 1);
+ case !(child instanceof XMLRaw):
+ return this.raw(child, level + 1);
+ case !(child instanceof XMLText):
+ return this.text(child, level + 1);
+ case !(child instanceof XMLProcessingInstruction):
+ return this.processingInstruction(child, level + 1);
+ default:
+ throw new Error("Unknown XML node type: " + child.constructor.name);
+ }
+ }).call(this);
+ }
+ if (textispresentwasset) {
+ this.textispresent--;
+ }
+ if (!this.textispresent) {
+ this.newline = this.newlinedefault;
+ this.pretty = this.prettydefault;
+ }
+ r += space + '' + node.name + '>' + this.newline;
+ }
+ return r;
+ };
+
+ XMLStringWriter.prototype.processingInstruction = function(node, level) {
+ var r;
+ r = this.space(level) + '' + node.target;
+ if (node.value) {
+ r += ' ' + node.value;
+ }
+ r += this.spacebeforeslash + '?>' + this.newline;
+ return r;
+ };
+
+ XMLStringWriter.prototype.raw = function(node, level) {
+ return this.space(level) + node.value + this.newline;
+ };
+
+ XMLStringWriter.prototype.text = function(node, level) {
+ return this.space(level) + node.value + this.newline;
+ };
+
+ XMLStringWriter.prototype.dtdAttList = function(node, level) {
+ var r;
+ r = this.space(level) + '' + this.newline;
+ return r;
+ };
+
+ XMLStringWriter.prototype.dtdElement = function(node, level) {
+ return this.space(level) + '' + this.newline;
+ };
+
+ XMLStringWriter.prototype.dtdEntity = function(node, level) {
+ var r;
+ r = this.space(level) + '' + this.newline;
+ return r;
+ };
+
+ XMLStringWriter.prototype.dtdNotation = function(node, level) {
+ var r;
+ r = this.space(level) + '' + this.newline;
+ return r;
+ };
+
+ XMLStringWriter.prototype.openNode = function(node, level) {
+ var att, name, r, ref;
+ level || (level = 0);
+ if (node instanceof XMLElement) {
+ r = this.space(level) + '<' + node.name;
+ ref = node.attributes;
+ for (name in ref) {
+ if (!hasProp.call(ref, name)) continue;
+ att = ref[name];
+ r += this.attribute(att);
+ }
+ r += (node.children ? '>' : '/>') + this.newline;
+ return r;
+ } else {
+ r = this.space(level) + '') + this.newline;
+ return r;
+ }
+ };
+
+ XMLStringWriter.prototype.closeNode = function(node, level) {
+ level || (level = 0);
+ switch (false) {
+ case !(node instanceof XMLElement):
+ return this.space(level) + '' + node.name + '>' + this.newline;
+ case !(node instanceof XMLDocType):
+ return this.space(level) + ']>' + this.newline;
+ }
+ };
+
+ return XMLStringWriter;
+
+ })(XMLWriterBase);
+
+}).call(this);
+
+},{"./XMLCData":6,"./XMLComment":7,"./XMLDTDAttList":8,"./XMLDTDElement":9,"./XMLDTDEntity":10,"./XMLDTDNotation":11,"./XMLDeclaration":12,"./XMLDocType":13,"./XMLElement":16,"./XMLProcessingInstruction":18,"./XMLRaw":19,"./XMLText":23,"./XMLWriterBase":24}],22:[function(require,module,exports){
+// Generated by CoffeeScript 1.12.7
+(function() {
+ var XMLStringifier,
+ bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
+ hasProp = {}.hasOwnProperty;
+
+ module.exports = XMLStringifier = (function() {
+ function XMLStringifier(options) {
+ this.assertLegalChar = bind(this.assertLegalChar, this);
+ var key, ref, value;
+ options || (options = {});
+ this.noDoubleEncoding = options.noDoubleEncoding;
+ ref = options.stringify || {};
+ for (key in ref) {
+ if (!hasProp.call(ref, key)) continue;
+ value = ref[key];
+ this[key] = value;
+ }
+ }
+
+ XMLStringifier.prototype.eleName = function(val) {
+ val = '' + val || '';
+ return this.assertLegalChar(val);
+ };
+
+ XMLStringifier.prototype.eleText = function(val) {
+ val = '' + val || '';
+ return this.assertLegalChar(this.elEscape(val));
+ };
+
+ XMLStringifier.prototype.cdata = function(val) {
+ val = '' + val || '';
+ val = val.replace(']]>', ']]]]>');
+ return this.assertLegalChar(val);
+ };
+
+ XMLStringifier.prototype.comment = function(val) {
+ val = '' + val || '';
+ if (val.match(/--/)) {
+ throw new Error("Comment text cannot contain double-hypen: " + val);
+ }
+ return this.assertLegalChar(val);
+ };
+
+ XMLStringifier.prototype.raw = function(val) {
+ return '' + val || '';
+ };
+
+ XMLStringifier.prototype.attName = function(val) {
+ return val = '' + val || '';
+ };
+
+ XMLStringifier.prototype.attValue = function(val) {
+ val = '' + val || '';
+ return this.attEscape(val);
+ };
+
+ XMLStringifier.prototype.insTarget = function(val) {
+ return '' + val || '';
+ };
+
+ XMLStringifier.prototype.insValue = function(val) {
+ val = '' + val || '';
+ if (val.match(/\?>/)) {
+ throw new Error("Invalid processing instruction value: " + val);
+ }
+ return val;
+ };
+
+ XMLStringifier.prototype.xmlVersion = function(val) {
+ val = '' + val || '';
+ if (!val.match(/1\.[0-9]+/)) {
+ throw new Error("Invalid version number: " + val);
+ }
+ return val;
+ };
+
+ XMLStringifier.prototype.xmlEncoding = function(val) {
+ val = '' + val || '';
+ if (!val.match(/^[A-Za-z](?:[A-Za-z0-9._-])*$/)) {
+ throw new Error("Invalid encoding: " + val);
+ }
+ return val;
+ };
+
+ XMLStringifier.prototype.xmlStandalone = function(val) {
+ if (val) {
+ return "yes";
+ } else {
+ return "no";
+ }
+ };
+
+ XMLStringifier.prototype.dtdPubID = function(val) {
+ return '' + val || '';
+ };
+
+ XMLStringifier.prototype.dtdSysID = function(val) {
+ return '' + val || '';
+ };
+
+ XMLStringifier.prototype.dtdElementValue = function(val) {
+ return '' + val || '';
+ };
+
+ XMLStringifier.prototype.dtdAttType = function(val) {
+ return '' + val || '';
+ };
+
+ XMLStringifier.prototype.dtdAttDefault = function(val) {
+ if (val != null) {
+ return '' + val || '';
+ } else {
+ return val;
+ }
+ };
+
+ XMLStringifier.prototype.dtdEntityValue = function(val) {
+ return '' + val || '';
+ };
+
+ XMLStringifier.prototype.dtdNData = function(val) {
+ return '' + val || '';
+ };
+
+ XMLStringifier.prototype.convertAttKey = '@';
+
+ XMLStringifier.prototype.convertPIKey = '?';
+
+ XMLStringifier.prototype.convertTextKey = '#text';
+
+ XMLStringifier.prototype.convertCDataKey = '#cdata';
+
+ XMLStringifier.prototype.convertCommentKey = '#comment';
+
+ XMLStringifier.prototype.convertRawKey = '#raw';
+
+ XMLStringifier.prototype.assertLegalChar = function(str) {
+ var res;
+ res = str.match(/[\0\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/);
+ if (res) {
+ throw new Error("Invalid character in string: " + str + " at index " + res.index);
+ }
+ return str;
+ };
+
+ XMLStringifier.prototype.elEscape = function(str) {
+ var ampregex;
+ ampregex = this.noDoubleEncoding ? /(?!&\S+;)&/g : /&/g;
+ return str.replace(ampregex, '&').replace(//g, '>').replace(/\r/g, '
');
+ };
+
+ XMLStringifier.prototype.attEscape = function(str) {
+ var ampregex;
+ ampregex = this.noDoubleEncoding ? /(?!&\S+;)&/g : /&/g;
+ return str.replace(ampregex, '&').replace(/ 0) {
+ return new Array(indent).join(this.indent);
+ } else {
+ return '';
+ }
+ } else {
+ return '';
+ }
+ };
+
+ return XMLWriterBase;
+
+ })();
+
+}).call(this);
+
+},{}],25:[function(require,module,exports){
+// Generated by CoffeeScript 1.12.7
+(function() {
+ var XMLDocument, XMLDocumentCB, XMLStreamWriter, XMLStringWriter, assign, isFunction, ref;
+
+ ref = require('./Utility'), assign = ref.assign, isFunction = ref.isFunction;
+
+ XMLDocument = require('./XMLDocument');
+
+ XMLDocumentCB = require('./XMLDocumentCB');
+
+ XMLStringWriter = require('./XMLStringWriter');
+
+ XMLStreamWriter = require('./XMLStreamWriter');
+
+ module.exports.create = function(name, xmldec, doctype, options) {
+ var doc, root;
+ if (name == null) {
+ throw new Error("Root element needs a name");
+ }
+ options = assign({}, xmldec, doctype, options);
+ doc = new XMLDocument(options);
+ root = doc.element(name);
+ if (!options.headless) {
+ doc.declaration(options);
+ if ((options.pubID != null) || (options.sysID != null)) {
+ doc.doctype(options);
+ }
+ }
+ return root;
+ };
+
+ module.exports.begin = function(options, onData, onEnd) {
+ var ref1;
+ if (isFunction(options)) {
+ ref1 = [options, onData], onData = ref1[0], onEnd = ref1[1];
+ options = {};
+ }
+ if (onData) {
+ return new XMLDocumentCB(options, onData, onEnd);
+ } else {
+ return new XMLDocument(options);
+ }
+ };
+
+ module.exports.stringWriter = function(options) {
+ return new XMLStringWriter(options);
+ };
+
+ module.exports.streamWriter = function(stream, options) {
+ return new XMLStreamWriter(stream, options);
+ };
+
+}).call(this);
+
+},{"./Utility":4,"./XMLDocument":14,"./XMLDocumentCB":15,"./XMLStreamWriter":20,"./XMLStringWriter":21}]},{},[1])(1)
+});
diff --git a/temporary_modules/trezor-connect/node_modules/plist/dist/plist-parse.js b/temporary_modules/trezor-connect/node_modules/plist/dist/plist-parse.js
new file mode 100644
index 00000000..81d2b302
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/plist/dist/plist-parse.js
@@ -0,0 +1,4670 @@
+(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.plist = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i,
+ * and raw CDATA nodes.
+ *
+ * @param {Element} node
+ * @returns {Boolean}
+ * @api private
+ */
+
+function shouldIgnoreNode (node) {
+ return node.nodeType === TEXT_NODE
+ || node.nodeType === COMMENT_NODE
+ || node.nodeType === CDATA_NODE;
+}
+
+/**
+ * Check if the node is empty. Some plist file has such node:
+ *
+ * this node shoud be ignored.
+ *
+ * @see https://github.com/TooTallNate/plist.js/issues/66
+ * @param {Element} node
+ * @returns {Boolean}
+ * @api private
+ */
+function isEmptyNode(node){
+ if(!node.childNodes || node.childNodes.length === 0) {
+ return true;
+ } else {
+ return false;
+ }
+}
+
+function invariant(test, message) {
+ if (!test) {
+ throw new Error(message);
+ }
+}
+
+/**
+ * Parses a Plist XML string. Returns an Object.
+ *
+ * @param {String} xml - the XML String to decode
+ * @returns {Mixed} the decoded value from the Plist XML
+ * @api public
+ */
+
+function parse (xml) {
+ var doc = new DOMParser().parseFromString(xml);
+ invariant(
+ doc.documentElement.nodeName === 'plist',
+ 'malformed document. First element should be '
+ );
+ var plist = parsePlistXML(doc.documentElement);
+
+ // the root node gets interpreted as an Array,
+ // so pull out the inner data first
+ if (plist.length == 1) plist = plist[0];
+
+ return plist;
+}
+
+/**
+ * Convert an XML based plist document into a JSON representation.
+ *
+ * @param {Object} xml_node - current XML node in the plist
+ * @returns {Mixed} built up JSON object
+ * @api private
+ */
+
+function parsePlistXML (node) {
+ var i, new_obj, key, val, new_arr, res, counter, type;
+
+ if (!node)
+ return null;
+
+ if (node.nodeName === 'plist') {
+ new_arr = [];
+ if (isEmptyNode(node)) {
+ return new_arr;
+ }
+ for (i=0; i < node.childNodes.length; i++) {
+ if (!shouldIgnoreNode(node.childNodes[i])) {
+ new_arr.push( parsePlistXML(node.childNodes[i]));
+ }
+ }
+ return new_arr;
+ } else if (node.nodeName === 'dict') {
+ new_obj = {};
+ key = null;
+ counter = 0;
+ if (isEmptyNode(node)) {
+ return new_obj;
+ }
+ for (i=0; i < node.childNodes.length; i++) {
+ if (shouldIgnoreNode(node.childNodes[i])) continue;
+ if (counter % 2 === 0) {
+ invariant(
+ node.childNodes[i].nodeName === 'key',
+ 'Missing key while parsing .'
+ );
+ key = parsePlistXML(node.childNodes[i]);
+ } else {
+ invariant(
+ node.childNodes[i].nodeName !== 'key',
+ 'Unexpected key "'
+ + parsePlistXML(node.childNodes[i])
+ + '" while parsing .'
+ );
+ new_obj[key] = parsePlistXML(node.childNodes[i]);
+ }
+ counter += 1;
+ }
+ if (counter % 2 === 1) {
+ throw new Error('Missing value for "' + key + '" while parsing ');
+ }
+ return new_obj;
+
+ } else if (node.nodeName === 'array') {
+ new_arr = [];
+ if (isEmptyNode(node)) {
+ return new_arr;
+ }
+ for (i=0; i < node.childNodes.length; i++) {
+ if (!shouldIgnoreNode(node.childNodes[i])) {
+ res = parsePlistXML(node.childNodes[i]);
+ if (null != res) new_arr.push(res);
+ }
+ }
+ return new_arr;
+
+ } else if (node.nodeName === '#text') {
+ // TODO: what should we do with text types? (CDATA sections)
+
+ } else if (node.nodeName === 'key') {
+ if (isEmptyNode(node)) {
+ return '';
+ }
+ return node.childNodes[0].nodeValue;
+ } else if (node.nodeName === 'string') {
+ res = '';
+ if (isEmptyNode(node)) {
+ return res;
+ }
+ for (i=0; i < node.childNodes.length; i++) {
+ var type = node.childNodes[i].nodeType;
+ if (type === TEXT_NODE || type === CDATA_NODE) {
+ res += node.childNodes[i].nodeValue;
+ }
+ }
+ return res;
+
+ } else if (node.nodeName === 'integer') {
+ invariant(
+ !isEmptyNode(node),
+ 'Cannot parse "" as integer.'
+ );
+ return parseInt(node.childNodes[0].nodeValue, 10);
+
+ } else if (node.nodeName === 'real') {
+ invariant(
+ !isEmptyNode(node),
+ 'Cannot parse "" as real.'
+ );
+ res = '';
+ for (i=0; i < node.childNodes.length; i++) {
+ if (node.childNodes[i].nodeType === TEXT_NODE) {
+ res += node.childNodes[i].nodeValue;
+ }
+ }
+ return parseFloat(res);
+
+ } else if (node.nodeName === 'data') {
+ res = '';
+ if (isEmptyNode(node)) {
+ return Buffer.from(res, 'base64');
+ }
+ for (i=0; i < node.childNodes.length; i++) {
+ if (node.childNodes[i].nodeType === TEXT_NODE) {
+ res += node.childNodes[i].nodeValue.replace(/\s+/g, '');
+ }
+ }
+ return Buffer.from(res, 'base64');
+
+ } else if (node.nodeName === 'date') {
+ invariant(
+ !isEmptyNode(node),
+ 'Cannot parse "" as Date.'
+ )
+ return new Date(node.childNodes[0].nodeValue);
+
+ } else if (node.nodeName === 'true') {
+ return true;
+
+ } else if (node.nodeName === 'false') {
+ return false;
+ }
+}
+
+}).call(this)}).call(this,require("buffer").Buffer)
+},{"./xmldom/dom-parser":2,"buffer":7}],2:[function(require,module,exports){
+function DOMParser(options){
+ this.options = options ||{locator:{}};
+}
+
+DOMParser.prototype.parseFromString = function(source,mimeType){
+ var options = this.options;
+ var sax = new XMLReader();
+ var domBuilder = options.domBuilder || new DOMHandler();//contentHandler and LexicalHandler
+ var errorHandler = options.errorHandler;
+ var locator = options.locator;
+ var defaultNSMap = options.xmlns||{};
+ var isHTML = /\/x?html?$/.test(mimeType);//mimeType.toLowerCase().indexOf('html') > -1;
+ var entityMap = isHTML?htmlEntity.entityMap:{'lt':'<','gt':'>','amp':'&','quot':'"','apos':"'"};
+ if(locator){
+ domBuilder.setDocumentLocator(locator)
+ }
+
+ sax.errorHandler = buildErrorHandler(errorHandler,domBuilder,locator);
+ sax.domBuilder = options.domBuilder || domBuilder;
+ if(isHTML){
+ defaultNSMap['']= 'http://www.w3.org/1999/xhtml';
+ }
+ defaultNSMap.xml = defaultNSMap.xml || 'http://www.w3.org/XML/1998/namespace';
+ if(source && typeof source === 'string'){
+ sax.parse(source,defaultNSMap,entityMap);
+ }else{
+ sax.errorHandler.error("invalid doc source");
+ }
+ return domBuilder.doc;
+}
+function buildErrorHandler(errorImpl,domBuilder,locator){
+ if(!errorImpl){
+ if(domBuilder instanceof DOMHandler){
+ return domBuilder;
+ }
+ errorImpl = domBuilder ;
+ }
+ var errorHandler = {}
+ var isCallback = errorImpl instanceof Function;
+ locator = locator||{}
+ function build(key){
+ var fn = errorImpl[key];
+ if(!fn && isCallback){
+ fn = errorImpl.length == 2?function(msg){errorImpl(key,msg)}:errorImpl;
+ }
+ errorHandler[key] = fn && function(msg){
+ fn('[xmldom '+key+']\t'+msg+_locator(locator));
+ }||function(){};
+ }
+ build('warning');
+ build('error');
+ build('fatalError');
+ return errorHandler;
+}
+
+//console.log('#\n\n\n\n\n\n\n####')
+/**
+ * +ContentHandler+ErrorHandler
+ * +LexicalHandler+EntityResolver2
+ * -DeclHandler-DTDHandler
+ *
+ * DefaultHandler:EntityResolver, DTDHandler, ContentHandler, ErrorHandler
+ * DefaultHandler2:DefaultHandler,LexicalHandler, DeclHandler, EntityResolver2
+ * @link http://www.saxproject.org/apidoc/org/xml/sax/helpers/DefaultHandler.html
+ */
+function DOMHandler() {
+ this.cdata = false;
+}
+function position(locator,node){
+ node.lineNumber = locator.lineNumber;
+ node.columnNumber = locator.columnNumber;
+}
+/**
+ * @see org.xml.sax.ContentHandler#startDocument
+ * @link http://www.saxproject.org/apidoc/org/xml/sax/ContentHandler.html
+ */
+DOMHandler.prototype = {
+ startDocument : function() {
+ this.doc = new DOMImplementation().createDocument(null, null, null);
+ if (this.locator) {
+ this.doc.documentURI = this.locator.systemId;
+ }
+ },
+ startElement:function(namespaceURI, localName, qName, attrs) {
+ var doc = this.doc;
+ var el = doc.createElementNS(namespaceURI, qName||localName);
+ var len = attrs.length;
+ appendElement(this, el);
+ this.currentElement = el;
+
+ this.locator && position(this.locator,el)
+ for (var i = 0 ; i < len; i++) {
+ var namespaceURI = attrs.getURI(i);
+ var value = attrs.getValue(i);
+ var qName = attrs.getQName(i);
+ var attr = doc.createAttributeNS(namespaceURI, qName);
+ this.locator &&position(attrs.getLocator(i),attr);
+ attr.value = attr.nodeValue = value;
+ el.setAttributeNode(attr)
+ }
+ },
+ endElement:function(namespaceURI, localName, qName) {
+ var current = this.currentElement
+ var tagName = current.tagName;
+ this.currentElement = current.parentNode;
+ },
+ startPrefixMapping:function(prefix, uri) {
+ },
+ endPrefixMapping:function(prefix) {
+ },
+ processingInstruction:function(target, data) {
+ var ins = this.doc.createProcessingInstruction(target, data);
+ this.locator && position(this.locator,ins)
+ appendElement(this, ins);
+ },
+ ignorableWhitespace:function(ch, start, length) {
+ },
+ characters:function(chars, start, length) {
+ chars = _toString.apply(this,arguments)
+ //console.log(chars)
+ if(chars){
+ if (this.cdata) {
+ var charNode = this.doc.createCDATASection(chars);
+ } else {
+ var charNode = this.doc.createTextNode(chars);
+ }
+ if(this.currentElement){
+ this.currentElement.appendChild(charNode);
+ }else if(/^\s*$/.test(chars)){
+ this.doc.appendChild(charNode);
+ //process xml
+ }
+ this.locator && position(this.locator,charNode)
+ }
+ },
+ skippedEntity:function(name) {
+ },
+ endDocument:function() {
+ this.doc.normalize();
+ },
+ setDocumentLocator:function (locator) {
+ if(this.locator = locator){// && !('lineNumber' in locator)){
+ locator.lineNumber = 0;
+ }
+ },
+ //LexicalHandler
+ comment:function(chars, start, length) {
+ chars = _toString.apply(this,arguments)
+ var comm = this.doc.createComment(chars);
+ this.locator && position(this.locator,comm)
+ appendElement(this, comm);
+ },
+
+ startCDATA:function() {
+ //used in characters() methods
+ this.cdata = true;
+ },
+ endCDATA:function() {
+ this.cdata = false;
+ },
+
+ startDTD:function(name, publicId, systemId) {
+ var impl = this.doc.implementation;
+ if (impl && impl.createDocumentType) {
+ var dt = impl.createDocumentType(name, publicId, systemId);
+ this.locator && position(this.locator,dt)
+ appendElement(this, dt);
+ }
+ },
+ /**
+ * @see org.xml.sax.ErrorHandler
+ * @link http://www.saxproject.org/apidoc/org/xml/sax/ErrorHandler.html
+ */
+ warning:function(error) {
+ console.warn('[xmldom warning]\t'+error,_locator(this.locator));
+ },
+ error:function(error) {
+ console.error('[xmldom error]\t'+error,_locator(this.locator));
+ },
+ fatalError:function(error) {
+ throw new ParseError(error, this.locator);
+ }
+}
+function _locator(l){
+ if(l){
+ return '\n@'+(l.systemId ||'')+'#[line:'+l.lineNumber+',col:'+l.columnNumber+']'
+ }
+}
+function _toString(chars,start,length){
+ if(typeof chars == 'string'){
+ return chars.substr(start,length)
+ }else{//java sax connect width xmldom on rhino(what about: "? && !(chars instanceof String)")
+ if(chars.length >= start+length || start){
+ return new java.lang.String(chars,start,length)+'';
+ }
+ return chars;
+ }
+}
+
+/*
+ * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/LexicalHandler.html
+ * used method of org.xml.sax.ext.LexicalHandler:
+ * #comment(chars, start, length)
+ * #startCDATA()
+ * #endCDATA()
+ * #startDTD(name, publicId, systemId)
+ *
+ *
+ * IGNORED method of org.xml.sax.ext.LexicalHandler:
+ * #endDTD()
+ * #startEntity(name)
+ * #endEntity(name)
+ *
+ *
+ * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/DeclHandler.html
+ * IGNORED method of org.xml.sax.ext.DeclHandler
+ * #attributeDecl(eName, aName, type, mode, value)
+ * #elementDecl(name, model)
+ * #externalEntityDecl(name, publicId, systemId)
+ * #internalEntityDecl(name, value)
+ * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/EntityResolver2.html
+ * IGNORED method of org.xml.sax.EntityResolver2
+ * #resolveEntity(String name,String publicId,String baseURI,String systemId)
+ * #resolveEntity(publicId, systemId)
+ * #getExternalSubset(name, baseURI)
+ * @link http://www.saxproject.org/apidoc/org/xml/sax/DTDHandler.html
+ * IGNORED method of org.xml.sax.DTDHandler
+ * #notationDecl(name, publicId, systemId) {};
+ * #unparsedEntityDecl(name, publicId, systemId, notationName) {};
+ */
+"endDTD,startEntity,endEntity,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,resolveEntity,getExternalSubset,notationDecl,unparsedEntityDecl".replace(/\w+/g,function(key){
+ DOMHandler.prototype[key] = function(){return null}
+})
+
+/* Private static helpers treated below as private instance methods, so don't need to add these to the public API; we might use a Relator to also get rid of non-standard public properties */
+function appendElement (hander,node) {
+ if (!hander.currentElement) {
+ hander.doc.appendChild(node);
+ } else {
+ hander.currentElement.appendChild(node);
+ }
+}//appendChild and setAttributeNS are preformance key
+
+//if(typeof require == 'function'){
+var htmlEntity = require('./entities');
+var sax = require('./sax');
+var XMLReader = sax.XMLReader;
+var ParseError = sax.ParseError;
+var DOMImplementation = exports.DOMImplementation = require('./dom').DOMImplementation;
+exports.XMLSerializer = require('./dom').XMLSerializer ;
+exports.DOMParser = DOMParser;
+exports.__DOMHandler = DOMHandler;
+//}
+
+},{"./dom":3,"./entities":4,"./sax":5}],3:[function(require,module,exports){
+function copy(src,dest){
+ for(var p in src){
+ dest[p] = src[p];
+ }
+}
+/**
+^\w+\.prototype\.([_\w]+)\s*=\s*((?:.*\{\s*?[\r\n][\s\S]*?^})|\S.*?(?=[;\r\n]));?
+^\w+\.prototype\.([_\w]+)\s*=\s*(\S.*?(?=[;\r\n]));?
+ */
+function _extends(Class,Super){
+ var pt = Class.prototype;
+ if(!(pt instanceof Super)){
+ function t(){};
+ t.prototype = Super.prototype;
+ t = new t();
+ copy(pt,t);
+ Class.prototype = pt = t;
+ }
+ if(pt.constructor != Class){
+ if(typeof Class != 'function'){
+ console.error("unknow Class:"+Class)
+ }
+ pt.constructor = Class
+ }
+}
+var htmlns = 'http://www.w3.org/1999/xhtml' ;
+// Node Types
+var NodeType = {}
+var ELEMENT_NODE = NodeType.ELEMENT_NODE = 1;
+var ATTRIBUTE_NODE = NodeType.ATTRIBUTE_NODE = 2;
+var TEXT_NODE = NodeType.TEXT_NODE = 3;
+var CDATA_SECTION_NODE = NodeType.CDATA_SECTION_NODE = 4;
+var ENTITY_REFERENCE_NODE = NodeType.ENTITY_REFERENCE_NODE = 5;
+var ENTITY_NODE = NodeType.ENTITY_NODE = 6;
+var PROCESSING_INSTRUCTION_NODE = NodeType.PROCESSING_INSTRUCTION_NODE = 7;
+var COMMENT_NODE = NodeType.COMMENT_NODE = 8;
+var DOCUMENT_NODE = NodeType.DOCUMENT_NODE = 9;
+var DOCUMENT_TYPE_NODE = NodeType.DOCUMENT_TYPE_NODE = 10;
+var DOCUMENT_FRAGMENT_NODE = NodeType.DOCUMENT_FRAGMENT_NODE = 11;
+var NOTATION_NODE = NodeType.NOTATION_NODE = 12;
+
+// ExceptionCode
+var ExceptionCode = {}
+var ExceptionMessage = {};
+var INDEX_SIZE_ERR = ExceptionCode.INDEX_SIZE_ERR = ((ExceptionMessage[1]="Index size error"),1);
+var DOMSTRING_SIZE_ERR = ExceptionCode.DOMSTRING_SIZE_ERR = ((ExceptionMessage[2]="DOMString size error"),2);
+var HIERARCHY_REQUEST_ERR = ExceptionCode.HIERARCHY_REQUEST_ERR = ((ExceptionMessage[3]="Hierarchy request error"),3);
+var WRONG_DOCUMENT_ERR = ExceptionCode.WRONG_DOCUMENT_ERR = ((ExceptionMessage[4]="Wrong document"),4);
+var INVALID_CHARACTER_ERR = ExceptionCode.INVALID_CHARACTER_ERR = ((ExceptionMessage[5]="Invalid character"),5);
+var NO_DATA_ALLOWED_ERR = ExceptionCode.NO_DATA_ALLOWED_ERR = ((ExceptionMessage[6]="No data allowed"),6);
+var NO_MODIFICATION_ALLOWED_ERR = ExceptionCode.NO_MODIFICATION_ALLOWED_ERR = ((ExceptionMessage[7]="No modification allowed"),7);
+var NOT_FOUND_ERR = ExceptionCode.NOT_FOUND_ERR = ((ExceptionMessage[8]="Not found"),8);
+var NOT_SUPPORTED_ERR = ExceptionCode.NOT_SUPPORTED_ERR = ((ExceptionMessage[9]="Not supported"),9);
+var INUSE_ATTRIBUTE_ERR = ExceptionCode.INUSE_ATTRIBUTE_ERR = ((ExceptionMessage[10]="Attribute in use"),10);
+//level2
+var INVALID_STATE_ERR = ExceptionCode.INVALID_STATE_ERR = ((ExceptionMessage[11]="Invalid state"),11);
+var SYNTAX_ERR = ExceptionCode.SYNTAX_ERR = ((ExceptionMessage[12]="Syntax error"),12);
+var INVALID_MODIFICATION_ERR = ExceptionCode.INVALID_MODIFICATION_ERR = ((ExceptionMessage[13]="Invalid modification"),13);
+var NAMESPACE_ERR = ExceptionCode.NAMESPACE_ERR = ((ExceptionMessage[14]="Invalid namespace"),14);
+var INVALID_ACCESS_ERR = ExceptionCode.INVALID_ACCESS_ERR = ((ExceptionMessage[15]="Invalid access"),15);
+
+/**
+ * DOM Level 2
+ * Object DOMException
+ * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html
+ * @see http://www.w3.org/TR/REC-DOM-Level-1/ecma-script-language-binding.html
+ */
+function DOMException(code, message) {
+ if(message instanceof Error){
+ var error = message;
+ }else{
+ error = this;
+ Error.call(this, ExceptionMessage[code]);
+ this.message = ExceptionMessage[code];
+ if(Error.captureStackTrace) Error.captureStackTrace(this, DOMException);
+ }
+ error.code = code;
+ if(message) this.message = this.message + ": " + message;
+ return error;
+};
+DOMException.prototype = Error.prototype;
+copy(ExceptionCode,DOMException)
+/**
+ * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-536297177
+ * The NodeList interface provides the abstraction of an ordered collection of nodes, without defining or constraining how this collection is implemented. NodeList objects in the DOM are live.
+ * The items in the NodeList are accessible via an integral index, starting from 0.
+ */
+function NodeList() {
+};
+NodeList.prototype = {
+ /**
+ * The number of nodes in the list. The range of valid child node indices is 0 to length-1 inclusive.
+ * @standard level1
+ */
+ length:0,
+ /**
+ * Returns the indexth item in the collection. If index is greater than or equal to the number of nodes in the list, this returns null.
+ * @standard level1
+ * @param index unsigned long
+ * Index into the collection.
+ * @return Node
+ * The node at the indexth position in the NodeList, or null if that is not a valid index.
+ */
+ item: function(index) {
+ return this[index] || null;
+ },
+ toString:function(isHTML,nodeFilter){
+ for(var buf = [], i = 0;i=0){
+ var lastIndex = list.length-1
+ while(i0 || key == 'xmlns'){
+// return null;
+// }
+ //console.log()
+ var i = this.length;
+ while(i--){
+ var attr = this[i];
+ //console.log(attr.nodeName,key)
+ if(attr.nodeName == key){
+ return attr;
+ }
+ }
+ },
+ setNamedItem: function(attr) {
+ var el = attr.ownerElement;
+ if(el && el!=this._ownerElement){
+ throw new DOMException(INUSE_ATTRIBUTE_ERR);
+ }
+ var oldAttr = this.getNamedItem(attr.nodeName);
+ _addNamedNode(this._ownerElement,this,attr,oldAttr);
+ return oldAttr;
+ },
+ /* returns Node */
+ setNamedItemNS: function(attr) {// raises: WRONG_DOCUMENT_ERR,NO_MODIFICATION_ALLOWED_ERR,INUSE_ATTRIBUTE_ERR
+ var el = attr.ownerElement, oldAttr;
+ if(el && el!=this._ownerElement){
+ throw new DOMException(INUSE_ATTRIBUTE_ERR);
+ }
+ oldAttr = this.getNamedItemNS(attr.namespaceURI,attr.localName);
+ _addNamedNode(this._ownerElement,this,attr,oldAttr);
+ return oldAttr;
+ },
+
+ /* returns Node */
+ removeNamedItem: function(key) {
+ var attr = this.getNamedItem(key);
+ _removeNamedNode(this._ownerElement,this,attr);
+ return attr;
+
+
+ },// raises: NOT_FOUND_ERR,NO_MODIFICATION_ALLOWED_ERR
+
+ //for level2
+ removeNamedItemNS:function(namespaceURI,localName){
+ var attr = this.getNamedItemNS(namespaceURI,localName);
+ _removeNamedNode(this._ownerElement,this,attr);
+ return attr;
+ },
+ getNamedItemNS: function(namespaceURI, localName) {
+ var i = this.length;
+ while(i--){
+ var node = this[i];
+ if(node.localName == localName && node.namespaceURI == namespaceURI){
+ return node;
+ }
+ }
+ return null;
+ }
+};
+/**
+ * @see http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#ID-102161490
+ */
+function DOMImplementation(/* Object */ features) {
+ this._features = {};
+ if (features) {
+ for (var feature in features) {
+ this._features = features[feature];
+ }
+ }
+};
+
+DOMImplementation.prototype = {
+ hasFeature: function(/* string */ feature, /* string */ version) {
+ var versions = this._features[feature.toLowerCase()];
+ if (versions && (!version || version in versions)) {
+ return true;
+ } else {
+ return false;
+ }
+ },
+ // Introduced in DOM Level 2:
+ createDocument:function(namespaceURI, qualifiedName, doctype){// raises:INVALID_CHARACTER_ERR,NAMESPACE_ERR,WRONG_DOCUMENT_ERR
+ var doc = new Document();
+ doc.implementation = this;
+ doc.childNodes = new NodeList();
+ doc.doctype = doctype;
+ if(doctype){
+ doc.appendChild(doctype);
+ }
+ if(qualifiedName){
+ var root = doc.createElementNS(namespaceURI,qualifiedName);
+ doc.appendChild(root);
+ }
+ return doc;
+ },
+ // Introduced in DOM Level 2:
+ createDocumentType:function(qualifiedName, publicId, systemId){// raises:INVALID_CHARACTER_ERR,NAMESPACE_ERR
+ var node = new DocumentType();
+ node.name = qualifiedName;
+ node.nodeName = qualifiedName;
+ node.publicId = publicId;
+ node.systemId = systemId;
+ // Introduced in DOM Level 2:
+ //readonly attribute DOMString internalSubset;
+
+ //TODO:..
+ // readonly attribute NamedNodeMap entities;
+ // readonly attribute NamedNodeMap notations;
+ return node;
+ }
+};
+
+
+/**
+ * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-1950641247
+ */
+
+function Node() {
+};
+
+Node.prototype = {
+ firstChild : null,
+ lastChild : null,
+ previousSibling : null,
+ nextSibling : null,
+ attributes : null,
+ parentNode : null,
+ childNodes : null,
+ ownerDocument : null,
+ nodeValue : null,
+ namespaceURI : null,
+ prefix : null,
+ localName : null,
+ // Modified in DOM Level 2:
+ insertBefore:function(newChild, refChild){//raises
+ return _insertBefore(this,newChild,refChild);
+ },
+ replaceChild:function(newChild, oldChild){//raises
+ this.insertBefore(newChild,oldChild);
+ if(oldChild){
+ this.removeChild(oldChild);
+ }
+ },
+ removeChild:function(oldChild){
+ return _removeChild(this,oldChild);
+ },
+ appendChild:function(newChild){
+ return this.insertBefore(newChild,null);
+ },
+ hasChildNodes:function(){
+ return this.firstChild != null;
+ },
+ cloneNode:function(deep){
+ return cloneNode(this.ownerDocument||this,this,deep);
+ },
+ // Modified in DOM Level 2:
+ normalize:function(){
+ var child = this.firstChild;
+ while(child){
+ var next = child.nextSibling;
+ if(next && next.nodeType == TEXT_NODE && child.nodeType == TEXT_NODE){
+ this.removeChild(next);
+ child.appendData(next.data);
+ }else{
+ child.normalize();
+ child = next;
+ }
+ }
+ },
+ // Introduced in DOM Level 2:
+ isSupported:function(feature, version){
+ return this.ownerDocument.implementation.hasFeature(feature,version);
+ },
+ // Introduced in DOM Level 2:
+ hasAttributes:function(){
+ return this.attributes.length>0;
+ },
+ lookupPrefix:function(namespaceURI){
+ var el = this;
+ while(el){
+ var map = el._nsMap;
+ //console.dir(map)
+ if(map){
+ for(var n in map){
+ if(map[n] == namespaceURI){
+ return n;
+ }
+ }
+ }
+ el = el.nodeType == ATTRIBUTE_NODE?el.ownerDocument : el.parentNode;
+ }
+ return null;
+ },
+ // Introduced in DOM Level 3:
+ lookupNamespaceURI:function(prefix){
+ var el = this;
+ while(el){
+ var map = el._nsMap;
+ //console.dir(map)
+ if(map){
+ if(prefix in map){
+ return map[prefix] ;
+ }
+ }
+ el = el.nodeType == ATTRIBUTE_NODE?el.ownerDocument : el.parentNode;
+ }
+ return null;
+ },
+ // Introduced in DOM Level 3:
+ isDefaultNamespace:function(namespaceURI){
+ var prefix = this.lookupPrefix(namespaceURI);
+ return prefix == null;
+ }
+};
+
+
+function _xmlEncoder(c){
+ return c == '<' && '<' ||
+ c == '>' && '>' ||
+ c == '&' && '&' ||
+ c == '"' && '"' ||
+ ''+c.charCodeAt()+';'
+}
+
+
+copy(NodeType,Node);
+copy(NodeType,Node.prototype);
+
+/**
+ * @param callback return true for continue,false for break
+ * @return boolean true: break visit;
+ */
+function _visitNode(node,callback){
+ if(callback(node)){
+ return true;
+ }
+ if(node = node.firstChild){
+ do{
+ if(_visitNode(node,callback)){return true}
+ }while(node=node.nextSibling)
+ }
+}
+
+
+
+function Document(){
+}
+function _onAddAttribute(doc,el,newAttr){
+ doc && doc._inc++;
+ var ns = newAttr.namespaceURI ;
+ if(ns == 'http://www.w3.org/2000/xmlns/'){
+ //update namespace
+ el._nsMap[newAttr.prefix?newAttr.localName:''] = newAttr.value
+ }
+}
+function _onRemoveAttribute(doc,el,newAttr,remove){
+ doc && doc._inc++;
+ var ns = newAttr.namespaceURI ;
+ if(ns == 'http://www.w3.org/2000/xmlns/'){
+ //update namespace
+ delete el._nsMap[newAttr.prefix?newAttr.localName:'']
+ }
+}
+function _onUpdateChild(doc,el,newChild){
+ if(doc && doc._inc){
+ doc._inc++;
+ //update childNodes
+ var cs = el.childNodes;
+ if(newChild){
+ cs[cs.length++] = newChild;
+ }else{
+ //console.log(1)
+ var child = el.firstChild;
+ var i = 0;
+ while(child){
+ cs[i++] = child;
+ child =child.nextSibling;
+ }
+ cs.length = i;
+ }
+ }
+}
+
+/**
+ * attributes;
+ * children;
+ *
+ * writeable properties:
+ * nodeValue,Attr:value,CharacterData:data
+ * prefix
+ */
+function _removeChild(parentNode,child){
+ var previous = child.previousSibling;
+ var next = child.nextSibling;
+ if(previous){
+ previous.nextSibling = next;
+ }else{
+ parentNode.firstChild = next
+ }
+ if(next){
+ next.previousSibling = previous;
+ }else{
+ parentNode.lastChild = previous;
+ }
+ _onUpdateChild(parentNode.ownerDocument,parentNode);
+ return child;
+}
+/**
+ * preformance key(refChild == null)
+ */
+function _insertBefore(parentNode,newChild,nextChild){
+ var cp = newChild.parentNode;
+ if(cp){
+ cp.removeChild(newChild);//remove and update
+ }
+ if(newChild.nodeType === DOCUMENT_FRAGMENT_NODE){
+ var newFirst = newChild.firstChild;
+ if (newFirst == null) {
+ return newChild;
+ }
+ var newLast = newChild.lastChild;
+ }else{
+ newFirst = newLast = newChild;
+ }
+ var pre = nextChild ? nextChild.previousSibling : parentNode.lastChild;
+
+ newFirst.previousSibling = pre;
+ newLast.nextSibling = nextChild;
+
+
+ if(pre){
+ pre.nextSibling = newFirst;
+ }else{
+ parentNode.firstChild = newFirst;
+ }
+ if(nextChild == null){
+ parentNode.lastChild = newLast;
+ }else{
+ nextChild.previousSibling = newLast;
+ }
+ do{
+ newFirst.parentNode = parentNode;
+ }while(newFirst !== newLast && (newFirst= newFirst.nextSibling))
+ _onUpdateChild(parentNode.ownerDocument||parentNode,parentNode);
+ //console.log(parentNode.lastChild.nextSibling == null)
+ if (newChild.nodeType == DOCUMENT_FRAGMENT_NODE) {
+ newChild.firstChild = newChild.lastChild = null;
+ }
+ return newChild;
+}
+function _appendSingleChild(parentNode,newChild){
+ var cp = newChild.parentNode;
+ if(cp){
+ var pre = parentNode.lastChild;
+ cp.removeChild(newChild);//remove and update
+ var pre = parentNode.lastChild;
+ }
+ var pre = parentNode.lastChild;
+ newChild.parentNode = parentNode;
+ newChild.previousSibling = pre;
+ newChild.nextSibling = null;
+ if(pre){
+ pre.nextSibling = newChild;
+ }else{
+ parentNode.firstChild = newChild;
+ }
+ parentNode.lastChild = newChild;
+ _onUpdateChild(parentNode.ownerDocument,parentNode,newChild);
+ return newChild;
+ //console.log("__aa",parentNode.lastChild.nextSibling == null)
+}
+Document.prototype = {
+ //implementation : null,
+ nodeName : '#document',
+ nodeType : DOCUMENT_NODE,
+ doctype : null,
+ documentElement : null,
+ _inc : 1,
+
+ insertBefore : function(newChild, refChild){//raises
+ if(newChild.nodeType == DOCUMENT_FRAGMENT_NODE){
+ var child = newChild.firstChild;
+ while(child){
+ var next = child.nextSibling;
+ this.insertBefore(child,refChild);
+ child = next;
+ }
+ return newChild;
+ }
+ if(this.documentElement == null && newChild.nodeType == ELEMENT_NODE){
+ this.documentElement = newChild;
+ }
+
+ return _insertBefore(this,newChild,refChild),(newChild.ownerDocument = this),newChild;
+ },
+ removeChild : function(oldChild){
+ if(this.documentElement == oldChild){
+ this.documentElement = null;
+ }
+ return _removeChild(this,oldChild);
+ },
+ // Introduced in DOM Level 2:
+ importNode : function(importedNode,deep){
+ return importNode(this,importedNode,deep);
+ },
+ // Introduced in DOM Level 2:
+ getElementById : function(id){
+ var rtv = null;
+ _visitNode(this.documentElement,function(node){
+ if(node.nodeType == ELEMENT_NODE){
+ if(node.getAttribute('id') == id){
+ rtv = node;
+ return true;
+ }
+ }
+ })
+ return rtv;
+ },
+
+ getElementsByClassName: function(className) {
+ var pattern = new RegExp("(^|\\s)" + className + "(\\s|$)");
+ return new LiveNodeList(this, function(base) {
+ var ls = [];
+ _visitNode(base.documentElement, function(node) {
+ if(node !== base && node.nodeType == ELEMENT_NODE) {
+ if(pattern.test(node.getAttribute('class'))) {
+ ls.push(node);
+ }
+ }
+ });
+ return ls;
+ });
+ },
+
+ //document factory method:
+ createElement : function(tagName){
+ var node = new Element();
+ node.ownerDocument = this;
+ node.nodeName = tagName;
+ node.tagName = tagName;
+ node.childNodes = new NodeList();
+ var attrs = node.attributes = new NamedNodeMap();
+ attrs._ownerElement = node;
+ return node;
+ },
+ createDocumentFragment : function(){
+ var node = new DocumentFragment();
+ node.ownerDocument = this;
+ node.childNodes = new NodeList();
+ return node;
+ },
+ createTextNode : function(data){
+ var node = new Text();
+ node.ownerDocument = this;
+ node.appendData(data)
+ return node;
+ },
+ createComment : function(data){
+ var node = new Comment();
+ node.ownerDocument = this;
+ node.appendData(data)
+ return node;
+ },
+ createCDATASection : function(data){
+ var node = new CDATASection();
+ node.ownerDocument = this;
+ node.appendData(data)
+ return node;
+ },
+ createProcessingInstruction : function(target,data){
+ var node = new ProcessingInstruction();
+ node.ownerDocument = this;
+ node.tagName = node.target = target;
+ node.nodeValue= node.data = data;
+ return node;
+ },
+ createAttribute : function(name){
+ var node = new Attr();
+ node.ownerDocument = this;
+ node.name = name;
+ node.nodeName = name;
+ node.localName = name;
+ node.specified = true;
+ return node;
+ },
+ createEntityReference : function(name){
+ var node = new EntityReference();
+ node.ownerDocument = this;
+ node.nodeName = name;
+ return node;
+ },
+ // Introduced in DOM Level 2:
+ createElementNS : function(namespaceURI,qualifiedName){
+ var node = new Element();
+ var pl = qualifiedName.split(':');
+ var attrs = node.attributes = new NamedNodeMap();
+ node.childNodes = new NodeList();
+ node.ownerDocument = this;
+ node.nodeName = qualifiedName;
+ node.tagName = qualifiedName;
+ node.namespaceURI = namespaceURI;
+ if(pl.length == 2){
+ node.prefix = pl[0];
+ node.localName = pl[1];
+ }else{
+ //el.prefix = null;
+ node.localName = qualifiedName;
+ }
+ attrs._ownerElement = node;
+ return node;
+ },
+ // Introduced in DOM Level 2:
+ createAttributeNS : function(namespaceURI,qualifiedName){
+ var node = new Attr();
+ var pl = qualifiedName.split(':');
+ node.ownerDocument = this;
+ node.nodeName = qualifiedName;
+ node.name = qualifiedName;
+ node.namespaceURI = namespaceURI;
+ node.specified = true;
+ if(pl.length == 2){
+ node.prefix = pl[0];
+ node.localName = pl[1];
+ }else{
+ //el.prefix = null;
+ node.localName = qualifiedName;
+ }
+ return node;
+ }
+};
+_extends(Document,Node);
+
+
+function Element() {
+ this._nsMap = {};
+};
+Element.prototype = {
+ nodeType : ELEMENT_NODE,
+ hasAttribute : function(name){
+ return this.getAttributeNode(name)!=null;
+ },
+ getAttribute : function(name){
+ var attr = this.getAttributeNode(name);
+ return attr && attr.value || '';
+ },
+ getAttributeNode : function(name){
+ return this.attributes.getNamedItem(name);
+ },
+ setAttribute : function(name, value){
+ var attr = this.ownerDocument.createAttribute(name);
+ attr.value = attr.nodeValue = "" + value;
+ this.setAttributeNode(attr)
+ },
+ removeAttribute : function(name){
+ var attr = this.getAttributeNode(name)
+ attr && this.removeAttributeNode(attr);
+ },
+
+ //four real opeartion method
+ appendChild:function(newChild){
+ if(newChild.nodeType === DOCUMENT_FRAGMENT_NODE){
+ return this.insertBefore(newChild,null);
+ }else{
+ return _appendSingleChild(this,newChild);
+ }
+ },
+ setAttributeNode : function(newAttr){
+ return this.attributes.setNamedItem(newAttr);
+ },
+ setAttributeNodeNS : function(newAttr){
+ return this.attributes.setNamedItemNS(newAttr);
+ },
+ removeAttributeNode : function(oldAttr){
+ //console.log(this == oldAttr.ownerElement)
+ return this.attributes.removeNamedItem(oldAttr.nodeName);
+ },
+ //get real attribute name,and remove it by removeAttributeNode
+ removeAttributeNS : function(namespaceURI, localName){
+ var old = this.getAttributeNodeNS(namespaceURI, localName);
+ old && this.removeAttributeNode(old);
+ },
+
+ hasAttributeNS : function(namespaceURI, localName){
+ return this.getAttributeNodeNS(namespaceURI, localName)!=null;
+ },
+ getAttributeNS : function(namespaceURI, localName){
+ var attr = this.getAttributeNodeNS(namespaceURI, localName);
+ return attr && attr.value || '';
+ },
+ setAttributeNS : function(namespaceURI, qualifiedName, value){
+ var attr = this.ownerDocument.createAttributeNS(namespaceURI, qualifiedName);
+ attr.value = attr.nodeValue = "" + value;
+ this.setAttributeNode(attr)
+ },
+ getAttributeNodeNS : function(namespaceURI, localName){
+ return this.attributes.getNamedItemNS(namespaceURI, localName);
+ },
+
+ getElementsByTagName : function(tagName){
+ return new LiveNodeList(this,function(base){
+ var ls = [];
+ _visitNode(base,function(node){
+ if(node !== base && node.nodeType == ELEMENT_NODE && (tagName === '*' || node.tagName == tagName)){
+ ls.push(node);
+ }
+ });
+ return ls;
+ });
+ },
+ getElementsByTagNameNS : function(namespaceURI, localName){
+ return new LiveNodeList(this,function(base){
+ var ls = [];
+ _visitNode(base,function(node){
+ if(node !== base && node.nodeType === ELEMENT_NODE && (namespaceURI === '*' || node.namespaceURI === namespaceURI) && (localName === '*' || node.localName == localName)){
+ ls.push(node);
+ }
+ });
+ return ls;
+
+ });
+ }
+};
+Document.prototype.getElementsByTagName = Element.prototype.getElementsByTagName;
+Document.prototype.getElementsByTagNameNS = Element.prototype.getElementsByTagNameNS;
+
+
+_extends(Element,Node);
+function Attr() {
+};
+Attr.prototype.nodeType = ATTRIBUTE_NODE;
+_extends(Attr,Node);
+
+
+function CharacterData() {
+};
+CharacterData.prototype = {
+ data : '',
+ substringData : function(offset, count) {
+ return this.data.substring(offset, offset+count);
+ },
+ appendData: function(text) {
+ text = this.data+text;
+ this.nodeValue = this.data = text;
+ this.length = text.length;
+ },
+ insertData: function(offset,text) {
+ this.replaceData(offset,0,text);
+
+ },
+ appendChild:function(newChild){
+ throw new Error(ExceptionMessage[HIERARCHY_REQUEST_ERR])
+ },
+ deleteData: function(offset, count) {
+ this.replaceData(offset,count,"");
+ },
+ replaceData: function(offset, count, text) {
+ var start = this.data.substring(0,offset);
+ var end = this.data.substring(offset+count);
+ text = start + text + end;
+ this.nodeValue = this.data = text;
+ this.length = text.length;
+ }
+}
+_extends(CharacterData,Node);
+function Text() {
+};
+Text.prototype = {
+ nodeName : "#text",
+ nodeType : TEXT_NODE,
+ splitText : function(offset) {
+ var text = this.data;
+ var newText = text.substring(offset);
+ text = text.substring(0, offset);
+ this.data = this.nodeValue = text;
+ this.length = text.length;
+ var newNode = this.ownerDocument.createTextNode(newText);
+ if(this.parentNode){
+ this.parentNode.insertBefore(newNode, this.nextSibling);
+ }
+ return newNode;
+ }
+}
+_extends(Text,CharacterData);
+function Comment() {
+};
+Comment.prototype = {
+ nodeName : "#comment",
+ nodeType : COMMENT_NODE
+}
+_extends(Comment,CharacterData);
+
+function CDATASection() {
+};
+CDATASection.prototype = {
+ nodeName : "#cdata-section",
+ nodeType : CDATA_SECTION_NODE
+}
+_extends(CDATASection,CharacterData);
+
+
+function DocumentType() {
+};
+DocumentType.prototype.nodeType = DOCUMENT_TYPE_NODE;
+_extends(DocumentType,Node);
+
+function Notation() {
+};
+Notation.prototype.nodeType = NOTATION_NODE;
+_extends(Notation,Node);
+
+function Entity() {
+};
+Entity.prototype.nodeType = ENTITY_NODE;
+_extends(Entity,Node);
+
+function EntityReference() {
+};
+EntityReference.prototype.nodeType = ENTITY_REFERENCE_NODE;
+_extends(EntityReference,Node);
+
+function DocumentFragment() {
+};
+DocumentFragment.prototype.nodeName = "#document-fragment";
+DocumentFragment.prototype.nodeType = DOCUMENT_FRAGMENT_NODE;
+_extends(DocumentFragment,Node);
+
+
+function ProcessingInstruction() {
+}
+ProcessingInstruction.prototype.nodeType = PROCESSING_INSTRUCTION_NODE;
+_extends(ProcessingInstruction,Node);
+function XMLSerializer(){}
+XMLSerializer.prototype.serializeToString = function(node,isHtml,nodeFilter){
+ return nodeSerializeToString.call(node,isHtml,nodeFilter);
+}
+Node.prototype.toString = nodeSerializeToString;
+function nodeSerializeToString(isHtml,nodeFilter){
+ var buf = [];
+ var refNode = this.nodeType == 9 && this.documentElement || this;
+ var prefix = refNode.prefix;
+ var uri = refNode.namespaceURI;
+
+ if(uri && prefix == null){
+ //console.log(prefix)
+ var prefix = refNode.lookupPrefix(uri);
+ if(prefix == null){
+ //isHTML = true;
+ var visibleNamespaces=[
+ {namespace:uri,prefix:null}
+ //{namespace:uri,prefix:''}
+ ]
+ }
+ }
+ serializeToString(this,buf,isHtml,nodeFilter,visibleNamespaces);
+ //console.log('###',this.nodeType,uri,prefix,buf.join(''))
+ return buf.join('');
+}
+function needNamespaceDefine(node,isHTML, visibleNamespaces) {
+ var prefix = node.prefix||'';
+ var uri = node.namespaceURI;
+ if (!prefix && !uri){
+ return false;
+ }
+ if (prefix === "xml" && uri === "http://www.w3.org/XML/1998/namespace"
+ || uri == 'http://www.w3.org/2000/xmlns/'){
+ return false;
+ }
+
+ var i = visibleNamespaces.length
+ //console.log('@@@@',node.tagName,prefix,uri,visibleNamespaces)
+ while (i--) {
+ var ns = visibleNamespaces[i];
+ // get namespace prefix
+ //console.log(node.nodeType,node.tagName,ns.prefix,prefix)
+ if (ns.prefix == prefix){
+ return ns.namespace != uri;
+ }
+ }
+ //console.log(isHTML,uri,prefix=='')
+ //if(isHTML && prefix ==null && uri == 'http://www.w3.org/1999/xhtml'){
+ // return false;
+ //}
+ //node.flag = '11111'
+ //console.error(3,true,node.flag,node.prefix,node.namespaceURI)
+ return true;
+}
+function serializeToString(node,buf,isHTML,nodeFilter,visibleNamespaces){
+ if(nodeFilter){
+ node = nodeFilter(node);
+ if(node){
+ if(typeof node == 'string'){
+ buf.push(node);
+ return;
+ }
+ }else{
+ return;
+ }
+ //buf.sort.apply(attrs, attributeSorter);
+ }
+ switch(node.nodeType){
+ case ELEMENT_NODE:
+ if (!visibleNamespaces) visibleNamespaces = [];
+ var startVisibleNamespaces = visibleNamespaces.length;
+ var attrs = node.attributes;
+ var len = attrs.length;
+ var child = node.firstChild;
+ var nodeName = node.tagName;
+
+ isHTML = (htmlns === node.namespaceURI) ||isHTML
+ buf.push('<',nodeName);
+
+
+
+ for(var i=0;i');
+ //if is cdata child node
+ if(isHTML && /^script$/i.test(nodeName)){
+ while(child){
+ if(child.data){
+ buf.push(child.data);
+ }else{
+ serializeToString(child,buf,isHTML,nodeFilter,visibleNamespaces);
+ }
+ child = child.nextSibling;
+ }
+ }else
+ {
+ while(child){
+ serializeToString(child,buf,isHTML,nodeFilter,visibleNamespaces);
+ child = child.nextSibling;
+ }
+ }
+ buf.push('',nodeName,'>');
+ }else{
+ buf.push('/>');
+ }
+ // remove added visible namespaces
+ //visibleNamespaces.length = startVisibleNamespaces;
+ return;
+ case DOCUMENT_NODE:
+ case DOCUMENT_FRAGMENT_NODE:
+ var child = node.firstChild;
+ while(child){
+ serializeToString(child,buf,isHTML,nodeFilter,visibleNamespaces);
+ child = child.nextSibling;
+ }
+ return;
+ case ATTRIBUTE_NODE:
+ /**
+ * Well-formedness constraint: No < in Attribute Values
+ * The replacement text of any entity referred to directly or indirectly in an attribute value must not contain a <.
+ * @see https://www.w3.org/TR/xml/#CleanAttrVals
+ * @see https://www.w3.org/TR/xml/#NT-AttValue
+ */
+ return buf.push(' ', node.name, '="', node.value.replace(/[<&"]/g,_xmlEncoder), '"');
+ case TEXT_NODE:
+ /**
+ * The ampersand character (&) and the left angle bracket (<) must not appear in their literal form,
+ * except when used as markup delimiters, or within a comment, a processing instruction, or a CDATA section.
+ * If they are needed elsewhere, they must be escaped using either numeric character references or the strings
+ * `&` and `<` respectively.
+ * The right angle bracket (>) may be represented using the string " > ", and must, for compatibility,
+ * be escaped using either `>` or a character reference when it appears in the string `]]>` in content,
+ * when that string is not marking the end of a CDATA section.
+ *
+ * In the content of elements, character data is any string of characters
+ * which does not contain the start-delimiter of any markup
+ * and does not include the CDATA-section-close delimiter, `]]>`.
+ *
+ * @see https://www.w3.org/TR/xml/#NT-CharData
+ */
+ return buf.push(node.data
+ .replace(/[<&]/g,_xmlEncoder)
+ .replace(/]]>/g, ']]>')
+ );
+ case CDATA_SECTION_NODE:
+ return buf.push( '');
+ case COMMENT_NODE:
+ return buf.push( "");
+ case DOCUMENT_TYPE_NODE:
+ var pubid = node.publicId;
+ var sysid = node.systemId;
+ buf.push('');
+ }else if(sysid && sysid!='.'){
+ buf.push(' SYSTEM ', sysid, '>');
+ }else{
+ var sub = node.internalSubset;
+ if(sub){
+ buf.push(" [",sub,"]");
+ }
+ buf.push(">");
+ }
+ return;
+ case PROCESSING_INSTRUCTION_NODE:
+ return buf.push( "",node.target," ",node.data,"?>");
+ case ENTITY_REFERENCE_NODE:
+ return buf.push( '&',node.nodeName,';');
+ //case ENTITY_NODE:
+ //case NOTATION_NODE:
+ default:
+ buf.push('??',node.nodeName);
+ }
+}
+function importNode(doc,node,deep){
+ var node2;
+ switch (node.nodeType) {
+ case ELEMENT_NODE:
+ node2 = node.cloneNode(false);
+ node2.ownerDocument = doc;
+ //var attrs = node2.attributes;
+ //var len = attrs.length;
+ //for(var i=0;i',
+ amp: '&',
+ quot: '"',
+ apos: "'",
+ Agrave: "À",
+ Aacute: "Á",
+ Acirc: "Â",
+ Atilde: "Ã",
+ Auml: "Ä",
+ Aring: "Å",
+ AElig: "Æ",
+ Ccedil: "Ç",
+ Egrave: "È",
+ Eacute: "É",
+ Ecirc: "Ê",
+ Euml: "Ë",
+ Igrave: "Ì",
+ Iacute: "Í",
+ Icirc: "Î",
+ Iuml: "Ï",
+ ETH: "Ð",
+ Ntilde: "Ñ",
+ Ograve: "Ò",
+ Oacute: "Ó",
+ Ocirc: "Ô",
+ Otilde: "Õ",
+ Ouml: "Ö",
+ Oslash: "Ø",
+ Ugrave: "Ù",
+ Uacute: "Ú",
+ Ucirc: "Û",
+ Uuml: "Ü",
+ Yacute: "Ý",
+ THORN: "Þ",
+ szlig: "ß",
+ agrave: "à",
+ aacute: "á",
+ acirc: "â",
+ atilde: "ã",
+ auml: "ä",
+ aring: "å",
+ aelig: "æ",
+ ccedil: "ç",
+ egrave: "è",
+ eacute: "é",
+ ecirc: "ê",
+ euml: "ë",
+ igrave: "ì",
+ iacute: "í",
+ icirc: "î",
+ iuml: "ï",
+ eth: "ð",
+ ntilde: "ñ",
+ ograve: "ò",
+ oacute: "ó",
+ ocirc: "ô",
+ otilde: "õ",
+ ouml: "ö",
+ oslash: "ø",
+ ugrave: "ù",
+ uacute: "ú",
+ ucirc: "û",
+ uuml: "ü",
+ yacute: "ý",
+ thorn: "þ",
+ yuml: "ÿ",
+ nbsp: "\u00a0",
+ iexcl: "¡",
+ cent: "¢",
+ pound: "£",
+ curren: "¤",
+ yen: "¥",
+ brvbar: "¦",
+ sect: "§",
+ uml: "¨",
+ copy: "©",
+ ordf: "ª",
+ laquo: "«",
+ not: "¬",
+ shy: "",
+ reg: "®",
+ macr: "¯",
+ deg: "°",
+ plusmn: "±",
+ sup2: "²",
+ sup3: "³",
+ acute: "´",
+ micro: "µ",
+ para: "¶",
+ middot: "·",
+ cedil: "¸",
+ sup1: "¹",
+ ordm: "º",
+ raquo: "»",
+ frac14: "¼",
+ frac12: "½",
+ frac34: "¾",
+ iquest: "¿",
+ times: "×",
+ divide: "÷",
+ forall: "∀",
+ part: "∂",
+ exist: "∃",
+ empty: "∅",
+ nabla: "∇",
+ isin: "∈",
+ notin: "∉",
+ ni: "∋",
+ prod: "∏",
+ sum: "∑",
+ minus: "−",
+ lowast: "∗",
+ radic: "√",
+ prop: "∝",
+ infin: "∞",
+ ang: "∠",
+ and: "∧",
+ or: "∨",
+ cap: "∩",
+ cup: "∪",
+ 'int': "∫",
+ there4: "∴",
+ sim: "∼",
+ cong: "≅",
+ asymp: "≈",
+ ne: "≠",
+ equiv: "≡",
+ le: "≤",
+ ge: "≥",
+ sub: "⊂",
+ sup: "⊃",
+ nsub: "⊄",
+ sube: "⊆",
+ supe: "⊇",
+ oplus: "⊕",
+ otimes: "⊗",
+ perp: "⊥",
+ sdot: "⋅",
+ Alpha: "Α",
+ Beta: "Β",
+ Gamma: "Γ",
+ Delta: "Δ",
+ Epsilon: "Ε",
+ Zeta: "Ζ",
+ Eta: "Η",
+ Theta: "Θ",
+ Iota: "Ι",
+ Kappa: "Κ",
+ Lambda: "Λ",
+ Mu: "Μ",
+ Nu: "Ν",
+ Xi: "Ξ",
+ Omicron: "Ο",
+ Pi: "Π",
+ Rho: "Ρ",
+ Sigma: "Σ",
+ Tau: "Τ",
+ Upsilon: "Υ",
+ Phi: "Φ",
+ Chi: "Χ",
+ Psi: "Ψ",
+ Omega: "Ω",
+ alpha: "α",
+ beta: "β",
+ gamma: "γ",
+ delta: "δ",
+ epsilon: "ε",
+ zeta: "ζ",
+ eta: "η",
+ theta: "θ",
+ iota: "ι",
+ kappa: "κ",
+ lambda: "λ",
+ mu: "μ",
+ nu: "ν",
+ xi: "ξ",
+ omicron: "ο",
+ pi: "π",
+ rho: "ρ",
+ sigmaf: "ς",
+ sigma: "σ",
+ tau: "τ",
+ upsilon: "υ",
+ phi: "φ",
+ chi: "χ",
+ psi: "ψ",
+ omega: "ω",
+ thetasym: "ϑ",
+ upsih: "ϒ",
+ piv: "ϖ",
+ OElig: "Œ",
+ oelig: "œ",
+ Scaron: "Š",
+ scaron: "š",
+ Yuml: "Ÿ",
+ fnof: "ƒ",
+ circ: "ˆ",
+ tilde: "˜",
+ ensp: " ",
+ emsp: " ",
+ thinsp: " ",
+ zwnj: "",
+ zwj: "",
+ lrm: "",
+ rlm: "",
+ ndash: "–",
+ mdash: "—",
+ lsquo: "‘",
+ rsquo: "’",
+ sbquo: "‚",
+ ldquo: "“",
+ rdquo: "”",
+ bdquo: "„",
+ dagger: "†",
+ Dagger: "‡",
+ bull: "•",
+ hellip: "…",
+ permil: "‰",
+ prime: "′",
+ Prime: "″",
+ lsaquo: "‹",
+ rsaquo: "›",
+ oline: "‾",
+ euro: "€",
+ trade: "™",
+ larr: "←",
+ uarr: "↑",
+ rarr: "→",
+ darr: "↓",
+ harr: "↔",
+ crarr: "↵",
+ lceil: "⌈",
+ rceil: "⌉",
+ lfloor: "⌊",
+ rfloor: "⌋",
+ loz: "◊",
+ spades: "♠",
+ clubs: "♣",
+ hearts: "♥",
+ diams: "♦"
+};
+
+},{}],5:[function(require,module,exports){
+//[4] NameStartChar ::= ":" | [A-Z] | "_" | [a-z] | [#xC0-#xD6] | [#xD8-#xF6] | [#xF8-#x2FF] | [#x370-#x37D] | [#x37F-#x1FFF] | [#x200C-#x200D] | [#x2070-#x218F] | [#x2C00-#x2FEF] | [#x3001-#xD7FF] | [#xF900-#xFDCF] | [#xFDF0-#xFFFD] | [#x10000-#xEFFFF]
+//[4a] NameChar ::= NameStartChar | "-" | "." | [0-9] | #xB7 | [#x0300-#x036F] | [#x203F-#x2040]
+//[5] Name ::= NameStartChar (NameChar)*
+var nameStartChar = /[A-Z_a-z\xC0-\xD6\xD8-\xF6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]///\u10000-\uEFFFF
+var nameChar = new RegExp("[\\-\\.0-9"+nameStartChar.source.slice(1,-1)+"\\u00B7\\u0300-\\u036F\\u203F-\\u2040]");
+var tagNamePattern = new RegExp('^'+nameStartChar.source+nameChar.source+'*(?:\:'+nameStartChar.source+nameChar.source+'*)?$');
+//var tagNamePattern = /^[a-zA-Z_][\w\-\.]*(?:\:[a-zA-Z_][\w\-\.]*)?$/
+//var handlers = 'resolveEntity,getExternalSubset,characters,endDocument,endElement,endPrefixMapping,ignorableWhitespace,processingInstruction,setDocumentLocator,skippedEntity,startDocument,startElement,startPrefixMapping,notationDecl,unparsedEntityDecl,error,fatalError,warning,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,comment,endCDATA,endDTD,endEntity,startCDATA,startDTD,startEntity'.split(',')
+
+//S_TAG, S_ATTR, S_EQ, S_ATTR_NOQUOT_VALUE
+//S_ATTR_SPACE, S_ATTR_END, S_TAG_SPACE, S_TAG_CLOSE
+var S_TAG = 0;//tag name offerring
+var S_ATTR = 1;//attr name offerring
+var S_ATTR_SPACE=2;//attr name end and space offer
+var S_EQ = 3;//=space?
+var S_ATTR_NOQUOT_VALUE = 4;//attr value(no quot value only)
+var S_ATTR_END = 5;//attr value end and no space(quot end)
+var S_TAG_SPACE = 6;//(attr value end || tag end ) && (space offer)
+var S_TAG_CLOSE = 7;//closed el
+
+/**
+ * Creates an error that will not be caught by XMLReader aka the SAX parser.
+ *
+ * @param {string} message
+ * @param {any?} locator Optional, can provide details about the location in the source
+ * @constructor
+ */
+function ParseError(message, locator) {
+ this.message = message
+ this.locator = locator
+ if(Error.captureStackTrace) Error.captureStackTrace(this, ParseError);
+}
+ParseError.prototype = new Error();
+ParseError.prototype.name = ParseError.name
+
+function XMLReader(){
+
+}
+
+XMLReader.prototype = {
+ parse:function(source,defaultNSMap,entityMap){
+ var domBuilder = this.domBuilder;
+ domBuilder.startDocument();
+ _copy(defaultNSMap ,defaultNSMap = {})
+ parse(source,defaultNSMap,entityMap,
+ domBuilder,this.errorHandler);
+ domBuilder.endDocument();
+ }
+}
+function parse(source,defaultNSMapCopy,entityMap,domBuilder,errorHandler){
+ function fixedFromCharCode(code) {
+ // String.prototype.fromCharCode does not supports
+ // > 2 bytes unicode chars directly
+ if (code > 0xffff) {
+ code -= 0x10000;
+ var surrogate1 = 0xd800 + (code >> 10)
+ , surrogate2 = 0xdc00 + (code & 0x3ff);
+
+ return String.fromCharCode(surrogate1, surrogate2);
+ } else {
+ return String.fromCharCode(code);
+ }
+ }
+ function entityReplacer(a){
+ var k = a.slice(1,-1);
+ if(k in entityMap){
+ return entityMap[k];
+ }else if(k.charAt(0) === '#'){
+ return fixedFromCharCode(parseInt(k.substr(1).replace('x','0x')))
+ }else{
+ errorHandler.error('entity not found:'+a);
+ return a;
+ }
+ }
+ function appendText(end){//has some bugs
+ if(end>start){
+ var xt = source.substring(start,end).replace(/?\w+;/g,entityReplacer);
+ locator&&position(start);
+ domBuilder.characters(xt,0,end-start);
+ start = end
+ }
+ }
+ function position(p,m){
+ while(p>=lineEnd && (m = linePattern.exec(source))){
+ lineStart = m.index;
+ lineEnd = lineStart + m[0].length;
+ locator.lineNumber++;
+ //console.log('line++:',locator,startPos,endPos)
+ }
+ locator.columnNumber = p-lineStart+1;
+ }
+ var lineStart = 0;
+ var lineEnd = 0;
+ var linePattern = /.*(?:\r\n?|\n)|.*$/g
+ var locator = domBuilder.locator;
+
+ var parseStack = [{currentNSMap:defaultNSMapCopy}]
+ var closeMap = {};
+ var start = 0;
+ while(true){
+ try{
+ var tagStart = source.indexOf('<',start);
+ if(tagStart<0){
+ if(!source.substr(start).match(/^\s*$/)){
+ var doc = domBuilder.doc;
+ var text = doc.createTextNode(source.substr(start));
+ doc.appendChild(text);
+ domBuilder.currentElement = text;
+ }
+ return;
+ }
+ if(tagStart>start){
+ appendText(tagStart);
+ }
+ switch(source.charAt(tagStart+1)){
+ case '/':
+ var end = source.indexOf('>',tagStart+3);
+ var tagName = source.substring(tagStart+2,end);
+ var config = parseStack.pop();
+ if(end<0){
+
+ tagName = source.substring(tagStart+2).replace(/[\s<].*/,'');
+ errorHandler.error("end tag name: "+tagName+' is not complete:'+config.tagName);
+ end = tagStart+1+tagName.length;
+ }else if(tagName.match(/\s)){
+ tagName = tagName.replace(/[\s<].*/,'');
+ errorHandler.error("end tag name: "+tagName+' maybe not complete');
+ end = tagStart+1+tagName.length;
+ }
+ var localNSMap = config.localNSMap;
+ var endMatch = config.tagName == tagName;
+ var endIgnoreCaseMach = endMatch || config.tagName&&config.tagName.toLowerCase() == tagName.toLowerCase()
+ if(endIgnoreCaseMach){
+ domBuilder.endElement(config.uri,config.localName,tagName);
+ if(localNSMap){
+ for(var prefix in localNSMap){
+ domBuilder.endPrefixMapping(prefix) ;
+ }
+ }
+ if(!endMatch){
+ errorHandler.fatalError("end tag name: "+tagName+' is not match the current start tagName:'+config.tagName ); // No known test case
+ }
+ }else{
+ parseStack.push(config)
+ }
+
+ end++;
+ break;
+ // end elment
+ case '?':// ...?>
+ locator&&position(tagStart);
+ end = parseInstruction(source,tagStart,domBuilder);
+ break;
+ case '!':// start){
+ start = end;
+ }else{
+ //TODO: 这里有可能sax回退,有位置错误风险
+ appendText(Math.max(tagStart,start)+1);
+ }
+ }
+}
+function copyLocator(f,t){
+ t.lineNumber = f.lineNumber;
+ t.columnNumber = f.columnNumber;
+ return t;
+}
+
+/**
+ * @see #appendElement(source,elStartEnd,el,selfClosed,entityReplacer,domBuilder,parseStack);
+ * @return end of the elementStartPart(end of elementEndPart for selfClosed el)
+ */
+function parseElementStartPart(source,start,el,currentNSMap,entityReplacer,errorHandler){
+
+ /**
+ * @param {string} qname
+ * @param {string} value
+ * @param {number} startIndex
+ */
+ function addAttribute(qname, value, startIndex) {
+ if (qname in el.attributeNames) errorHandler.fatalError('Attribute ' + qname + ' redefined')
+ el.addValue(qname, value, startIndex)
+ }
+ var attrName;
+ var value;
+ var p = ++start;
+ var s = S_TAG;//status
+ while(true){
+ var c = source.charAt(p);
+ switch(c){
+ case '=':
+ if(s === S_ATTR){//attrName
+ attrName = source.slice(start,p);
+ s = S_EQ;
+ }else if(s === S_ATTR_SPACE){
+ s = S_EQ;
+ }else{
+ //fatalError: equal must after attrName or space after attrName
+ throw new Error('attribute equal must after attrName'); // No known test case
+ }
+ break;
+ case '\'':
+ case '"':
+ if(s === S_EQ || s === S_ATTR //|| s == S_ATTR_SPACE
+ ){//equal
+ if(s === S_ATTR){
+ errorHandler.warning('attribute value must after "="')
+ attrName = source.slice(start,p)
+ }
+ start = p+1;
+ p = source.indexOf(c,start)
+ if(p>0){
+ value = source.slice(start,p).replace(/?\w+;/g,entityReplacer);
+ addAttribute(attrName, value, start-1);
+ s = S_ATTR_END;
+ }else{
+ //fatalError: no end quot match
+ throw new Error('attribute value no end \''+c+'\' match');
+ }
+ }else if(s == S_ATTR_NOQUOT_VALUE){
+ value = source.slice(start,p).replace(/?\w+;/g,entityReplacer);
+ //console.log(attrName,value,start,p)
+ addAttribute(attrName, value, start);
+ //console.dir(el)
+ errorHandler.warning('attribute "'+attrName+'" missed start quot('+c+')!!');
+ start = p+1;
+ s = S_ATTR_END
+ }else{
+ //fatalError: no equal before
+ throw new Error('attribute value must after "="'); // No known test case
+ }
+ break;
+ case '/':
+ switch(s){
+ case S_TAG:
+ el.setTagName(source.slice(start,p));
+ case S_ATTR_END:
+ case S_TAG_SPACE:
+ case S_TAG_CLOSE:
+ s =S_TAG_CLOSE;
+ el.closed = true;
+ case S_ATTR_NOQUOT_VALUE:
+ case S_ATTR:
+ case S_ATTR_SPACE:
+ break;
+ //case S_EQ:
+ default:
+ throw new Error("attribute invalid close char('/')") // No known test case
+ }
+ break;
+ case ''://end document
+ errorHandler.error('unexpected end of input');
+ if(s == S_TAG){
+ el.setTagName(source.slice(start,p));
+ }
+ return p;
+ case '>':
+ switch(s){
+ case S_TAG:
+ el.setTagName(source.slice(start,p));
+ case S_ATTR_END:
+ case S_TAG_SPACE:
+ case S_TAG_CLOSE:
+ break;//normal
+ case S_ATTR_NOQUOT_VALUE://Compatible state
+ case S_ATTR:
+ value = source.slice(start,p);
+ if(value.slice(-1) === '/'){
+ el.closed = true;
+ value = value.slice(0,-1)
+ }
+ case S_ATTR_SPACE:
+ if(s === S_ATTR_SPACE){
+ value = attrName;
+ }
+ if(s == S_ATTR_NOQUOT_VALUE){
+ errorHandler.warning('attribute "'+value+'" missed quot(")!');
+ addAttribute(attrName, value.replace(/?\w+;/g,entityReplacer), start)
+ }else{
+ if(currentNSMap[''] !== 'http://www.w3.org/1999/xhtml' || !value.match(/^(?:disabled|checked|selected)$/i)){
+ errorHandler.warning('attribute "'+value+'" missed value!! "'+value+'" instead!!')
+ }
+ addAttribute(value, value, start)
+ }
+ break;
+ case S_EQ:
+ throw new Error('attribute value missed!!');
+ }
+// console.log(tagName,tagNamePattern,tagNamePattern.test(tagName))
+ return p;
+ /*xml space '\x20' | #x9 | #xD | #xA; */
+ case '\u0080':
+ c = ' ';
+ default:
+ if(c<= ' '){//space
+ switch(s){
+ case S_TAG:
+ el.setTagName(source.slice(start,p));//tagName
+ s = S_TAG_SPACE;
+ break;
+ case S_ATTR:
+ attrName = source.slice(start,p)
+ s = S_ATTR_SPACE;
+ break;
+ case S_ATTR_NOQUOT_VALUE:
+ var value = source.slice(start,p).replace(/?\w+;/g,entityReplacer);
+ errorHandler.warning('attribute "'+value+'" missed quot(")!!');
+ addAttribute(attrName, value, start)
+ case S_ATTR_END:
+ s = S_TAG_SPACE;
+ break;
+ //case S_TAG_SPACE:
+ //case S_EQ:
+ //case S_ATTR_SPACE:
+ // void();break;
+ //case S_TAG_CLOSE:
+ //ignore warning
+ }
+ }else{//not space
+//S_TAG, S_ATTR, S_EQ, S_ATTR_NOQUOT_VALUE
+//S_ATTR_SPACE, S_ATTR_END, S_TAG_SPACE, S_TAG_CLOSE
+ switch(s){
+ //case S_TAG:void();break;
+ //case S_ATTR:void();break;
+ //case S_ATTR_NOQUOT_VALUE:void();break;
+ case S_ATTR_SPACE:
+ var tagName = el.tagName;
+ if(currentNSMap[''] !== 'http://www.w3.org/1999/xhtml' || !attrName.match(/^(?:disabled|checked|selected)$/i)){
+ errorHandler.warning('attribute "'+attrName+'" missed value!! "'+attrName+'" instead2!!')
+ }
+ addAttribute(attrName, attrName, start);
+ start = p;
+ s = S_ATTR;
+ break;
+ case S_ATTR_END:
+ errorHandler.warning('attribute space is required"'+attrName+'"!!')
+ case S_TAG_SPACE:
+ s = S_ATTR;
+ start = p;
+ break;
+ case S_EQ:
+ s = S_ATTR_NOQUOT_VALUE;
+ start = p;
+ break;
+ case S_TAG_CLOSE:
+ throw new Error("elements closed character '/' and '>' must be connected to");
+ }
+ }
+ }//end outer switch
+ //console.log('p++',p)
+ p++;
+ }
+}
+/**
+ * @return true if has new namespace define
+ */
+function appendElement(el,domBuilder,currentNSMap){
+ var tagName = el.tagName;
+ var localNSMap = null;
+ //var currentNSMap = parseStack[parseStack.length-1].currentNSMap;
+ var i = el.length;
+ while(i--){
+ var a = el[i];
+ var qName = a.qName;
+ var value = a.value;
+ var nsp = qName.indexOf(':');
+ if(nsp>0){
+ var prefix = a.prefix = qName.slice(0,nsp);
+ var localName = qName.slice(nsp+1);
+ var nsPrefix = prefix === 'xmlns' && localName
+ }else{
+ localName = qName;
+ prefix = null
+ nsPrefix = qName === 'xmlns' && ''
+ }
+ //can not set prefix,because prefix !== ''
+ a.localName = localName ;
+ //prefix == null for no ns prefix attribute
+ if(nsPrefix !== false){//hack!!
+ if(localNSMap == null){
+ localNSMap = {}
+ //console.log(currentNSMap,0)
+ _copy(currentNSMap,currentNSMap={})
+ //console.log(currentNSMap,1)
+ }
+ currentNSMap[nsPrefix] = localNSMap[nsPrefix] = value;
+ a.uri = 'http://www.w3.org/2000/xmlns/'
+ domBuilder.startPrefixMapping(nsPrefix, value)
+ }
+ }
+ var i = el.length;
+ while(i--){
+ a = el[i];
+ var prefix = a.prefix;
+ if(prefix){//no prefix attribute has no namespace
+ if(prefix === 'xml'){
+ a.uri = 'http://www.w3.org/XML/1998/namespace';
+ }if(prefix !== 'xmlns'){
+ a.uri = currentNSMap[prefix || '']
+
+ //{console.log('###'+a.qName,domBuilder.locator.systemId+'',currentNSMap,a.uri)}
+ }
+ }
+ }
+ var nsp = tagName.indexOf(':');
+ if(nsp>0){
+ prefix = el.prefix = tagName.slice(0,nsp);
+ localName = el.localName = tagName.slice(nsp+1);
+ }else{
+ prefix = null;//important!!
+ localName = el.localName = tagName;
+ }
+ //no prefix element has default namespace
+ var ns = el.uri = currentNSMap[prefix || ''];
+ domBuilder.startElement(ns,localName,tagName,el);
+ //endPrefixMapping and startPrefixMapping have not any help for dom builder
+ //localNSMap = null
+ if(el.closed){
+ domBuilder.endElement(ns,localName,tagName);
+ if(localNSMap){
+ for(prefix in localNSMap){
+ domBuilder.endPrefixMapping(prefix)
+ }
+ }
+ }else{
+ el.currentNSMap = currentNSMap;
+ el.localNSMap = localNSMap;
+ //parseStack.push(el);
+ return true;
+ }
+}
+function parseHtmlSpecialContent(source,elStartEnd,tagName,entityReplacer,domBuilder){
+ if(/^(?:script|textarea)$/i.test(tagName)){
+ var elEndStart = source.indexOf(''+tagName+'>',elStartEnd);
+ var text = source.substring(elStartEnd+1,elEndStart);
+ if(/[&<]/.test(text)){
+ if(/^script$/i.test(tagName)){
+ //if(!/\]\]>/.test(text)){
+ //lexHandler.startCDATA();
+ domBuilder.characters(text,0,text.length);
+ //lexHandler.endCDATA();
+ return elEndStart;
+ //}
+ }//}else{//text area
+ text = text.replace(/?\w+;/g,entityReplacer);
+ domBuilder.characters(text,0,text.length);
+ return elEndStart;
+ //}
+
+ }
+ }
+ return elStartEnd+1;
+}
+function fixSelfClosed(source,elStartEnd,tagName,closeMap){
+ //if(tagName in closeMap){
+ var pos = closeMap[tagName];
+ if(pos == null){
+ //console.log(tagName)
+ pos = source.lastIndexOf(''+tagName+'>')
+ if(pos',start+4);
+ //append comment source.substring(4,end)//,
+ * and raw CDATA nodes.
+ *
+ * @param {Element} node
+ * @returns {Boolean}
+ * @api private
+ */
+
+function shouldIgnoreNode (node) {
+ return node.nodeType === TEXT_NODE
+ || node.nodeType === COMMENT_NODE
+ || node.nodeType === CDATA_NODE;
+}
+
+/**
+ * Check if the node is empty. Some plist file has such node:
+ *
+ * this node shoud be ignored.
+ *
+ * @see https://github.com/TooTallNate/plist.js/issues/66
+ * @param {Element} node
+ * @returns {Boolean}
+ * @api private
+ */
+function isEmptyNode(node){
+ if(!node.childNodes || node.childNodes.length === 0) {
+ return true;
+ } else {
+ return false;
+ }
+}
+
+function invariant(test, message) {
+ if (!test) {
+ throw new Error(message);
+ }
+}
+
+/**
+ * Parses a Plist XML string. Returns an Object.
+ *
+ * @param {String} xml - the XML String to decode
+ * @returns {Mixed} the decoded value from the Plist XML
+ * @api public
+ */
+
+function parse (xml) {
+ var doc = new DOMParser().parseFromString(xml);
+ invariant(
+ doc.documentElement.nodeName === 'plist',
+ 'malformed document. First element should be '
+ );
+ var plist = parsePlistXML(doc.documentElement);
+
+ // the root node gets interpreted as an Array,
+ // so pull out the inner data first
+ if (plist.length == 1) plist = plist[0];
+
+ return plist;
+}
+
+/**
+ * Convert an XML based plist document into a JSON representation.
+ *
+ * @param {Object} xml_node - current XML node in the plist
+ * @returns {Mixed} built up JSON object
+ * @api private
+ */
+
+function parsePlistXML (node) {
+ var i, new_obj, key, val, new_arr, res, counter, type;
+
+ if (!node)
+ return null;
+
+ if (node.nodeName === 'plist') {
+ new_arr = [];
+ if (isEmptyNode(node)) {
+ return new_arr;
+ }
+ for (i=0; i < node.childNodes.length; i++) {
+ if (!shouldIgnoreNode(node.childNodes[i])) {
+ new_arr.push( parsePlistXML(node.childNodes[i]));
+ }
+ }
+ return new_arr;
+ } else if (node.nodeName === 'dict') {
+ new_obj = {};
+ key = null;
+ counter = 0;
+ if (isEmptyNode(node)) {
+ return new_obj;
+ }
+ for (i=0; i < node.childNodes.length; i++) {
+ if (shouldIgnoreNode(node.childNodes[i])) continue;
+ if (counter % 2 === 0) {
+ invariant(
+ node.childNodes[i].nodeName === 'key',
+ 'Missing key while parsing .'
+ );
+ key = parsePlistXML(node.childNodes[i]);
+ } else {
+ invariant(
+ node.childNodes[i].nodeName !== 'key',
+ 'Unexpected key "'
+ + parsePlistXML(node.childNodes[i])
+ + '" while parsing .'
+ );
+ new_obj[key] = parsePlistXML(node.childNodes[i]);
+ }
+ counter += 1;
+ }
+ if (counter % 2 === 1) {
+ throw new Error('Missing value for "' + key + '" while parsing ');
+ }
+ return new_obj;
+
+ } else if (node.nodeName === 'array') {
+ new_arr = [];
+ if (isEmptyNode(node)) {
+ return new_arr;
+ }
+ for (i=0; i < node.childNodes.length; i++) {
+ if (!shouldIgnoreNode(node.childNodes[i])) {
+ res = parsePlistXML(node.childNodes[i]);
+ if (null != res) new_arr.push(res);
+ }
+ }
+ return new_arr;
+
+ } else if (node.nodeName === '#text') {
+ // TODO: what should we do with text types? (CDATA sections)
+
+ } else if (node.nodeName === 'key') {
+ if (isEmptyNode(node)) {
+ return '';
+ }
+ return node.childNodes[0].nodeValue;
+ } else if (node.nodeName === 'string') {
+ res = '';
+ if (isEmptyNode(node)) {
+ return res;
+ }
+ for (i=0; i < node.childNodes.length; i++) {
+ var type = node.childNodes[i].nodeType;
+ if (type === TEXT_NODE || type === CDATA_NODE) {
+ res += node.childNodes[i].nodeValue;
+ }
+ }
+ return res;
+
+ } else if (node.nodeName === 'integer') {
+ invariant(
+ !isEmptyNode(node),
+ 'Cannot parse "" as integer.'
+ );
+ return parseInt(node.childNodes[0].nodeValue, 10);
+
+ } else if (node.nodeName === 'real') {
+ invariant(
+ !isEmptyNode(node),
+ 'Cannot parse "" as real.'
+ );
+ res = '';
+ for (i=0; i < node.childNodes.length; i++) {
+ if (node.childNodes[i].nodeType === TEXT_NODE) {
+ res += node.childNodes[i].nodeValue;
+ }
+ }
+ return parseFloat(res);
+
+ } else if (node.nodeName === 'data') {
+ res = '';
+ if (isEmptyNode(node)) {
+ return Buffer.from(res, 'base64');
+ }
+ for (i=0; i < node.childNodes.length; i++) {
+ if (node.childNodes[i].nodeType === TEXT_NODE) {
+ res += node.childNodes[i].nodeValue.replace(/\s+/g, '');
+ }
+ }
+ return Buffer.from(res, 'base64');
+
+ } else if (node.nodeName === 'date') {
+ invariant(
+ !isEmptyNode(node),
+ 'Cannot parse "" as Date.'
+ )
+ return new Date(node.childNodes[0].nodeValue);
+
+ } else if (node.nodeName === 'true') {
+ return true;
+
+ } else if (node.nodeName === 'false') {
+ return false;
+ }
+}
+
+}).call(this)}).call(this,require("buffer").Buffer)
+},{"./xmldom/dom-parser":4,"buffer":9}],4:[function(require,module,exports){
+function DOMParser(options){
+ this.options = options ||{locator:{}};
+}
+
+DOMParser.prototype.parseFromString = function(source,mimeType){
+ var options = this.options;
+ var sax = new XMLReader();
+ var domBuilder = options.domBuilder || new DOMHandler();//contentHandler and LexicalHandler
+ var errorHandler = options.errorHandler;
+ var locator = options.locator;
+ var defaultNSMap = options.xmlns||{};
+ var isHTML = /\/x?html?$/.test(mimeType);//mimeType.toLowerCase().indexOf('html') > -1;
+ var entityMap = isHTML?htmlEntity.entityMap:{'lt':'<','gt':'>','amp':'&','quot':'"','apos':"'"};
+ if(locator){
+ domBuilder.setDocumentLocator(locator)
+ }
+
+ sax.errorHandler = buildErrorHandler(errorHandler,domBuilder,locator);
+ sax.domBuilder = options.domBuilder || domBuilder;
+ if(isHTML){
+ defaultNSMap['']= 'http://www.w3.org/1999/xhtml';
+ }
+ defaultNSMap.xml = defaultNSMap.xml || 'http://www.w3.org/XML/1998/namespace';
+ if(source && typeof source === 'string'){
+ sax.parse(source,defaultNSMap,entityMap);
+ }else{
+ sax.errorHandler.error("invalid doc source");
+ }
+ return domBuilder.doc;
+}
+function buildErrorHandler(errorImpl,domBuilder,locator){
+ if(!errorImpl){
+ if(domBuilder instanceof DOMHandler){
+ return domBuilder;
+ }
+ errorImpl = domBuilder ;
+ }
+ var errorHandler = {}
+ var isCallback = errorImpl instanceof Function;
+ locator = locator||{}
+ function build(key){
+ var fn = errorImpl[key];
+ if(!fn && isCallback){
+ fn = errorImpl.length == 2?function(msg){errorImpl(key,msg)}:errorImpl;
+ }
+ errorHandler[key] = fn && function(msg){
+ fn('[xmldom '+key+']\t'+msg+_locator(locator));
+ }||function(){};
+ }
+ build('warning');
+ build('error');
+ build('fatalError');
+ return errorHandler;
+}
+
+//console.log('#\n\n\n\n\n\n\n####')
+/**
+ * +ContentHandler+ErrorHandler
+ * +LexicalHandler+EntityResolver2
+ * -DeclHandler-DTDHandler
+ *
+ * DefaultHandler:EntityResolver, DTDHandler, ContentHandler, ErrorHandler
+ * DefaultHandler2:DefaultHandler,LexicalHandler, DeclHandler, EntityResolver2
+ * @link http://www.saxproject.org/apidoc/org/xml/sax/helpers/DefaultHandler.html
+ */
+function DOMHandler() {
+ this.cdata = false;
+}
+function position(locator,node){
+ node.lineNumber = locator.lineNumber;
+ node.columnNumber = locator.columnNumber;
+}
+/**
+ * @see org.xml.sax.ContentHandler#startDocument
+ * @link http://www.saxproject.org/apidoc/org/xml/sax/ContentHandler.html
+ */
+DOMHandler.prototype = {
+ startDocument : function() {
+ this.doc = new DOMImplementation().createDocument(null, null, null);
+ if (this.locator) {
+ this.doc.documentURI = this.locator.systemId;
+ }
+ },
+ startElement:function(namespaceURI, localName, qName, attrs) {
+ var doc = this.doc;
+ var el = doc.createElementNS(namespaceURI, qName||localName);
+ var len = attrs.length;
+ appendElement(this, el);
+ this.currentElement = el;
+
+ this.locator && position(this.locator,el)
+ for (var i = 0 ; i < len; i++) {
+ var namespaceURI = attrs.getURI(i);
+ var value = attrs.getValue(i);
+ var qName = attrs.getQName(i);
+ var attr = doc.createAttributeNS(namespaceURI, qName);
+ this.locator &&position(attrs.getLocator(i),attr);
+ attr.value = attr.nodeValue = value;
+ el.setAttributeNode(attr)
+ }
+ },
+ endElement:function(namespaceURI, localName, qName) {
+ var current = this.currentElement
+ var tagName = current.tagName;
+ this.currentElement = current.parentNode;
+ },
+ startPrefixMapping:function(prefix, uri) {
+ },
+ endPrefixMapping:function(prefix) {
+ },
+ processingInstruction:function(target, data) {
+ var ins = this.doc.createProcessingInstruction(target, data);
+ this.locator && position(this.locator,ins)
+ appendElement(this, ins);
+ },
+ ignorableWhitespace:function(ch, start, length) {
+ },
+ characters:function(chars, start, length) {
+ chars = _toString.apply(this,arguments)
+ //console.log(chars)
+ if(chars){
+ if (this.cdata) {
+ var charNode = this.doc.createCDATASection(chars);
+ } else {
+ var charNode = this.doc.createTextNode(chars);
+ }
+ if(this.currentElement){
+ this.currentElement.appendChild(charNode);
+ }else if(/^\s*$/.test(chars)){
+ this.doc.appendChild(charNode);
+ //process xml
+ }
+ this.locator && position(this.locator,charNode)
+ }
+ },
+ skippedEntity:function(name) {
+ },
+ endDocument:function() {
+ this.doc.normalize();
+ },
+ setDocumentLocator:function (locator) {
+ if(this.locator = locator){// && !('lineNumber' in locator)){
+ locator.lineNumber = 0;
+ }
+ },
+ //LexicalHandler
+ comment:function(chars, start, length) {
+ chars = _toString.apply(this,arguments)
+ var comm = this.doc.createComment(chars);
+ this.locator && position(this.locator,comm)
+ appendElement(this, comm);
+ },
+
+ startCDATA:function() {
+ //used in characters() methods
+ this.cdata = true;
+ },
+ endCDATA:function() {
+ this.cdata = false;
+ },
+
+ startDTD:function(name, publicId, systemId) {
+ var impl = this.doc.implementation;
+ if (impl && impl.createDocumentType) {
+ var dt = impl.createDocumentType(name, publicId, systemId);
+ this.locator && position(this.locator,dt)
+ appendElement(this, dt);
+ }
+ },
+ /**
+ * @see org.xml.sax.ErrorHandler
+ * @link http://www.saxproject.org/apidoc/org/xml/sax/ErrorHandler.html
+ */
+ warning:function(error) {
+ console.warn('[xmldom warning]\t'+error,_locator(this.locator));
+ },
+ error:function(error) {
+ console.error('[xmldom error]\t'+error,_locator(this.locator));
+ },
+ fatalError:function(error) {
+ throw new ParseError(error, this.locator);
+ }
+}
+function _locator(l){
+ if(l){
+ return '\n@'+(l.systemId ||'')+'#[line:'+l.lineNumber+',col:'+l.columnNumber+']'
+ }
+}
+function _toString(chars,start,length){
+ if(typeof chars == 'string'){
+ return chars.substr(start,length)
+ }else{//java sax connect width xmldom on rhino(what about: "? && !(chars instanceof String)")
+ if(chars.length >= start+length || start){
+ return new java.lang.String(chars,start,length)+'';
+ }
+ return chars;
+ }
+}
+
+/*
+ * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/LexicalHandler.html
+ * used method of org.xml.sax.ext.LexicalHandler:
+ * #comment(chars, start, length)
+ * #startCDATA()
+ * #endCDATA()
+ * #startDTD(name, publicId, systemId)
+ *
+ *
+ * IGNORED method of org.xml.sax.ext.LexicalHandler:
+ * #endDTD()
+ * #startEntity(name)
+ * #endEntity(name)
+ *
+ *
+ * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/DeclHandler.html
+ * IGNORED method of org.xml.sax.ext.DeclHandler
+ * #attributeDecl(eName, aName, type, mode, value)
+ * #elementDecl(name, model)
+ * #externalEntityDecl(name, publicId, systemId)
+ * #internalEntityDecl(name, value)
+ * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/EntityResolver2.html
+ * IGNORED method of org.xml.sax.EntityResolver2
+ * #resolveEntity(String name,String publicId,String baseURI,String systemId)
+ * #resolveEntity(publicId, systemId)
+ * #getExternalSubset(name, baseURI)
+ * @link http://www.saxproject.org/apidoc/org/xml/sax/DTDHandler.html
+ * IGNORED method of org.xml.sax.DTDHandler
+ * #notationDecl(name, publicId, systemId) {};
+ * #unparsedEntityDecl(name, publicId, systemId, notationName) {};
+ */
+"endDTD,startEntity,endEntity,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,resolveEntity,getExternalSubset,notationDecl,unparsedEntityDecl".replace(/\w+/g,function(key){
+ DOMHandler.prototype[key] = function(){return null}
+})
+
+/* Private static helpers treated below as private instance methods, so don't need to add these to the public API; we might use a Relator to also get rid of non-standard public properties */
+function appendElement (hander,node) {
+ if (!hander.currentElement) {
+ hander.doc.appendChild(node);
+ } else {
+ hander.currentElement.appendChild(node);
+ }
+}//appendChild and setAttributeNS are preformance key
+
+//if(typeof require == 'function'){
+var htmlEntity = require('./entities');
+var sax = require('./sax');
+var XMLReader = sax.XMLReader;
+var ParseError = sax.ParseError;
+var DOMImplementation = exports.DOMImplementation = require('./dom').DOMImplementation;
+exports.XMLSerializer = require('./dom').XMLSerializer ;
+exports.DOMParser = DOMParser;
+exports.__DOMHandler = DOMHandler;
+//}
+
+},{"./dom":5,"./entities":6,"./sax":7}],5:[function(require,module,exports){
+function copy(src,dest){
+ for(var p in src){
+ dest[p] = src[p];
+ }
+}
+/**
+^\w+\.prototype\.([_\w]+)\s*=\s*((?:.*\{\s*?[\r\n][\s\S]*?^})|\S.*?(?=[;\r\n]));?
+^\w+\.prototype\.([_\w]+)\s*=\s*(\S.*?(?=[;\r\n]));?
+ */
+function _extends(Class,Super){
+ var pt = Class.prototype;
+ if(!(pt instanceof Super)){
+ function t(){};
+ t.prototype = Super.prototype;
+ t = new t();
+ copy(pt,t);
+ Class.prototype = pt = t;
+ }
+ if(pt.constructor != Class){
+ if(typeof Class != 'function'){
+ console.error("unknow Class:"+Class)
+ }
+ pt.constructor = Class
+ }
+}
+var htmlns = 'http://www.w3.org/1999/xhtml' ;
+// Node Types
+var NodeType = {}
+var ELEMENT_NODE = NodeType.ELEMENT_NODE = 1;
+var ATTRIBUTE_NODE = NodeType.ATTRIBUTE_NODE = 2;
+var TEXT_NODE = NodeType.TEXT_NODE = 3;
+var CDATA_SECTION_NODE = NodeType.CDATA_SECTION_NODE = 4;
+var ENTITY_REFERENCE_NODE = NodeType.ENTITY_REFERENCE_NODE = 5;
+var ENTITY_NODE = NodeType.ENTITY_NODE = 6;
+var PROCESSING_INSTRUCTION_NODE = NodeType.PROCESSING_INSTRUCTION_NODE = 7;
+var COMMENT_NODE = NodeType.COMMENT_NODE = 8;
+var DOCUMENT_NODE = NodeType.DOCUMENT_NODE = 9;
+var DOCUMENT_TYPE_NODE = NodeType.DOCUMENT_TYPE_NODE = 10;
+var DOCUMENT_FRAGMENT_NODE = NodeType.DOCUMENT_FRAGMENT_NODE = 11;
+var NOTATION_NODE = NodeType.NOTATION_NODE = 12;
+
+// ExceptionCode
+var ExceptionCode = {}
+var ExceptionMessage = {};
+var INDEX_SIZE_ERR = ExceptionCode.INDEX_SIZE_ERR = ((ExceptionMessage[1]="Index size error"),1);
+var DOMSTRING_SIZE_ERR = ExceptionCode.DOMSTRING_SIZE_ERR = ((ExceptionMessage[2]="DOMString size error"),2);
+var HIERARCHY_REQUEST_ERR = ExceptionCode.HIERARCHY_REQUEST_ERR = ((ExceptionMessage[3]="Hierarchy request error"),3);
+var WRONG_DOCUMENT_ERR = ExceptionCode.WRONG_DOCUMENT_ERR = ((ExceptionMessage[4]="Wrong document"),4);
+var INVALID_CHARACTER_ERR = ExceptionCode.INVALID_CHARACTER_ERR = ((ExceptionMessage[5]="Invalid character"),5);
+var NO_DATA_ALLOWED_ERR = ExceptionCode.NO_DATA_ALLOWED_ERR = ((ExceptionMessage[6]="No data allowed"),6);
+var NO_MODIFICATION_ALLOWED_ERR = ExceptionCode.NO_MODIFICATION_ALLOWED_ERR = ((ExceptionMessage[7]="No modification allowed"),7);
+var NOT_FOUND_ERR = ExceptionCode.NOT_FOUND_ERR = ((ExceptionMessage[8]="Not found"),8);
+var NOT_SUPPORTED_ERR = ExceptionCode.NOT_SUPPORTED_ERR = ((ExceptionMessage[9]="Not supported"),9);
+var INUSE_ATTRIBUTE_ERR = ExceptionCode.INUSE_ATTRIBUTE_ERR = ((ExceptionMessage[10]="Attribute in use"),10);
+//level2
+var INVALID_STATE_ERR = ExceptionCode.INVALID_STATE_ERR = ((ExceptionMessage[11]="Invalid state"),11);
+var SYNTAX_ERR = ExceptionCode.SYNTAX_ERR = ((ExceptionMessage[12]="Syntax error"),12);
+var INVALID_MODIFICATION_ERR = ExceptionCode.INVALID_MODIFICATION_ERR = ((ExceptionMessage[13]="Invalid modification"),13);
+var NAMESPACE_ERR = ExceptionCode.NAMESPACE_ERR = ((ExceptionMessage[14]="Invalid namespace"),14);
+var INVALID_ACCESS_ERR = ExceptionCode.INVALID_ACCESS_ERR = ((ExceptionMessage[15]="Invalid access"),15);
+
+/**
+ * DOM Level 2
+ * Object DOMException
+ * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html
+ * @see http://www.w3.org/TR/REC-DOM-Level-1/ecma-script-language-binding.html
+ */
+function DOMException(code, message) {
+ if(message instanceof Error){
+ var error = message;
+ }else{
+ error = this;
+ Error.call(this, ExceptionMessage[code]);
+ this.message = ExceptionMessage[code];
+ if(Error.captureStackTrace) Error.captureStackTrace(this, DOMException);
+ }
+ error.code = code;
+ if(message) this.message = this.message + ": " + message;
+ return error;
+};
+DOMException.prototype = Error.prototype;
+copy(ExceptionCode,DOMException)
+/**
+ * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-536297177
+ * The NodeList interface provides the abstraction of an ordered collection of nodes, without defining or constraining how this collection is implemented. NodeList objects in the DOM are live.
+ * The items in the NodeList are accessible via an integral index, starting from 0.
+ */
+function NodeList() {
+};
+NodeList.prototype = {
+ /**
+ * The number of nodes in the list. The range of valid child node indices is 0 to length-1 inclusive.
+ * @standard level1
+ */
+ length:0,
+ /**
+ * Returns the indexth item in the collection. If index is greater than or equal to the number of nodes in the list, this returns null.
+ * @standard level1
+ * @param index unsigned long
+ * Index into the collection.
+ * @return Node
+ * The node at the indexth position in the NodeList, or null if that is not a valid index.
+ */
+ item: function(index) {
+ return this[index] || null;
+ },
+ toString:function(isHTML,nodeFilter){
+ for(var buf = [], i = 0;i=0){
+ var lastIndex = list.length-1
+ while(i0 || key == 'xmlns'){
+// return null;
+// }
+ //console.log()
+ var i = this.length;
+ while(i--){
+ var attr = this[i];
+ //console.log(attr.nodeName,key)
+ if(attr.nodeName == key){
+ return attr;
+ }
+ }
+ },
+ setNamedItem: function(attr) {
+ var el = attr.ownerElement;
+ if(el && el!=this._ownerElement){
+ throw new DOMException(INUSE_ATTRIBUTE_ERR);
+ }
+ var oldAttr = this.getNamedItem(attr.nodeName);
+ _addNamedNode(this._ownerElement,this,attr,oldAttr);
+ return oldAttr;
+ },
+ /* returns Node */
+ setNamedItemNS: function(attr) {// raises: WRONG_DOCUMENT_ERR,NO_MODIFICATION_ALLOWED_ERR,INUSE_ATTRIBUTE_ERR
+ var el = attr.ownerElement, oldAttr;
+ if(el && el!=this._ownerElement){
+ throw new DOMException(INUSE_ATTRIBUTE_ERR);
+ }
+ oldAttr = this.getNamedItemNS(attr.namespaceURI,attr.localName);
+ _addNamedNode(this._ownerElement,this,attr,oldAttr);
+ return oldAttr;
+ },
+
+ /* returns Node */
+ removeNamedItem: function(key) {
+ var attr = this.getNamedItem(key);
+ _removeNamedNode(this._ownerElement,this,attr);
+ return attr;
+
+
+ },// raises: NOT_FOUND_ERR,NO_MODIFICATION_ALLOWED_ERR
+
+ //for level2
+ removeNamedItemNS:function(namespaceURI,localName){
+ var attr = this.getNamedItemNS(namespaceURI,localName);
+ _removeNamedNode(this._ownerElement,this,attr);
+ return attr;
+ },
+ getNamedItemNS: function(namespaceURI, localName) {
+ var i = this.length;
+ while(i--){
+ var node = this[i];
+ if(node.localName == localName && node.namespaceURI == namespaceURI){
+ return node;
+ }
+ }
+ return null;
+ }
+};
+/**
+ * @see http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#ID-102161490
+ */
+function DOMImplementation(/* Object */ features) {
+ this._features = {};
+ if (features) {
+ for (var feature in features) {
+ this._features = features[feature];
+ }
+ }
+};
+
+DOMImplementation.prototype = {
+ hasFeature: function(/* string */ feature, /* string */ version) {
+ var versions = this._features[feature.toLowerCase()];
+ if (versions && (!version || version in versions)) {
+ return true;
+ } else {
+ return false;
+ }
+ },
+ // Introduced in DOM Level 2:
+ createDocument:function(namespaceURI, qualifiedName, doctype){// raises:INVALID_CHARACTER_ERR,NAMESPACE_ERR,WRONG_DOCUMENT_ERR
+ var doc = new Document();
+ doc.implementation = this;
+ doc.childNodes = new NodeList();
+ doc.doctype = doctype;
+ if(doctype){
+ doc.appendChild(doctype);
+ }
+ if(qualifiedName){
+ var root = doc.createElementNS(namespaceURI,qualifiedName);
+ doc.appendChild(root);
+ }
+ return doc;
+ },
+ // Introduced in DOM Level 2:
+ createDocumentType:function(qualifiedName, publicId, systemId){// raises:INVALID_CHARACTER_ERR,NAMESPACE_ERR
+ var node = new DocumentType();
+ node.name = qualifiedName;
+ node.nodeName = qualifiedName;
+ node.publicId = publicId;
+ node.systemId = systemId;
+ // Introduced in DOM Level 2:
+ //readonly attribute DOMString internalSubset;
+
+ //TODO:..
+ // readonly attribute NamedNodeMap entities;
+ // readonly attribute NamedNodeMap notations;
+ return node;
+ }
+};
+
+
+/**
+ * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-1950641247
+ */
+
+function Node() {
+};
+
+Node.prototype = {
+ firstChild : null,
+ lastChild : null,
+ previousSibling : null,
+ nextSibling : null,
+ attributes : null,
+ parentNode : null,
+ childNodes : null,
+ ownerDocument : null,
+ nodeValue : null,
+ namespaceURI : null,
+ prefix : null,
+ localName : null,
+ // Modified in DOM Level 2:
+ insertBefore:function(newChild, refChild){//raises
+ return _insertBefore(this,newChild,refChild);
+ },
+ replaceChild:function(newChild, oldChild){//raises
+ this.insertBefore(newChild,oldChild);
+ if(oldChild){
+ this.removeChild(oldChild);
+ }
+ },
+ removeChild:function(oldChild){
+ return _removeChild(this,oldChild);
+ },
+ appendChild:function(newChild){
+ return this.insertBefore(newChild,null);
+ },
+ hasChildNodes:function(){
+ return this.firstChild != null;
+ },
+ cloneNode:function(deep){
+ return cloneNode(this.ownerDocument||this,this,deep);
+ },
+ // Modified in DOM Level 2:
+ normalize:function(){
+ var child = this.firstChild;
+ while(child){
+ var next = child.nextSibling;
+ if(next && next.nodeType == TEXT_NODE && child.nodeType == TEXT_NODE){
+ this.removeChild(next);
+ child.appendData(next.data);
+ }else{
+ child.normalize();
+ child = next;
+ }
+ }
+ },
+ // Introduced in DOM Level 2:
+ isSupported:function(feature, version){
+ return this.ownerDocument.implementation.hasFeature(feature,version);
+ },
+ // Introduced in DOM Level 2:
+ hasAttributes:function(){
+ return this.attributes.length>0;
+ },
+ lookupPrefix:function(namespaceURI){
+ var el = this;
+ while(el){
+ var map = el._nsMap;
+ //console.dir(map)
+ if(map){
+ for(var n in map){
+ if(map[n] == namespaceURI){
+ return n;
+ }
+ }
+ }
+ el = el.nodeType == ATTRIBUTE_NODE?el.ownerDocument : el.parentNode;
+ }
+ return null;
+ },
+ // Introduced in DOM Level 3:
+ lookupNamespaceURI:function(prefix){
+ var el = this;
+ while(el){
+ var map = el._nsMap;
+ //console.dir(map)
+ if(map){
+ if(prefix in map){
+ return map[prefix] ;
+ }
+ }
+ el = el.nodeType == ATTRIBUTE_NODE?el.ownerDocument : el.parentNode;
+ }
+ return null;
+ },
+ // Introduced in DOM Level 3:
+ isDefaultNamespace:function(namespaceURI){
+ var prefix = this.lookupPrefix(namespaceURI);
+ return prefix == null;
+ }
+};
+
+
+function _xmlEncoder(c){
+ return c == '<' && '<' ||
+ c == '>' && '>' ||
+ c == '&' && '&' ||
+ c == '"' && '"' ||
+ ''+c.charCodeAt()+';'
+}
+
+
+copy(NodeType,Node);
+copy(NodeType,Node.prototype);
+
+/**
+ * @param callback return true for continue,false for break
+ * @return boolean true: break visit;
+ */
+function _visitNode(node,callback){
+ if(callback(node)){
+ return true;
+ }
+ if(node = node.firstChild){
+ do{
+ if(_visitNode(node,callback)){return true}
+ }while(node=node.nextSibling)
+ }
+}
+
+
+
+function Document(){
+}
+function _onAddAttribute(doc,el,newAttr){
+ doc && doc._inc++;
+ var ns = newAttr.namespaceURI ;
+ if(ns == 'http://www.w3.org/2000/xmlns/'){
+ //update namespace
+ el._nsMap[newAttr.prefix?newAttr.localName:''] = newAttr.value
+ }
+}
+function _onRemoveAttribute(doc,el,newAttr,remove){
+ doc && doc._inc++;
+ var ns = newAttr.namespaceURI ;
+ if(ns == 'http://www.w3.org/2000/xmlns/'){
+ //update namespace
+ delete el._nsMap[newAttr.prefix?newAttr.localName:'']
+ }
+}
+function _onUpdateChild(doc,el,newChild){
+ if(doc && doc._inc){
+ doc._inc++;
+ //update childNodes
+ var cs = el.childNodes;
+ if(newChild){
+ cs[cs.length++] = newChild;
+ }else{
+ //console.log(1)
+ var child = el.firstChild;
+ var i = 0;
+ while(child){
+ cs[i++] = child;
+ child =child.nextSibling;
+ }
+ cs.length = i;
+ }
+ }
+}
+
+/**
+ * attributes;
+ * children;
+ *
+ * writeable properties:
+ * nodeValue,Attr:value,CharacterData:data
+ * prefix
+ */
+function _removeChild(parentNode,child){
+ var previous = child.previousSibling;
+ var next = child.nextSibling;
+ if(previous){
+ previous.nextSibling = next;
+ }else{
+ parentNode.firstChild = next
+ }
+ if(next){
+ next.previousSibling = previous;
+ }else{
+ parentNode.lastChild = previous;
+ }
+ _onUpdateChild(parentNode.ownerDocument,parentNode);
+ return child;
+}
+/**
+ * preformance key(refChild == null)
+ */
+function _insertBefore(parentNode,newChild,nextChild){
+ var cp = newChild.parentNode;
+ if(cp){
+ cp.removeChild(newChild);//remove and update
+ }
+ if(newChild.nodeType === DOCUMENT_FRAGMENT_NODE){
+ var newFirst = newChild.firstChild;
+ if (newFirst == null) {
+ return newChild;
+ }
+ var newLast = newChild.lastChild;
+ }else{
+ newFirst = newLast = newChild;
+ }
+ var pre = nextChild ? nextChild.previousSibling : parentNode.lastChild;
+
+ newFirst.previousSibling = pre;
+ newLast.nextSibling = nextChild;
+
+
+ if(pre){
+ pre.nextSibling = newFirst;
+ }else{
+ parentNode.firstChild = newFirst;
+ }
+ if(nextChild == null){
+ parentNode.lastChild = newLast;
+ }else{
+ nextChild.previousSibling = newLast;
+ }
+ do{
+ newFirst.parentNode = parentNode;
+ }while(newFirst !== newLast && (newFirst= newFirst.nextSibling))
+ _onUpdateChild(parentNode.ownerDocument||parentNode,parentNode);
+ //console.log(parentNode.lastChild.nextSibling == null)
+ if (newChild.nodeType == DOCUMENT_FRAGMENT_NODE) {
+ newChild.firstChild = newChild.lastChild = null;
+ }
+ return newChild;
+}
+function _appendSingleChild(parentNode,newChild){
+ var cp = newChild.parentNode;
+ if(cp){
+ var pre = parentNode.lastChild;
+ cp.removeChild(newChild);//remove and update
+ var pre = parentNode.lastChild;
+ }
+ var pre = parentNode.lastChild;
+ newChild.parentNode = parentNode;
+ newChild.previousSibling = pre;
+ newChild.nextSibling = null;
+ if(pre){
+ pre.nextSibling = newChild;
+ }else{
+ parentNode.firstChild = newChild;
+ }
+ parentNode.lastChild = newChild;
+ _onUpdateChild(parentNode.ownerDocument,parentNode,newChild);
+ return newChild;
+ //console.log("__aa",parentNode.lastChild.nextSibling == null)
+}
+Document.prototype = {
+ //implementation : null,
+ nodeName : '#document',
+ nodeType : DOCUMENT_NODE,
+ doctype : null,
+ documentElement : null,
+ _inc : 1,
+
+ insertBefore : function(newChild, refChild){//raises
+ if(newChild.nodeType == DOCUMENT_FRAGMENT_NODE){
+ var child = newChild.firstChild;
+ while(child){
+ var next = child.nextSibling;
+ this.insertBefore(child,refChild);
+ child = next;
+ }
+ return newChild;
+ }
+ if(this.documentElement == null && newChild.nodeType == ELEMENT_NODE){
+ this.documentElement = newChild;
+ }
+
+ return _insertBefore(this,newChild,refChild),(newChild.ownerDocument = this),newChild;
+ },
+ removeChild : function(oldChild){
+ if(this.documentElement == oldChild){
+ this.documentElement = null;
+ }
+ return _removeChild(this,oldChild);
+ },
+ // Introduced in DOM Level 2:
+ importNode : function(importedNode,deep){
+ return importNode(this,importedNode,deep);
+ },
+ // Introduced in DOM Level 2:
+ getElementById : function(id){
+ var rtv = null;
+ _visitNode(this.documentElement,function(node){
+ if(node.nodeType == ELEMENT_NODE){
+ if(node.getAttribute('id') == id){
+ rtv = node;
+ return true;
+ }
+ }
+ })
+ return rtv;
+ },
+
+ getElementsByClassName: function(className) {
+ var pattern = new RegExp("(^|\\s)" + className + "(\\s|$)");
+ return new LiveNodeList(this, function(base) {
+ var ls = [];
+ _visitNode(base.documentElement, function(node) {
+ if(node !== base && node.nodeType == ELEMENT_NODE) {
+ if(pattern.test(node.getAttribute('class'))) {
+ ls.push(node);
+ }
+ }
+ });
+ return ls;
+ });
+ },
+
+ //document factory method:
+ createElement : function(tagName){
+ var node = new Element();
+ node.ownerDocument = this;
+ node.nodeName = tagName;
+ node.tagName = tagName;
+ node.childNodes = new NodeList();
+ var attrs = node.attributes = new NamedNodeMap();
+ attrs._ownerElement = node;
+ return node;
+ },
+ createDocumentFragment : function(){
+ var node = new DocumentFragment();
+ node.ownerDocument = this;
+ node.childNodes = new NodeList();
+ return node;
+ },
+ createTextNode : function(data){
+ var node = new Text();
+ node.ownerDocument = this;
+ node.appendData(data)
+ return node;
+ },
+ createComment : function(data){
+ var node = new Comment();
+ node.ownerDocument = this;
+ node.appendData(data)
+ return node;
+ },
+ createCDATASection : function(data){
+ var node = new CDATASection();
+ node.ownerDocument = this;
+ node.appendData(data)
+ return node;
+ },
+ createProcessingInstruction : function(target,data){
+ var node = new ProcessingInstruction();
+ node.ownerDocument = this;
+ node.tagName = node.target = target;
+ node.nodeValue= node.data = data;
+ return node;
+ },
+ createAttribute : function(name){
+ var node = new Attr();
+ node.ownerDocument = this;
+ node.name = name;
+ node.nodeName = name;
+ node.localName = name;
+ node.specified = true;
+ return node;
+ },
+ createEntityReference : function(name){
+ var node = new EntityReference();
+ node.ownerDocument = this;
+ node.nodeName = name;
+ return node;
+ },
+ // Introduced in DOM Level 2:
+ createElementNS : function(namespaceURI,qualifiedName){
+ var node = new Element();
+ var pl = qualifiedName.split(':');
+ var attrs = node.attributes = new NamedNodeMap();
+ node.childNodes = new NodeList();
+ node.ownerDocument = this;
+ node.nodeName = qualifiedName;
+ node.tagName = qualifiedName;
+ node.namespaceURI = namespaceURI;
+ if(pl.length == 2){
+ node.prefix = pl[0];
+ node.localName = pl[1];
+ }else{
+ //el.prefix = null;
+ node.localName = qualifiedName;
+ }
+ attrs._ownerElement = node;
+ return node;
+ },
+ // Introduced in DOM Level 2:
+ createAttributeNS : function(namespaceURI,qualifiedName){
+ var node = new Attr();
+ var pl = qualifiedName.split(':');
+ node.ownerDocument = this;
+ node.nodeName = qualifiedName;
+ node.name = qualifiedName;
+ node.namespaceURI = namespaceURI;
+ node.specified = true;
+ if(pl.length == 2){
+ node.prefix = pl[0];
+ node.localName = pl[1];
+ }else{
+ //el.prefix = null;
+ node.localName = qualifiedName;
+ }
+ return node;
+ }
+};
+_extends(Document,Node);
+
+
+function Element() {
+ this._nsMap = {};
+};
+Element.prototype = {
+ nodeType : ELEMENT_NODE,
+ hasAttribute : function(name){
+ return this.getAttributeNode(name)!=null;
+ },
+ getAttribute : function(name){
+ var attr = this.getAttributeNode(name);
+ return attr && attr.value || '';
+ },
+ getAttributeNode : function(name){
+ return this.attributes.getNamedItem(name);
+ },
+ setAttribute : function(name, value){
+ var attr = this.ownerDocument.createAttribute(name);
+ attr.value = attr.nodeValue = "" + value;
+ this.setAttributeNode(attr)
+ },
+ removeAttribute : function(name){
+ var attr = this.getAttributeNode(name)
+ attr && this.removeAttributeNode(attr);
+ },
+
+ //four real opeartion method
+ appendChild:function(newChild){
+ if(newChild.nodeType === DOCUMENT_FRAGMENT_NODE){
+ return this.insertBefore(newChild,null);
+ }else{
+ return _appendSingleChild(this,newChild);
+ }
+ },
+ setAttributeNode : function(newAttr){
+ return this.attributes.setNamedItem(newAttr);
+ },
+ setAttributeNodeNS : function(newAttr){
+ return this.attributes.setNamedItemNS(newAttr);
+ },
+ removeAttributeNode : function(oldAttr){
+ //console.log(this == oldAttr.ownerElement)
+ return this.attributes.removeNamedItem(oldAttr.nodeName);
+ },
+ //get real attribute name,and remove it by removeAttributeNode
+ removeAttributeNS : function(namespaceURI, localName){
+ var old = this.getAttributeNodeNS(namespaceURI, localName);
+ old && this.removeAttributeNode(old);
+ },
+
+ hasAttributeNS : function(namespaceURI, localName){
+ return this.getAttributeNodeNS(namespaceURI, localName)!=null;
+ },
+ getAttributeNS : function(namespaceURI, localName){
+ var attr = this.getAttributeNodeNS(namespaceURI, localName);
+ return attr && attr.value || '';
+ },
+ setAttributeNS : function(namespaceURI, qualifiedName, value){
+ var attr = this.ownerDocument.createAttributeNS(namespaceURI, qualifiedName);
+ attr.value = attr.nodeValue = "" + value;
+ this.setAttributeNode(attr)
+ },
+ getAttributeNodeNS : function(namespaceURI, localName){
+ return this.attributes.getNamedItemNS(namespaceURI, localName);
+ },
+
+ getElementsByTagName : function(tagName){
+ return new LiveNodeList(this,function(base){
+ var ls = [];
+ _visitNode(base,function(node){
+ if(node !== base && node.nodeType == ELEMENT_NODE && (tagName === '*' || node.tagName == tagName)){
+ ls.push(node);
+ }
+ });
+ return ls;
+ });
+ },
+ getElementsByTagNameNS : function(namespaceURI, localName){
+ return new LiveNodeList(this,function(base){
+ var ls = [];
+ _visitNode(base,function(node){
+ if(node !== base && node.nodeType === ELEMENT_NODE && (namespaceURI === '*' || node.namespaceURI === namespaceURI) && (localName === '*' || node.localName == localName)){
+ ls.push(node);
+ }
+ });
+ return ls;
+
+ });
+ }
+};
+Document.prototype.getElementsByTagName = Element.prototype.getElementsByTagName;
+Document.prototype.getElementsByTagNameNS = Element.prototype.getElementsByTagNameNS;
+
+
+_extends(Element,Node);
+function Attr() {
+};
+Attr.prototype.nodeType = ATTRIBUTE_NODE;
+_extends(Attr,Node);
+
+
+function CharacterData() {
+};
+CharacterData.prototype = {
+ data : '',
+ substringData : function(offset, count) {
+ return this.data.substring(offset, offset+count);
+ },
+ appendData: function(text) {
+ text = this.data+text;
+ this.nodeValue = this.data = text;
+ this.length = text.length;
+ },
+ insertData: function(offset,text) {
+ this.replaceData(offset,0,text);
+
+ },
+ appendChild:function(newChild){
+ throw new Error(ExceptionMessage[HIERARCHY_REQUEST_ERR])
+ },
+ deleteData: function(offset, count) {
+ this.replaceData(offset,count,"");
+ },
+ replaceData: function(offset, count, text) {
+ var start = this.data.substring(0,offset);
+ var end = this.data.substring(offset+count);
+ text = start + text + end;
+ this.nodeValue = this.data = text;
+ this.length = text.length;
+ }
+}
+_extends(CharacterData,Node);
+function Text() {
+};
+Text.prototype = {
+ nodeName : "#text",
+ nodeType : TEXT_NODE,
+ splitText : function(offset) {
+ var text = this.data;
+ var newText = text.substring(offset);
+ text = text.substring(0, offset);
+ this.data = this.nodeValue = text;
+ this.length = text.length;
+ var newNode = this.ownerDocument.createTextNode(newText);
+ if(this.parentNode){
+ this.parentNode.insertBefore(newNode, this.nextSibling);
+ }
+ return newNode;
+ }
+}
+_extends(Text,CharacterData);
+function Comment() {
+};
+Comment.prototype = {
+ nodeName : "#comment",
+ nodeType : COMMENT_NODE
+}
+_extends(Comment,CharacterData);
+
+function CDATASection() {
+};
+CDATASection.prototype = {
+ nodeName : "#cdata-section",
+ nodeType : CDATA_SECTION_NODE
+}
+_extends(CDATASection,CharacterData);
+
+
+function DocumentType() {
+};
+DocumentType.prototype.nodeType = DOCUMENT_TYPE_NODE;
+_extends(DocumentType,Node);
+
+function Notation() {
+};
+Notation.prototype.nodeType = NOTATION_NODE;
+_extends(Notation,Node);
+
+function Entity() {
+};
+Entity.prototype.nodeType = ENTITY_NODE;
+_extends(Entity,Node);
+
+function EntityReference() {
+};
+EntityReference.prototype.nodeType = ENTITY_REFERENCE_NODE;
+_extends(EntityReference,Node);
+
+function DocumentFragment() {
+};
+DocumentFragment.prototype.nodeName = "#document-fragment";
+DocumentFragment.prototype.nodeType = DOCUMENT_FRAGMENT_NODE;
+_extends(DocumentFragment,Node);
+
+
+function ProcessingInstruction() {
+}
+ProcessingInstruction.prototype.nodeType = PROCESSING_INSTRUCTION_NODE;
+_extends(ProcessingInstruction,Node);
+function XMLSerializer(){}
+XMLSerializer.prototype.serializeToString = function(node,isHtml,nodeFilter){
+ return nodeSerializeToString.call(node,isHtml,nodeFilter);
+}
+Node.prototype.toString = nodeSerializeToString;
+function nodeSerializeToString(isHtml,nodeFilter){
+ var buf = [];
+ var refNode = this.nodeType == 9 && this.documentElement || this;
+ var prefix = refNode.prefix;
+ var uri = refNode.namespaceURI;
+
+ if(uri && prefix == null){
+ //console.log(prefix)
+ var prefix = refNode.lookupPrefix(uri);
+ if(prefix == null){
+ //isHTML = true;
+ var visibleNamespaces=[
+ {namespace:uri,prefix:null}
+ //{namespace:uri,prefix:''}
+ ]
+ }
+ }
+ serializeToString(this,buf,isHtml,nodeFilter,visibleNamespaces);
+ //console.log('###',this.nodeType,uri,prefix,buf.join(''))
+ return buf.join('');
+}
+function needNamespaceDefine(node,isHTML, visibleNamespaces) {
+ var prefix = node.prefix||'';
+ var uri = node.namespaceURI;
+ if (!prefix && !uri){
+ return false;
+ }
+ if (prefix === "xml" && uri === "http://www.w3.org/XML/1998/namespace"
+ || uri == 'http://www.w3.org/2000/xmlns/'){
+ return false;
+ }
+
+ var i = visibleNamespaces.length
+ //console.log('@@@@',node.tagName,prefix,uri,visibleNamespaces)
+ while (i--) {
+ var ns = visibleNamespaces[i];
+ // get namespace prefix
+ //console.log(node.nodeType,node.tagName,ns.prefix,prefix)
+ if (ns.prefix == prefix){
+ return ns.namespace != uri;
+ }
+ }
+ //console.log(isHTML,uri,prefix=='')
+ //if(isHTML && prefix ==null && uri == 'http://www.w3.org/1999/xhtml'){
+ // return false;
+ //}
+ //node.flag = '11111'
+ //console.error(3,true,node.flag,node.prefix,node.namespaceURI)
+ return true;
+}
+function serializeToString(node,buf,isHTML,nodeFilter,visibleNamespaces){
+ if(nodeFilter){
+ node = nodeFilter(node);
+ if(node){
+ if(typeof node == 'string'){
+ buf.push(node);
+ return;
+ }
+ }else{
+ return;
+ }
+ //buf.sort.apply(attrs, attributeSorter);
+ }
+ switch(node.nodeType){
+ case ELEMENT_NODE:
+ if (!visibleNamespaces) visibleNamespaces = [];
+ var startVisibleNamespaces = visibleNamespaces.length;
+ var attrs = node.attributes;
+ var len = attrs.length;
+ var child = node.firstChild;
+ var nodeName = node.tagName;
+
+ isHTML = (htmlns === node.namespaceURI) ||isHTML
+ buf.push('<',nodeName);
+
+
+
+ for(var i=0;i');
+ //if is cdata child node
+ if(isHTML && /^script$/i.test(nodeName)){
+ while(child){
+ if(child.data){
+ buf.push(child.data);
+ }else{
+ serializeToString(child,buf,isHTML,nodeFilter,visibleNamespaces);
+ }
+ child = child.nextSibling;
+ }
+ }else
+ {
+ while(child){
+ serializeToString(child,buf,isHTML,nodeFilter,visibleNamespaces);
+ child = child.nextSibling;
+ }
+ }
+ buf.push('',nodeName,'>');
+ }else{
+ buf.push('/>');
+ }
+ // remove added visible namespaces
+ //visibleNamespaces.length = startVisibleNamespaces;
+ return;
+ case DOCUMENT_NODE:
+ case DOCUMENT_FRAGMENT_NODE:
+ var child = node.firstChild;
+ while(child){
+ serializeToString(child,buf,isHTML,nodeFilter,visibleNamespaces);
+ child = child.nextSibling;
+ }
+ return;
+ case ATTRIBUTE_NODE:
+ /**
+ * Well-formedness constraint: No < in Attribute Values
+ * The replacement text of any entity referred to directly or indirectly in an attribute value must not contain a <.
+ * @see https://www.w3.org/TR/xml/#CleanAttrVals
+ * @see https://www.w3.org/TR/xml/#NT-AttValue
+ */
+ return buf.push(' ', node.name, '="', node.value.replace(/[<&"]/g,_xmlEncoder), '"');
+ case TEXT_NODE:
+ /**
+ * The ampersand character (&) and the left angle bracket (<) must not appear in their literal form,
+ * except when used as markup delimiters, or within a comment, a processing instruction, or a CDATA section.
+ * If they are needed elsewhere, they must be escaped using either numeric character references or the strings
+ * `&` and `<` respectively.
+ * The right angle bracket (>) may be represented using the string " > ", and must, for compatibility,
+ * be escaped using either `>` or a character reference when it appears in the string `]]>` in content,
+ * when that string is not marking the end of a CDATA section.
+ *
+ * In the content of elements, character data is any string of characters
+ * which does not contain the start-delimiter of any markup
+ * and does not include the CDATA-section-close delimiter, `]]>`.
+ *
+ * @see https://www.w3.org/TR/xml/#NT-CharData
+ */
+ return buf.push(node.data
+ .replace(/[<&]/g,_xmlEncoder)
+ .replace(/]]>/g, ']]>')
+ );
+ case CDATA_SECTION_NODE:
+ return buf.push( '');
+ case COMMENT_NODE:
+ return buf.push( "");
+ case DOCUMENT_TYPE_NODE:
+ var pubid = node.publicId;
+ var sysid = node.systemId;
+ buf.push('');
+ }else if(sysid && sysid!='.'){
+ buf.push(' SYSTEM ', sysid, '>');
+ }else{
+ var sub = node.internalSubset;
+ if(sub){
+ buf.push(" [",sub,"]");
+ }
+ buf.push(">");
+ }
+ return;
+ case PROCESSING_INSTRUCTION_NODE:
+ return buf.push( "",node.target," ",node.data,"?>");
+ case ENTITY_REFERENCE_NODE:
+ return buf.push( '&',node.nodeName,';');
+ //case ENTITY_NODE:
+ //case NOTATION_NODE:
+ default:
+ buf.push('??',node.nodeName);
+ }
+}
+function importNode(doc,node,deep){
+ var node2;
+ switch (node.nodeType) {
+ case ELEMENT_NODE:
+ node2 = node.cloneNode(false);
+ node2.ownerDocument = doc;
+ //var attrs = node2.attributes;
+ //var len = attrs.length;
+ //for(var i=0;i',
+ amp: '&',
+ quot: '"',
+ apos: "'",
+ Agrave: "À",
+ Aacute: "Á",
+ Acirc: "Â",
+ Atilde: "Ã",
+ Auml: "Ä",
+ Aring: "Å",
+ AElig: "Æ",
+ Ccedil: "Ç",
+ Egrave: "È",
+ Eacute: "É",
+ Ecirc: "Ê",
+ Euml: "Ë",
+ Igrave: "Ì",
+ Iacute: "Í",
+ Icirc: "Î",
+ Iuml: "Ï",
+ ETH: "Ð",
+ Ntilde: "Ñ",
+ Ograve: "Ò",
+ Oacute: "Ó",
+ Ocirc: "Ô",
+ Otilde: "Õ",
+ Ouml: "Ö",
+ Oslash: "Ø",
+ Ugrave: "Ù",
+ Uacute: "Ú",
+ Ucirc: "Û",
+ Uuml: "Ü",
+ Yacute: "Ý",
+ THORN: "Þ",
+ szlig: "ß",
+ agrave: "à",
+ aacute: "á",
+ acirc: "â",
+ atilde: "ã",
+ auml: "ä",
+ aring: "å",
+ aelig: "æ",
+ ccedil: "ç",
+ egrave: "è",
+ eacute: "é",
+ ecirc: "ê",
+ euml: "ë",
+ igrave: "ì",
+ iacute: "í",
+ icirc: "î",
+ iuml: "ï",
+ eth: "ð",
+ ntilde: "ñ",
+ ograve: "ò",
+ oacute: "ó",
+ ocirc: "ô",
+ otilde: "õ",
+ ouml: "ö",
+ oslash: "ø",
+ ugrave: "ù",
+ uacute: "ú",
+ ucirc: "û",
+ uuml: "ü",
+ yacute: "ý",
+ thorn: "þ",
+ yuml: "ÿ",
+ nbsp: "\u00a0",
+ iexcl: "¡",
+ cent: "¢",
+ pound: "£",
+ curren: "¤",
+ yen: "¥",
+ brvbar: "¦",
+ sect: "§",
+ uml: "¨",
+ copy: "©",
+ ordf: "ª",
+ laquo: "«",
+ not: "¬",
+ shy: "",
+ reg: "®",
+ macr: "¯",
+ deg: "°",
+ plusmn: "±",
+ sup2: "²",
+ sup3: "³",
+ acute: "´",
+ micro: "µ",
+ para: "¶",
+ middot: "·",
+ cedil: "¸",
+ sup1: "¹",
+ ordm: "º",
+ raquo: "»",
+ frac14: "¼",
+ frac12: "½",
+ frac34: "¾",
+ iquest: "¿",
+ times: "×",
+ divide: "÷",
+ forall: "∀",
+ part: "∂",
+ exist: "∃",
+ empty: "∅",
+ nabla: "∇",
+ isin: "∈",
+ notin: "∉",
+ ni: "∋",
+ prod: "∏",
+ sum: "∑",
+ minus: "−",
+ lowast: "∗",
+ radic: "√",
+ prop: "∝",
+ infin: "∞",
+ ang: "∠",
+ and: "∧",
+ or: "∨",
+ cap: "∩",
+ cup: "∪",
+ 'int': "∫",
+ there4: "∴",
+ sim: "∼",
+ cong: "≅",
+ asymp: "≈",
+ ne: "≠",
+ equiv: "≡",
+ le: "≤",
+ ge: "≥",
+ sub: "⊂",
+ sup: "⊃",
+ nsub: "⊄",
+ sube: "⊆",
+ supe: "⊇",
+ oplus: "⊕",
+ otimes: "⊗",
+ perp: "⊥",
+ sdot: "⋅",
+ Alpha: "Α",
+ Beta: "Β",
+ Gamma: "Γ",
+ Delta: "Δ",
+ Epsilon: "Ε",
+ Zeta: "Ζ",
+ Eta: "Η",
+ Theta: "Θ",
+ Iota: "Ι",
+ Kappa: "Κ",
+ Lambda: "Λ",
+ Mu: "Μ",
+ Nu: "Ν",
+ Xi: "Ξ",
+ Omicron: "Ο",
+ Pi: "Π",
+ Rho: "Ρ",
+ Sigma: "Σ",
+ Tau: "Τ",
+ Upsilon: "Υ",
+ Phi: "Φ",
+ Chi: "Χ",
+ Psi: "Ψ",
+ Omega: "Ω",
+ alpha: "α",
+ beta: "β",
+ gamma: "γ",
+ delta: "δ",
+ epsilon: "ε",
+ zeta: "ζ",
+ eta: "η",
+ theta: "θ",
+ iota: "ι",
+ kappa: "κ",
+ lambda: "λ",
+ mu: "μ",
+ nu: "ν",
+ xi: "ξ",
+ omicron: "ο",
+ pi: "π",
+ rho: "ρ",
+ sigmaf: "ς",
+ sigma: "σ",
+ tau: "τ",
+ upsilon: "υ",
+ phi: "φ",
+ chi: "χ",
+ psi: "ψ",
+ omega: "ω",
+ thetasym: "ϑ",
+ upsih: "ϒ",
+ piv: "ϖ",
+ OElig: "Œ",
+ oelig: "œ",
+ Scaron: "Š",
+ scaron: "š",
+ Yuml: "Ÿ",
+ fnof: "ƒ",
+ circ: "ˆ",
+ tilde: "˜",
+ ensp: " ",
+ emsp: " ",
+ thinsp: " ",
+ zwnj: "",
+ zwj: "",
+ lrm: "",
+ rlm: "",
+ ndash: "–",
+ mdash: "—",
+ lsquo: "‘",
+ rsquo: "’",
+ sbquo: "‚",
+ ldquo: "“",
+ rdquo: "”",
+ bdquo: "„",
+ dagger: "†",
+ Dagger: "‡",
+ bull: "•",
+ hellip: "…",
+ permil: "‰",
+ prime: "′",
+ Prime: "″",
+ lsaquo: "‹",
+ rsaquo: "›",
+ oline: "‾",
+ euro: "€",
+ trade: "™",
+ larr: "←",
+ uarr: "↑",
+ rarr: "→",
+ darr: "↓",
+ harr: "↔",
+ crarr: "↵",
+ lceil: "⌈",
+ rceil: "⌉",
+ lfloor: "⌊",
+ rfloor: "⌋",
+ loz: "◊",
+ spades: "♠",
+ clubs: "♣",
+ hearts: "♥",
+ diams: "♦"
+};
+
+},{}],7:[function(require,module,exports){
+//[4] NameStartChar ::= ":" | [A-Z] | "_" | [a-z] | [#xC0-#xD6] | [#xD8-#xF6] | [#xF8-#x2FF] | [#x370-#x37D] | [#x37F-#x1FFF] | [#x200C-#x200D] | [#x2070-#x218F] | [#x2C00-#x2FEF] | [#x3001-#xD7FF] | [#xF900-#xFDCF] | [#xFDF0-#xFFFD] | [#x10000-#xEFFFF]
+//[4a] NameChar ::= NameStartChar | "-" | "." | [0-9] | #xB7 | [#x0300-#x036F] | [#x203F-#x2040]
+//[5] Name ::= NameStartChar (NameChar)*
+var nameStartChar = /[A-Z_a-z\xC0-\xD6\xD8-\xF6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]///\u10000-\uEFFFF
+var nameChar = new RegExp("[\\-\\.0-9"+nameStartChar.source.slice(1,-1)+"\\u00B7\\u0300-\\u036F\\u203F-\\u2040]");
+var tagNamePattern = new RegExp('^'+nameStartChar.source+nameChar.source+'*(?:\:'+nameStartChar.source+nameChar.source+'*)?$');
+//var tagNamePattern = /^[a-zA-Z_][\w\-\.]*(?:\:[a-zA-Z_][\w\-\.]*)?$/
+//var handlers = 'resolveEntity,getExternalSubset,characters,endDocument,endElement,endPrefixMapping,ignorableWhitespace,processingInstruction,setDocumentLocator,skippedEntity,startDocument,startElement,startPrefixMapping,notationDecl,unparsedEntityDecl,error,fatalError,warning,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,comment,endCDATA,endDTD,endEntity,startCDATA,startDTD,startEntity'.split(',')
+
+//S_TAG, S_ATTR, S_EQ, S_ATTR_NOQUOT_VALUE
+//S_ATTR_SPACE, S_ATTR_END, S_TAG_SPACE, S_TAG_CLOSE
+var S_TAG = 0;//tag name offerring
+var S_ATTR = 1;//attr name offerring
+var S_ATTR_SPACE=2;//attr name end and space offer
+var S_EQ = 3;//=space?
+var S_ATTR_NOQUOT_VALUE = 4;//attr value(no quot value only)
+var S_ATTR_END = 5;//attr value end and no space(quot end)
+var S_TAG_SPACE = 6;//(attr value end || tag end ) && (space offer)
+var S_TAG_CLOSE = 7;//closed el
+
+/**
+ * Creates an error that will not be caught by XMLReader aka the SAX parser.
+ *
+ * @param {string} message
+ * @param {any?} locator Optional, can provide details about the location in the source
+ * @constructor
+ */
+function ParseError(message, locator) {
+ this.message = message
+ this.locator = locator
+ if(Error.captureStackTrace) Error.captureStackTrace(this, ParseError);
+}
+ParseError.prototype = new Error();
+ParseError.prototype.name = ParseError.name
+
+function XMLReader(){
+
+}
+
+XMLReader.prototype = {
+ parse:function(source,defaultNSMap,entityMap){
+ var domBuilder = this.domBuilder;
+ domBuilder.startDocument();
+ _copy(defaultNSMap ,defaultNSMap = {})
+ parse(source,defaultNSMap,entityMap,
+ domBuilder,this.errorHandler);
+ domBuilder.endDocument();
+ }
+}
+function parse(source,defaultNSMapCopy,entityMap,domBuilder,errorHandler){
+ function fixedFromCharCode(code) {
+ // String.prototype.fromCharCode does not supports
+ // > 2 bytes unicode chars directly
+ if (code > 0xffff) {
+ code -= 0x10000;
+ var surrogate1 = 0xd800 + (code >> 10)
+ , surrogate2 = 0xdc00 + (code & 0x3ff);
+
+ return String.fromCharCode(surrogate1, surrogate2);
+ } else {
+ return String.fromCharCode(code);
+ }
+ }
+ function entityReplacer(a){
+ var k = a.slice(1,-1);
+ if(k in entityMap){
+ return entityMap[k];
+ }else if(k.charAt(0) === '#'){
+ return fixedFromCharCode(parseInt(k.substr(1).replace('x','0x')))
+ }else{
+ errorHandler.error('entity not found:'+a);
+ return a;
+ }
+ }
+ function appendText(end){//has some bugs
+ if(end>start){
+ var xt = source.substring(start,end).replace(/?\w+;/g,entityReplacer);
+ locator&&position(start);
+ domBuilder.characters(xt,0,end-start);
+ start = end
+ }
+ }
+ function position(p,m){
+ while(p>=lineEnd && (m = linePattern.exec(source))){
+ lineStart = m.index;
+ lineEnd = lineStart + m[0].length;
+ locator.lineNumber++;
+ //console.log('line++:',locator,startPos,endPos)
+ }
+ locator.columnNumber = p-lineStart+1;
+ }
+ var lineStart = 0;
+ var lineEnd = 0;
+ var linePattern = /.*(?:\r\n?|\n)|.*$/g
+ var locator = domBuilder.locator;
+
+ var parseStack = [{currentNSMap:defaultNSMapCopy}]
+ var closeMap = {};
+ var start = 0;
+ while(true){
+ try{
+ var tagStart = source.indexOf('<',start);
+ if(tagStart<0){
+ if(!source.substr(start).match(/^\s*$/)){
+ var doc = domBuilder.doc;
+ var text = doc.createTextNode(source.substr(start));
+ doc.appendChild(text);
+ domBuilder.currentElement = text;
+ }
+ return;
+ }
+ if(tagStart>start){
+ appendText(tagStart);
+ }
+ switch(source.charAt(tagStart+1)){
+ case '/':
+ var end = source.indexOf('>',tagStart+3);
+ var tagName = source.substring(tagStart+2,end);
+ var config = parseStack.pop();
+ if(end<0){
+
+ tagName = source.substring(tagStart+2).replace(/[\s<].*/,'');
+ errorHandler.error("end tag name: "+tagName+' is not complete:'+config.tagName);
+ end = tagStart+1+tagName.length;
+ }else if(tagName.match(/\s)){
+ tagName = tagName.replace(/[\s<].*/,'');
+ errorHandler.error("end tag name: "+tagName+' maybe not complete');
+ end = tagStart+1+tagName.length;
+ }
+ var localNSMap = config.localNSMap;
+ var endMatch = config.tagName == tagName;
+ var endIgnoreCaseMach = endMatch || config.tagName&&config.tagName.toLowerCase() == tagName.toLowerCase()
+ if(endIgnoreCaseMach){
+ domBuilder.endElement(config.uri,config.localName,tagName);
+ if(localNSMap){
+ for(var prefix in localNSMap){
+ domBuilder.endPrefixMapping(prefix) ;
+ }
+ }
+ if(!endMatch){
+ errorHandler.fatalError("end tag name: "+tagName+' is not match the current start tagName:'+config.tagName ); // No known test case
+ }
+ }else{
+ parseStack.push(config)
+ }
+
+ end++;
+ break;
+ // end elment
+ case '?':// ...?>
+ locator&&position(tagStart);
+ end = parseInstruction(source,tagStart,domBuilder);
+ break;
+ case '!':// start){
+ start = end;
+ }else{
+ //TODO: 这里有可能sax回退,有位置错误风险
+ appendText(Math.max(tagStart,start)+1);
+ }
+ }
+}
+function copyLocator(f,t){
+ t.lineNumber = f.lineNumber;
+ t.columnNumber = f.columnNumber;
+ return t;
+}
+
+/**
+ * @see #appendElement(source,elStartEnd,el,selfClosed,entityReplacer,domBuilder,parseStack);
+ * @return end of the elementStartPart(end of elementEndPart for selfClosed el)
+ */
+function parseElementStartPart(source,start,el,currentNSMap,entityReplacer,errorHandler){
+
+ /**
+ * @param {string} qname
+ * @param {string} value
+ * @param {number} startIndex
+ */
+ function addAttribute(qname, value, startIndex) {
+ if (qname in el.attributeNames) errorHandler.fatalError('Attribute ' + qname + ' redefined')
+ el.addValue(qname, value, startIndex)
+ }
+ var attrName;
+ var value;
+ var p = ++start;
+ var s = S_TAG;//status
+ while(true){
+ var c = source.charAt(p);
+ switch(c){
+ case '=':
+ if(s === S_ATTR){//attrName
+ attrName = source.slice(start,p);
+ s = S_EQ;
+ }else if(s === S_ATTR_SPACE){
+ s = S_EQ;
+ }else{
+ //fatalError: equal must after attrName or space after attrName
+ throw new Error('attribute equal must after attrName'); // No known test case
+ }
+ break;
+ case '\'':
+ case '"':
+ if(s === S_EQ || s === S_ATTR //|| s == S_ATTR_SPACE
+ ){//equal
+ if(s === S_ATTR){
+ errorHandler.warning('attribute value must after "="')
+ attrName = source.slice(start,p)
+ }
+ start = p+1;
+ p = source.indexOf(c,start)
+ if(p>0){
+ value = source.slice(start,p).replace(/?\w+;/g,entityReplacer);
+ addAttribute(attrName, value, start-1);
+ s = S_ATTR_END;
+ }else{
+ //fatalError: no end quot match
+ throw new Error('attribute value no end \''+c+'\' match');
+ }
+ }else if(s == S_ATTR_NOQUOT_VALUE){
+ value = source.slice(start,p).replace(/?\w+;/g,entityReplacer);
+ //console.log(attrName,value,start,p)
+ addAttribute(attrName, value, start);
+ //console.dir(el)
+ errorHandler.warning('attribute "'+attrName+'" missed start quot('+c+')!!');
+ start = p+1;
+ s = S_ATTR_END
+ }else{
+ //fatalError: no equal before
+ throw new Error('attribute value must after "="'); // No known test case
+ }
+ break;
+ case '/':
+ switch(s){
+ case S_TAG:
+ el.setTagName(source.slice(start,p));
+ case S_ATTR_END:
+ case S_TAG_SPACE:
+ case S_TAG_CLOSE:
+ s =S_TAG_CLOSE;
+ el.closed = true;
+ case S_ATTR_NOQUOT_VALUE:
+ case S_ATTR:
+ case S_ATTR_SPACE:
+ break;
+ //case S_EQ:
+ default:
+ throw new Error("attribute invalid close char('/')") // No known test case
+ }
+ break;
+ case ''://end document
+ errorHandler.error('unexpected end of input');
+ if(s == S_TAG){
+ el.setTagName(source.slice(start,p));
+ }
+ return p;
+ case '>':
+ switch(s){
+ case S_TAG:
+ el.setTagName(source.slice(start,p));
+ case S_ATTR_END:
+ case S_TAG_SPACE:
+ case S_TAG_CLOSE:
+ break;//normal
+ case S_ATTR_NOQUOT_VALUE://Compatible state
+ case S_ATTR:
+ value = source.slice(start,p);
+ if(value.slice(-1) === '/'){
+ el.closed = true;
+ value = value.slice(0,-1)
+ }
+ case S_ATTR_SPACE:
+ if(s === S_ATTR_SPACE){
+ value = attrName;
+ }
+ if(s == S_ATTR_NOQUOT_VALUE){
+ errorHandler.warning('attribute "'+value+'" missed quot(")!');
+ addAttribute(attrName, value.replace(/?\w+;/g,entityReplacer), start)
+ }else{
+ if(currentNSMap[''] !== 'http://www.w3.org/1999/xhtml' || !value.match(/^(?:disabled|checked|selected)$/i)){
+ errorHandler.warning('attribute "'+value+'" missed value!! "'+value+'" instead!!')
+ }
+ addAttribute(value, value, start)
+ }
+ break;
+ case S_EQ:
+ throw new Error('attribute value missed!!');
+ }
+// console.log(tagName,tagNamePattern,tagNamePattern.test(tagName))
+ return p;
+ /*xml space '\x20' | #x9 | #xD | #xA; */
+ case '\u0080':
+ c = ' ';
+ default:
+ if(c<= ' '){//space
+ switch(s){
+ case S_TAG:
+ el.setTagName(source.slice(start,p));//tagName
+ s = S_TAG_SPACE;
+ break;
+ case S_ATTR:
+ attrName = source.slice(start,p)
+ s = S_ATTR_SPACE;
+ break;
+ case S_ATTR_NOQUOT_VALUE:
+ var value = source.slice(start,p).replace(/?\w+;/g,entityReplacer);
+ errorHandler.warning('attribute "'+value+'" missed quot(")!!');
+ addAttribute(attrName, value, start)
+ case S_ATTR_END:
+ s = S_TAG_SPACE;
+ break;
+ //case S_TAG_SPACE:
+ //case S_EQ:
+ //case S_ATTR_SPACE:
+ // void();break;
+ //case S_TAG_CLOSE:
+ //ignore warning
+ }
+ }else{//not space
+//S_TAG, S_ATTR, S_EQ, S_ATTR_NOQUOT_VALUE
+//S_ATTR_SPACE, S_ATTR_END, S_TAG_SPACE, S_TAG_CLOSE
+ switch(s){
+ //case S_TAG:void();break;
+ //case S_ATTR:void();break;
+ //case S_ATTR_NOQUOT_VALUE:void();break;
+ case S_ATTR_SPACE:
+ var tagName = el.tagName;
+ if(currentNSMap[''] !== 'http://www.w3.org/1999/xhtml' || !attrName.match(/^(?:disabled|checked|selected)$/i)){
+ errorHandler.warning('attribute "'+attrName+'" missed value!! "'+attrName+'" instead2!!')
+ }
+ addAttribute(attrName, attrName, start);
+ start = p;
+ s = S_ATTR;
+ break;
+ case S_ATTR_END:
+ errorHandler.warning('attribute space is required"'+attrName+'"!!')
+ case S_TAG_SPACE:
+ s = S_ATTR;
+ start = p;
+ break;
+ case S_EQ:
+ s = S_ATTR_NOQUOT_VALUE;
+ start = p;
+ break;
+ case S_TAG_CLOSE:
+ throw new Error("elements closed character '/' and '>' must be connected to");
+ }
+ }
+ }//end outer switch
+ //console.log('p++',p)
+ p++;
+ }
+}
+/**
+ * @return true if has new namespace define
+ */
+function appendElement(el,domBuilder,currentNSMap){
+ var tagName = el.tagName;
+ var localNSMap = null;
+ //var currentNSMap = parseStack[parseStack.length-1].currentNSMap;
+ var i = el.length;
+ while(i--){
+ var a = el[i];
+ var qName = a.qName;
+ var value = a.value;
+ var nsp = qName.indexOf(':');
+ if(nsp>0){
+ var prefix = a.prefix = qName.slice(0,nsp);
+ var localName = qName.slice(nsp+1);
+ var nsPrefix = prefix === 'xmlns' && localName
+ }else{
+ localName = qName;
+ prefix = null
+ nsPrefix = qName === 'xmlns' && ''
+ }
+ //can not set prefix,because prefix !== ''
+ a.localName = localName ;
+ //prefix == null for no ns prefix attribute
+ if(nsPrefix !== false){//hack!!
+ if(localNSMap == null){
+ localNSMap = {}
+ //console.log(currentNSMap,0)
+ _copy(currentNSMap,currentNSMap={})
+ //console.log(currentNSMap,1)
+ }
+ currentNSMap[nsPrefix] = localNSMap[nsPrefix] = value;
+ a.uri = 'http://www.w3.org/2000/xmlns/'
+ domBuilder.startPrefixMapping(nsPrefix, value)
+ }
+ }
+ var i = el.length;
+ while(i--){
+ a = el[i];
+ var prefix = a.prefix;
+ if(prefix){//no prefix attribute has no namespace
+ if(prefix === 'xml'){
+ a.uri = 'http://www.w3.org/XML/1998/namespace';
+ }if(prefix !== 'xmlns'){
+ a.uri = currentNSMap[prefix || '']
+
+ //{console.log('###'+a.qName,domBuilder.locator.systemId+'',currentNSMap,a.uri)}
+ }
+ }
+ }
+ var nsp = tagName.indexOf(':');
+ if(nsp>0){
+ prefix = el.prefix = tagName.slice(0,nsp);
+ localName = el.localName = tagName.slice(nsp+1);
+ }else{
+ prefix = null;//important!!
+ localName = el.localName = tagName;
+ }
+ //no prefix element has default namespace
+ var ns = el.uri = currentNSMap[prefix || ''];
+ domBuilder.startElement(ns,localName,tagName,el);
+ //endPrefixMapping and startPrefixMapping have not any help for dom builder
+ //localNSMap = null
+ if(el.closed){
+ domBuilder.endElement(ns,localName,tagName);
+ if(localNSMap){
+ for(prefix in localNSMap){
+ domBuilder.endPrefixMapping(prefix)
+ }
+ }
+ }else{
+ el.currentNSMap = currentNSMap;
+ el.localNSMap = localNSMap;
+ //parseStack.push(el);
+ return true;
+ }
+}
+function parseHtmlSpecialContent(source,elStartEnd,tagName,entityReplacer,domBuilder){
+ if(/^(?:script|textarea)$/i.test(tagName)){
+ var elEndStart = source.indexOf(''+tagName+'>',elStartEnd);
+ var text = source.substring(elStartEnd+1,elEndStart);
+ if(/[&<]/.test(text)){
+ if(/^script$/i.test(tagName)){
+ //if(!/\]\]>/.test(text)){
+ //lexHandler.startCDATA();
+ domBuilder.characters(text,0,text.length);
+ //lexHandler.endCDATA();
+ return elEndStart;
+ //}
+ }//}else{//text area
+ text = text.replace(/?\w+;/g,entityReplacer);
+ domBuilder.characters(text,0,text.length);
+ return elEndStart;
+ //}
+
+ }
+ }
+ return elStartEnd+1;
+}
+function fixSelfClosed(source,elStartEnd,tagName,closeMap){
+ //if(tagName in closeMap){
+ var pos = closeMap[tagName];
+ if(pos == null){
+ //console.log(tagName)
+ pos = source.lastIndexOf(''+tagName+'>')
+ if(pos',start+4);
+ //append comment source.substring(4,end)//' + this.endline(node));
+ };
+
+ XMLStreamWriter.prototype.declaration = function(node, level) {
+ this.stream.write(this.space(level));
+ this.stream.write('');
+ return this.stream.write(this.endline(node));
+ };
+
+ XMLStreamWriter.prototype.docType = function(node, level) {
+ var child, i, len, ref;
+ level || (level = 0);
+ this.stream.write(this.space(level));
+ this.stream.write(' 0) {
+ this.stream.write(' [');
+ this.stream.write(this.endline(node));
+ ref = node.children;
+ for (i = 0, len = ref.length; i < len; i++) {
+ child = ref[i];
+ switch (false) {
+ case !(child instanceof XMLDTDAttList):
+ this.dtdAttList(child, level + 1);
+ break;
+ case !(child instanceof XMLDTDElement):
+ this.dtdElement(child, level + 1);
+ break;
+ case !(child instanceof XMLDTDEntity):
+ this.dtdEntity(child, level + 1);
+ break;
+ case !(child instanceof XMLDTDNotation):
+ this.dtdNotation(child, level + 1);
+ break;
+ case !(child instanceof XMLCData):
+ this.cdata(child, level + 1);
+ break;
+ case !(child instanceof XMLComment):
+ this.comment(child, level + 1);
+ break;
+ case !(child instanceof XMLProcessingInstruction):
+ this.processingInstruction(child, level + 1);
+ break;
+ default:
+ throw new Error("Unknown DTD node type: " + child.constructor.name);
+ }
+ }
+ this.stream.write(']');
+ }
+ this.stream.write(this.spacebeforeslash + '>');
+ return this.stream.write(this.endline(node));
+ };
+
+ XMLStreamWriter.prototype.element = function(node, level) {
+ var att, child, i, len, name, ref, ref1, space;
+ level || (level = 0);
+ space = this.space(level);
+ this.stream.write(space + '<' + node.name);
+ ref = node.attributes;
+ for (name in ref) {
+ if (!hasProp.call(ref, name)) continue;
+ att = ref[name];
+ this.attribute(att);
+ }
+ if (node.children.length === 0 || node.children.every(function(e) {
+ return e.value === '';
+ })) {
+ if (this.allowEmpty) {
+ this.stream.write('>' + node.name + '>');
+ } else {
+ this.stream.write(this.spacebeforeslash + '/>');
+ }
+ } else if (this.pretty && node.children.length === 1 && (node.children[0].value != null)) {
+ this.stream.write('>');
+ this.stream.write(node.children[0].value);
+ this.stream.write('' + node.name + '>');
+ } else {
+ this.stream.write('>' + this.newline);
+ ref1 = node.children;
+ for (i = 0, len = ref1.length; i < len; i++) {
+ child = ref1[i];
+ switch (false) {
+ case !(child instanceof XMLCData):
+ this.cdata(child, level + 1);
+ break;
+ case !(child instanceof XMLComment):
+ this.comment(child, level + 1);
+ break;
+ case !(child instanceof XMLElement):
+ this.element(child, level + 1);
+ break;
+ case !(child instanceof XMLRaw):
+ this.raw(child, level + 1);
+ break;
+ case !(child instanceof XMLText):
+ this.text(child, level + 1);
+ break;
+ case !(child instanceof XMLProcessingInstruction):
+ this.processingInstruction(child, level + 1);
+ break;
+ default:
+ throw new Error("Unknown XML node type: " + child.constructor.name);
+ }
+ }
+ this.stream.write(space + '' + node.name + '>');
+ }
+ return this.stream.write(this.endline(node));
+ };
+
+ XMLStreamWriter.prototype.processingInstruction = function(node, level) {
+ this.stream.write(this.space(level) + '' + node.target);
+ if (node.value) {
+ this.stream.write(' ' + node.value);
+ }
+ return this.stream.write(this.spacebeforeslash + '?>' + this.endline(node));
+ };
+
+ XMLStreamWriter.prototype.raw = function(node, level) {
+ return this.stream.write(this.space(level) + node.value + this.endline(node));
+ };
+
+ XMLStreamWriter.prototype.text = function(node, level) {
+ return this.stream.write(this.space(level) + node.value + this.endline(node));
+ };
+
+ XMLStreamWriter.prototype.dtdAttList = function(node, level) {
+ this.stream.write(this.space(level) + '' + this.endline(node));
+ };
+
+ XMLStreamWriter.prototype.dtdElement = function(node, level) {
+ this.stream.write(this.space(level) + '' + this.endline(node));
+ };
+
+ XMLStreamWriter.prototype.dtdEntity = function(node, level) {
+ this.stream.write(this.space(level) + '' + this.endline(node));
+ };
+
+ XMLStreamWriter.prototype.dtdNotation = function(node, level) {
+ this.stream.write(this.space(level) + '' + this.endline(node));
+ };
+
+ XMLStreamWriter.prototype.endline = function(node) {
+ if (!node.isLastRootNode) {
+ return this.newline;
+ } else {
+ return '';
+ }
+ };
+
+ return XMLStreamWriter;
+
+ })(XMLWriterBase);
+
+}).call(this);
+
+},{"./XMLCData":14,"./XMLComment":15,"./XMLDTDAttList":16,"./XMLDTDElement":17,"./XMLDTDEntity":18,"./XMLDTDNotation":19,"./XMLDeclaration":20,"./XMLDocType":21,"./XMLElement":24,"./XMLProcessingInstruction":26,"./XMLRaw":27,"./XMLText":31,"./XMLWriterBase":32}],29:[function(require,module,exports){
+// Generated by CoffeeScript 1.12.7
+(function() {
+ var XMLCData, XMLComment, XMLDTDAttList, XMLDTDElement, XMLDTDEntity, XMLDTDNotation, XMLDeclaration, XMLDocType, XMLElement, XMLProcessingInstruction, XMLRaw, XMLStringWriter, XMLText, XMLWriterBase,
+ extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
+ hasProp = {}.hasOwnProperty;
+
+ XMLDeclaration = require('./XMLDeclaration');
+
+ XMLDocType = require('./XMLDocType');
+
+ XMLCData = require('./XMLCData');
+
+ XMLComment = require('./XMLComment');
+
+ XMLElement = require('./XMLElement');
+
+ XMLRaw = require('./XMLRaw');
+
+ XMLText = require('./XMLText');
+
+ XMLProcessingInstruction = require('./XMLProcessingInstruction');
+
+ XMLDTDAttList = require('./XMLDTDAttList');
+
+ XMLDTDElement = require('./XMLDTDElement');
+
+ XMLDTDEntity = require('./XMLDTDEntity');
+
+ XMLDTDNotation = require('./XMLDTDNotation');
+
+ XMLWriterBase = require('./XMLWriterBase');
+
+ module.exports = XMLStringWriter = (function(superClass) {
+ extend(XMLStringWriter, superClass);
+
+ function XMLStringWriter(options) {
+ XMLStringWriter.__super__.constructor.call(this, options);
+ }
+
+ XMLStringWriter.prototype.document = function(doc) {
+ var child, i, len, r, ref;
+ this.textispresent = false;
+ r = '';
+ ref = doc.children;
+ for (i = 0, len = ref.length; i < len; i++) {
+ child = ref[i];
+ r += (function() {
+ switch (false) {
+ case !(child instanceof XMLDeclaration):
+ return this.declaration(child);
+ case !(child instanceof XMLDocType):
+ return this.docType(child);
+ case !(child instanceof XMLComment):
+ return this.comment(child);
+ case !(child instanceof XMLProcessingInstruction):
+ return this.processingInstruction(child);
+ default:
+ return this.element(child, 0);
+ }
+ }).call(this);
+ }
+ if (this.pretty && r.slice(-this.newline.length) === this.newline) {
+ r = r.slice(0, -this.newline.length);
+ }
+ return r;
+ };
+
+ XMLStringWriter.prototype.attribute = function(att) {
+ return ' ' + att.name + '="' + att.value + '"';
+ };
+
+ XMLStringWriter.prototype.cdata = function(node, level) {
+ return this.space(level) + '' + this.newline;
+ };
+
+ XMLStringWriter.prototype.comment = function(node, level) {
+ return this.space(level) + '' + this.newline;
+ };
+
+ XMLStringWriter.prototype.declaration = function(node, level) {
+ var r;
+ r = this.space(level);
+ r += '';
+ r += this.newline;
+ return r;
+ };
+
+ XMLStringWriter.prototype.docType = function(node, level) {
+ var child, i, len, r, ref;
+ level || (level = 0);
+ r = this.space(level);
+ r += ' 0) {
+ r += ' [';
+ r += this.newline;
+ ref = node.children;
+ for (i = 0, len = ref.length; i < len; i++) {
+ child = ref[i];
+ r += (function() {
+ switch (false) {
+ case !(child instanceof XMLDTDAttList):
+ return this.dtdAttList(child, level + 1);
+ case !(child instanceof XMLDTDElement):
+ return this.dtdElement(child, level + 1);
+ case !(child instanceof XMLDTDEntity):
+ return this.dtdEntity(child, level + 1);
+ case !(child instanceof XMLDTDNotation):
+ return this.dtdNotation(child, level + 1);
+ case !(child instanceof XMLCData):
+ return this.cdata(child, level + 1);
+ case !(child instanceof XMLComment):
+ return this.comment(child, level + 1);
+ case !(child instanceof XMLProcessingInstruction):
+ return this.processingInstruction(child, level + 1);
+ default:
+ throw new Error("Unknown DTD node type: " + child.constructor.name);
+ }
+ }).call(this);
+ }
+ r += ']';
+ }
+ r += this.spacebeforeslash + '>';
+ r += this.newline;
+ return r;
+ };
+
+ XMLStringWriter.prototype.element = function(node, level) {
+ var att, child, i, j, len, len1, name, r, ref, ref1, ref2, space, textispresentwasset;
+ level || (level = 0);
+ textispresentwasset = false;
+ if (this.textispresent) {
+ this.newline = '';
+ this.pretty = false;
+ } else {
+ this.newline = this.newlinedefault;
+ this.pretty = this.prettydefault;
+ }
+ space = this.space(level);
+ r = '';
+ r += space + '<' + node.name;
+ ref = node.attributes;
+ for (name in ref) {
+ if (!hasProp.call(ref, name)) continue;
+ att = ref[name];
+ r += this.attribute(att);
+ }
+ if (node.children.length === 0 || node.children.every(function(e) {
+ return e.value === '';
+ })) {
+ if (this.allowEmpty) {
+ r += '>' + node.name + '>' + this.newline;
+ } else {
+ r += this.spacebeforeslash + '/>' + this.newline;
+ }
+ } else if (this.pretty && node.children.length === 1 && (node.children[0].value != null)) {
+ r += '>';
+ r += node.children[0].value;
+ r += '' + node.name + '>' + this.newline;
+ } else {
+ if (this.dontprettytextnodes) {
+ ref1 = node.children;
+ for (i = 0, len = ref1.length; i < len; i++) {
+ child = ref1[i];
+ if (child.value != null) {
+ this.textispresent++;
+ textispresentwasset = true;
+ break;
+ }
+ }
+ }
+ if (this.textispresent) {
+ this.newline = '';
+ this.pretty = false;
+ space = this.space(level);
+ }
+ r += '>' + this.newline;
+ ref2 = node.children;
+ for (j = 0, len1 = ref2.length; j < len1; j++) {
+ child = ref2[j];
+ r += (function() {
+ switch (false) {
+ case !(child instanceof XMLCData):
+ return this.cdata(child, level + 1);
+ case !(child instanceof XMLComment):
+ return this.comment(child, level + 1);
+ case !(child instanceof XMLElement):
+ return this.element(child, level + 1);
+ case !(child instanceof XMLRaw):
+ return this.raw(child, level + 1);
+ case !(child instanceof XMLText):
+ return this.text(child, level + 1);
+ case !(child instanceof XMLProcessingInstruction):
+ return this.processingInstruction(child, level + 1);
+ default:
+ throw new Error("Unknown XML node type: " + child.constructor.name);
+ }
+ }).call(this);
+ }
+ if (textispresentwasset) {
+ this.textispresent--;
+ }
+ if (!this.textispresent) {
+ this.newline = this.newlinedefault;
+ this.pretty = this.prettydefault;
+ }
+ r += space + '' + node.name + '>' + this.newline;
+ }
+ return r;
+ };
+
+ XMLStringWriter.prototype.processingInstruction = function(node, level) {
+ var r;
+ r = this.space(level) + '' + node.target;
+ if (node.value) {
+ r += ' ' + node.value;
+ }
+ r += this.spacebeforeslash + '?>' + this.newline;
+ return r;
+ };
+
+ XMLStringWriter.prototype.raw = function(node, level) {
+ return this.space(level) + node.value + this.newline;
+ };
+
+ XMLStringWriter.prototype.text = function(node, level) {
+ return this.space(level) + node.value + this.newline;
+ };
+
+ XMLStringWriter.prototype.dtdAttList = function(node, level) {
+ var r;
+ r = this.space(level) + '' + this.newline;
+ return r;
+ };
+
+ XMLStringWriter.prototype.dtdElement = function(node, level) {
+ return this.space(level) + '' + this.newline;
+ };
+
+ XMLStringWriter.prototype.dtdEntity = function(node, level) {
+ var r;
+ r = this.space(level) + '' + this.newline;
+ return r;
+ };
+
+ XMLStringWriter.prototype.dtdNotation = function(node, level) {
+ var r;
+ r = this.space(level) + '' + this.newline;
+ return r;
+ };
+
+ XMLStringWriter.prototype.openNode = function(node, level) {
+ var att, name, r, ref;
+ level || (level = 0);
+ if (node instanceof XMLElement) {
+ r = this.space(level) + '<' + node.name;
+ ref = node.attributes;
+ for (name in ref) {
+ if (!hasProp.call(ref, name)) continue;
+ att = ref[name];
+ r += this.attribute(att);
+ }
+ r += (node.children ? '>' : '/>') + this.newline;
+ return r;
+ } else {
+ r = this.space(level) + '') + this.newline;
+ return r;
+ }
+ };
+
+ XMLStringWriter.prototype.closeNode = function(node, level) {
+ level || (level = 0);
+ switch (false) {
+ case !(node instanceof XMLElement):
+ return this.space(level) + '' + node.name + '>' + this.newline;
+ case !(node instanceof XMLDocType):
+ return this.space(level) + ']>' + this.newline;
+ }
+ };
+
+ return XMLStringWriter;
+
+ })(XMLWriterBase);
+
+}).call(this);
+
+},{"./XMLCData":14,"./XMLComment":15,"./XMLDTDAttList":16,"./XMLDTDElement":17,"./XMLDTDEntity":18,"./XMLDTDNotation":19,"./XMLDeclaration":20,"./XMLDocType":21,"./XMLElement":24,"./XMLProcessingInstruction":26,"./XMLRaw":27,"./XMLText":31,"./XMLWriterBase":32}],30:[function(require,module,exports){
+// Generated by CoffeeScript 1.12.7
+(function() {
+ var XMLStringifier,
+ bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
+ hasProp = {}.hasOwnProperty;
+
+ module.exports = XMLStringifier = (function() {
+ function XMLStringifier(options) {
+ this.assertLegalChar = bind(this.assertLegalChar, this);
+ var key, ref, value;
+ options || (options = {});
+ this.noDoubleEncoding = options.noDoubleEncoding;
+ ref = options.stringify || {};
+ for (key in ref) {
+ if (!hasProp.call(ref, key)) continue;
+ value = ref[key];
+ this[key] = value;
+ }
+ }
+
+ XMLStringifier.prototype.eleName = function(val) {
+ val = '' + val || '';
+ return this.assertLegalChar(val);
+ };
+
+ XMLStringifier.prototype.eleText = function(val) {
+ val = '' + val || '';
+ return this.assertLegalChar(this.elEscape(val));
+ };
+
+ XMLStringifier.prototype.cdata = function(val) {
+ val = '' + val || '';
+ val = val.replace(']]>', ']]]]>');
+ return this.assertLegalChar(val);
+ };
+
+ XMLStringifier.prototype.comment = function(val) {
+ val = '' + val || '';
+ if (val.match(/--/)) {
+ throw new Error("Comment text cannot contain double-hypen: " + val);
+ }
+ return this.assertLegalChar(val);
+ };
+
+ XMLStringifier.prototype.raw = function(val) {
+ return '' + val || '';
+ };
+
+ XMLStringifier.prototype.attName = function(val) {
+ return val = '' + val || '';
+ };
+
+ XMLStringifier.prototype.attValue = function(val) {
+ val = '' + val || '';
+ return this.attEscape(val);
+ };
+
+ XMLStringifier.prototype.insTarget = function(val) {
+ return '' + val || '';
+ };
+
+ XMLStringifier.prototype.insValue = function(val) {
+ val = '' + val || '';
+ if (val.match(/\?>/)) {
+ throw new Error("Invalid processing instruction value: " + val);
+ }
+ return val;
+ };
+
+ XMLStringifier.prototype.xmlVersion = function(val) {
+ val = '' + val || '';
+ if (!val.match(/1\.[0-9]+/)) {
+ throw new Error("Invalid version number: " + val);
+ }
+ return val;
+ };
+
+ XMLStringifier.prototype.xmlEncoding = function(val) {
+ val = '' + val || '';
+ if (!val.match(/^[A-Za-z](?:[A-Za-z0-9._-])*$/)) {
+ throw new Error("Invalid encoding: " + val);
+ }
+ return val;
+ };
+
+ XMLStringifier.prototype.xmlStandalone = function(val) {
+ if (val) {
+ return "yes";
+ } else {
+ return "no";
+ }
+ };
+
+ XMLStringifier.prototype.dtdPubID = function(val) {
+ return '' + val || '';
+ };
+
+ XMLStringifier.prototype.dtdSysID = function(val) {
+ return '' + val || '';
+ };
+
+ XMLStringifier.prototype.dtdElementValue = function(val) {
+ return '' + val || '';
+ };
+
+ XMLStringifier.prototype.dtdAttType = function(val) {
+ return '' + val || '';
+ };
+
+ XMLStringifier.prototype.dtdAttDefault = function(val) {
+ if (val != null) {
+ return '' + val || '';
+ } else {
+ return val;
+ }
+ };
+
+ XMLStringifier.prototype.dtdEntityValue = function(val) {
+ return '' + val || '';
+ };
+
+ XMLStringifier.prototype.dtdNData = function(val) {
+ return '' + val || '';
+ };
+
+ XMLStringifier.prototype.convertAttKey = '@';
+
+ XMLStringifier.prototype.convertPIKey = '?';
+
+ XMLStringifier.prototype.convertTextKey = '#text';
+
+ XMLStringifier.prototype.convertCDataKey = '#cdata';
+
+ XMLStringifier.prototype.convertCommentKey = '#comment';
+
+ XMLStringifier.prototype.convertRawKey = '#raw';
+
+ XMLStringifier.prototype.assertLegalChar = function(str) {
+ var res;
+ res = str.match(/[\0\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/);
+ if (res) {
+ throw new Error("Invalid character in string: " + str + " at index " + res.index);
+ }
+ return str;
+ };
+
+ XMLStringifier.prototype.elEscape = function(str) {
+ var ampregex;
+ ampregex = this.noDoubleEncoding ? /(?!&\S+;)&/g : /&/g;
+ return str.replace(ampregex, '&').replace(//g, '>').replace(/\r/g, '
');
+ };
+
+ XMLStringifier.prototype.attEscape = function(str) {
+ var ampregex;
+ ampregex = this.noDoubleEncoding ? /(?!&\S+;)&/g : /&/g;
+ return str.replace(ampregex, '&').replace(/ 0) {
+ return new Array(indent).join(this.indent);
+ } else {
+ return '';
+ }
+ } else {
+ return '';
+ }
+ };
+
+ return XMLWriterBase;
+
+ })();
+
+}).call(this);
+
+},{}],33:[function(require,module,exports){
+// Generated by CoffeeScript 1.12.7
+(function() {
+ var XMLDocument, XMLDocumentCB, XMLStreamWriter, XMLStringWriter, assign, isFunction, ref;
+
+ ref = require('./Utility'), assign = ref.assign, isFunction = ref.isFunction;
+
+ XMLDocument = require('./XMLDocument');
+
+ XMLDocumentCB = require('./XMLDocumentCB');
+
+ XMLStringWriter = require('./XMLStringWriter');
+
+ XMLStreamWriter = require('./XMLStreamWriter');
+
+ module.exports.create = function(name, xmldec, doctype, options) {
+ var doc, root;
+ if (name == null) {
+ throw new Error("Root element needs a name");
+ }
+ options = assign({}, xmldec, doctype, options);
+ doc = new XMLDocument(options);
+ root = doc.element(name);
+ if (!options.headless) {
+ doc.declaration(options);
+ if ((options.pubID != null) || (options.sysID != null)) {
+ doc.doctype(options);
+ }
+ }
+ return root;
+ };
+
+ module.exports.begin = function(options, onData, onEnd) {
+ var ref1;
+ if (isFunction(options)) {
+ ref1 = [options, onData], onData = ref1[0], onEnd = ref1[1];
+ options = {};
+ }
+ if (onData) {
+ return new XMLDocumentCB(options, onData, onEnd);
+ } else {
+ return new XMLDocument(options);
+ }
+ };
+
+ module.exports.stringWriter = function(options) {
+ return new XMLStringWriter(options);
+ };
+
+ module.exports.streamWriter = function(stream, options) {
+ return new XMLStreamWriter(stream, options);
+ };
+
+}).call(this);
+
+},{"./Utility":12,"./XMLDocument":22,"./XMLDocumentCB":23,"./XMLStreamWriter":28,"./XMLStringWriter":29}]},{},[1])(1)
+});
diff --git a/temporary_modules/trezor-connect/node_modules/plist/examples/browser/index.html b/temporary_modules/trezor-connect/node_modules/plist/examples/browser/index.html
new file mode 100644
index 00000000..8ce7d923
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/plist/examples/browser/index.html
@@ -0,0 +1,14 @@
+
+
+
+ plist.js browser example
+
+
+
+
+
+
+
diff --git a/temporary_modules/trezor-connect/node_modules/plist/index.js b/temporary_modules/trezor-connect/node_modules/plist/index.js
new file mode 100644
index 00000000..d7385aeb
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/plist/index.js
@@ -0,0 +1,13 @@
+/**
+ * Parser functions.
+ */
+
+var parserFunctions = require('./lib/parse');
+Object.keys(parserFunctions).forEach(function (k) { exports[k] = parserFunctions[k]; });
+
+/**
+ * Builder functions.
+ */
+
+var builderFunctions = require('./lib/build');
+Object.keys(builderFunctions).forEach(function (k) { exports[k] = builderFunctions[k]; });
diff --git a/temporary_modules/trezor-connect/node_modules/plist/lib/build.js b/temporary_modules/trezor-connect/node_modules/plist/lib/build.js
new file mode 100644
index 00000000..83ea5578
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/plist/lib/build.js
@@ -0,0 +1,137 @@
+/**
+ * Module dependencies.
+ */
+
+var base64 = require('base64-js');
+var xmlbuilder = require('xmlbuilder');
+
+/**
+ * Module exports.
+ */
+
+exports.build = build;
+
+/**
+ * Accepts a `Date` instance and returns an ISO date string.
+ *
+ * @param {Date} d - Date instance to serialize
+ * @returns {String} ISO date string representation of `d`
+ * @api private
+ */
+
+function ISODateString(d){
+ function pad(n){
+ return n < 10 ? '0' + n : n;
+ }
+ return d.getUTCFullYear()+'-'
+ + pad(d.getUTCMonth()+1)+'-'
+ + pad(d.getUTCDate())+'T'
+ + pad(d.getUTCHours())+':'
+ + pad(d.getUTCMinutes())+':'
+ + pad(d.getUTCSeconds())+'Z';
+}
+
+/**
+ * Returns the internal "type" of `obj` via the
+ * `Object.prototype.toString()` trick.
+ *
+ * @param {Mixed} obj - any value
+ * @returns {String} the internal "type" name
+ * @api private
+ */
+
+var toString = Object.prototype.toString;
+function type (obj) {
+ var m = toString.call(obj).match(/\[object (.*)\]/);
+ return m ? m[1] : m;
+}
+
+/**
+ * Generate an XML plist string from the input object `obj`.
+ *
+ * @param {Object} obj - the object to convert
+ * @param {Object} [opts] - optional options object
+ * @returns {String} converted plist XML string
+ * @api public
+ */
+
+function build (obj, opts) {
+ var XMLHDR = {
+ version: '1.0',
+ encoding: 'UTF-8'
+ };
+
+ var XMLDTD = {
+ pubid: '-//Apple//DTD PLIST 1.0//EN',
+ sysid: 'http://www.apple.com/DTDs/PropertyList-1.0.dtd'
+ };
+
+ var doc = xmlbuilder.create('plist');
+
+ doc.dec(XMLHDR.version, XMLHDR.encoding, XMLHDR.standalone);
+ doc.dtd(XMLDTD.pubid, XMLDTD.sysid);
+ doc.att('version', '1.0');
+
+ walk_obj(obj, doc);
+
+ if (!opts) opts = {};
+ // default `pretty` to `true`
+ opts.pretty = opts.pretty !== false;
+ return doc.end(opts);
+}
+
+/**
+ * depth first, recursive traversal of a javascript object. when complete,
+ * next_child contains a reference to the build XML object.
+ *
+ * @api private
+ */
+
+function walk_obj(next, next_child) {
+ var tag_type, i, prop;
+ var name = type(next);
+
+ if ('Undefined' == name) {
+ return;
+ } else if (Array.isArray(next)) {
+ next_child = next_child.ele('array');
+ for (i = 0; i < next.length; i++) {
+ walk_obj(next[i], next_child);
+ }
+
+ } else if (Buffer.isBuffer(next)) {
+ next_child.ele('data').raw(next.toString('base64'));
+
+ } else if ('Object' == name) {
+ next_child = next_child.ele('dict');
+ for (prop in next) {
+ if (next.hasOwnProperty(prop)) {
+ next_child.ele('key').txt(prop);
+ walk_obj(next[prop], next_child);
+ }
+ }
+
+ } else if ('Number' == name) {
+ // detect if this is an integer or real
+ // TODO: add an ability to force one way or another via a "cast"
+ tag_type = (next % 1 === 0) ? 'integer' : 'real';
+ next_child.ele(tag_type).txt(next.toString());
+
+ } else if ('Date' == name) {
+ next_child.ele('date').txt(ISODateString(new Date(next)));
+
+ } else if ('Boolean' == name) {
+ next_child.ele(next ? 'true' : 'false');
+
+ } else if ('String' == name) {
+ next_child.ele('string').txt(next);
+
+ } else if ('ArrayBuffer' == name) {
+ next_child.ele('data').raw(base64.fromByteArray(next));
+
+ } else if (next && next.buffer && 'ArrayBuffer' == type(next.buffer)) {
+ // a typed array
+ next_child.ele('data').raw(base64.fromByteArray(new Uint8Array(next.buffer), next_child));
+
+ }
+}
diff --git a/temporary_modules/trezor-connect/node_modules/plist/lib/parse.js b/temporary_modules/trezor-connect/node_modules/plist/lib/parse.js
new file mode 100644
index 00000000..807c4aed
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/plist/lib/parse.js
@@ -0,0 +1,221 @@
+/**
+ * Module dependencies.
+ */
+
+var DOMParser = require('./xmldom/dom-parser').DOMParser;
+
+/**
+ * Module exports.
+ */
+
+exports.parse = parse;
+
+var TEXT_NODE = 3;
+var CDATA_NODE = 4;
+var COMMENT_NODE = 8;
+
+
+/**
+ * We ignore raw text (usually whitespace), ,
+ * and raw CDATA nodes.
+ *
+ * @param {Element} node
+ * @returns {Boolean}
+ * @api private
+ */
+
+function shouldIgnoreNode (node) {
+ return node.nodeType === TEXT_NODE
+ || node.nodeType === COMMENT_NODE
+ || node.nodeType === CDATA_NODE;
+}
+
+/**
+ * Check if the node is empty. Some plist file has such node:
+ *
+ * this node shoud be ignored.
+ *
+ * @see https://github.com/TooTallNate/plist.js/issues/66
+ * @param {Element} node
+ * @returns {Boolean}
+ * @api private
+ */
+function isEmptyNode(node){
+ if(!node.childNodes || node.childNodes.length === 0) {
+ return true;
+ } else {
+ return false;
+ }
+}
+
+function invariant(test, message) {
+ if (!test) {
+ throw new Error(message);
+ }
+}
+
+/**
+ * Parses a Plist XML string. Returns an Object.
+ *
+ * @param {String} xml - the XML String to decode
+ * @returns {Mixed} the decoded value from the Plist XML
+ * @api public
+ */
+
+function parse (xml) {
+ var doc = new DOMParser().parseFromString(xml);
+ invariant(
+ doc.documentElement.nodeName === 'plist',
+ 'malformed document. First element should be '
+ );
+ var plist = parsePlistXML(doc.documentElement);
+
+ // the root node gets interpreted as an Array,
+ // so pull out the inner data first
+ if (plist.length == 1) plist = plist[0];
+
+ return plist;
+}
+
+/**
+ * Convert an XML based plist document into a JSON representation.
+ *
+ * @param {Object} xml_node - current XML node in the plist
+ * @returns {Mixed} built up JSON object
+ * @api private
+ */
+
+function parsePlistXML (node) {
+ var i, new_obj, key, val, new_arr, res, counter, type;
+
+ if (!node)
+ return null;
+
+ if (node.nodeName === 'plist') {
+ new_arr = [];
+ if (isEmptyNode(node)) {
+ return new_arr;
+ }
+ for (i=0; i < node.childNodes.length; i++) {
+ if (!shouldIgnoreNode(node.childNodes[i])) {
+ new_arr.push( parsePlistXML(node.childNodes[i]));
+ }
+ }
+ return new_arr;
+ } else if (node.nodeName === 'dict') {
+ new_obj = {};
+ key = null;
+ counter = 0;
+ if (isEmptyNode(node)) {
+ return new_obj;
+ }
+ for (i=0; i < node.childNodes.length; i++) {
+ if (shouldIgnoreNode(node.childNodes[i])) continue;
+ if (counter % 2 === 0) {
+ invariant(
+ node.childNodes[i].nodeName === 'key',
+ 'Missing key while parsing .'
+ );
+ key = parsePlistXML(node.childNodes[i]);
+ } else {
+ invariant(
+ node.childNodes[i].nodeName !== 'key',
+ 'Unexpected key "'
+ + parsePlistXML(node.childNodes[i])
+ + '" while parsing .'
+ );
+ new_obj[key] = parsePlistXML(node.childNodes[i]);
+ }
+ counter += 1;
+ }
+ if (counter % 2 === 1) {
+ throw new Error('Missing value for "' + key + '" while parsing ');
+ }
+ return new_obj;
+
+ } else if (node.nodeName === 'array') {
+ new_arr = [];
+ if (isEmptyNode(node)) {
+ return new_arr;
+ }
+ for (i=0; i < node.childNodes.length; i++) {
+ if (!shouldIgnoreNode(node.childNodes[i])) {
+ res = parsePlistXML(node.childNodes[i]);
+ if (null != res) new_arr.push(res);
+ }
+ }
+ return new_arr;
+
+ } else if (node.nodeName === '#text') {
+ // TODO: what should we do with text types? (CDATA sections)
+
+ } else if (node.nodeName === 'key') {
+ if (isEmptyNode(node)) {
+ return '';
+ }
+
+ invariant(
+ node.childNodes[0].nodeValue !== '__proto__',
+ '__proto__ keys can lead to prototype pollution. More details on CVE-2022-22912'
+ );
+
+ return node.childNodes[0].nodeValue;
+ } else if (node.nodeName === 'string') {
+ res = '';
+ if (isEmptyNode(node)) {
+ return res;
+ }
+ for (i=0; i < node.childNodes.length; i++) {
+ var type = node.childNodes[i].nodeType;
+ if (type === TEXT_NODE || type === CDATA_NODE) {
+ res += node.childNodes[i].nodeValue;
+ }
+ }
+ return res;
+
+ } else if (node.nodeName === 'integer') {
+ invariant(
+ !isEmptyNode(node),
+ 'Cannot parse "" as integer.'
+ );
+ return parseInt(node.childNodes[0].nodeValue, 10);
+
+ } else if (node.nodeName === 'real') {
+ invariant(
+ !isEmptyNode(node),
+ 'Cannot parse "" as real.'
+ );
+ res = '';
+ for (i=0; i < node.childNodes.length; i++) {
+ if (node.childNodes[i].nodeType === TEXT_NODE) {
+ res += node.childNodes[i].nodeValue;
+ }
+ }
+ return parseFloat(res);
+
+ } else if (node.nodeName === 'data') {
+ res = '';
+ if (isEmptyNode(node)) {
+ return Buffer.from(res, 'base64');
+ }
+ for (i=0; i < node.childNodes.length; i++) {
+ if (node.childNodes[i].nodeType === TEXT_NODE) {
+ res += node.childNodes[i].nodeValue.replace(/\s+/g, '');
+ }
+ }
+ return Buffer.from(res, 'base64');
+
+ } else if (node.nodeName === 'date') {
+ invariant(
+ !isEmptyNode(node),
+ 'Cannot parse "" as Date.'
+ )
+ return new Date(node.childNodes[0].nodeValue);
+
+ } else if (node.nodeName === 'true') {
+ return true;
+
+ } else if (node.nodeName === 'false') {
+ return false;
+ }
+}
diff --git a/temporary_modules/trezor-connect/node_modules/plist/lib/xmldom/dom-parser.js b/temporary_modules/trezor-connect/node_modules/plist/lib/xmldom/dom-parser.js
new file mode 100644
index 00000000..2ad090de
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/plist/lib/xmldom/dom-parser.js
@@ -0,0 +1,253 @@
+function DOMParser(options){
+ this.options = options ||{locator:{}};
+}
+
+DOMParser.prototype.parseFromString = function(source,mimeType){
+ var options = this.options;
+ var sax = new XMLReader();
+ var domBuilder = options.domBuilder || new DOMHandler();//contentHandler and LexicalHandler
+ var errorHandler = options.errorHandler;
+ var locator = options.locator;
+ var defaultNSMap = options.xmlns||{};
+ var isHTML = /\/x?html?$/.test(mimeType);//mimeType.toLowerCase().indexOf('html') > -1;
+ var entityMap = isHTML?htmlEntity.entityMap:{'lt':'<','gt':'>','amp':'&','quot':'"','apos':"'"};
+ if(locator){
+ domBuilder.setDocumentLocator(locator)
+ }
+
+ sax.errorHandler = buildErrorHandler(errorHandler,domBuilder,locator);
+ sax.domBuilder = options.domBuilder || domBuilder;
+ if(isHTML){
+ defaultNSMap['']= 'http://www.w3.org/1999/xhtml';
+ }
+ defaultNSMap.xml = defaultNSMap.xml || 'http://www.w3.org/XML/1998/namespace';
+ if(source && typeof source === 'string'){
+ sax.parse(source,defaultNSMap,entityMap);
+ }else{
+ sax.errorHandler.error("invalid doc source");
+ }
+ return domBuilder.doc;
+}
+function buildErrorHandler(errorImpl,domBuilder,locator){
+ if(!errorImpl){
+ if(domBuilder instanceof DOMHandler){
+ return domBuilder;
+ }
+ errorImpl = domBuilder ;
+ }
+ var errorHandler = {}
+ var isCallback = errorImpl instanceof Function;
+ locator = locator||{}
+ function build(key){
+ var fn = errorImpl[key];
+ if(!fn && isCallback){
+ fn = errorImpl.length == 2?function(msg){errorImpl(key,msg)}:errorImpl;
+ }
+ errorHandler[key] = fn && function(msg){
+ fn('[xmldom '+key+']\t'+msg+_locator(locator));
+ }||function(){};
+ }
+ build('warning');
+ build('error');
+ build('fatalError');
+ return errorHandler;
+}
+
+//console.log('#\n\n\n\n\n\n\n####')
+/**
+ * +ContentHandler+ErrorHandler
+ * +LexicalHandler+EntityResolver2
+ * -DeclHandler-DTDHandler
+ *
+ * DefaultHandler:EntityResolver, DTDHandler, ContentHandler, ErrorHandler
+ * DefaultHandler2:DefaultHandler,LexicalHandler, DeclHandler, EntityResolver2
+ * @link http://www.saxproject.org/apidoc/org/xml/sax/helpers/DefaultHandler.html
+ */
+function DOMHandler() {
+ this.cdata = false;
+}
+function position(locator,node){
+ node.lineNumber = locator.lineNumber;
+ node.columnNumber = locator.columnNumber;
+}
+/**
+ * @see org.xml.sax.ContentHandler#startDocument
+ * @link http://www.saxproject.org/apidoc/org/xml/sax/ContentHandler.html
+ */
+DOMHandler.prototype = {
+ startDocument : function() {
+ this.doc = new DOMImplementation().createDocument(null, null, null);
+ if (this.locator) {
+ this.doc.documentURI = this.locator.systemId;
+ }
+ },
+ startElement:function(namespaceURI, localName, qName, attrs) {
+ var doc = this.doc;
+ var el = doc.createElementNS(namespaceURI, qName||localName);
+ var len = attrs.length;
+ appendElement(this, el);
+ this.currentElement = el;
+
+ this.locator && position(this.locator,el)
+ for (var i = 0 ; i < len; i++) {
+ var namespaceURI = attrs.getURI(i);
+ var value = attrs.getValue(i);
+ var qName = attrs.getQName(i);
+ var attr = doc.createAttributeNS(namespaceURI, qName);
+ this.locator &&position(attrs.getLocator(i),attr);
+ attr.value = attr.nodeValue = value;
+ el.setAttributeNode(attr)
+ }
+ },
+ endElement:function(namespaceURI, localName, qName) {
+ var current = this.currentElement
+ var tagName = current.tagName;
+ this.currentElement = current.parentNode;
+ },
+ startPrefixMapping:function(prefix, uri) {
+ },
+ endPrefixMapping:function(prefix) {
+ },
+ processingInstruction:function(target, data) {
+ var ins = this.doc.createProcessingInstruction(target, data);
+ this.locator && position(this.locator,ins)
+ appendElement(this, ins);
+ },
+ ignorableWhitespace:function(ch, start, length) {
+ },
+ characters:function(chars, start, length) {
+ chars = _toString.apply(this,arguments)
+ //console.log(chars)
+ if(chars){
+ if (this.cdata) {
+ var charNode = this.doc.createCDATASection(chars);
+ } else {
+ var charNode = this.doc.createTextNode(chars);
+ }
+ if(this.currentElement){
+ this.currentElement.appendChild(charNode);
+ }else if(/^\s*$/.test(chars)){
+ this.doc.appendChild(charNode);
+ //process xml
+ }
+ this.locator && position(this.locator,charNode)
+ }
+ },
+ skippedEntity:function(name) {
+ },
+ endDocument:function() {
+ this.doc.normalize();
+ },
+ setDocumentLocator:function (locator) {
+ if(this.locator = locator){// && !('lineNumber' in locator)){
+ locator.lineNumber = 0;
+ }
+ },
+ //LexicalHandler
+ comment:function(chars, start, length) {
+ chars = _toString.apply(this,arguments)
+ var comm = this.doc.createComment(chars);
+ this.locator && position(this.locator,comm)
+ appendElement(this, comm);
+ },
+
+ startCDATA:function() {
+ //used in characters() methods
+ this.cdata = true;
+ },
+ endCDATA:function() {
+ this.cdata = false;
+ },
+
+ startDTD:function(name, publicId, systemId) {
+ var impl = this.doc.implementation;
+ if (impl && impl.createDocumentType) {
+ var dt = impl.createDocumentType(name, publicId, systemId);
+ this.locator && position(this.locator,dt)
+ appendElement(this, dt);
+ }
+ },
+ /**
+ * @see org.xml.sax.ErrorHandler
+ * @link http://www.saxproject.org/apidoc/org/xml/sax/ErrorHandler.html
+ */
+ warning:function(error) {
+ console.warn('[xmldom warning]\t'+error,_locator(this.locator));
+ },
+ error:function(error) {
+ console.error('[xmldom error]\t'+error,_locator(this.locator));
+ },
+ fatalError:function(error) {
+ throw new ParseError(error, this.locator);
+ }
+}
+function _locator(l){
+ if(l){
+ return '\n@'+(l.systemId ||'')+'#[line:'+l.lineNumber+',col:'+l.columnNumber+']'
+ }
+}
+function _toString(chars,start,length){
+ if(typeof chars == 'string'){
+ return chars.substr(start,length)
+ }else{//java sax connect width xmldom on rhino(what about: "? && !(chars instanceof String)")
+ if(chars.length >= start+length || start){
+ return new java.lang.String(chars,start,length)+'';
+ }
+ return chars;
+ }
+}
+
+/*
+ * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/LexicalHandler.html
+ * used method of org.xml.sax.ext.LexicalHandler:
+ * #comment(chars, start, length)
+ * #startCDATA()
+ * #endCDATA()
+ * #startDTD(name, publicId, systemId)
+ *
+ *
+ * IGNORED method of org.xml.sax.ext.LexicalHandler:
+ * #endDTD()
+ * #startEntity(name)
+ * #endEntity(name)
+ *
+ *
+ * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/DeclHandler.html
+ * IGNORED method of org.xml.sax.ext.DeclHandler
+ * #attributeDecl(eName, aName, type, mode, value)
+ * #elementDecl(name, model)
+ * #externalEntityDecl(name, publicId, systemId)
+ * #internalEntityDecl(name, value)
+ * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/EntityResolver2.html
+ * IGNORED method of org.xml.sax.EntityResolver2
+ * #resolveEntity(String name,String publicId,String baseURI,String systemId)
+ * #resolveEntity(publicId, systemId)
+ * #getExternalSubset(name, baseURI)
+ * @link http://www.saxproject.org/apidoc/org/xml/sax/DTDHandler.html
+ * IGNORED method of org.xml.sax.DTDHandler
+ * #notationDecl(name, publicId, systemId) {};
+ * #unparsedEntityDecl(name, publicId, systemId, notationName) {};
+ */
+"endDTD,startEntity,endEntity,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,resolveEntity,getExternalSubset,notationDecl,unparsedEntityDecl".replace(/\w+/g,function(key){
+ DOMHandler.prototype[key] = function(){return null}
+})
+
+/* Private static helpers treated below as private instance methods, so don't need to add these to the public API; we might use a Relator to also get rid of non-standard public properties */
+function appendElement (hander,node) {
+ if (!hander.currentElement) {
+ hander.doc.appendChild(node);
+ } else {
+ hander.currentElement.appendChild(node);
+ }
+}//appendChild and setAttributeNS are preformance key
+
+//if(typeof require == 'function'){
+var htmlEntity = require('./entities');
+var sax = require('./sax');
+var XMLReader = sax.XMLReader;
+var ParseError = sax.ParseError;
+var DOMImplementation = exports.DOMImplementation = require('./dom').DOMImplementation;
+exports.XMLSerializer = require('./dom').XMLSerializer ;
+exports.DOMParser = DOMParser;
+exports.__DOMHandler = DOMHandler;
+//}
diff --git a/temporary_modules/trezor-connect/node_modules/plist/lib/xmldom/dom.js b/temporary_modules/trezor-connect/node_modules/plist/lib/xmldom/dom.js
new file mode 100644
index 00000000..12288c8a
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/plist/lib/xmldom/dom.js
@@ -0,0 +1,1283 @@
+function copy(src,dest){
+ for(var p in src){
+ dest[p] = src[p];
+ }
+}
+/**
+^\w+\.prototype\.([_\w]+)\s*=\s*((?:.*\{\s*?[\r\n][\s\S]*?^})|\S.*?(?=[;\r\n]));?
+^\w+\.prototype\.([_\w]+)\s*=\s*(\S.*?(?=[;\r\n]));?
+ */
+function _extends(Class,Super){
+ var pt = Class.prototype;
+ if(!(pt instanceof Super)){
+ function t(){};
+ t.prototype = Super.prototype;
+ t = new t();
+ copy(pt,t);
+ Class.prototype = pt = t;
+ }
+ if(pt.constructor != Class){
+ if(typeof Class != 'function'){
+ console.error("unknow Class:"+Class)
+ }
+ pt.constructor = Class
+ }
+}
+var htmlns = 'http://www.w3.org/1999/xhtml' ;
+// Node Types
+var NodeType = {}
+var ELEMENT_NODE = NodeType.ELEMENT_NODE = 1;
+var ATTRIBUTE_NODE = NodeType.ATTRIBUTE_NODE = 2;
+var TEXT_NODE = NodeType.TEXT_NODE = 3;
+var CDATA_SECTION_NODE = NodeType.CDATA_SECTION_NODE = 4;
+var ENTITY_REFERENCE_NODE = NodeType.ENTITY_REFERENCE_NODE = 5;
+var ENTITY_NODE = NodeType.ENTITY_NODE = 6;
+var PROCESSING_INSTRUCTION_NODE = NodeType.PROCESSING_INSTRUCTION_NODE = 7;
+var COMMENT_NODE = NodeType.COMMENT_NODE = 8;
+var DOCUMENT_NODE = NodeType.DOCUMENT_NODE = 9;
+var DOCUMENT_TYPE_NODE = NodeType.DOCUMENT_TYPE_NODE = 10;
+var DOCUMENT_FRAGMENT_NODE = NodeType.DOCUMENT_FRAGMENT_NODE = 11;
+var NOTATION_NODE = NodeType.NOTATION_NODE = 12;
+
+// ExceptionCode
+var ExceptionCode = {}
+var ExceptionMessage = {};
+var INDEX_SIZE_ERR = ExceptionCode.INDEX_SIZE_ERR = ((ExceptionMessage[1]="Index size error"),1);
+var DOMSTRING_SIZE_ERR = ExceptionCode.DOMSTRING_SIZE_ERR = ((ExceptionMessage[2]="DOMString size error"),2);
+var HIERARCHY_REQUEST_ERR = ExceptionCode.HIERARCHY_REQUEST_ERR = ((ExceptionMessage[3]="Hierarchy request error"),3);
+var WRONG_DOCUMENT_ERR = ExceptionCode.WRONG_DOCUMENT_ERR = ((ExceptionMessage[4]="Wrong document"),4);
+var INVALID_CHARACTER_ERR = ExceptionCode.INVALID_CHARACTER_ERR = ((ExceptionMessage[5]="Invalid character"),5);
+var NO_DATA_ALLOWED_ERR = ExceptionCode.NO_DATA_ALLOWED_ERR = ((ExceptionMessage[6]="No data allowed"),6);
+var NO_MODIFICATION_ALLOWED_ERR = ExceptionCode.NO_MODIFICATION_ALLOWED_ERR = ((ExceptionMessage[7]="No modification allowed"),7);
+var NOT_FOUND_ERR = ExceptionCode.NOT_FOUND_ERR = ((ExceptionMessage[8]="Not found"),8);
+var NOT_SUPPORTED_ERR = ExceptionCode.NOT_SUPPORTED_ERR = ((ExceptionMessage[9]="Not supported"),9);
+var INUSE_ATTRIBUTE_ERR = ExceptionCode.INUSE_ATTRIBUTE_ERR = ((ExceptionMessage[10]="Attribute in use"),10);
+//level2
+var INVALID_STATE_ERR = ExceptionCode.INVALID_STATE_ERR = ((ExceptionMessage[11]="Invalid state"),11);
+var SYNTAX_ERR = ExceptionCode.SYNTAX_ERR = ((ExceptionMessage[12]="Syntax error"),12);
+var INVALID_MODIFICATION_ERR = ExceptionCode.INVALID_MODIFICATION_ERR = ((ExceptionMessage[13]="Invalid modification"),13);
+var NAMESPACE_ERR = ExceptionCode.NAMESPACE_ERR = ((ExceptionMessage[14]="Invalid namespace"),14);
+var INVALID_ACCESS_ERR = ExceptionCode.INVALID_ACCESS_ERR = ((ExceptionMessage[15]="Invalid access"),15);
+
+/**
+ * DOM Level 2
+ * Object DOMException
+ * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html
+ * @see http://www.w3.org/TR/REC-DOM-Level-1/ecma-script-language-binding.html
+ */
+function DOMException(code, message) {
+ if(message instanceof Error){
+ var error = message;
+ }else{
+ error = this;
+ Error.call(this, ExceptionMessage[code]);
+ this.message = ExceptionMessage[code];
+ if(Error.captureStackTrace) Error.captureStackTrace(this, DOMException);
+ }
+ error.code = code;
+ if(message) this.message = this.message + ": " + message;
+ return error;
+};
+DOMException.prototype = Error.prototype;
+copy(ExceptionCode,DOMException)
+/**
+ * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-536297177
+ * The NodeList interface provides the abstraction of an ordered collection of nodes, without defining or constraining how this collection is implemented. NodeList objects in the DOM are live.
+ * The items in the NodeList are accessible via an integral index, starting from 0.
+ */
+function NodeList() {
+};
+NodeList.prototype = {
+ /**
+ * The number of nodes in the list. The range of valid child node indices is 0 to length-1 inclusive.
+ * @standard level1
+ */
+ length:0,
+ /**
+ * Returns the indexth item in the collection. If index is greater than or equal to the number of nodes in the list, this returns null.
+ * @standard level1
+ * @param index unsigned long
+ * Index into the collection.
+ * @return Node
+ * The node at the indexth position in the NodeList, or null if that is not a valid index.
+ */
+ item: function(index) {
+ return this[index] || null;
+ },
+ toString:function(isHTML,nodeFilter){
+ for(var buf = [], i = 0;i=0){
+ var lastIndex = list.length-1
+ while(i0 || key == 'xmlns'){
+// return null;
+// }
+ //console.log()
+ var i = this.length;
+ while(i--){
+ var attr = this[i];
+ //console.log(attr.nodeName,key)
+ if(attr.nodeName == key){
+ return attr;
+ }
+ }
+ },
+ setNamedItem: function(attr) {
+ var el = attr.ownerElement;
+ if(el && el!=this._ownerElement){
+ throw new DOMException(INUSE_ATTRIBUTE_ERR);
+ }
+ var oldAttr = this.getNamedItem(attr.nodeName);
+ _addNamedNode(this._ownerElement,this,attr,oldAttr);
+ return oldAttr;
+ },
+ /* returns Node */
+ setNamedItemNS: function(attr) {// raises: WRONG_DOCUMENT_ERR,NO_MODIFICATION_ALLOWED_ERR,INUSE_ATTRIBUTE_ERR
+ var el = attr.ownerElement, oldAttr;
+ if(el && el!=this._ownerElement){
+ throw new DOMException(INUSE_ATTRIBUTE_ERR);
+ }
+ oldAttr = this.getNamedItemNS(attr.namespaceURI,attr.localName);
+ _addNamedNode(this._ownerElement,this,attr,oldAttr);
+ return oldAttr;
+ },
+
+ /* returns Node */
+ removeNamedItem: function(key) {
+ var attr = this.getNamedItem(key);
+ _removeNamedNode(this._ownerElement,this,attr);
+ return attr;
+
+
+ },// raises: NOT_FOUND_ERR,NO_MODIFICATION_ALLOWED_ERR
+
+ //for level2
+ removeNamedItemNS:function(namespaceURI,localName){
+ var attr = this.getNamedItemNS(namespaceURI,localName);
+ _removeNamedNode(this._ownerElement,this,attr);
+ return attr;
+ },
+ getNamedItemNS: function(namespaceURI, localName) {
+ var i = this.length;
+ while(i--){
+ var node = this[i];
+ if(node.localName == localName && node.namespaceURI == namespaceURI){
+ return node;
+ }
+ }
+ return null;
+ }
+};
+/**
+ * @see http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#ID-102161490
+ */
+function DOMImplementation(/* Object */ features) {
+ this._features = {};
+ if (features) {
+ for (var feature in features) {
+ this._features = features[feature];
+ }
+ }
+};
+
+DOMImplementation.prototype = {
+ hasFeature: function(/* string */ feature, /* string */ version) {
+ var versions = this._features[feature.toLowerCase()];
+ if (versions && (!version || version in versions)) {
+ return true;
+ } else {
+ return false;
+ }
+ },
+ // Introduced in DOM Level 2:
+ createDocument:function(namespaceURI, qualifiedName, doctype){// raises:INVALID_CHARACTER_ERR,NAMESPACE_ERR,WRONG_DOCUMENT_ERR
+ var doc = new Document();
+ doc.implementation = this;
+ doc.childNodes = new NodeList();
+ doc.doctype = doctype;
+ if(doctype){
+ doc.appendChild(doctype);
+ }
+ if(qualifiedName){
+ var root = doc.createElementNS(namespaceURI,qualifiedName);
+ doc.appendChild(root);
+ }
+ return doc;
+ },
+ // Introduced in DOM Level 2:
+ createDocumentType:function(qualifiedName, publicId, systemId){// raises:INVALID_CHARACTER_ERR,NAMESPACE_ERR
+ var node = new DocumentType();
+ node.name = qualifiedName;
+ node.nodeName = qualifiedName;
+ node.publicId = publicId;
+ node.systemId = systemId;
+ // Introduced in DOM Level 2:
+ //readonly attribute DOMString internalSubset;
+
+ //TODO:..
+ // readonly attribute NamedNodeMap entities;
+ // readonly attribute NamedNodeMap notations;
+ return node;
+ }
+};
+
+
+/**
+ * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-1950641247
+ */
+
+function Node() {
+};
+
+Node.prototype = {
+ firstChild : null,
+ lastChild : null,
+ previousSibling : null,
+ nextSibling : null,
+ attributes : null,
+ parentNode : null,
+ childNodes : null,
+ ownerDocument : null,
+ nodeValue : null,
+ namespaceURI : null,
+ prefix : null,
+ localName : null,
+ // Modified in DOM Level 2:
+ insertBefore:function(newChild, refChild){//raises
+ return _insertBefore(this,newChild,refChild);
+ },
+ replaceChild:function(newChild, oldChild){//raises
+ this.insertBefore(newChild,oldChild);
+ if(oldChild){
+ this.removeChild(oldChild);
+ }
+ },
+ removeChild:function(oldChild){
+ return _removeChild(this,oldChild);
+ },
+ appendChild:function(newChild){
+ return this.insertBefore(newChild,null);
+ },
+ hasChildNodes:function(){
+ return this.firstChild != null;
+ },
+ cloneNode:function(deep){
+ return cloneNode(this.ownerDocument||this,this,deep);
+ },
+ // Modified in DOM Level 2:
+ normalize:function(){
+ var child = this.firstChild;
+ while(child){
+ var next = child.nextSibling;
+ if(next && next.nodeType == TEXT_NODE && child.nodeType == TEXT_NODE){
+ this.removeChild(next);
+ child.appendData(next.data);
+ }else{
+ child.normalize();
+ child = next;
+ }
+ }
+ },
+ // Introduced in DOM Level 2:
+ isSupported:function(feature, version){
+ return this.ownerDocument.implementation.hasFeature(feature,version);
+ },
+ // Introduced in DOM Level 2:
+ hasAttributes:function(){
+ return this.attributes.length>0;
+ },
+ lookupPrefix:function(namespaceURI){
+ var el = this;
+ while(el){
+ var map = el._nsMap;
+ //console.dir(map)
+ if(map){
+ for(var n in map){
+ if(map[n] == namespaceURI){
+ return n;
+ }
+ }
+ }
+ el = el.nodeType == ATTRIBUTE_NODE?el.ownerDocument : el.parentNode;
+ }
+ return null;
+ },
+ // Introduced in DOM Level 3:
+ lookupNamespaceURI:function(prefix){
+ var el = this;
+ while(el){
+ var map = el._nsMap;
+ //console.dir(map)
+ if(map){
+ if(prefix in map){
+ return map[prefix] ;
+ }
+ }
+ el = el.nodeType == ATTRIBUTE_NODE?el.ownerDocument : el.parentNode;
+ }
+ return null;
+ },
+ // Introduced in DOM Level 3:
+ isDefaultNamespace:function(namespaceURI){
+ var prefix = this.lookupPrefix(namespaceURI);
+ return prefix == null;
+ }
+};
+
+
+function _xmlEncoder(c){
+ return c == '<' && '<' ||
+ c == '>' && '>' ||
+ c == '&' && '&' ||
+ c == '"' && '"' ||
+ ''+c.charCodeAt()+';'
+}
+
+
+copy(NodeType,Node);
+copy(NodeType,Node.prototype);
+
+/**
+ * @param callback return true for continue,false for break
+ * @return boolean true: break visit;
+ */
+function _visitNode(node,callback){
+ if(callback(node)){
+ return true;
+ }
+ if(node = node.firstChild){
+ do{
+ if(_visitNode(node,callback)){return true}
+ }while(node=node.nextSibling)
+ }
+}
+
+
+
+function Document(){
+}
+function _onAddAttribute(doc,el,newAttr){
+ doc && doc._inc++;
+ var ns = newAttr.namespaceURI ;
+ if(ns == 'http://www.w3.org/2000/xmlns/'){
+ //update namespace
+ el._nsMap[newAttr.prefix?newAttr.localName:''] = newAttr.value
+ }
+}
+function _onRemoveAttribute(doc,el,newAttr,remove){
+ doc && doc._inc++;
+ var ns = newAttr.namespaceURI ;
+ if(ns == 'http://www.w3.org/2000/xmlns/'){
+ //update namespace
+ delete el._nsMap[newAttr.prefix?newAttr.localName:'']
+ }
+}
+function _onUpdateChild(doc,el,newChild){
+ if(doc && doc._inc){
+ doc._inc++;
+ //update childNodes
+ var cs = el.childNodes;
+ if(newChild){
+ cs[cs.length++] = newChild;
+ }else{
+ //console.log(1)
+ var child = el.firstChild;
+ var i = 0;
+ while(child){
+ cs[i++] = child;
+ child =child.nextSibling;
+ }
+ cs.length = i;
+ }
+ }
+}
+
+/**
+ * attributes;
+ * children;
+ *
+ * writeable properties:
+ * nodeValue,Attr:value,CharacterData:data
+ * prefix
+ */
+function _removeChild(parentNode,child){
+ var previous = child.previousSibling;
+ var next = child.nextSibling;
+ if(previous){
+ previous.nextSibling = next;
+ }else{
+ parentNode.firstChild = next
+ }
+ if(next){
+ next.previousSibling = previous;
+ }else{
+ parentNode.lastChild = previous;
+ }
+ _onUpdateChild(parentNode.ownerDocument,parentNode);
+ return child;
+}
+/**
+ * preformance key(refChild == null)
+ */
+function _insertBefore(parentNode,newChild,nextChild){
+ var cp = newChild.parentNode;
+ if(cp){
+ cp.removeChild(newChild);//remove and update
+ }
+ if(newChild.nodeType === DOCUMENT_FRAGMENT_NODE){
+ var newFirst = newChild.firstChild;
+ if (newFirst == null) {
+ return newChild;
+ }
+ var newLast = newChild.lastChild;
+ }else{
+ newFirst = newLast = newChild;
+ }
+ var pre = nextChild ? nextChild.previousSibling : parentNode.lastChild;
+
+ newFirst.previousSibling = pre;
+ newLast.nextSibling = nextChild;
+
+
+ if(pre){
+ pre.nextSibling = newFirst;
+ }else{
+ parentNode.firstChild = newFirst;
+ }
+ if(nextChild == null){
+ parentNode.lastChild = newLast;
+ }else{
+ nextChild.previousSibling = newLast;
+ }
+ do{
+ newFirst.parentNode = parentNode;
+ }while(newFirst !== newLast && (newFirst= newFirst.nextSibling))
+ _onUpdateChild(parentNode.ownerDocument||parentNode,parentNode);
+ //console.log(parentNode.lastChild.nextSibling == null)
+ if (newChild.nodeType == DOCUMENT_FRAGMENT_NODE) {
+ newChild.firstChild = newChild.lastChild = null;
+ }
+ return newChild;
+}
+function _appendSingleChild(parentNode,newChild){
+ var cp = newChild.parentNode;
+ if(cp){
+ var pre = parentNode.lastChild;
+ cp.removeChild(newChild);//remove and update
+ var pre = parentNode.lastChild;
+ }
+ var pre = parentNode.lastChild;
+ newChild.parentNode = parentNode;
+ newChild.previousSibling = pre;
+ newChild.nextSibling = null;
+ if(pre){
+ pre.nextSibling = newChild;
+ }else{
+ parentNode.firstChild = newChild;
+ }
+ parentNode.lastChild = newChild;
+ _onUpdateChild(parentNode.ownerDocument,parentNode,newChild);
+ return newChild;
+ //console.log("__aa",parentNode.lastChild.nextSibling == null)
+}
+Document.prototype = {
+ //implementation : null,
+ nodeName : '#document',
+ nodeType : DOCUMENT_NODE,
+ doctype : null,
+ documentElement : null,
+ _inc : 1,
+
+ insertBefore : function(newChild, refChild){//raises
+ if(newChild.nodeType == DOCUMENT_FRAGMENT_NODE){
+ var child = newChild.firstChild;
+ while(child){
+ var next = child.nextSibling;
+ this.insertBefore(child,refChild);
+ child = next;
+ }
+ return newChild;
+ }
+ if(this.documentElement == null && newChild.nodeType == ELEMENT_NODE){
+ this.documentElement = newChild;
+ }
+
+ return _insertBefore(this,newChild,refChild),(newChild.ownerDocument = this),newChild;
+ },
+ removeChild : function(oldChild){
+ if(this.documentElement == oldChild){
+ this.documentElement = null;
+ }
+ return _removeChild(this,oldChild);
+ },
+ // Introduced in DOM Level 2:
+ importNode : function(importedNode,deep){
+ return importNode(this,importedNode,deep);
+ },
+ // Introduced in DOM Level 2:
+ getElementById : function(id){
+ var rtv = null;
+ _visitNode(this.documentElement,function(node){
+ if(node.nodeType == ELEMENT_NODE){
+ if(node.getAttribute('id') == id){
+ rtv = node;
+ return true;
+ }
+ }
+ })
+ return rtv;
+ },
+
+ getElementsByClassName: function(className) {
+ var pattern = new RegExp("(^|\\s)" + className + "(\\s|$)");
+ return new LiveNodeList(this, function(base) {
+ var ls = [];
+ _visitNode(base.documentElement, function(node) {
+ if(node !== base && node.nodeType == ELEMENT_NODE) {
+ if(pattern.test(node.getAttribute('class'))) {
+ ls.push(node);
+ }
+ }
+ });
+ return ls;
+ });
+ },
+
+ //document factory method:
+ createElement : function(tagName){
+ var node = new Element();
+ node.ownerDocument = this;
+ node.nodeName = tagName;
+ node.tagName = tagName;
+ node.childNodes = new NodeList();
+ var attrs = node.attributes = new NamedNodeMap();
+ attrs._ownerElement = node;
+ return node;
+ },
+ createDocumentFragment : function(){
+ var node = new DocumentFragment();
+ node.ownerDocument = this;
+ node.childNodes = new NodeList();
+ return node;
+ },
+ createTextNode : function(data){
+ var node = new Text();
+ node.ownerDocument = this;
+ node.appendData(data)
+ return node;
+ },
+ createComment : function(data){
+ var node = new Comment();
+ node.ownerDocument = this;
+ node.appendData(data)
+ return node;
+ },
+ createCDATASection : function(data){
+ var node = new CDATASection();
+ node.ownerDocument = this;
+ node.appendData(data)
+ return node;
+ },
+ createProcessingInstruction : function(target,data){
+ var node = new ProcessingInstruction();
+ node.ownerDocument = this;
+ node.tagName = node.target = target;
+ node.nodeValue= node.data = data;
+ return node;
+ },
+ createAttribute : function(name){
+ var node = new Attr();
+ node.ownerDocument = this;
+ node.name = name;
+ node.nodeName = name;
+ node.localName = name;
+ node.specified = true;
+ return node;
+ },
+ createEntityReference : function(name){
+ var node = new EntityReference();
+ node.ownerDocument = this;
+ node.nodeName = name;
+ return node;
+ },
+ // Introduced in DOM Level 2:
+ createElementNS : function(namespaceURI,qualifiedName){
+ var node = new Element();
+ var pl = qualifiedName.split(':');
+ var attrs = node.attributes = new NamedNodeMap();
+ node.childNodes = new NodeList();
+ node.ownerDocument = this;
+ node.nodeName = qualifiedName;
+ node.tagName = qualifiedName;
+ node.namespaceURI = namespaceURI;
+ if(pl.length == 2){
+ node.prefix = pl[0];
+ node.localName = pl[1];
+ }else{
+ //el.prefix = null;
+ node.localName = qualifiedName;
+ }
+ attrs._ownerElement = node;
+ return node;
+ },
+ // Introduced in DOM Level 2:
+ createAttributeNS : function(namespaceURI,qualifiedName){
+ var node = new Attr();
+ var pl = qualifiedName.split(':');
+ node.ownerDocument = this;
+ node.nodeName = qualifiedName;
+ node.name = qualifiedName;
+ node.namespaceURI = namespaceURI;
+ node.specified = true;
+ if(pl.length == 2){
+ node.prefix = pl[0];
+ node.localName = pl[1];
+ }else{
+ //el.prefix = null;
+ node.localName = qualifiedName;
+ }
+ return node;
+ }
+};
+_extends(Document,Node);
+
+
+function Element() {
+ this._nsMap = {};
+};
+Element.prototype = {
+ nodeType : ELEMENT_NODE,
+ hasAttribute : function(name){
+ return this.getAttributeNode(name)!=null;
+ },
+ getAttribute : function(name){
+ var attr = this.getAttributeNode(name);
+ return attr && attr.value || '';
+ },
+ getAttributeNode : function(name){
+ return this.attributes.getNamedItem(name);
+ },
+ setAttribute : function(name, value){
+ var attr = this.ownerDocument.createAttribute(name);
+ attr.value = attr.nodeValue = "" + value;
+ this.setAttributeNode(attr)
+ },
+ removeAttribute : function(name){
+ var attr = this.getAttributeNode(name)
+ attr && this.removeAttributeNode(attr);
+ },
+
+ //four real opeartion method
+ appendChild:function(newChild){
+ if(newChild.nodeType === DOCUMENT_FRAGMENT_NODE){
+ return this.insertBefore(newChild,null);
+ }else{
+ return _appendSingleChild(this,newChild);
+ }
+ },
+ setAttributeNode : function(newAttr){
+ return this.attributes.setNamedItem(newAttr);
+ },
+ setAttributeNodeNS : function(newAttr){
+ return this.attributes.setNamedItemNS(newAttr);
+ },
+ removeAttributeNode : function(oldAttr){
+ //console.log(this == oldAttr.ownerElement)
+ return this.attributes.removeNamedItem(oldAttr.nodeName);
+ },
+ //get real attribute name,and remove it by removeAttributeNode
+ removeAttributeNS : function(namespaceURI, localName){
+ var old = this.getAttributeNodeNS(namespaceURI, localName);
+ old && this.removeAttributeNode(old);
+ },
+
+ hasAttributeNS : function(namespaceURI, localName){
+ return this.getAttributeNodeNS(namespaceURI, localName)!=null;
+ },
+ getAttributeNS : function(namespaceURI, localName){
+ var attr = this.getAttributeNodeNS(namespaceURI, localName);
+ return attr && attr.value || '';
+ },
+ setAttributeNS : function(namespaceURI, qualifiedName, value){
+ var attr = this.ownerDocument.createAttributeNS(namespaceURI, qualifiedName);
+ attr.value = attr.nodeValue = "" + value;
+ this.setAttributeNode(attr)
+ },
+ getAttributeNodeNS : function(namespaceURI, localName){
+ return this.attributes.getNamedItemNS(namespaceURI, localName);
+ },
+
+ getElementsByTagName : function(tagName){
+ return new LiveNodeList(this,function(base){
+ var ls = [];
+ _visitNode(base,function(node){
+ if(node !== base && node.nodeType == ELEMENT_NODE && (tagName === '*' || node.tagName == tagName)){
+ ls.push(node);
+ }
+ });
+ return ls;
+ });
+ },
+ getElementsByTagNameNS : function(namespaceURI, localName){
+ return new LiveNodeList(this,function(base){
+ var ls = [];
+ _visitNode(base,function(node){
+ if(node !== base && node.nodeType === ELEMENT_NODE && (namespaceURI === '*' || node.namespaceURI === namespaceURI) && (localName === '*' || node.localName == localName)){
+ ls.push(node);
+ }
+ });
+ return ls;
+
+ });
+ }
+};
+Document.prototype.getElementsByTagName = Element.prototype.getElementsByTagName;
+Document.prototype.getElementsByTagNameNS = Element.prototype.getElementsByTagNameNS;
+
+
+_extends(Element,Node);
+function Attr() {
+};
+Attr.prototype.nodeType = ATTRIBUTE_NODE;
+_extends(Attr,Node);
+
+
+function CharacterData() {
+};
+CharacterData.prototype = {
+ data : '',
+ substringData : function(offset, count) {
+ return this.data.substring(offset, offset+count);
+ },
+ appendData: function(text) {
+ text = this.data+text;
+ this.nodeValue = this.data = text;
+ this.length = text.length;
+ },
+ insertData: function(offset,text) {
+ this.replaceData(offset,0,text);
+
+ },
+ appendChild:function(newChild){
+ throw new Error(ExceptionMessage[HIERARCHY_REQUEST_ERR])
+ },
+ deleteData: function(offset, count) {
+ this.replaceData(offset,count,"");
+ },
+ replaceData: function(offset, count, text) {
+ var start = this.data.substring(0,offset);
+ var end = this.data.substring(offset+count);
+ text = start + text + end;
+ this.nodeValue = this.data = text;
+ this.length = text.length;
+ }
+}
+_extends(CharacterData,Node);
+function Text() {
+};
+Text.prototype = {
+ nodeName : "#text",
+ nodeType : TEXT_NODE,
+ splitText : function(offset) {
+ var text = this.data;
+ var newText = text.substring(offset);
+ text = text.substring(0, offset);
+ this.data = this.nodeValue = text;
+ this.length = text.length;
+ var newNode = this.ownerDocument.createTextNode(newText);
+ if(this.parentNode){
+ this.parentNode.insertBefore(newNode, this.nextSibling);
+ }
+ return newNode;
+ }
+}
+_extends(Text,CharacterData);
+function Comment() {
+};
+Comment.prototype = {
+ nodeName : "#comment",
+ nodeType : COMMENT_NODE
+}
+_extends(Comment,CharacterData);
+
+function CDATASection() {
+};
+CDATASection.prototype = {
+ nodeName : "#cdata-section",
+ nodeType : CDATA_SECTION_NODE
+}
+_extends(CDATASection,CharacterData);
+
+
+function DocumentType() {
+};
+DocumentType.prototype.nodeType = DOCUMENT_TYPE_NODE;
+_extends(DocumentType,Node);
+
+function Notation() {
+};
+Notation.prototype.nodeType = NOTATION_NODE;
+_extends(Notation,Node);
+
+function Entity() {
+};
+Entity.prototype.nodeType = ENTITY_NODE;
+_extends(Entity,Node);
+
+function EntityReference() {
+};
+EntityReference.prototype.nodeType = ENTITY_REFERENCE_NODE;
+_extends(EntityReference,Node);
+
+function DocumentFragment() {
+};
+DocumentFragment.prototype.nodeName = "#document-fragment";
+DocumentFragment.prototype.nodeType = DOCUMENT_FRAGMENT_NODE;
+_extends(DocumentFragment,Node);
+
+
+function ProcessingInstruction() {
+}
+ProcessingInstruction.prototype.nodeType = PROCESSING_INSTRUCTION_NODE;
+_extends(ProcessingInstruction,Node);
+function XMLSerializer(){}
+XMLSerializer.prototype.serializeToString = function(node,isHtml,nodeFilter){
+ return nodeSerializeToString.call(node,isHtml,nodeFilter);
+}
+Node.prototype.toString = nodeSerializeToString;
+function nodeSerializeToString(isHtml,nodeFilter){
+ var buf = [];
+ var refNode = this.nodeType == 9 && this.documentElement || this;
+ var prefix = refNode.prefix;
+ var uri = refNode.namespaceURI;
+
+ if(uri && prefix == null){
+ //console.log(prefix)
+ var prefix = refNode.lookupPrefix(uri);
+ if(prefix == null){
+ //isHTML = true;
+ var visibleNamespaces=[
+ {namespace:uri,prefix:null}
+ //{namespace:uri,prefix:''}
+ ]
+ }
+ }
+ serializeToString(this,buf,isHtml,nodeFilter,visibleNamespaces);
+ //console.log('###',this.nodeType,uri,prefix,buf.join(''))
+ return buf.join('');
+}
+function needNamespaceDefine(node,isHTML, visibleNamespaces) {
+ var prefix = node.prefix||'';
+ var uri = node.namespaceURI;
+ if (!prefix && !uri){
+ return false;
+ }
+ if (prefix === "xml" && uri === "http://www.w3.org/XML/1998/namespace"
+ || uri == 'http://www.w3.org/2000/xmlns/'){
+ return false;
+ }
+
+ var i = visibleNamespaces.length
+ //console.log('@@@@',node.tagName,prefix,uri,visibleNamespaces)
+ while (i--) {
+ var ns = visibleNamespaces[i];
+ // get namespace prefix
+ //console.log(node.nodeType,node.tagName,ns.prefix,prefix)
+ if (ns.prefix == prefix){
+ return ns.namespace != uri;
+ }
+ }
+ //console.log(isHTML,uri,prefix=='')
+ //if(isHTML && prefix ==null && uri == 'http://www.w3.org/1999/xhtml'){
+ // return false;
+ //}
+ //node.flag = '11111'
+ //console.error(3,true,node.flag,node.prefix,node.namespaceURI)
+ return true;
+}
+function serializeToString(node,buf,isHTML,nodeFilter,visibleNamespaces){
+ if(nodeFilter){
+ node = nodeFilter(node);
+ if(node){
+ if(typeof node == 'string'){
+ buf.push(node);
+ return;
+ }
+ }else{
+ return;
+ }
+ //buf.sort.apply(attrs, attributeSorter);
+ }
+ switch(node.nodeType){
+ case ELEMENT_NODE:
+ if (!visibleNamespaces) visibleNamespaces = [];
+ var startVisibleNamespaces = visibleNamespaces.length;
+ var attrs = node.attributes;
+ var len = attrs.length;
+ var child = node.firstChild;
+ var nodeName = node.tagName;
+
+ isHTML = (htmlns === node.namespaceURI) ||isHTML
+ buf.push('<',nodeName);
+
+
+
+ for(var i=0;i');
+ //if is cdata child node
+ if(isHTML && /^script$/i.test(nodeName)){
+ while(child){
+ if(child.data){
+ buf.push(child.data);
+ }else{
+ serializeToString(child,buf,isHTML,nodeFilter,visibleNamespaces);
+ }
+ child = child.nextSibling;
+ }
+ }else
+ {
+ while(child){
+ serializeToString(child,buf,isHTML,nodeFilter,visibleNamespaces);
+ child = child.nextSibling;
+ }
+ }
+ buf.push('',nodeName,'>');
+ }else{
+ buf.push('/>');
+ }
+ // remove added visible namespaces
+ //visibleNamespaces.length = startVisibleNamespaces;
+ return;
+ case DOCUMENT_NODE:
+ case DOCUMENT_FRAGMENT_NODE:
+ var child = node.firstChild;
+ while(child){
+ serializeToString(child,buf,isHTML,nodeFilter,visibleNamespaces);
+ child = child.nextSibling;
+ }
+ return;
+ case ATTRIBUTE_NODE:
+ /**
+ * Well-formedness constraint: No < in Attribute Values
+ * The replacement text of any entity referred to directly or indirectly in an attribute value must not contain a <.
+ * @see https://www.w3.org/TR/xml/#CleanAttrVals
+ * @see https://www.w3.org/TR/xml/#NT-AttValue
+ */
+ return buf.push(' ', node.name, '="', node.value.replace(/[<&"]/g,_xmlEncoder), '"');
+ case TEXT_NODE:
+ /**
+ * The ampersand character (&) and the left angle bracket (<) must not appear in their literal form,
+ * except when used as markup delimiters, or within a comment, a processing instruction, or a CDATA section.
+ * If they are needed elsewhere, they must be escaped using either numeric character references or the strings
+ * `&` and `<` respectively.
+ * The right angle bracket (>) may be represented using the string " > ", and must, for compatibility,
+ * be escaped using either `>` or a character reference when it appears in the string `]]>` in content,
+ * when that string is not marking the end of a CDATA section.
+ *
+ * In the content of elements, character data is any string of characters
+ * which does not contain the start-delimiter of any markup
+ * and does not include the CDATA-section-close delimiter, `]]>`.
+ *
+ * @see https://www.w3.org/TR/xml/#NT-CharData
+ */
+ return buf.push(node.data
+ .replace(/[<&]/g,_xmlEncoder)
+ .replace(/]]>/g, ']]>')
+ );
+ case CDATA_SECTION_NODE:
+ return buf.push( '');
+ case COMMENT_NODE:
+ return buf.push( "");
+ case DOCUMENT_TYPE_NODE:
+ var pubid = node.publicId;
+ var sysid = node.systemId;
+ buf.push('');
+ }else if(sysid && sysid!='.'){
+ buf.push(' SYSTEM ', sysid, '>');
+ }else{
+ var sub = node.internalSubset;
+ if(sub){
+ buf.push(" [",sub,"]");
+ }
+ buf.push(">");
+ }
+ return;
+ case PROCESSING_INSTRUCTION_NODE:
+ return buf.push( "",node.target," ",node.data,"?>");
+ case ENTITY_REFERENCE_NODE:
+ return buf.push( '&',node.nodeName,';');
+ //case ENTITY_NODE:
+ //case NOTATION_NODE:
+ default:
+ buf.push('??',node.nodeName);
+ }
+}
+function importNode(doc,node,deep){
+ var node2;
+ switch (node.nodeType) {
+ case ELEMENT_NODE:
+ node2 = node.cloneNode(false);
+ node2.ownerDocument = doc;
+ //var attrs = node2.attributes;
+ //var len = attrs.length;
+ //for(var i=0;i',
+ amp: '&',
+ quot: '"',
+ apos: "'",
+ Agrave: "À",
+ Aacute: "Á",
+ Acirc: "Â",
+ Atilde: "Ã",
+ Auml: "Ä",
+ Aring: "Å",
+ AElig: "Æ",
+ Ccedil: "Ç",
+ Egrave: "È",
+ Eacute: "É",
+ Ecirc: "Ê",
+ Euml: "Ë",
+ Igrave: "Ì",
+ Iacute: "Í",
+ Icirc: "Î",
+ Iuml: "Ï",
+ ETH: "Ð",
+ Ntilde: "Ñ",
+ Ograve: "Ò",
+ Oacute: "Ó",
+ Ocirc: "Ô",
+ Otilde: "Õ",
+ Ouml: "Ö",
+ Oslash: "Ø",
+ Ugrave: "Ù",
+ Uacute: "Ú",
+ Ucirc: "Û",
+ Uuml: "Ü",
+ Yacute: "Ý",
+ THORN: "Þ",
+ szlig: "ß",
+ agrave: "à",
+ aacute: "á",
+ acirc: "â",
+ atilde: "ã",
+ auml: "ä",
+ aring: "å",
+ aelig: "æ",
+ ccedil: "ç",
+ egrave: "è",
+ eacute: "é",
+ ecirc: "ê",
+ euml: "ë",
+ igrave: "ì",
+ iacute: "í",
+ icirc: "î",
+ iuml: "ï",
+ eth: "ð",
+ ntilde: "ñ",
+ ograve: "ò",
+ oacute: "ó",
+ ocirc: "ô",
+ otilde: "õ",
+ ouml: "ö",
+ oslash: "ø",
+ ugrave: "ù",
+ uacute: "ú",
+ ucirc: "û",
+ uuml: "ü",
+ yacute: "ý",
+ thorn: "þ",
+ yuml: "ÿ",
+ nbsp: "\u00a0",
+ iexcl: "¡",
+ cent: "¢",
+ pound: "£",
+ curren: "¤",
+ yen: "¥",
+ brvbar: "¦",
+ sect: "§",
+ uml: "¨",
+ copy: "©",
+ ordf: "ª",
+ laquo: "«",
+ not: "¬",
+ shy: "",
+ reg: "®",
+ macr: "¯",
+ deg: "°",
+ plusmn: "±",
+ sup2: "²",
+ sup3: "³",
+ acute: "´",
+ micro: "µ",
+ para: "¶",
+ middot: "·",
+ cedil: "¸",
+ sup1: "¹",
+ ordm: "º",
+ raquo: "»",
+ frac14: "¼",
+ frac12: "½",
+ frac34: "¾",
+ iquest: "¿",
+ times: "×",
+ divide: "÷",
+ forall: "∀",
+ part: "∂",
+ exist: "∃",
+ empty: "∅",
+ nabla: "∇",
+ isin: "∈",
+ notin: "∉",
+ ni: "∋",
+ prod: "∏",
+ sum: "∑",
+ minus: "−",
+ lowast: "∗",
+ radic: "√",
+ prop: "∝",
+ infin: "∞",
+ ang: "∠",
+ and: "∧",
+ or: "∨",
+ cap: "∩",
+ cup: "∪",
+ 'int': "∫",
+ there4: "∴",
+ sim: "∼",
+ cong: "≅",
+ asymp: "≈",
+ ne: "≠",
+ equiv: "≡",
+ le: "≤",
+ ge: "≥",
+ sub: "⊂",
+ sup: "⊃",
+ nsub: "⊄",
+ sube: "⊆",
+ supe: "⊇",
+ oplus: "⊕",
+ otimes: "⊗",
+ perp: "⊥",
+ sdot: "⋅",
+ Alpha: "Α",
+ Beta: "Β",
+ Gamma: "Γ",
+ Delta: "Δ",
+ Epsilon: "Ε",
+ Zeta: "Ζ",
+ Eta: "Η",
+ Theta: "Θ",
+ Iota: "Ι",
+ Kappa: "Κ",
+ Lambda: "Λ",
+ Mu: "Μ",
+ Nu: "Ν",
+ Xi: "Ξ",
+ Omicron: "Ο",
+ Pi: "Π",
+ Rho: "Ρ",
+ Sigma: "Σ",
+ Tau: "Τ",
+ Upsilon: "Υ",
+ Phi: "Φ",
+ Chi: "Χ",
+ Psi: "Ψ",
+ Omega: "Ω",
+ alpha: "α",
+ beta: "β",
+ gamma: "γ",
+ delta: "δ",
+ epsilon: "ε",
+ zeta: "ζ",
+ eta: "η",
+ theta: "θ",
+ iota: "ι",
+ kappa: "κ",
+ lambda: "λ",
+ mu: "μ",
+ nu: "ν",
+ xi: "ξ",
+ omicron: "ο",
+ pi: "π",
+ rho: "ρ",
+ sigmaf: "ς",
+ sigma: "σ",
+ tau: "τ",
+ upsilon: "υ",
+ phi: "φ",
+ chi: "χ",
+ psi: "ψ",
+ omega: "ω",
+ thetasym: "ϑ",
+ upsih: "ϒ",
+ piv: "ϖ",
+ OElig: "Œ",
+ oelig: "œ",
+ Scaron: "Š",
+ scaron: "š",
+ Yuml: "Ÿ",
+ fnof: "ƒ",
+ circ: "ˆ",
+ tilde: "˜",
+ ensp: " ",
+ emsp: " ",
+ thinsp: " ",
+ zwnj: "",
+ zwj: "",
+ lrm: "",
+ rlm: "",
+ ndash: "–",
+ mdash: "—",
+ lsquo: "‘",
+ rsquo: "’",
+ sbquo: "‚",
+ ldquo: "“",
+ rdquo: "”",
+ bdquo: "„",
+ dagger: "†",
+ Dagger: "‡",
+ bull: "•",
+ hellip: "…",
+ permil: "‰",
+ prime: "′",
+ Prime: "″",
+ lsaquo: "‹",
+ rsaquo: "›",
+ oline: "‾",
+ euro: "€",
+ trade: "™",
+ larr: "←",
+ uarr: "↑",
+ rarr: "→",
+ darr: "↓",
+ harr: "↔",
+ crarr: "↵",
+ lceil: "⌈",
+ rceil: "⌉",
+ lfloor: "⌊",
+ rfloor: "⌋",
+ loz: "◊",
+ spades: "♠",
+ clubs: "♣",
+ hearts: "♥",
+ diams: "♦"
+};
diff --git a/temporary_modules/trezor-connect/node_modules/plist/lib/xmldom/sax.js b/temporary_modules/trezor-connect/node_modules/plist/lib/xmldom/sax.js
new file mode 100644
index 00000000..ad9f1846
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/plist/lib/xmldom/sax.js
@@ -0,0 +1,642 @@
+//[4] NameStartChar ::= ":" | [A-Z] | "_" | [a-z] | [#xC0-#xD6] | [#xD8-#xF6] | [#xF8-#x2FF] | [#x370-#x37D] | [#x37F-#x1FFF] | [#x200C-#x200D] | [#x2070-#x218F] | [#x2C00-#x2FEF] | [#x3001-#xD7FF] | [#xF900-#xFDCF] | [#xFDF0-#xFFFD] | [#x10000-#xEFFFF]
+//[4a] NameChar ::= NameStartChar | "-" | "." | [0-9] | #xB7 | [#x0300-#x036F] | [#x203F-#x2040]
+//[5] Name ::= NameStartChar (NameChar)*
+var nameStartChar = /[A-Z_a-z\xC0-\xD6\xD8-\xF6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]///\u10000-\uEFFFF
+var nameChar = new RegExp("[\\-\\.0-9"+nameStartChar.source.slice(1,-1)+"\\u00B7\\u0300-\\u036F\\u203F-\\u2040]");
+var tagNamePattern = new RegExp('^'+nameStartChar.source+nameChar.source+'*(?:\:'+nameStartChar.source+nameChar.source+'*)?$');
+//var tagNamePattern = /^[a-zA-Z_][\w\-\.]*(?:\:[a-zA-Z_][\w\-\.]*)?$/
+//var handlers = 'resolveEntity,getExternalSubset,characters,endDocument,endElement,endPrefixMapping,ignorableWhitespace,processingInstruction,setDocumentLocator,skippedEntity,startDocument,startElement,startPrefixMapping,notationDecl,unparsedEntityDecl,error,fatalError,warning,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,comment,endCDATA,endDTD,endEntity,startCDATA,startDTD,startEntity'.split(',')
+
+//S_TAG, S_ATTR, S_EQ, S_ATTR_NOQUOT_VALUE
+//S_ATTR_SPACE, S_ATTR_END, S_TAG_SPACE, S_TAG_CLOSE
+var S_TAG = 0;//tag name offerring
+var S_ATTR = 1;//attr name offerring
+var S_ATTR_SPACE=2;//attr name end and space offer
+var S_EQ = 3;//=space?
+var S_ATTR_NOQUOT_VALUE = 4;//attr value(no quot value only)
+var S_ATTR_END = 5;//attr value end and no space(quot end)
+var S_TAG_SPACE = 6;//(attr value end || tag end ) && (space offer)
+var S_TAG_CLOSE = 7;//closed el
+
+/**
+ * Creates an error that will not be caught by XMLReader aka the SAX parser.
+ *
+ * @param {string} message
+ * @param {any?} locator Optional, can provide details about the location in the source
+ * @constructor
+ */
+function ParseError(message, locator) {
+ this.message = message
+ this.locator = locator
+ if(Error.captureStackTrace) Error.captureStackTrace(this, ParseError);
+}
+ParseError.prototype = new Error();
+ParseError.prototype.name = ParseError.name
+
+function XMLReader(){
+
+}
+
+XMLReader.prototype = {
+ parse:function(source,defaultNSMap,entityMap){
+ var domBuilder = this.domBuilder;
+ domBuilder.startDocument();
+ _copy(defaultNSMap ,defaultNSMap = {})
+ parse(source,defaultNSMap,entityMap,
+ domBuilder,this.errorHandler);
+ domBuilder.endDocument();
+ }
+}
+function parse(source,defaultNSMapCopy,entityMap,domBuilder,errorHandler){
+ function fixedFromCharCode(code) {
+ // String.prototype.fromCharCode does not supports
+ // > 2 bytes unicode chars directly
+ if (code > 0xffff) {
+ code -= 0x10000;
+ var surrogate1 = 0xd800 + (code >> 10)
+ , surrogate2 = 0xdc00 + (code & 0x3ff);
+
+ return String.fromCharCode(surrogate1, surrogate2);
+ } else {
+ return String.fromCharCode(code);
+ }
+ }
+ function entityReplacer(a){
+ var k = a.slice(1,-1);
+ if(k in entityMap){
+ return entityMap[k];
+ }else if(k.charAt(0) === '#'){
+ return fixedFromCharCode(parseInt(k.substr(1).replace('x','0x')))
+ }else{
+ errorHandler.error('entity not found:'+a);
+ return a;
+ }
+ }
+ function appendText(end){//has some bugs
+ if(end>start){
+ var xt = source.substring(start,end).replace(/?\w+;/g,entityReplacer);
+ locator&&position(start);
+ domBuilder.characters(xt,0,end-start);
+ start = end
+ }
+ }
+ function position(p,m){
+ while(p>=lineEnd && (m = linePattern.exec(source))){
+ lineStart = m.index;
+ lineEnd = lineStart + m[0].length;
+ locator.lineNumber++;
+ //console.log('line++:',locator,startPos,endPos)
+ }
+ locator.columnNumber = p-lineStart+1;
+ }
+ var lineStart = 0;
+ var lineEnd = 0;
+ var linePattern = /.*(?:\r\n?|\n)|.*$/g
+ var locator = domBuilder.locator;
+
+ var parseStack = [{currentNSMap:defaultNSMapCopy}]
+ var closeMap = {};
+ var start = 0;
+ while(true){
+ try{
+ var tagStart = source.indexOf('<',start);
+ if(tagStart<0){
+ if(!source.substr(start).match(/^\s*$/)){
+ var doc = domBuilder.doc;
+ var text = doc.createTextNode(source.substr(start));
+ doc.appendChild(text);
+ domBuilder.currentElement = text;
+ }
+ return;
+ }
+ if(tagStart>start){
+ appendText(tagStart);
+ }
+ switch(source.charAt(tagStart+1)){
+ case '/':
+ var end = source.indexOf('>',tagStart+3);
+ var tagName = source.substring(tagStart+2,end);
+ var config = parseStack.pop();
+ if(end<0){
+
+ tagName = source.substring(tagStart+2).replace(/[\s<].*/,'');
+ errorHandler.error("end tag name: "+tagName+' is not complete:'+config.tagName);
+ end = tagStart+1+tagName.length;
+ }else if(tagName.match(/\s)){
+ tagName = tagName.replace(/[\s<].*/,'');
+ errorHandler.error("end tag name: "+tagName+' maybe not complete');
+ end = tagStart+1+tagName.length;
+ }
+ var localNSMap = config.localNSMap;
+ var endMatch = config.tagName == tagName;
+ var endIgnoreCaseMach = endMatch || config.tagName&&config.tagName.toLowerCase() == tagName.toLowerCase()
+ if(endIgnoreCaseMach){
+ domBuilder.endElement(config.uri,config.localName,tagName);
+ if(localNSMap){
+ for(var prefix in localNSMap){
+ domBuilder.endPrefixMapping(prefix) ;
+ }
+ }
+ if(!endMatch){
+ errorHandler.fatalError("end tag name: "+tagName+' is not match the current start tagName:'+config.tagName ); // No known test case
+ }
+ }else{
+ parseStack.push(config)
+ }
+
+ end++;
+ break;
+ // end elment
+ case '?':// ...?>
+ locator&&position(tagStart);
+ end = parseInstruction(source,tagStart,domBuilder);
+ break;
+ case '!':// start){
+ start = end;
+ }else{
+ //TODO: 这里有可能sax回退,有位置错误风险
+ appendText(Math.max(tagStart,start)+1);
+ }
+ }
+}
+function copyLocator(f,t){
+ t.lineNumber = f.lineNumber;
+ t.columnNumber = f.columnNumber;
+ return t;
+}
+
+/**
+ * @see #appendElement(source,elStartEnd,el,selfClosed,entityReplacer,domBuilder,parseStack);
+ * @return end of the elementStartPart(end of elementEndPart for selfClosed el)
+ */
+function parseElementStartPart(source,start,el,currentNSMap,entityReplacer,errorHandler){
+
+ /**
+ * @param {string} qname
+ * @param {string} value
+ * @param {number} startIndex
+ */
+ function addAttribute(qname, value, startIndex) {
+ if (qname in el.attributeNames) errorHandler.fatalError('Attribute ' + qname + ' redefined')
+ el.addValue(qname, value, startIndex)
+ }
+ var attrName;
+ var value;
+ var p = ++start;
+ var s = S_TAG;//status
+ while(true){
+ var c = source.charAt(p);
+ switch(c){
+ case '=':
+ if(s === S_ATTR){//attrName
+ attrName = source.slice(start,p);
+ s = S_EQ;
+ }else if(s === S_ATTR_SPACE){
+ s = S_EQ;
+ }else{
+ //fatalError: equal must after attrName or space after attrName
+ throw new Error('attribute equal must after attrName'); // No known test case
+ }
+ break;
+ case '\'':
+ case '"':
+ if(s === S_EQ || s === S_ATTR //|| s == S_ATTR_SPACE
+ ){//equal
+ if(s === S_ATTR){
+ errorHandler.warning('attribute value must after "="')
+ attrName = source.slice(start,p)
+ }
+ start = p+1;
+ p = source.indexOf(c,start)
+ if(p>0){
+ value = source.slice(start,p).replace(/?\w+;/g,entityReplacer);
+ addAttribute(attrName, value, start-1);
+ s = S_ATTR_END;
+ }else{
+ //fatalError: no end quot match
+ throw new Error('attribute value no end \''+c+'\' match');
+ }
+ }else if(s == S_ATTR_NOQUOT_VALUE){
+ value = source.slice(start,p).replace(/?\w+;/g,entityReplacer);
+ //console.log(attrName,value,start,p)
+ addAttribute(attrName, value, start);
+ //console.dir(el)
+ errorHandler.warning('attribute "'+attrName+'" missed start quot('+c+')!!');
+ start = p+1;
+ s = S_ATTR_END
+ }else{
+ //fatalError: no equal before
+ throw new Error('attribute value must after "="'); // No known test case
+ }
+ break;
+ case '/':
+ switch(s){
+ case S_TAG:
+ el.setTagName(source.slice(start,p));
+ case S_ATTR_END:
+ case S_TAG_SPACE:
+ case S_TAG_CLOSE:
+ s =S_TAG_CLOSE;
+ el.closed = true;
+ case S_ATTR_NOQUOT_VALUE:
+ case S_ATTR:
+ case S_ATTR_SPACE:
+ break;
+ //case S_EQ:
+ default:
+ throw new Error("attribute invalid close char('/')") // No known test case
+ }
+ break;
+ case ''://end document
+ errorHandler.error('unexpected end of input');
+ if(s == S_TAG){
+ el.setTagName(source.slice(start,p));
+ }
+ return p;
+ case '>':
+ switch(s){
+ case S_TAG:
+ el.setTagName(source.slice(start,p));
+ case S_ATTR_END:
+ case S_TAG_SPACE:
+ case S_TAG_CLOSE:
+ break;//normal
+ case S_ATTR_NOQUOT_VALUE://Compatible state
+ case S_ATTR:
+ value = source.slice(start,p);
+ if(value.slice(-1) === '/'){
+ el.closed = true;
+ value = value.slice(0,-1)
+ }
+ case S_ATTR_SPACE:
+ if(s === S_ATTR_SPACE){
+ value = attrName;
+ }
+ if(s == S_ATTR_NOQUOT_VALUE){
+ errorHandler.warning('attribute "'+value+'" missed quot(")!');
+ addAttribute(attrName, value.replace(/?\w+;/g,entityReplacer), start)
+ }else{
+ if(currentNSMap[''] !== 'http://www.w3.org/1999/xhtml' || !value.match(/^(?:disabled|checked|selected)$/i)){
+ errorHandler.warning('attribute "'+value+'" missed value!! "'+value+'" instead!!')
+ }
+ addAttribute(value, value, start)
+ }
+ break;
+ case S_EQ:
+ throw new Error('attribute value missed!!');
+ }
+// console.log(tagName,tagNamePattern,tagNamePattern.test(tagName))
+ return p;
+ /*xml space '\x20' | #x9 | #xD | #xA; */
+ case '\u0080':
+ c = ' ';
+ default:
+ if(c<= ' '){//space
+ switch(s){
+ case S_TAG:
+ el.setTagName(source.slice(start,p));//tagName
+ s = S_TAG_SPACE;
+ break;
+ case S_ATTR:
+ attrName = source.slice(start,p)
+ s = S_ATTR_SPACE;
+ break;
+ case S_ATTR_NOQUOT_VALUE:
+ var value = source.slice(start,p).replace(/?\w+;/g,entityReplacer);
+ errorHandler.warning('attribute "'+value+'" missed quot(")!!');
+ addAttribute(attrName, value, start)
+ case S_ATTR_END:
+ s = S_TAG_SPACE;
+ break;
+ //case S_TAG_SPACE:
+ //case S_EQ:
+ //case S_ATTR_SPACE:
+ // void();break;
+ //case S_TAG_CLOSE:
+ //ignore warning
+ }
+ }else{//not space
+//S_TAG, S_ATTR, S_EQ, S_ATTR_NOQUOT_VALUE
+//S_ATTR_SPACE, S_ATTR_END, S_TAG_SPACE, S_TAG_CLOSE
+ switch(s){
+ //case S_TAG:void();break;
+ //case S_ATTR:void();break;
+ //case S_ATTR_NOQUOT_VALUE:void();break;
+ case S_ATTR_SPACE:
+ var tagName = el.tagName;
+ if(currentNSMap[''] !== 'http://www.w3.org/1999/xhtml' || !attrName.match(/^(?:disabled|checked|selected)$/i)){
+ errorHandler.warning('attribute "'+attrName+'" missed value!! "'+attrName+'" instead2!!')
+ }
+ addAttribute(attrName, attrName, start);
+ start = p;
+ s = S_ATTR;
+ break;
+ case S_ATTR_END:
+ errorHandler.warning('attribute space is required"'+attrName+'"!!')
+ case S_TAG_SPACE:
+ s = S_ATTR;
+ start = p;
+ break;
+ case S_EQ:
+ s = S_ATTR_NOQUOT_VALUE;
+ start = p;
+ break;
+ case S_TAG_CLOSE:
+ throw new Error("elements closed character '/' and '>' must be connected to");
+ }
+ }
+ }//end outer switch
+ //console.log('p++',p)
+ p++;
+ }
+}
+/**
+ * @return true if has new namespace define
+ */
+function appendElement(el,domBuilder,currentNSMap){
+ var tagName = el.tagName;
+ var localNSMap = null;
+ //var currentNSMap = parseStack[parseStack.length-1].currentNSMap;
+ var i = el.length;
+ while(i--){
+ var a = el[i];
+ var qName = a.qName;
+ var value = a.value;
+ var nsp = qName.indexOf(':');
+ if(nsp>0){
+ var prefix = a.prefix = qName.slice(0,nsp);
+ var localName = qName.slice(nsp+1);
+ var nsPrefix = prefix === 'xmlns' && localName
+ }else{
+ localName = qName;
+ prefix = null
+ nsPrefix = qName === 'xmlns' && ''
+ }
+ //can not set prefix,because prefix !== ''
+ a.localName = localName ;
+ //prefix == null for no ns prefix attribute
+ if(nsPrefix !== false){//hack!!
+ if(localNSMap == null){
+ localNSMap = {}
+ //console.log(currentNSMap,0)
+ _copy(currentNSMap,currentNSMap={})
+ //console.log(currentNSMap,1)
+ }
+ currentNSMap[nsPrefix] = localNSMap[nsPrefix] = value;
+ a.uri = 'http://www.w3.org/2000/xmlns/'
+ domBuilder.startPrefixMapping(nsPrefix, value)
+ }
+ }
+ var i = el.length;
+ while(i--){
+ a = el[i];
+ var prefix = a.prefix;
+ if(prefix){//no prefix attribute has no namespace
+ if(prefix === 'xml'){
+ a.uri = 'http://www.w3.org/XML/1998/namespace';
+ }if(prefix !== 'xmlns'){
+ a.uri = currentNSMap[prefix || '']
+
+ //{console.log('###'+a.qName,domBuilder.locator.systemId+'',currentNSMap,a.uri)}
+ }
+ }
+ }
+ var nsp = tagName.indexOf(':');
+ if(nsp>0){
+ prefix = el.prefix = tagName.slice(0,nsp);
+ localName = el.localName = tagName.slice(nsp+1);
+ }else{
+ prefix = null;//important!!
+ localName = el.localName = tagName;
+ }
+ //no prefix element has default namespace
+ var ns = el.uri = currentNSMap[prefix || ''];
+ domBuilder.startElement(ns,localName,tagName,el);
+ //endPrefixMapping and startPrefixMapping have not any help for dom builder
+ //localNSMap = null
+ if(el.closed){
+ domBuilder.endElement(ns,localName,tagName);
+ if(localNSMap){
+ for(prefix in localNSMap){
+ domBuilder.endPrefixMapping(prefix)
+ }
+ }
+ }else{
+ el.currentNSMap = currentNSMap;
+ el.localNSMap = localNSMap;
+ //parseStack.push(el);
+ return true;
+ }
+}
+function parseHtmlSpecialContent(source,elStartEnd,tagName,entityReplacer,domBuilder){
+ if(/^(?:script|textarea)$/i.test(tagName)){
+ var elEndStart = source.indexOf(''+tagName+'>',elStartEnd);
+ var text = source.substring(elStartEnd+1,elEndStart);
+ if(/[&<]/.test(text)){
+ if(/^script$/i.test(tagName)){
+ //if(!/\]\]>/.test(text)){
+ //lexHandler.startCDATA();
+ domBuilder.characters(text,0,text.length);
+ //lexHandler.endCDATA();
+ return elEndStart;
+ //}
+ }//}else{//text area
+ text = text.replace(/?\w+;/g,entityReplacer);
+ domBuilder.characters(text,0,text.length);
+ return elEndStart;
+ //}
+
+ }
+ }
+ return elStartEnd+1;
+}
+function fixSelfClosed(source,elStartEnd,tagName,closeMap){
+ //if(tagName in closeMap){
+ var pos = closeMap[tagName];
+ if(pos == null){
+ //console.log(tagName)
+ pos = source.lastIndexOf(''+tagName+'>')
+ if(pos',start+4);
+ //append comment source.substring(4,end)//
+
+
+
+ Lightweight, beautiful and user-friendly interactive prompts
+ >_ Easy to use CLI prompts to enquire users for information▌
+
+
+
+
+* **Simple**: prompts has [no big dependencies](http://npm.anvaka.com/#/view/2d/prompts) nor is it broken into a [dozen](http://npm.anvaka.com/#/view/2d/inquirer) tiny modules that only work well together.
+* **User friendly**: prompt uses layout and colors to create beautiful cli interfaces.
+* **Promised**: uses promises and `async`/`await`. No callback hell.
+* **Flexible**: all prompts are independent and can be used on their own.
+* **Testable**: provides a way to submit answers programmatically.
+* **Unified**: consistent experience across all [prompts](#-types).
+
+
+
+
+
+## ❯ Install
+
+```
+$ npm install --save prompts
+```
+
+> This package supports Node 6 and above
+
+
+
+## ❯ Usage
+
+
+
+```js
+const prompts = require('prompts');
+
+(async () => {
+ const response = await prompts({
+ type: 'number',
+ name: 'value',
+ message: 'How old are you?',
+ validate: value => value < 18 ? `Nightclub is 18+ only` : true
+ });
+
+ console.log(response); // => { value: 24 }
+})();
+```
+
+> See [`example.js`](https://github.com/terkelg/prompts/blob/master/example.js) for more options.
+
+
+
+
+
+## ❯ Examples
+
+### Single Prompt
+
+Prompt with a single prompt object. Returns an object with the response.
+
+```js
+const prompts = require('prompts');
+
+(async () => {
+ const response = await prompts({
+ type: 'text',
+ name: 'meaning',
+ message: 'What is the meaning of life?'
+ });
+
+ console.log(response.meaning);
+})();
+```
+
+### Prompt Chain
+
+Prompt with a list of prompt objects. Returns an object with the responses.
+Make sure to give each prompt a unique `name` property to prevent overwriting values.
+
+```js
+const prompts = require('prompts');
+
+const questions = [
+ {
+ type: 'text',
+ name: 'username',
+ message: 'What is your GitHub username?'
+ },
+ {
+ type: 'number',
+ name: 'age',
+ message: 'How old are you?'
+ },
+ {
+ type: 'text',
+ name: 'about',
+ message: 'Tell something about yourself',
+ initial: 'Why should I?'
+ }
+];
+
+(async () => {
+ const response = await prompts(questions);
+
+ // => response => { username, age, about }
+})();
+```
+
+### Dynamic Prompts
+
+Prompt properties can be functions too.
+Prompt Objects with `type` set to `falsy` values are skipped.
+
+```js
+const prompts = require('prompts');
+
+const questions = [
+ {
+ type: 'text',
+ name: 'dish',
+ message: 'Do you like pizza?'
+ },
+ {
+ type: prev => prev == 'pizza' ? 'text' : null,
+ name: 'topping',
+ message: 'Name a topping'
+ }
+];
+
+(async () => {
+ const response = await prompts(questions);
+})();
+```
+
+
+
+
+
+## ❯ API
+
+### prompts(prompts, options)
+
+Type: `Function`
+Returns: `Object`
+
+Prompter function which takes your [prompt objects](#-prompt-objects) and returns an object with responses.
+
+
+#### prompts
+
+Type: `Array|Object`
+
+Array of [prompt objects](#-prompt-objects).
+ These are the questions the user will be prompted. You can see the list of supported [prompt types here](#-types).
+
+Prompts can be submitted (return, enter) or canceled (esc, abort, ctrl+c, ctrl+d). No property is being defined on the returned response object when a prompt is canceled.
+
+#### options.onSubmit
+
+Type: `Function`
+Default: `() => {}`
+
+Callback that's invoked after each prompt submission.
+Its signature is `(prompt, answer, answers)` where `prompt` is the current prompt object, `answer` the user answer to the current question and `answers` the user answers so far. Async functions are supported.
+
+Return `true` to quit the prompt chain and return all collected responses so far, otherwise continue to iterate prompt objects.
+
+**Example:**
+```js
+(async () => {
+ const questions = [{ ... }];
+ const onSubmit = (prompt, answer) => console.log(`Thanks I got ${answer} from ${prompt.name}`);
+ const response = await prompts(questions, { onSubmit });
+})();
+```
+
+#### options.onCancel
+
+Type: `Function`
+Default: `() => {}`
+
+Callback that's invoked when the user cancels/exits the prompt.
+Its signature is `(prompt, answers)` where `prompt` is the current prompt object and `answers` the user answers so far. Async functions are supported.
+
+Return `true` to continue and prevent the prompt loop from aborting.
+On cancel responses collected so far are returned.
+
+**Example:**
+```js
+(async () => {
+ const questions = [{ ... }];
+ const onCancel = prompt => {
+ console.log('Never stop prompting!');
+ return true;
+ }
+ const response = await prompts(questions, { onCancel });
+})();
+```
+
+### override
+
+Type: `Function`
+
+Preanswer questions by passing an object with answers to `prompts.override`.
+Powerful when combined with arguments of process.
+
+**Example**
+```js
+const prompts = require('prompts');
+prompts.override(require('yargs').argv);
+
+(async () => {
+ const response = await prompts([
+ {
+ type: 'text',
+ name: 'twitter',
+ message: `What's your twitter handle?`
+ },
+ {
+ type: 'multiselect',
+ name: 'color',
+ message: 'Pick colors',
+ choices: [
+ { title: 'Red', value: '#ff0000' },
+ { title: 'Green', value: '#00ff00' },
+ { title: 'Blue', value: '#0000ff' }
+ ],
+ }
+ ]);
+
+ console.log(response);
+})();
+```
+
+### inject(values)
+
+Type: `Function`
+
+Programmatically inject responses. This enables you to prepare the responses ahead of time.
+If any injected value is found the prompt is immediately resolved with the injected value.
+This feature is intended for testing only.
+
+#### values
+
+Type: `Array`
+
+Array with values to inject. Resolved values are removed from the internal inject array.
+Each value can be an array of values in order to provide answers for a question asked multiple times.
+If a value is an instance of `Error` it will simulate the user cancelling/exiting the prompt.
+
+**Example:**
+```js
+const prompts = require('prompts');
+
+prompts.inject([ '@terkelg', ['#ff0000', '#0000ff'] ]);
+
+(async () => {
+ const response = await prompts([
+ {
+ type: 'text',
+ name: 'twitter',
+ message: `What's your twitter handle?`
+ },
+ {
+ type: 'multiselect',
+ name: 'color',
+ message: 'Pick colors',
+ choices: [
+ { title: 'Red', value: '#ff0000' },
+ { title: 'Green', value: '#00ff00' },
+ { title: 'Blue', value: '#0000ff' }
+ ],
+ }
+ ]);
+
+ // => { twitter: 'terkelg', color: [ '#ff0000', '#0000ff' ] }
+})();
+```
+
+
+
+
+## ❯ Prompt Objects
+
+Prompts Objects are JavaScript objects that define the "questions" and the [type of prompt](#-types).
+Almost all prompt objects have the following properties:
+
+```js
+{
+ type: String | Function,
+ name: String | Function,
+ message: String | Function,
+ initial: String | Function | Async Function
+ format: Function | Async Function,
+ onRender: Function
+ onState: Function
+ stdin: Readable
+ stdout: Writeable
+}
+```
+
+Each property be of type `function` and will be invoked right before prompting the user.
+
+The function signature is `(prev, values, prompt)`, where `prev` is the value from the previous prompt,
+`values` is the response object with all values collected so far and `prompt` is the previous prompt object.
+
+**Function example:**
+```js
+{
+ type: prev => prev > 3 ? 'confirm' : null,
+ name: 'confirm',
+ message: (prev, values) => `Please confirm that you eat ${values.dish} times ${prev} a day?`
+}
+```
+
+The above prompt will be skipped if the value of the previous prompt is less than 3.
+
+### type
+
+Type: `String|Function`
+
+Defines the type of prompt to display. See the list of [prompt types](#-types) for valid values.
+
+If `type` is a falsy value the prompter will skip that question.
+```js
+{
+ type: null,
+ name: 'forgetme',
+ message: `I'll never be shown anyway`,
+}
+```
+
+### name
+
+Type: `String|Function`
+
+The response will be saved under this key/property in the returned response object.
+In case you have multiple prompts with the same name only the latest response will be stored.
+
+> Make sure to give prompts unique names if you don't want to overwrite previous values.
+
+### message
+
+Type: `String|Function`
+
+The message to be displayed to the user.
+
+### initial
+
+Type: `String|Function`
+
+Optional default prompt value. Async functions are supported too.
+
+### format
+
+Type: `Function`
+
+Receive the user input and return the formatted value to be used inside the program.
+The value returned will be added to the response object.
+
+The function signature is `(val, values)`, where `val` is the value from the current prompt and
+`values` is the current response object in case you need to format based on previous responses.
+
+**Example:**
+```js
+{
+ type: 'number',
+ name: 'price',
+ message: 'Enter price',
+ format: val => Intl.NumberFormat(undefined, { style: 'currency', currency: 'USD' }).format(val);
+}
+```
+
+### onRender
+
+Type: `Function`
+
+Callback for when the prompt is rendered.
+The function receives [kleur](https://github.com/lukeed/kleur) as its first argument and `this` refers to the current prompt.
+
+**Example:**
+```js
+{
+ type: 'number',
+ message: 'This message will be overridden',
+ onRender(kleur) {
+ this.msg = kleur.cyan('Enter a number');
+ }
+}
+```
+
+### onState
+
+Type: `Function`
+
+Callback for when the state of the current prompt changes.
+The function signature is `(state)` where `state` is an object with a snapshot of the current state.
+The state object has two properties `value` and `aborted`. E.g `{ value: 'This is ', aborted: false }`
+
+### stdin and stdout
+
+Type: `Stream`
+
+By default, prompts uses `process.stdin` for receiving input and `process.stdout` for writing output.
+If you need to use different streams, for instance `process.stderr`, you can set these with the `stdin` and `stdout` properties.
+
+
+
+
+
+## ❯ Types
+
+* [text](#textmessage-initial-style)
+* [password](#passwordmessage-initial)
+* [invisible](#invisiblemessage-initial)
+* [number](#numbermessage-initial-max-min-style)
+* [confirm](#confirmmessage-initial)
+* [list](#listmessage-initial)
+* [toggle](#togglemessage-initial-active-inactive)
+* [select](#selectmessage-choices-initial-hint-warn)
+* [multiselect](#multiselectmessage-choices-initial-max-hint-warn)
+* [autocompleteMultiselect](#multiselectmessage-choices-initial-max-hint-warn)
+* [autocomplete](#autocompletemessage-choices-initial-suggest-limit-style)
+* [date](#datemessage-initial-warn)
+
+***
+
+### text(message, [initial], [style])
+> Text prompt for free text input.
+
+Hit tab to autocomplete to `initial` value when provided.
+
+#### Example
+
+
+```js
+{
+ type: 'text',
+ name: 'value',
+ message: `What's your twitter handle?`
+}
+```
+
+#### Options
+| Param | Type | Description |
+| ----- | :--: | ----------- |
+| message | `string` | Prompt message to display |
+| initial | `string` | Default string value |
+| style | `string` | Render style (`default`, `password`, `invisible`, `emoji`). Defaults to `default` |
+| format | `function` | Receive user input. The returned value will be added to the response object |
+| validate | `function` | Receive user input. Should return `true` if the value is valid, and an error message `String` otherwise. If `false` is returned, a default error message is shown |
+| onRender | `function` | On render callback. Keyword `this` refers to the current prompt |
+| onState | `function` | On state change callback. Function signature is an `object` with two properties: `value` and `aborted` |
+
+**↑ back to:** [Prompt types](#-types)
+
+***
+
+### password(message, [initial])
+> Password prompt with masked input.
+
+This prompt is a similar to a prompt of type `'text'` with `style` set to `'password'`.
+
+#### Example
+
+
+```js
+{
+ type: 'password',
+ name: 'value',
+ message: 'Tell me a secret'
+}
+```
+
+#### Options
+| Param | Type | Description |
+| ----- | :--: | ----------- |
+| message | `string` | Prompt message to display |
+| initial | `string` | Default string value |
+| format | `function` | Receive user input. The returned value will be added to the response object |
+| validate | `function` | Receive user input. Should return `true` if the value is valid, and an error message `String` otherwise. If `false` is returned, a default error message is shown |
+| onRender | `function` | On render callback. Keyword `this` refers to the current prompt |
+| onState | `function` | On state change callback. Function signature is an `object` with two properties: `value` and `aborted` |
+
+**↑ back to:** [Prompt types](#-types)
+
+***
+
+### invisible(message, [initial])
+> Prompts user for invisible text input.
+
+This prompt is working like `sudo` where the input is invisible.
+This prompt is a similar to a prompt of type `'text'` with style set to `'invisible'`.
+
+#### Example
+
+
+```js
+{
+ type: 'invisible',
+ name: 'value',
+ message: 'Enter password'
+}
+```
+
+#### Options
+| Param | Type | Description |
+| ----- | :--: | ----------- |
+| message | `string` | Prompt message to display |
+| initial | `string` | Default string value |
+| format | `function` | Receive user input. The returned value will be added to the response object |
+| validate | `function` | Receive user input. Should return `true` if the value is valid, and an error message `String` otherwise. If `false` is returned, a default error message is shown |
+| onRender | `function` | On render callback. Keyword `this` refers to the current prompt |
+| onState | `function` | On state change callback. Function signature is an `object` with two properties: `value` and `aborted` |
+
+**↑ back to:** [Prompt types](#-types)
+
+***
+
+### number(message, initial, [max], [min], [style])
+> Prompts user for number input.
+
+You can type in numbers and use up/down to increase/decrease the value. Only numbers are allowed as input. Hit tab to autocomplete to `initial` value when provided.
+
+#### Example
+
+
+```js
+{
+ type: 'number',
+ name: 'value',
+ message: 'How old are you?',
+ initial: 0,
+ style: 'default',
+ min: 2,
+ max: 10
+}
+```
+
+#### Options
+| Param | Type | Description |
+| ----- | :--: | ----------- |
+| message | `string` | Prompt message to display |
+| initial | `number` | Default number value |
+| format | `function` | Receive user input. The returned value will be added to the response object |
+| validate | `function` | Receive user input. Should return `true` if the value is valid, and an error message `String` otherwise. If `false` is returned, a default error message is shown |
+| max | `number` | Max value. Defaults to `Infinity` |
+| min | `number` | Min value. Defaults to `-infinity` |
+| float | `boolean` | Allow floating point inputs. Defaults to `false` |
+| round | `number` | Round `float` values to x decimals. Defaults to `2` |
+| increment | `number` | Increment step when using arrow keys. Defaults to `1` |
+| style | `string` | Render style (`default`, `password`, `invisible`, `emoji`). Defaults to `default` |
+| onRender | `function` | On render callback. Keyword `this` refers to the current prompt |
+| onState | `function` | On state change callback. Function signature is an `object` with two properties: `value` and `aborted` |
+
+**↑ back to:** [Prompt types](#-types)
+
+***
+
+### confirm(message, [initial])
+> Classic yes/no prompt.
+
+Hit y or n to confirm/reject.
+
+#### Example
+
+
+```js
+{
+ type: 'confirm',
+ name: 'value',
+ message: 'Can you confirm?',
+ initial: true
+}
+```
+
+
+#### Options
+| Param | Type | Description |
+| ----- | :--: | ----------- |
+| message | `string` | Prompt message to display |
+| initial | `boolean` | Default value. Default is `false` |
+| format | `function` | Receive user input. The returned value will be added to the response object |
+| onRender | `function` | On render callback. Keyword `this` refers to the current prompt |
+| onState | `function` | On state change callback. Function signature is an `object` with two properties: `value` and `aborted` |
+
+**↑ back to:** [Prompt types](#-types)
+
+***
+
+### list(message, [initial])
+> List prompt that return an array.
+
+Similar to the `text` prompt, but the output is an `Array` containing the
+string separated by `separator`.
+
+```js
+{
+ type: 'list',
+ name: 'value',
+ message: 'Enter keywords',
+ initial: '',
+ separator: ','
+}
+```
+
+
+
+
+| Param | Type | Description |
+| ----- | :--: | ----------- |
+| message | `string` | Prompt message to display |
+| initial | `boolean` | Default value |
+| format | `function` | Receive user input. The returned value will be added to the response object |
+| separator | `string` | String separator. Will trim all white-spaces from start and end of string. Defaults to `','` |
+| onRender | `function` | On render callback. Keyword `this` refers to the current prompt |
+| onState | `function` | On state change callback. Function signature is an `object` with two properties: `value` and `aborted` |
+
+**↑ back to:** [Prompt types](#-types)
+
+***
+
+### toggle(message, [initial], [active], [inactive])
+> Interactive toggle/switch prompt.
+
+Use tab or arrow keys/tab/space to switch between options.
+
+#### Example
+
+
+```js
+{
+ type: 'toggle',
+ name: 'value',
+ message: 'Can you confirm?',
+ initial: true,
+ active: 'yes',
+ inactive: 'no'
+}
+```
+
+#### Options
+| Param | Type | Description |
+| ----- | :--: | ----------- |
+| message | `string` | Prompt message to display |
+| initial | `boolean` | Default value. Defaults to `false` |
+| format | `function` | Receive user input. The returned value will be added to the response object |
+| active | `string` | Text for `active` state. Defaults to `'on'` |
+| inactive | `string` | Text for `inactive` state. Defaults to `'off'` |
+| onRender | `function` | On render callback. Keyword `this` refers to the current prompt |
+| onState | `function` | On state change callback. Function signature is an `object` with two properties: `value` and `aborted` |
+
+**↑ back to:** [Prompt types](#-types)
+
+***
+
+### select(message, choices, [initial], [hint], [warn])
+> Interactive select prompt.
+
+Use up/down to navigate. Use tab to cycle the list.
+
+#### Example
+
+
+```js
+{
+ type: 'select',
+ name: 'value',
+ message: 'Pick a color',
+ choices: [
+ { title: 'Red', description: 'This option has a description', value: '#ff0000' },
+ { title: 'Green', value: '#00ff00', disabled: true },
+ { title: 'Blue', value: '#0000ff' }
+ ],
+ initial: 1
+}
+```
+
+#### Options
+| Param | Type | Description |
+| ----- | :--: | ----------- |
+| message | `string` | Prompt message to display |
+| initial | `number` | Index of default value |
+| format | `function` | Receive user input. The returned value will be added to the response object |
+| hint | `string` | Hint to display to the user |
+| warn | `string` | Message to display when selecting a disabled option |
+| choices | `Array` | Array of strings or choices objects `[{ title, description, value, disabled }, ...]`. The choice's index in the array will be used as its value if it is not specified. |
+| onRender | `function` | On render callback. Keyword `this` refers to the current prompt |
+| onState | `function` | On state change callback. Function signature is an `object` with two properties: `value` and `aborted` |
+
+**↑ back to:** [Prompt types](#-types)
+
+***
+
+### multiselect(message, choices, [initial], [max], [hint], [warn])
+### autocompleteMultiselect(same)
+> Interactive multi-select prompt.
+> Autocomplete is a searchable multiselect prompt with the same options. Useful for long lists.
+
+Use space to toggle select/unselect and up/down to navigate. Use tab to cycle the list. You can also use right to select and left to deselect.
+By default this prompt returns an `array` containing the **values** of the selected items - not their display title.
+
+#### Example
+
+
+```js
+{
+ type: 'multiselect',
+ name: 'value',
+ message: 'Pick colors',
+ choices: [
+ { title: 'Red', value: '#ff0000' },
+ { title: 'Green', value: '#00ff00', disabled: true },
+ { title: 'Blue', value: '#0000ff', selected: true }
+ ],
+ max: 2,
+ hint: '- Space to select. Return to submit'
+}
+```
+
+#### Options
+| Param | Type | Description |
+| ----- | :--: | ----------- |
+| message | `string` | Prompt message to display |
+| format | `function` | Receive user input. The returned value will be added to the response object |
+| instructions | `string` or `boolean` | Prompt instructions to display |
+| choices | `Array` | Array of strings or choices objects `[{ title, value, disabled }, ...]`. The choice's index in the array will be used as its value if it is not specified. |
+| optionsPerPage | `number` | Number of options displayed per page (default: 10) |
+| min | `number` | Min select - will display error |
+| max | `number` | Max select |
+| hint | `string` | Hint to display to the user |
+| warn | `string` | Message to display when selecting a disabled option |
+| onRender | `function` | On render callback. Keyword `this` refers to the current prompt |
+| onState | `function` | On state change callback. Function signature is an `object` with two properties: `value` and `aborted` |
+
+This is one of the few prompts that don't take a initial value.
+If you want to predefine selected values, give the choice object an `selected` property of `true`.
+
+**↑ back to:** [Prompt types](#-types)
+
+***
+
+### autocomplete(message, choices, [initial], [suggest], [limit], [style])
+> Interactive auto complete prompt.
+
+The prompt will list options based on user input. Type to filter the list.
+Use ⇧/⇩ to navigate. Use tab to cycle the result. Use Page Up/Page Down (on Mac: fn + ⇧ / ⇩) to change page. Hit enter to select the highlighted item below the prompt.
+
+The default suggests function is sorting based on the `title` property of the choices.
+You can overwrite how choices are being filtered by passing your own suggest function.
+
+#### Example
+
+
+```js
+{
+ type: 'autocomplete',
+ name: 'value',
+ message: 'Pick your favorite actor',
+ choices: [
+ { title: 'Cage' },
+ { title: 'Clooney', value: 'silver-fox' },
+ { title: 'Gyllenhaal' },
+ { title: 'Gibson' },
+ { title: 'Grant' }
+ ]
+}
+```
+
+#### Options
+| Param | Type | Description |
+| ----- | :--: | ----------- |
+| message | `string` | Prompt message to display |
+| format | `function` | Receive user input. The returned value will be added to the response object |
+| choices | `Array` | Array of auto-complete choices objects `[{ title, value }, ...]` |
+| suggest | `function` | Filter function. Defaults to sort by `title` property. `suggest` should always return a promise. Filters using `title` by default |
+| limit | `number` | Max number of results to show. Defaults to `10` |
+| style | `string` | Render style (`default`, `password`, `invisible`, `emoji`). Defaults to `'default'` |
+| initial | `string \| number` | Default initial value |
+| clearFirst | `boolean` | The first ESCAPE keypress will clear the input |
+| fallback | `string` | Fallback message when no match is found. Defaults to `initial` value if provided |
+| onRender | `function` | On render callback. Keyword `this` refers to the current prompt |
+| onState | `function` | On state change callback. Function signature is an `object` with three properties: `value`, `aborted` and `exited` |
+
+Example on what a `suggest` function might look like:
+```js
+const suggestByTitle = (input, choices) =>
+ Promise.resolve(choices.filter(i => i.title.slice(0, input.length) === input))
+```
+
+**↑ back to:** [Prompt types](#-types)
+
+***
+
+### date(message, [initial], [warn])
+> Interactive date prompt.
+
+Use left/right/tab to navigate. Use up/down to change date.
+
+#### Example
+
+
+```js
+{
+ type: 'date',
+ name: 'value',
+ message: 'Pick a date',
+ initial: new Date(1997, 09, 12),
+ validate: date => date > Date.now() ? 'Not in the future' : true
+}
+```
+
+#### Options
+| Param | Type | Description |
+| ----- | :--: | ----------- |
+| message | `string` | Prompt message to display |
+| initial | `date` | Default date |
+| locales | `object` | Use to define custom locales. See below for an example. |
+| mask | `string` | The format mask of the date. See below for more information.
Default: `YYYY-MM-DD HH:mm:ss` |
+| validate | `function` | Receive user input. Should return `true` if the value is valid, and an error message `String` otherwise. If `false` is returned, a default error message is shown |
+| onRender | `function` | On render callback. Keyword `this` refers to the current prompt |
+| onState | `function` | On state change callback. Function signature is an `object` with two properties: `value` and `aborted` |
+
+Default locales:
+
+```javascript
+{
+ months: [
+ 'January', 'February', 'March', 'April',
+ 'May', 'June', 'July', 'August',
+ 'September', 'October', 'November', 'December'
+ ],
+ monthsShort: [
+ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
+ 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
+ ],
+ weekdays: [
+ 'Sunday', 'Monday', 'Tuesday', 'Wednesday',
+ 'Thursday', 'Friday', 'Saturday'
+ ],
+ weekdaysShort: [
+ 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'
+ ]
+}
+```
+>**Formatting**: See full list of formatting options in the [wiki](https://github.com/terkelg/prompts/wiki/Date-Time-Formatting)
+
+
+
+**↑ back to:** [Prompt types](#-types)
+
+***
+
+## ❯ Credit
+Many of the prompts are based on the work of [derhuerst](https://github.com/derhuerst).
+
+
+## ❯ License
+
+MIT © [Terkel Gjervig](https://terkel.com)
diff --git a/temporary_modules/trezor-connect/node_modules/readable-stream/CONTRIBUTING.md b/temporary_modules/trezor-connect/node_modules/readable-stream/CONTRIBUTING.md
new file mode 100644
index 00000000..f478d58d
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/readable-stream/CONTRIBUTING.md
@@ -0,0 +1,38 @@
+# Developer's Certificate of Origin 1.1
+
+By making a contribution to this project, I certify that:
+
+* (a) The contribution was created in whole or in part by me and I
+ have the right to submit it under the open source license
+ indicated in the file; or
+
+* (b) The contribution is based upon previous work that, to the best
+ of my knowledge, is covered under an appropriate open source
+ license and I have the right under that license to submit that
+ work with modifications, whether created in whole or in part
+ by me, under the same open source license (unless I am
+ permitted to submit under a different license), as indicated
+ in the file; or
+
+* (c) The contribution was provided directly to me by some other
+ person who certified (a), (b) or (c) and I have not modified
+ it.
+
+* (d) I understand and agree that this project and the contribution
+ are public and that a record of the contribution (including all
+ personal information I submit with it, including my sign-off) is
+ maintained indefinitely and may be redistributed consistent with
+ this project or the open source license(s) involved.
+
+## Moderation Policy
+
+The [Node.js Moderation Policy] applies to this WG.
+
+## Code of Conduct
+
+The [Node.js Code of Conduct][] applies to this WG.
+
+[Node.js Code of Conduct]:
+https://github.com/nodejs/node/blob/master/CODE_OF_CONDUCT.md
+[Node.js Moderation Policy]:
+https://github.com/nodejs/TSC/blob/master/Moderation-Policy.md
diff --git a/temporary_modules/trezor-connect/node_modules/readable-stream/GOVERNANCE.md b/temporary_modules/trezor-connect/node_modules/readable-stream/GOVERNANCE.md
new file mode 100644
index 00000000..16ffb93f
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/readable-stream/GOVERNANCE.md
@@ -0,0 +1,136 @@
+### Streams Working Group
+
+The Node.js Streams is jointly governed by a Working Group
+(WG)
+that is responsible for high-level guidance of the project.
+
+The WG has final authority over this project including:
+
+* Technical direction
+* Project governance and process (including this policy)
+* Contribution policy
+* GitHub repository hosting
+* Conduct guidelines
+* Maintaining the list of additional Collaborators
+
+For the current list of WG members, see the project
+[README.md](./README.md#current-project-team-members).
+
+### Collaborators
+
+The readable-stream GitHub repository is
+maintained by the WG and additional Collaborators who are added by the
+WG on an ongoing basis.
+
+Individuals making significant and valuable contributions are made
+Collaborators and given commit-access to the project. These
+individuals are identified by the WG and their addition as
+Collaborators is discussed during the WG meeting.
+
+_Note:_ If you make a significant contribution and are not considered
+for commit-access log an issue or contact a WG member directly and it
+will be brought up in the next WG meeting.
+
+Modifications of the contents of the readable-stream repository are
+made on
+a collaborative basis. Anybody with a GitHub account may propose a
+modification via pull request and it will be considered by the project
+Collaborators. All pull requests must be reviewed and accepted by a
+Collaborator with sufficient expertise who is able to take full
+responsibility for the change. In the case of pull requests proposed
+by an existing Collaborator, an additional Collaborator is required
+for sign-off. Consensus should be sought if additional Collaborators
+participate and there is disagreement around a particular
+modification. See _Consensus Seeking Process_ below for further detail
+on the consensus model used for governance.
+
+Collaborators may opt to elevate significant or controversial
+modifications, or modifications that have not found consensus to the
+WG for discussion by assigning the ***WG-agenda*** tag to a pull
+request or issue. The WG should serve as the final arbiter where
+required.
+
+For the current list of Collaborators, see the project
+[README.md](./README.md#members).
+
+### WG Membership
+
+WG seats are not time-limited. There is no fixed size of the WG.
+However, the expected target is between 6 and 12, to ensure adequate
+coverage of important areas of expertise, balanced with the ability to
+make decisions efficiently.
+
+There is no specific set of requirements or qualifications for WG
+membership beyond these rules.
+
+The WG may add additional members to the WG by unanimous consensus.
+
+A WG member may be removed from the WG by voluntary resignation, or by
+unanimous consensus of all other WG members.
+
+Changes to WG membership should be posted in the agenda, and may be
+suggested as any other agenda item (see "WG Meetings" below).
+
+If an addition or removal is proposed during a meeting, and the full
+WG is not in attendance to participate, then the addition or removal
+is added to the agenda for the subsequent meeting. This is to ensure
+that all members are given the opportunity to participate in all
+membership decisions. If a WG member is unable to attend a meeting
+where a planned membership decision is being made, then their consent
+is assumed.
+
+No more than 1/3 of the WG members may be affiliated with the same
+employer. If removal or resignation of a WG member, or a change of
+employment by a WG member, creates a situation where more than 1/3 of
+the WG membership shares an employer, then the situation must be
+immediately remedied by the resignation or removal of one or more WG
+members affiliated with the over-represented employer(s).
+
+### WG Meetings
+
+The WG meets occasionally on a Google Hangout On Air. A designated moderator
+approved by the WG runs the meeting. Each meeting should be
+published to YouTube.
+
+Items are added to the WG agenda that are considered contentious or
+are modifications of governance, contribution policy, WG membership,
+or release process.
+
+The intention of the agenda is not to approve or review all patches;
+that should happen continuously on GitHub and be handled by the larger
+group of Collaborators.
+
+Any community member or contributor can ask that something be added to
+the next meeting's agenda by logging a GitHub Issue. Any Collaborator,
+WG member or the moderator can add the item to the agenda by adding
+the ***WG-agenda*** tag to the issue.
+
+Prior to each WG meeting the moderator will share the Agenda with
+members of the WG. WG members can add any items they like to the
+agenda at the beginning of each meeting. The moderator and the WG
+cannot veto or remove items.
+
+The WG may invite persons or representatives from certain projects to
+participate in a non-voting capacity.
+
+The moderator is responsible for summarizing the discussion of each
+agenda item and sends it as a pull request after the meeting.
+
+### Consensus Seeking Process
+
+The WG follows a
+[Consensus
+Seeking](http://en.wikipedia.org/wiki/Consensus-seeking_decision-making)
+decision-making model.
+
+When an agenda item has appeared to reach a consensus the moderator
+will ask "Does anyone object?" as a final call for dissent from the
+consensus.
+
+If an agenda item cannot reach a consensus a WG member can call for
+either a closing vote or a vote to table the issue to the next
+meeting. The call for a vote must be seconded by a majority of the WG
+or else the discussion will continue. Simple majority wins.
+
+Note that changes to WG membership require a majority consensus. See
+"WG Membership" above.
diff --git a/temporary_modules/trezor-connect/node_modules/readable-stream/LICENSE b/temporary_modules/trezor-connect/node_modules/readable-stream/LICENSE
new file mode 100644
index 00000000..2873b3b2
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/readable-stream/LICENSE
@@ -0,0 +1,47 @@
+Node.js is licensed for use as follows:
+
+"""
+Copyright Node.js contributors. All rights reserved.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to
+deal in the Software without restriction, including without limitation the
+rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+sell copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+IN THE SOFTWARE.
+"""
+
+This license applies to parts of Node.js originating from the
+https://github.com/joyent/node repository:
+
+"""
+Copyright Joyent, Inc. and other Node contributors. All rights reserved.
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to
+deal in the Software without restriction, including without limitation the
+rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+sell copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+IN THE SOFTWARE.
+"""
diff --git a/temporary_modules/trezor-connect/node_modules/readable-stream/README.md b/temporary_modules/trezor-connect/node_modules/readable-stream/README.md
new file mode 100644
index 00000000..6f035ab1
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/readable-stream/README.md
@@ -0,0 +1,106 @@
+# readable-stream
+
+***Node.js core streams for userland*** [](https://travis-ci.com/nodejs/readable-stream)
+
+
+[](https://nodei.co/npm/readable-stream/)
+[](https://nodei.co/npm/readable-stream/)
+
+
+[](https://saucelabs.com/u/readabe-stream)
+
+```bash
+npm install --save readable-stream
+```
+
+This package is a mirror of the streams implementations in Node.js.
+
+Full documentation may be found on the [Node.js website](https://nodejs.org/dist/v10.19.0/docs/api/stream.html).
+
+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, for background see [this blogpost](http://r.va.gg/2014/06/why-i-dont-use-nodes-core-stream-module.html).
+
+As of version 2.0.0 **readable-stream** uses semantic versioning.
+
+## Version 3.x.x
+
+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:
+
+1. Error codes: https://github.com/nodejs/node/pull/13310,
+ https://github.com/nodejs/node/pull/13291,
+ https://github.com/nodejs/node/pull/16589,
+ https://github.com/nodejs/node/pull/15042,
+ https://github.com/nodejs/node/pull/15665,
+ https://github.com/nodejs/readable-stream/pull/344
+2. 'readable' have precedence over flowing
+ https://github.com/nodejs/node/pull/18994
+3. make virtual methods errors consistent
+ https://github.com/nodejs/node/pull/18813
+4. updated streams error handling
+ https://github.com/nodejs/node/pull/18438
+5. writable.end should return this.
+ https://github.com/nodejs/node/pull/18780
+6. readable continues to read when push('')
+ https://github.com/nodejs/node/pull/18211
+7. add custom inspect to BufferList
+ https://github.com/nodejs/node/pull/17907
+8. always defer 'readable' with nextTick
+ https://github.com/nodejs/node/pull/17979
+
+## Version 2.x.x
+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.
+
+### Big Thanks
+
+Cross-browser Testing Platform and Open Source <3 Provided by [Sauce Labs][sauce]
+
+# Usage
+
+You can swap your `require('stream')` with `require('readable-stream')`
+without any changes, if you are just using one of the main classes and
+functions.
+
+```js
+const {
+ Readable,
+ Writable,
+ Transform,
+ Duplex,
+ pipeline,
+ finished
+} = require('readable-stream')
+````
+
+Note that `require('stream')` will return `Stream`, while
+`require('readable-stream')` will return `Readable`. We discourage using
+whatever is exported directly, but rather use one of the properties as
+shown in the example above.
+
+# Streams Working Group
+
+`readable-stream` is maintained by the Streams Working Group, which
+oversees the development and maintenance of the Streams API within
+Node.js. The responsibilities of the Streams Working Group include:
+
+* Addressing stream issues on the Node.js issue tracker.
+* Authoring and editing stream documentation within the Node.js project.
+* Reviewing changes to stream subclasses within the Node.js project.
+* Redirecting changes to streams from the Node.js project to this
+ project.
+* Assisting in the implementation of stream providers within Node.js.
+* Recommending versions of `readable-stream` to be included in Node.js.
+* Messaging about the future of streams to give the community advance
+ notice of changes.
+
+
+## Team Members
+
+* **Calvin Metcalf** ([@calvinmetcalf](https://github.com/calvinmetcalf)) <calvin.metcalf@gmail.com>
+ - Release GPG key: F3EF5F62A87FC27A22E643F714CE4FF5015AA242
+* **Mathias Buus** ([@mafintosh](https://github.com/mafintosh)) <mathiasbuus@gmail.com>
+* **Matteo Collina** ([@mcollina](https://github.com/mcollina)) <matteo.collina@gmail.com>
+ - Release GPG key: 3ABC01543F22DD2239285CDD818674489FBC127E
+* **Irina Shestak** ([@lrlna](https://github.com/lrlna)) <shestak.irina@gmail.com>
+* **Yoshua Wyuts** ([@yoshuawuyts](https://github.com/yoshuawuyts)) <yoshuawuyts@gmail.com>
+
+[sauce]: https://saucelabs.com
diff --git a/temporary_modules/trezor-connect/node_modules/readable-stream/errors-browser.js b/temporary_modules/trezor-connect/node_modules/readable-stream/errors-browser.js
new file mode 100644
index 00000000..fb8e73e1
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/readable-stream/errors-browser.js
@@ -0,0 +1,127 @@
+'use strict';
+
+function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
+
+var codes = {};
+
+function createErrorType(code, message, Base) {
+ if (!Base) {
+ Base = Error;
+ }
+
+ function getMessage(arg1, arg2, arg3) {
+ if (typeof message === 'string') {
+ return message;
+ } else {
+ return message(arg1, arg2, arg3);
+ }
+ }
+
+ var NodeError =
+ /*#__PURE__*/
+ function (_Base) {
+ _inheritsLoose(NodeError, _Base);
+
+ function NodeError(arg1, arg2, arg3) {
+ return _Base.call(this, getMessage(arg1, arg2, arg3)) || this;
+ }
+
+ return NodeError;
+ }(Base);
+
+ NodeError.prototype.name = Base.name;
+ NodeError.prototype.code = code;
+ codes[code] = NodeError;
+} // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js
+
+
+function oneOf(expected, thing) {
+ if (Array.isArray(expected)) {
+ var len = expected.length;
+ expected = expected.map(function (i) {
+ return String(i);
+ });
+
+ if (len > 2) {
+ return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(', '), ", or ") + expected[len - 1];
+ } else if (len === 2) {
+ return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]);
+ } else {
+ return "of ".concat(thing, " ").concat(expected[0]);
+ }
+ } else {
+ return "of ".concat(thing, " ").concat(String(expected));
+ }
+} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith
+
+
+function startsWith(str, search, pos) {
+ return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search;
+} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith
+
+
+function endsWith(str, search, this_len) {
+ if (this_len === undefined || this_len > str.length) {
+ this_len = str.length;
+ }
+
+ return str.substring(this_len - search.length, this_len) === search;
+} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes
+
+
+function includes(str, search, start) {
+ if (typeof start !== 'number') {
+ start = 0;
+ }
+
+ if (start + search.length > str.length) {
+ return false;
+ } else {
+ return str.indexOf(search, start) !== -1;
+ }
+}
+
+createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) {
+ return 'The value "' + value + '" is invalid for option "' + name + '"';
+}, TypeError);
+createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) {
+ // determiner: 'must be' or 'must not be'
+ var determiner;
+
+ if (typeof expected === 'string' && startsWith(expected, 'not ')) {
+ determiner = 'must not be';
+ expected = expected.replace(/^not /, '');
+ } else {
+ determiner = 'must be';
+ }
+
+ var msg;
+
+ if (endsWith(name, ' argument')) {
+ // For cases like 'first argument'
+ msg = "The ".concat(name, " ").concat(determiner, " ").concat(oneOf(expected, 'type'));
+ } else {
+ var type = includes(name, '.') ? 'property' : 'argument';
+ msg = "The \"".concat(name, "\" ").concat(type, " ").concat(determiner, " ").concat(oneOf(expected, 'type'));
+ }
+
+ msg += ". Received type ".concat(typeof actual);
+ return msg;
+}, TypeError);
+createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF');
+createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) {
+ return 'The ' + name + ' method is not implemented';
+});
+createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close');
+createErrorType('ERR_STREAM_DESTROYED', function (name) {
+ return 'Cannot call ' + name + ' after a stream was destroyed';
+});
+createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times');
+createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable');
+createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end');
+createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError);
+createErrorType('ERR_UNKNOWN_ENCODING', function (arg) {
+ return 'Unknown encoding: ' + arg;
+}, TypeError);
+createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event');
+module.exports.codes = codes;
diff --git a/temporary_modules/trezor-connect/node_modules/readable-stream/errors.js b/temporary_modules/trezor-connect/node_modules/readable-stream/errors.js
new file mode 100644
index 00000000..8471526d
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/readable-stream/errors.js
@@ -0,0 +1,116 @@
+'use strict';
+
+const codes = {};
+
+function createErrorType(code, message, Base) {
+ if (!Base) {
+ Base = Error
+ }
+
+ function getMessage (arg1, arg2, arg3) {
+ if (typeof message === 'string') {
+ return message
+ } else {
+ return message(arg1, arg2, arg3)
+ }
+ }
+
+ class NodeError extends Base {
+ constructor (arg1, arg2, arg3) {
+ super(getMessage(arg1, arg2, arg3));
+ }
+ }
+
+ NodeError.prototype.name = Base.name;
+ NodeError.prototype.code = code;
+
+ codes[code] = NodeError;
+}
+
+// https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js
+function oneOf(expected, thing) {
+ if (Array.isArray(expected)) {
+ const len = expected.length;
+ expected = expected.map((i) => String(i));
+ if (len > 2) {
+ return `one of ${thing} ${expected.slice(0, len - 1).join(', ')}, or ` +
+ expected[len - 1];
+ } else if (len === 2) {
+ return `one of ${thing} ${expected[0]} or ${expected[1]}`;
+ } else {
+ return `of ${thing} ${expected[0]}`;
+ }
+ } else {
+ return `of ${thing} ${String(expected)}`;
+ }
+}
+
+// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith
+function startsWith(str, search, pos) {
+ return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search;
+}
+
+// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith
+function endsWith(str, search, this_len) {
+ if (this_len === undefined || this_len > str.length) {
+ this_len = str.length;
+ }
+ return str.substring(this_len - search.length, this_len) === search;
+}
+
+// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes
+function includes(str, search, start) {
+ if (typeof start !== 'number') {
+ start = 0;
+ }
+
+ if (start + search.length > str.length) {
+ return false;
+ } else {
+ return str.indexOf(search, start) !== -1;
+ }
+}
+
+createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) {
+ return 'The value "' + value + '" is invalid for option "' + name + '"'
+}, TypeError);
+createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) {
+ // determiner: 'must be' or 'must not be'
+ let determiner;
+ if (typeof expected === 'string' && startsWith(expected, 'not ')) {
+ determiner = 'must not be';
+ expected = expected.replace(/^not /, '');
+ } else {
+ determiner = 'must be';
+ }
+
+ let msg;
+ if (endsWith(name, ' argument')) {
+ // For cases like 'first argument'
+ msg = `The ${name} ${determiner} ${oneOf(expected, 'type')}`;
+ } else {
+ const type = includes(name, '.') ? 'property' : 'argument';
+ msg = `The "${name}" ${type} ${determiner} ${oneOf(expected, 'type')}`;
+ }
+
+ msg += `. Received type ${typeof actual}`;
+ return msg;
+}, TypeError);
+createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF');
+createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) {
+ return 'The ' + name + ' method is not implemented'
+});
+createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close');
+createErrorType('ERR_STREAM_DESTROYED', function (name) {
+ return 'Cannot call ' + name + ' after a stream was destroyed';
+});
+createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times');
+createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable');
+createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end');
+createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError);
+createErrorType('ERR_UNKNOWN_ENCODING', function (arg) {
+ return 'Unknown encoding: ' + arg
+}, TypeError);
+createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event');
+
+module.exports.codes = codes;
diff --git a/temporary_modules/trezor-connect/node_modules/readable-stream/experimentalWarning.js b/temporary_modules/trezor-connect/node_modules/readable-stream/experimentalWarning.js
new file mode 100644
index 00000000..78e84149
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/readable-stream/experimentalWarning.js
@@ -0,0 +1,17 @@
+'use strict'
+
+var experimentalWarnings = new Set();
+
+function emitExperimentalWarning(feature) {
+ if (experimentalWarnings.has(feature)) return;
+ var msg = feature + ' is an experimental feature. This feature could ' +
+ 'change at any time';
+ experimentalWarnings.add(feature);
+ process.emitWarning(msg, 'ExperimentalWarning');
+}
+
+function noop() {}
+
+module.exports.emitExperimentalWarning = process.emitWarning
+ ? emitExperimentalWarning
+ : noop;
diff --git a/temporary_modules/trezor-connect/node_modules/readable-stream/lib/_stream_duplex.js b/temporary_modules/trezor-connect/node_modules/readable-stream/lib/_stream_duplex.js
new file mode 100644
index 00000000..67525192
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/readable-stream/lib/_stream_duplex.js
@@ -0,0 +1,139 @@
+// Copyright Joyent, Inc. and other Node contributors.
+//
+// Permission is hereby granted, free of charge, to any person obtaining a
+// copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to permit
+// persons to whom the Software is furnished to do so, subject to the
+// following conditions:
+//
+// The above copyright notice and this permission notice shall be included
+// in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
+// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
+// USE OR OTHER DEALINGS IN THE SOFTWARE.
+// a duplex stream is just a stream that is both readable and writable.
+// Since JS doesn't have multiple prototypal inheritance, this class
+// prototypally inherits from Readable, and then parasitically from
+// Writable.
+'use strict';
+/**/
+
+var objectKeys = Object.keys || function (obj) {
+ var keys = [];
+
+ for (var key in obj) {
+ keys.push(key);
+ }
+
+ return keys;
+};
+/**/
+
+
+module.exports = Duplex;
+
+var Readable = require('./_stream_readable');
+
+var Writable = require('./_stream_writable');
+
+require('inherits')(Duplex, Readable);
+
+{
+ // Allow the keys array to be GC'ed.
+ var keys = objectKeys(Writable.prototype);
+
+ for (var v = 0; v < keys.length; v++) {
+ var method = keys[v];
+ if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
+ }
+}
+
+function Duplex(options) {
+ if (!(this instanceof Duplex)) return new Duplex(options);
+ Readable.call(this, options);
+ Writable.call(this, options);
+ this.allowHalfOpen = true;
+
+ if (options) {
+ if (options.readable === false) this.readable = false;
+ if (options.writable === false) this.writable = false;
+
+ if (options.allowHalfOpen === false) {
+ this.allowHalfOpen = false;
+ this.once('end', onend);
+ }
+ }
+}
+
+Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
+ // making it explicit this property is not enumerable
+ // because otherwise some prototype manipulation in
+ // userland will fail
+ enumerable: false,
+ get: function get() {
+ return this._writableState.highWaterMark;
+ }
+});
+Object.defineProperty(Duplex.prototype, 'writableBuffer', {
+ // making it explicit this property is not enumerable
+ // because otherwise some prototype manipulation in
+ // userland will fail
+ enumerable: false,
+ get: function get() {
+ return this._writableState && this._writableState.getBuffer();
+ }
+});
+Object.defineProperty(Duplex.prototype, 'writableLength', {
+ // making it explicit this property is not enumerable
+ // because otherwise some prototype manipulation in
+ // userland will fail
+ enumerable: false,
+ get: function get() {
+ return this._writableState.length;
+ }
+}); // the no-half-open enforcer
+
+function onend() {
+ // If the writable side ended, then we're ok.
+ if (this._writableState.ended) return; // no more data can be written.
+ // But allow more writes to happen in this tick.
+
+ process.nextTick(onEndNT, this);
+}
+
+function onEndNT(self) {
+ self.end();
+}
+
+Object.defineProperty(Duplex.prototype, 'destroyed', {
+ // making it explicit this property is not enumerable
+ // because otherwise some prototype manipulation in
+ // userland will fail
+ enumerable: false,
+ get: function get() {
+ if (this._readableState === undefined || this._writableState === undefined) {
+ return false;
+ }
+
+ return this._readableState.destroyed && this._writableState.destroyed;
+ },
+ set: function set(value) {
+ // we ignore the value if the stream
+ // has not been initialized yet
+ if (this._readableState === undefined || this._writableState === undefined) {
+ return;
+ } // backward compatibility, the user is explicitly
+ // managing destroyed
+
+
+ this._readableState.destroyed = value;
+ this._writableState.destroyed = value;
+ }
+});
\ No newline at end of file
diff --git a/temporary_modules/trezor-connect/node_modules/readable-stream/lib/_stream_passthrough.js b/temporary_modules/trezor-connect/node_modules/readable-stream/lib/_stream_passthrough.js
new file mode 100644
index 00000000..32e7414c
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/readable-stream/lib/_stream_passthrough.js
@@ -0,0 +1,39 @@
+// Copyright Joyent, Inc. and other Node contributors.
+//
+// Permission is hereby granted, free of charge, to any person obtaining a
+// copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to permit
+// persons to whom the Software is furnished to do so, subject to the
+// following conditions:
+//
+// The above copyright notice and this permission notice shall be included
+// in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
+// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
+// USE OR OTHER DEALINGS IN THE SOFTWARE.
+// a passthrough stream.
+// basically just the most minimal sort of Transform stream.
+// Every written chunk gets output as-is.
+'use strict';
+
+module.exports = PassThrough;
+
+var Transform = require('./_stream_transform');
+
+require('inherits')(PassThrough, Transform);
+
+function PassThrough(options) {
+ if (!(this instanceof PassThrough)) return new PassThrough(options);
+ Transform.call(this, options);
+}
+
+PassThrough.prototype._transform = function (chunk, encoding, cb) {
+ cb(null, chunk);
+};
\ No newline at end of file
diff --git a/temporary_modules/trezor-connect/node_modules/readable-stream/lib/_stream_readable.js b/temporary_modules/trezor-connect/node_modules/readable-stream/lib/_stream_readable.js
new file mode 100644
index 00000000..192d4514
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/readable-stream/lib/_stream_readable.js
@@ -0,0 +1,1124 @@
+// Copyright Joyent, Inc. and other Node contributors.
+//
+// Permission is hereby granted, free of charge, to any person obtaining a
+// copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to permit
+// persons to whom the Software is furnished to do so, subject to the
+// following conditions:
+//
+// The above copyright notice and this permission notice shall be included
+// in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
+// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
+// USE OR OTHER DEALINGS IN THE SOFTWARE.
+'use strict';
+
+module.exports = Readable;
+/**/
+
+var Duplex;
+/**/
+
+Readable.ReadableState = ReadableState;
+/**/
+
+var EE = require('events').EventEmitter;
+
+var EElistenerCount = function EElistenerCount(emitter, type) {
+ return emitter.listeners(type).length;
+};
+/**/
+
+/**/
+
+
+var Stream = require('./internal/streams/stream');
+/**/
+
+
+var Buffer = require('buffer').Buffer;
+
+var OurUint8Array = global.Uint8Array || function () {};
+
+function _uint8ArrayToBuffer(chunk) {
+ return Buffer.from(chunk);
+}
+
+function _isUint8Array(obj) {
+ return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
+}
+/**/
+
+
+var debugUtil = require('util');
+
+var debug;
+
+if (debugUtil && debugUtil.debuglog) {
+ debug = debugUtil.debuglog('stream');
+} else {
+ debug = function debug() {};
+}
+/**/
+
+
+var BufferList = require('./internal/streams/buffer_list');
+
+var destroyImpl = require('./internal/streams/destroy');
+
+var _require = require('./internal/streams/state'),
+ getHighWaterMark = _require.getHighWaterMark;
+
+var _require$codes = require('../errors').codes,
+ ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,
+ ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF,
+ ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
+ ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance.
+
+
+var StringDecoder;
+var createReadableStreamAsyncIterator;
+var from;
+
+require('inherits')(Readable, Stream);
+
+var errorOrDestroy = destroyImpl.errorOrDestroy;
+var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
+
+function prependListener(emitter, event, fn) {
+ // Sadly this is not cacheable as some libraries bundle their own
+ // event emitter implementation with them.
+ 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
+ // userland ones. NEVER DO THIS. This is here only because this code needs
+ // to continue to work with older versions of Node.js that do not include
+ // the prependListener() method. The goal is to eventually remove this hack.
+
+ 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]];
+}
+
+function ReadableState(options, stream, isDuplex) {
+ Duplex = Duplex || require('./_stream_duplex');
+ options = options || {}; // Duplex streams are both readable and writable, but share
+ // the same options object.
+ // However, some cases require setting options to different
+ // values for the readable and the writable sides of the duplex stream.
+ // These options can be provided separately as readableXXX and writableXXX.
+
+ if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag. Used to make read(n) ignore n and to
+ // make all the buffer merging and length checks go away
+
+ this.objectMode = !!options.objectMode;
+ if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer
+ // Note: 0 is a valid value, means "don't call _read preemptively ever"
+
+ this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the
+ // linked list can remove elements from the beginning faster than
+ // array.shift()
+
+ this.buffer = new BufferList();
+ this.length = 0;
+ this.pipes = null;
+ this.pipesCount = 0;
+ this.flowing = null;
+ this.ended = false;
+ this.endEmitted = false;
+ this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted
+ // immediately, or on a later tick. We set this to true at first, because
+ // any actions that shouldn't happen until "later" should generally also
+ // not happen before the first read call.
+
+ this.sync = true; // whenever we return null, then we set a flag to say
+ // that we're awaiting a 'readable' event emission.
+
+ this.needReadable = false;
+ this.emittedReadable = false;
+ this.readableListening = false;
+ this.resumeScheduled = false;
+ this.paused = true; // Should close be emitted on destroy. Defaults to true.
+
+ this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'end' (and potentially 'finish')
+
+ this.autoDestroy = !!options.autoDestroy; // has it been destroyed
+
+ this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string
+ // encoding is 'binary' so we have to make this configurable.
+ // Everything else in the universe uses 'utf8', though.
+
+ this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s
+
+ this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled
+
+ this.readingMore = false;
+ this.decoder = null;
+ this.encoding = null;
+
+ if (options.encoding) {
+ if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
+ this.decoder = new StringDecoder(options.encoding);
+ this.encoding = options.encoding;
+ }
+}
+
+function Readable(options) {
+ Duplex = Duplex || require('./_stream_duplex');
+ if (!(this instanceof Readable)) return new Readable(options); // Checking for a Stream.Duplex instance is faster here instead of inside
+ // the ReadableState constructor, at least with V8 6.5
+
+ var isDuplex = this instanceof Duplex;
+ this._readableState = new ReadableState(options, this, isDuplex); // legacy
+
+ this.readable = true;
+
+ if (options) {
+ if (typeof options.read === 'function') this._read = options.read;
+ if (typeof options.destroy === 'function') this._destroy = options.destroy;
+ }
+
+ Stream.call(this);
+}
+
+Object.defineProperty(Readable.prototype, 'destroyed', {
+ // making it explicit this property is not enumerable
+ // because otherwise some prototype manipulation in
+ // userland will fail
+ enumerable: false,
+ get: function get() {
+ if (this._readableState === undefined) {
+ return false;
+ }
+
+ return this._readableState.destroyed;
+ },
+ set: function set(value) {
+ // we ignore the value if the stream
+ // has not been initialized yet
+ if (!this._readableState) {
+ return;
+ } // backward compatibility, the user is explicitly
+ // managing destroyed
+
+
+ this._readableState.destroyed = value;
+ }
+});
+Readable.prototype.destroy = destroyImpl.destroy;
+Readable.prototype._undestroy = destroyImpl.undestroy;
+
+Readable.prototype._destroy = function (err, cb) {
+ cb(err);
+}; // Manually shove something into the read() buffer.
+// This returns true if the highWaterMark has not been hit yet,
+// similar to how Writable.write() returns true if you should
+// write() some more.
+
+
+Readable.prototype.push = function (chunk, encoding) {
+ var state = this._readableState;
+ var skipChunkCheck;
+
+ if (!state.objectMode) {
+ if (typeof chunk === 'string') {
+ encoding = encoding || state.defaultEncoding;
+
+ if (encoding !== state.encoding) {
+ chunk = Buffer.from(chunk, encoding);
+ encoding = '';
+ }
+
+ skipChunkCheck = true;
+ }
+ } else {
+ skipChunkCheck = true;
+ }
+
+ return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
+}; // Unshift should *always* be something directly out of read()
+
+
+Readable.prototype.unshift = function (chunk) {
+ return readableAddChunk(this, chunk, null, true, false);
+};
+
+function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
+ debug('readableAddChunk', chunk);
+ var state = stream._readableState;
+
+ if (chunk === null) {
+ state.reading = false;
+ onEofChunk(stream, state);
+ } else {
+ var er;
+ if (!skipChunkCheck) er = chunkInvalid(state, chunk);
+
+ if (er) {
+ errorOrDestroy(stream, er);
+ } else if (state.objectMode || chunk && chunk.length > 0) {
+ if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
+ chunk = _uint8ArrayToBuffer(chunk);
+ }
+
+ if (addToFront) {
+ if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true);
+ } else if (state.ended) {
+ errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF());
+ } else if (state.destroyed) {
+ return false;
+ } else {
+ state.reading = false;
+
+ if (state.decoder && !encoding) {
+ chunk = state.decoder.write(chunk);
+ if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
+ } else {
+ addChunk(stream, state, chunk, false);
+ }
+ }
+ } else if (!addToFront) {
+ state.reading = false;
+ maybeReadMore(stream, state);
+ }
+ } // We can push more data if we are below the highWaterMark.
+ // Also, if we have no data yet, we can stand some more bytes.
+ // This is to work around cases where hwm=0, such as the repl.
+
+
+ return !state.ended && (state.length < state.highWaterMark || state.length === 0);
+}
+
+function addChunk(stream, state, chunk, addToFront) {
+ if (state.flowing && state.length === 0 && !state.sync) {
+ state.awaitDrain = 0;
+ stream.emit('data', chunk);
+ } else {
+ // update the buffer info.
+ state.length += state.objectMode ? 1 : chunk.length;
+ if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
+ if (state.needReadable) emitReadable(stream);
+ }
+
+ maybeReadMore(stream, state);
+}
+
+function chunkInvalid(state, chunk) {
+ var er;
+
+ if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
+ er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk);
+ }
+
+ return er;
+}
+
+Readable.prototype.isPaused = function () {
+ return this._readableState.flowing === false;
+}; // backwards compatibility.
+
+
+Readable.prototype.setEncoding = function (enc) {
+ if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
+ var decoder = new StringDecoder(enc);
+ this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8
+
+ this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers:
+
+ var p = this._readableState.buffer.head;
+ var content = '';
+
+ while (p !== null) {
+ content += decoder.write(p.data);
+ p = p.next;
+ }
+
+ this._readableState.buffer.clear();
+
+ if (content !== '') this._readableState.buffer.push(content);
+ this._readableState.length = content.length;
+ return this;
+}; // Don't raise the hwm > 1GB
+
+
+var MAX_HWM = 0x40000000;
+
+function computeNewHighWaterMark(n) {
+ if (n >= MAX_HWM) {
+ // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE.
+ n = MAX_HWM;
+ } else {
+ // Get the next highest power of 2 to prevent increasing hwm excessively in
+ // tiny amounts
+ n--;
+ n |= n >>> 1;
+ n |= n >>> 2;
+ n |= n >>> 4;
+ n |= n >>> 8;
+ n |= n >>> 16;
+ n++;
+ }
+
+ return n;
+} // This function is designed to be inlinable, so please take care when making
+// changes to the function body.
+
+
+function howMuchToRead(n, state) {
+ if (n <= 0 || state.length === 0 && state.ended) return 0;
+ if (state.objectMode) return 1;
+
+ if (n !== n) {
+ // Only flow one buffer at a time
+ if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
+ } // If we're asking for more than the current hwm, then raise the hwm.
+
+
+ if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
+ if (n <= state.length) return n; // Don't have enough
+
+ if (!state.ended) {
+ state.needReadable = true;
+ return 0;
+ }
+
+ return state.length;
+} // you can override either this method, or the async _read(n) below.
+
+
+Readable.prototype.read = function (n) {
+ debug('read', n);
+ n = parseInt(n, 10);
+ var state = this._readableState;
+ var nOrig = n;
+ if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we
+ // already have a bunch of data in the buffer, then just trigger
+ // the 'readable' event and move on.
+
+ if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) {
+ debug('read: emitReadable', state.length, state.ended);
+ if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
+ return null;
+ }
+
+ n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up.
+
+ if (n === 0 && state.ended) {
+ if (state.length === 0) endReadable(this);
+ return null;
+ } // All the actual chunk generation logic needs to be
+ // *below* the call to _read. The reason is that in certain
+ // synthetic stream cases, such as passthrough streams, _read
+ // may be a completely synchronous operation which may change
+ // the state of the read buffer, providing enough data when
+ // before there was *not* enough.
+ //
+ // So, the steps are:
+ // 1. Figure out what the state of things will be after we do
+ // a read from the buffer.
+ //
+ // 2. If that resulting state will trigger a _read, then call _read.
+ // Note that this may be asynchronous, or synchronous. Yes, it is
+ // deeply ugly to write APIs this way, but that still doesn't mean
+ // that the Readable class should behave improperly, as streams are
+ // designed to be sync/async agnostic.
+ // Take note if the _read call is sync or async (ie, if the read call
+ // has returned yet), so that we know whether or not it's safe to emit
+ // 'readable' etc.
+ //
+ // 3. Actually pull the requested chunks out of the buffer and return.
+ // if we need a readable event, then we need to do some reading.
+
+
+ var doRead = state.needReadable;
+ debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some
+
+ if (state.length === 0 || state.length - n < state.highWaterMark) {
+ doRead = true;
+ debug('length less than watermark', doRead);
+ } // however, if we've ended, then there's no point, and if we're already
+ // reading, then it's unnecessary.
+
+
+ if (state.ended || state.reading) {
+ doRead = false;
+ debug('reading or ended', doRead);
+ } else if (doRead) {
+ debug('do read');
+ state.reading = true;
+ state.sync = true; // if the length is currently zero, then we *need* a readable event.
+
+ if (state.length === 0) state.needReadable = true; // call internal read method
+
+ this._read(state.highWaterMark);
+
+ state.sync = false; // If _read pushed data synchronously, then `reading` will be false,
+ // and we need to re-evaluate how much data we can return to the user.
+
+ if (!state.reading) n = howMuchToRead(nOrig, state);
+ }
+
+ var ret;
+ if (n > 0) ret = fromList(n, state);else ret = null;
+
+ if (ret === null) {
+ state.needReadable = state.length <= state.highWaterMark;
+ n = 0;
+ } else {
+ state.length -= n;
+ state.awaitDrain = 0;
+ }
+
+ if (state.length === 0) {
+ // If we have nothing in the buffer, then we want to know
+ // as soon as we *do* get something into the buffer.
+ if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick.
+
+ if (nOrig !== n && state.ended) endReadable(this);
+ }
+
+ if (ret !== null) this.emit('data', ret);
+ return ret;
+};
+
+function onEofChunk(stream, state) {
+ debug('onEofChunk');
+ if (state.ended) return;
+
+ if (state.decoder) {
+ var chunk = state.decoder.end();
+
+ if (chunk && chunk.length) {
+ state.buffer.push(chunk);
+ state.length += state.objectMode ? 1 : chunk.length;
+ }
+ }
+
+ state.ended = true;
+
+ if (state.sync) {
+ // if we are sync, wait until next tick to emit the data.
+ // Otherwise we risk emitting data in the flow()
+ // the readable code triggers during a read() call
+ emitReadable(stream);
+ } else {
+ // emit 'readable' now to make sure it gets picked up.
+ state.needReadable = false;
+
+ if (!state.emittedReadable) {
+ state.emittedReadable = true;
+ emitReadable_(stream);
+ }
+ }
+} // Don't emit readable right away in sync mode, because this can trigger
+// another read() call => stack overflow. This way, it might trigger
+// a nextTick recursion warning, but that's not so bad.
+
+
+function emitReadable(stream) {
+ var state = stream._readableState;
+ debug('emitReadable', state.needReadable, state.emittedReadable);
+ state.needReadable = false;
+
+ if (!state.emittedReadable) {
+ debug('emitReadable', state.flowing);
+ state.emittedReadable = true;
+ process.nextTick(emitReadable_, stream);
+ }
+}
+
+function emitReadable_(stream) {
+ var state = stream._readableState;
+ debug('emitReadable_', state.destroyed, state.length, state.ended);
+
+ if (!state.destroyed && (state.length || state.ended)) {
+ stream.emit('readable');
+ state.emittedReadable = false;
+ } // The stream needs another readable event if
+ // 1. It is not flowing, as the flow mechanism will take
+ // care of it.
+ // 2. It is not ended.
+ // 3. It is below the highWaterMark, so we can schedule
+ // another readable later.
+
+
+ state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark;
+ flow(stream);
+} // at this point, the user has presumably seen the 'readable' event,
+// and called read() to consume some data. that may have triggered
+// in turn another _read(n) call, in which case reading = true if
+// it's in progress.
+// However, if we're not ended, or reading, and the length < hwm,
+// then go ahead and try to read some more preemptively.
+
+
+function maybeReadMore(stream, state) {
+ if (!state.readingMore) {
+ state.readingMore = true;
+ process.nextTick(maybeReadMore_, stream, state);
+ }
+}
+
+function maybeReadMore_(stream, state) {
+ // Attempt to read more data if we should.
+ //
+ // The conditions for reading more data are (one of):
+ // - Not enough data buffered (state.length < state.highWaterMark). The loop
+ // is responsible for filling the buffer with enough data if such data
+ // is available. If highWaterMark is 0 and we are not in the flowing mode
+ // we should _not_ attempt to buffer any extra data. We'll get more data
+ // when the stream consumer calls read() instead.
+ // - No data in the buffer, and the stream is in flowing mode. In this mode
+ // the loop below is responsible for ensuring read() is called. Failing to
+ // call read here would abort the flow and there's no other mechanism for
+ // continuing the flow if the stream consumer has just subscribed to the
+ // 'data' event.
+ //
+ // In addition to the above conditions to keep reading data, the following
+ // conditions prevent the data from being read:
+ // - The stream has ended (state.ended).
+ // - There is already a pending 'read' operation (state.reading). This is a
+ // case where the the stream has called the implementation defined _read()
+ // method, but they are processing the call asynchronously and have _not_
+ // called push() with new data. In this case we skip performing more
+ // read()s. The execution ends in this method again after the _read() ends
+ // up calling push() with more data.
+ while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) {
+ var len = state.length;
+ debug('maybeReadMore read 0');
+ stream.read(0);
+ if (len === state.length) // didn't get any data, stop spinning.
+ break;
+ }
+
+ state.readingMore = false;
+} // abstract method. to be overridden in specific implementation classes.
+// call cb(er, data) where data is <= n in length.
+// for virtual (non-string, non-buffer) streams, "length" is somewhat
+// arbitrary, and perhaps not very meaningful.
+
+
+Readable.prototype._read = function (n) {
+ errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()'));
+};
+
+Readable.prototype.pipe = function (dest, pipeOpts) {
+ var src = this;
+ var state = this._readableState;
+
+ switch (state.pipesCount) {
+ case 0:
+ state.pipes = dest;
+ break;
+
+ case 1:
+ state.pipes = [state.pipes, dest];
+ break;
+
+ default:
+ state.pipes.push(dest);
+ break;
+ }
+
+ state.pipesCount += 1;
+ debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
+ var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
+ var endFn = doEnd ? onend : unpipe;
+ if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn);
+ dest.on('unpipe', onunpipe);
+
+ function onunpipe(readable, unpipeInfo) {
+ debug('onunpipe');
+
+ if (readable === src) {
+ if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
+ unpipeInfo.hasUnpiped = true;
+ cleanup();
+ }
+ }
+ }
+
+ function onend() {
+ debug('onend');
+ dest.end();
+ } // when the dest drains, it reduces the awaitDrain counter
+ // on the source. This would be more elegant with a .once()
+ // handler in flow(), but adding and removing repeatedly is
+ // too slow.
+
+
+ var ondrain = pipeOnDrain(src);
+ dest.on('drain', ondrain);
+ var cleanedUp = false;
+
+ function cleanup() {
+ debug('cleanup'); // cleanup event handlers once the pipe is broken
+
+ dest.removeListener('close', onclose);
+ dest.removeListener('finish', onfinish);
+ dest.removeListener('drain', ondrain);
+ dest.removeListener('error', onerror);
+ dest.removeListener('unpipe', onunpipe);
+ src.removeListener('end', onend);
+ src.removeListener('end', unpipe);
+ src.removeListener('data', ondata);
+ cleanedUp = true; // if the reader is waiting for a drain event from this
+ // specific writer, then it would cause it to never start
+ // flowing again.
+ // So, if this is awaiting a drain, then we just call it now.
+ // If we don't know, then assume that we are waiting for one.
+
+ if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
+ }
+
+ src.on('data', ondata);
+
+ function ondata(chunk) {
+ debug('ondata');
+ var ret = dest.write(chunk);
+ debug('dest.write', ret);
+
+ if (ret === false) {
+ // If the user unpiped during `dest.write()`, it is possible
+ // to get stuck in a permanently paused state if that write
+ // also returned false.
+ // => Check whether `dest` is still a piping destination.
+ if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
+ debug('false write response, pause', state.awaitDrain);
+ state.awaitDrain++;
+ }
+
+ src.pause();
+ }
+ } // if the dest has an error, then stop piping into it.
+ // however, don't suppress the throwing behavior for this.
+
+
+ function onerror(er) {
+ debug('onerror', er);
+ unpipe();
+ dest.removeListener('error', onerror);
+ if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er);
+ } // Make sure our error handler is attached before userland ones.
+
+
+ prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once.
+
+ function onclose() {
+ dest.removeListener('finish', onfinish);
+ unpipe();
+ }
+
+ dest.once('close', onclose);
+
+ function onfinish() {
+ debug('onfinish');
+ dest.removeListener('close', onclose);
+ unpipe();
+ }
+
+ dest.once('finish', onfinish);
+
+ function unpipe() {
+ debug('unpipe');
+ src.unpipe(dest);
+ } // tell the dest that it's being piped to
+
+
+ dest.emit('pipe', src); // start the flow if it hasn't been started already.
+
+ if (!state.flowing) {
+ debug('pipe resume');
+ src.resume();
+ }
+
+ return dest;
+};
+
+function pipeOnDrain(src) {
+ return function pipeOnDrainFunctionResult() {
+ var state = src._readableState;
+ debug('pipeOnDrain', state.awaitDrain);
+ if (state.awaitDrain) state.awaitDrain--;
+
+ if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
+ state.flowing = true;
+ flow(src);
+ }
+ };
+}
+
+Readable.prototype.unpipe = function (dest) {
+ var state = this._readableState;
+ var unpipeInfo = {
+ hasUnpiped: false
+ }; // if we're not piping anywhere, then do nothing.
+
+ if (state.pipesCount === 0) return this; // just one destination. most common case.
+
+ if (state.pipesCount === 1) {
+ // passed in one, but it's not the right one.
+ if (dest && dest !== state.pipes) return this;
+ if (!dest) dest = state.pipes; // got a match.
+
+ state.pipes = null;
+ state.pipesCount = 0;
+ state.flowing = false;
+ if (dest) dest.emit('unpipe', this, unpipeInfo);
+ return this;
+ } // slow case. multiple pipe destinations.
+
+
+ if (!dest) {
+ // remove all.
+ var dests = state.pipes;
+ var len = state.pipesCount;
+ state.pipes = null;
+ state.pipesCount = 0;
+ state.flowing = false;
+
+ for (var i = 0; i < len; i++) {
+ dests[i].emit('unpipe', this, {
+ hasUnpiped: false
+ });
+ }
+
+ return this;
+ } // try to find the right one.
+
+
+ var index = indexOf(state.pipes, dest);
+ if (index === -1) return this;
+ state.pipes.splice(index, 1);
+ state.pipesCount -= 1;
+ if (state.pipesCount === 1) state.pipes = state.pipes[0];
+ dest.emit('unpipe', this, unpipeInfo);
+ return this;
+}; // set up data events if they are asked for
+// Ensure readable listeners eventually get something
+
+
+Readable.prototype.on = function (ev, fn) {
+ var res = Stream.prototype.on.call(this, ev, fn);
+ var state = this._readableState;
+
+ if (ev === 'data') {
+ // update readableListening so that resume() may be a no-op
+ // a few lines down. This is needed to support once('readable').
+ state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused
+
+ if (state.flowing !== false) this.resume();
+ } else if (ev === 'readable') {
+ if (!state.endEmitted && !state.readableListening) {
+ state.readableListening = state.needReadable = true;
+ state.flowing = false;
+ state.emittedReadable = false;
+ debug('on readable', state.length, state.reading);
+
+ if (state.length) {
+ emitReadable(this);
+ } else if (!state.reading) {
+ process.nextTick(nReadingNextTick, this);
+ }
+ }
+ }
+
+ return res;
+};
+
+Readable.prototype.addListener = Readable.prototype.on;
+
+Readable.prototype.removeListener = function (ev, fn) {
+ var res = Stream.prototype.removeListener.call(this, ev, fn);
+
+ if (ev === 'readable') {
+ // We need to check if there is someone still listening to
+ // readable and reset the state. However this needs to happen
+ // after readable has been emitted but before I/O (nextTick) to
+ // support once('readable', fn) cycles. This means that calling
+ // resume within the same tick will have no
+ // effect.
+ process.nextTick(updateReadableListening, this);
+ }
+
+ return res;
+};
+
+Readable.prototype.removeAllListeners = function (ev) {
+ var res = Stream.prototype.removeAllListeners.apply(this, arguments);
+
+ if (ev === 'readable' || ev === undefined) {
+ // We need to check if there is someone still listening to
+ // readable and reset the state. However this needs to happen
+ // after readable has been emitted but before I/O (nextTick) to
+ // support once('readable', fn) cycles. This means that calling
+ // resume within the same tick will have no
+ // effect.
+ process.nextTick(updateReadableListening, this);
+ }
+
+ return res;
+};
+
+function updateReadableListening(self) {
+ var state = self._readableState;
+ state.readableListening = self.listenerCount('readable') > 0;
+
+ if (state.resumeScheduled && !state.paused) {
+ // flowing needs to be set to true now, otherwise
+ // the upcoming resume will not flow.
+ state.flowing = true; // crude way to check if we should resume
+ } else if (self.listenerCount('data') > 0) {
+ self.resume();
+ }
+}
+
+function nReadingNextTick(self) {
+ debug('readable nexttick read 0');
+ self.read(0);
+} // pause() and resume() are remnants of the legacy readable stream API
+// If the user uses them, then switch into old mode.
+
+
+Readable.prototype.resume = function () {
+ var state = this._readableState;
+
+ if (!state.flowing) {
+ debug('resume'); // we flow only if there is no one listening
+ // for readable, but we still have to call
+ // resume()
+
+ state.flowing = !state.readableListening;
+ resume(this, state);
+ }
+
+ state.paused = false;
+ return this;
+};
+
+function resume(stream, state) {
+ if (!state.resumeScheduled) {
+ state.resumeScheduled = true;
+ process.nextTick(resume_, stream, state);
+ }
+}
+
+function resume_(stream, state) {
+ debug('resume', state.reading);
+
+ if (!state.reading) {
+ stream.read(0);
+ }
+
+ state.resumeScheduled = false;
+ stream.emit('resume');
+ flow(stream);
+ if (state.flowing && !state.reading) stream.read(0);
+}
+
+Readable.prototype.pause = function () {
+ debug('call pause flowing=%j', this._readableState.flowing);
+
+ if (this._readableState.flowing !== false) {
+ debug('pause');
+ this._readableState.flowing = false;
+ this.emit('pause');
+ }
+
+ this._readableState.paused = true;
+ return this;
+};
+
+function flow(stream) {
+ var state = stream._readableState;
+ debug('flow', state.flowing);
+
+ while (state.flowing && stream.read() !== null) {
+ ;
+ }
+} // wrap an old-style stream as the async data source.
+// This is *not* part of the readable stream interface.
+// It is an ugly unfortunate mess of history.
+
+
+Readable.prototype.wrap = function (stream) {
+ var _this = this;
+
+ var state = this._readableState;
+ var paused = false;
+ stream.on('end', function () {
+ debug('wrapped end');
+
+ if (state.decoder && !state.ended) {
+ var chunk = state.decoder.end();
+ if (chunk && chunk.length) _this.push(chunk);
+ }
+
+ _this.push(null);
+ });
+ stream.on('data', function (chunk) {
+ debug('wrapped data');
+ if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode
+
+ if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
+
+ var ret = _this.push(chunk);
+
+ if (!ret) {
+ paused = true;
+ stream.pause();
+ }
+ }); // proxy all the other methods.
+ // important when wrapping filters and duplexes.
+
+ for (var i in stream) {
+ if (this[i] === undefined && typeof stream[i] === 'function') {
+ this[i] = function methodWrap(method) {
+ return function methodWrapReturnFunction() {
+ return stream[method].apply(stream, arguments);
+ };
+ }(i);
+ }
+ } // proxy certain important events.
+
+
+ for (var n = 0; n < kProxyEvents.length; n++) {
+ stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));
+ } // when we try to consume some more bytes, simply unpause the
+ // underlying stream.
+
+
+ this._read = function (n) {
+ debug('wrapped _read', n);
+
+ if (paused) {
+ paused = false;
+ stream.resume();
+ }
+ };
+
+ return this;
+};
+
+if (typeof Symbol === 'function') {
+ Readable.prototype[Symbol.asyncIterator] = function () {
+ if (createReadableStreamAsyncIterator === undefined) {
+ createReadableStreamAsyncIterator = require('./internal/streams/async_iterator');
+ }
+
+ return createReadableStreamAsyncIterator(this);
+ };
+}
+
+Object.defineProperty(Readable.prototype, 'readableHighWaterMark', {
+ // making it explicit this property is not enumerable
+ // because otherwise some prototype manipulation in
+ // userland will fail
+ enumerable: false,
+ get: function get() {
+ return this._readableState.highWaterMark;
+ }
+});
+Object.defineProperty(Readable.prototype, 'readableBuffer', {
+ // making it explicit this property is not enumerable
+ // because otherwise some prototype manipulation in
+ // userland will fail
+ enumerable: false,
+ get: function get() {
+ return this._readableState && this._readableState.buffer;
+ }
+});
+Object.defineProperty(Readable.prototype, 'readableFlowing', {
+ // making it explicit this property is not enumerable
+ // because otherwise some prototype manipulation in
+ // userland will fail
+ enumerable: false,
+ get: function get() {
+ return this._readableState.flowing;
+ },
+ set: function set(state) {
+ if (this._readableState) {
+ this._readableState.flowing = state;
+ }
+ }
+}); // exposed for testing purposes only.
+
+Readable._fromList = fromList;
+Object.defineProperty(Readable.prototype, 'readableLength', {
+ // making it explicit this property is not enumerable
+ // because otherwise some prototype manipulation in
+ // userland will fail
+ enumerable: false,
+ get: function get() {
+ return this._readableState.length;
+ }
+}); // Pluck off n bytes from an array of buffers.
+// Length is the combined lengths of all the buffers in the list.
+// This function is designed to be inlinable, so please take care when making
+// changes to the function body.
+
+function fromList(n, state) {
+ // nothing buffered
+ if (state.length === 0) return null;
+ var ret;
+ if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
+ // read it all, truncate the list
+ if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length);
+ state.buffer.clear();
+ } else {
+ // read part of list
+ ret = state.buffer.consume(n, state.decoder);
+ }
+ return ret;
+}
+
+function endReadable(stream) {
+ var state = stream._readableState;
+ debug('endReadable', state.endEmitted);
+
+ if (!state.endEmitted) {
+ state.ended = true;
+ process.nextTick(endReadableNT, state, stream);
+ }
+}
+
+function endReadableNT(state, stream) {
+ debug('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift.
+
+ if (!state.endEmitted && state.length === 0) {
+ state.endEmitted = true;
+ stream.readable = false;
+ stream.emit('end');
+
+ if (state.autoDestroy) {
+ // In case of duplex streams we need a way to detect
+ // if the writable side is ready for autoDestroy as well
+ var wState = stream._writableState;
+
+ if (!wState || wState.autoDestroy && wState.finished) {
+ stream.destroy();
+ }
+ }
+ }
+}
+
+if (typeof Symbol === 'function') {
+ Readable.from = function (iterable, opts) {
+ if (from === undefined) {
+ from = require('./internal/streams/from');
+ }
+
+ return from(Readable, iterable, opts);
+ };
+}
+
+function indexOf(xs, x) {
+ for (var i = 0, l = xs.length; i < l; i++) {
+ if (xs[i] === x) return i;
+ }
+
+ return -1;
+}
\ No newline at end of file
diff --git a/temporary_modules/trezor-connect/node_modules/readable-stream/lib/_stream_transform.js b/temporary_modules/trezor-connect/node_modules/readable-stream/lib/_stream_transform.js
new file mode 100644
index 00000000..41a738c4
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/readable-stream/lib/_stream_transform.js
@@ -0,0 +1,201 @@
+// Copyright Joyent, Inc. and other Node contributors.
+//
+// Permission is hereby granted, free of charge, to any person obtaining a
+// copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to permit
+// persons to whom the Software is furnished to do so, subject to the
+// following conditions:
+//
+// The above copyright notice and this permission notice shall be included
+// in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
+// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
+// USE OR OTHER DEALINGS IN THE SOFTWARE.
+// a transform stream is a readable/writable stream where you do
+// something with the data. Sometimes it's called a "filter",
+// but that's not a great name for it, since that implies a thing where
+// some bits pass through, and others are simply ignored. (That would
+// be a valid example of a transform, of course.)
+//
+// While the output is causally related to the input, it's not a
+// necessarily symmetric or synchronous transformation. For example,
+// a zlib stream might take multiple plain-text writes(), and then
+// emit a single compressed chunk some time in the future.
+//
+// Here's how this works:
+//
+// The Transform stream has all the aspects of the readable and writable
+// stream classes. When you write(chunk), that calls _write(chunk,cb)
+// internally, and returns false if there's a lot of pending writes
+// buffered up. When you call read(), that calls _read(n) until
+// there's enough pending readable data buffered up.
+//
+// In a transform stream, the written data is placed in a buffer. When
+// _read(n) is called, it transforms the queued up data, calling the
+// buffered _write cb's as it consumes chunks. If consuming a single
+// written chunk would result in multiple output chunks, then the first
+// outputted bit calls the readcb, and subsequent chunks just go into
+// the read buffer, and will cause it to emit 'readable' if necessary.
+//
+// This way, back-pressure is actually determined by the reading side,
+// since _read has to be called to start processing a new chunk. However,
+// a pathological inflate type of transform can cause excessive buffering
+// here. For example, imagine a stream where every byte of input is
+// interpreted as an integer from 0-255, and then results in that many
+// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
+// 1kb of data being output. In this case, you could write a very small
+// amount of input, and end up with a very large amount of output. In
+// such a pathological inflating mechanism, there'd be no way to tell
+// the system to stop doing the transform. A single 4MB write could
+// cause the system to run out of memory.
+//
+// However, even in such a pathological case, only a single written chunk
+// would be consumed, and then the rest would wait (un-transformed) until
+// the results of the previous transformed chunk were consumed.
+'use strict';
+
+module.exports = Transform;
+
+var _require$codes = require('../errors').codes,
+ ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
+ ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,
+ ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING,
+ ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0;
+
+var Duplex = require('./_stream_duplex');
+
+require('inherits')(Transform, Duplex);
+
+function afterTransform(er, data) {
+ var ts = this._transformState;
+ ts.transforming = false;
+ var cb = ts.writecb;
+
+ if (cb === null) {
+ return this.emit('error', new ERR_MULTIPLE_CALLBACK());
+ }
+
+ ts.writechunk = null;
+ ts.writecb = null;
+ if (data != null) // single equals check for both `null` and `undefined`
+ this.push(data);
+ cb(er);
+ var rs = this._readableState;
+ rs.reading = false;
+
+ if (rs.needReadable || rs.length < rs.highWaterMark) {
+ this._read(rs.highWaterMark);
+ }
+}
+
+function Transform(options) {
+ if (!(this instanceof Transform)) return new Transform(options);
+ Duplex.call(this, options);
+ this._transformState = {
+ afterTransform: afterTransform.bind(this),
+ needTransform: false,
+ transforming: false,
+ writecb: null,
+ writechunk: null,
+ writeencoding: null
+ }; // start out asking for a readable event once data is transformed.
+
+ this._readableState.needReadable = true; // we have implemented the _read method, and done the other things
+ // that Readable wants before the first _read call, so unset the
+ // sync guard flag.
+
+ this._readableState.sync = false;
+
+ if (options) {
+ if (typeof options.transform === 'function') this._transform = options.transform;
+ if (typeof options.flush === 'function') this._flush = options.flush;
+ } // When the writable side finishes, then flush out anything remaining.
+
+
+ this.on('prefinish', prefinish);
+}
+
+function prefinish() {
+ var _this = this;
+
+ if (typeof this._flush === 'function' && !this._readableState.destroyed) {
+ this._flush(function (er, data) {
+ done(_this, er, data);
+ });
+ } else {
+ done(this, null, null);
+ }
+}
+
+Transform.prototype.push = function (chunk, encoding) {
+ this._transformState.needTransform = false;
+ return Duplex.prototype.push.call(this, chunk, encoding);
+}; // This is the part where you do stuff!
+// override this function in implementation classes.
+// 'chunk' is an input chunk.
+//
+// Call `push(newChunk)` to pass along transformed output
+// to the readable side. You may call 'push' zero or more times.
+//
+// Call `cb(err)` when you are done with this chunk. If you pass
+// an error, then that'll put the hurt on the whole operation. If you
+// never call cb(), then you'll never get another chunk.
+
+
+Transform.prototype._transform = function (chunk, encoding, cb) {
+ cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()'));
+};
+
+Transform.prototype._write = function (chunk, encoding, cb) {
+ var ts = this._transformState;
+ ts.writecb = cb;
+ ts.writechunk = chunk;
+ ts.writeencoding = encoding;
+
+ if (!ts.transforming) {
+ var rs = this._readableState;
+ if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
+ }
+}; // Doesn't matter what the args are here.
+// _transform does all the work.
+// That we got here means that the readable side wants more data.
+
+
+Transform.prototype._read = function (n) {
+ var ts = this._transformState;
+
+ if (ts.writechunk !== null && !ts.transforming) {
+ ts.transforming = true;
+
+ this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
+ } else {
+ // mark that we need a transform, so that any data that comes in
+ // will get processed, now that we've asked for it.
+ ts.needTransform = true;
+ }
+};
+
+Transform.prototype._destroy = function (err, cb) {
+ Duplex.prototype._destroy.call(this, err, function (err2) {
+ cb(err2);
+ });
+};
+
+function done(stream, er, data) {
+ if (er) return stream.emit('error', er);
+ if (data != null) // single equals check for both `null` and `undefined`
+ stream.push(data); // TODO(BridgeAR): Write a test for these two error cases
+ // if there's nothing in the write buffer, then that means
+ // that nothing more will ever be provided
+
+ if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0();
+ if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING();
+ return stream.push(null);
+}
\ No newline at end of file
diff --git a/temporary_modules/trezor-connect/node_modules/readable-stream/lib/_stream_writable.js b/temporary_modules/trezor-connect/node_modules/readable-stream/lib/_stream_writable.js
new file mode 100644
index 00000000..a2634d7c
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/readable-stream/lib/_stream_writable.js
@@ -0,0 +1,697 @@
+// Copyright Joyent, Inc. and other Node contributors.
+//
+// Permission is hereby granted, free of charge, to any person obtaining a
+// copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to permit
+// persons to whom the Software is furnished to do so, subject to the
+// following conditions:
+//
+// The above copyright notice and this permission notice shall be included
+// in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
+// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
+// USE OR OTHER DEALINGS IN THE SOFTWARE.
+// A bit simpler than readable streams.
+// Implement an async ._write(chunk, encoding, cb), and it'll handle all
+// the drain event emission and buffering.
+'use strict';
+
+module.exports = Writable;
+/* */
+
+function WriteReq(chunk, encoding, cb) {
+ this.chunk = chunk;
+ this.encoding = encoding;
+ this.callback = cb;
+ this.next = null;
+} // It seems a linked list but it is not
+// there will be only 2 of these for each stream
+
+
+function CorkedRequest(state) {
+ var _this = this;
+
+ this.next = null;
+ this.entry = null;
+
+ this.finish = function () {
+ onCorkedFinish(_this, state);
+ };
+}
+/* */
+
+/**/
+
+
+var Duplex;
+/**/
+
+Writable.WritableState = WritableState;
+/**/
+
+var internalUtil = {
+ deprecate: require('util-deprecate')
+};
+/**/
+
+/**/
+
+var Stream = require('./internal/streams/stream');
+/**/
+
+
+var Buffer = require('buffer').Buffer;
+
+var OurUint8Array = global.Uint8Array || function () {};
+
+function _uint8ArrayToBuffer(chunk) {
+ return Buffer.from(chunk);
+}
+
+function _isUint8Array(obj) {
+ return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
+}
+
+var destroyImpl = require('./internal/streams/destroy');
+
+var _require = require('./internal/streams/state'),
+ getHighWaterMark = _require.getHighWaterMark;
+
+var _require$codes = require('../errors').codes,
+ ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,
+ ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
+ ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,
+ ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE,
+ ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED,
+ ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES,
+ ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END,
+ ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING;
+
+var errorOrDestroy = destroyImpl.errorOrDestroy;
+
+require('inherits')(Writable, Stream);
+
+function nop() {}
+
+function WritableState(options, stream, isDuplex) {
+ Duplex = Duplex || require('./_stream_duplex');
+ options = options || {}; // Duplex streams are both readable and writable, but share
+ // the same options object.
+ // However, some cases require setting options to different
+ // values for the readable and the writable sides of the duplex stream,
+ // e.g. options.readableObjectMode vs. options.writableObjectMode, etc.
+
+ if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag to indicate whether or not this stream
+ // contains buffers or objects.
+
+ this.objectMode = !!options.objectMode;
+ if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false
+ // Note: 0 is a valid value, means that we always return false if
+ // the entire buffer is not flushed immediately on write()
+
+ this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called
+
+ this.finalCalled = false; // drain event flag.
+
+ this.needDrain = false; // at the start of calling end()
+
+ this.ending = false; // when end() has been called, and returned
+
+ this.ended = false; // when 'finish' is emitted
+
+ this.finished = false; // has it been destroyed
+
+ this.destroyed = false; // should we decode strings into buffers before passing to _write?
+ // this is here so that some node-core streams can optimize string
+ // handling at a lower level.
+
+ var noDecode = options.decodeStrings === false;
+ this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string
+ // encoding is 'binary' so we have to make this configurable.
+ // Everything else in the universe uses 'utf8', though.
+
+ this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement
+ // of how much we're waiting to get pushed to some underlying
+ // socket or file.
+
+ this.length = 0; // a flag to see when we're in the middle of a write.
+
+ this.writing = false; // when true all writes will be buffered until .uncork() call
+
+ this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately,
+ // or on a later tick. We set this to true at first, because any
+ // actions that shouldn't happen until "later" should generally also
+ // not happen before the first write call.
+
+ this.sync = true; // a flag to know if we're processing previously buffered items, which
+ // may call the _write() callback in the same tick, so that we don't
+ // end up in an overlapped onwrite situation.
+
+ this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb)
+
+ this.onwrite = function (er) {
+ onwrite(stream, er);
+ }; // the callback that the user supplies to write(chunk,encoding,cb)
+
+
+ this.writecb = null; // the amount that is being written when _write is called.
+
+ this.writelen = 0;
+ this.bufferedRequest = null;
+ this.lastBufferedRequest = null; // number of pending user-supplied write callbacks
+ // this must be 0 before 'finish' can be emitted
+
+ this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs
+ // This is relevant for synchronous Transform streams
+
+ this.prefinished = false; // True if the error was already emitted and should not be thrown again
+
+ this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true.
+
+ this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'finish' (and potentially 'end')
+
+ this.autoDestroy = !!options.autoDestroy; // count buffered requests
+
+ this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always
+ // one allocated and free to use, and we maintain at most two
+
+ this.corkedRequestsFree = new CorkedRequest(this);
+}
+
+WritableState.prototype.getBuffer = function getBuffer() {
+ var current = this.bufferedRequest;
+ var out = [];
+
+ while (current) {
+ out.push(current);
+ current = current.next;
+ }
+
+ return out;
+};
+
+(function () {
+ try {
+ Object.defineProperty(WritableState.prototype, 'buffer', {
+ get: internalUtil.deprecate(function writableStateBufferGetter() {
+ return this.getBuffer();
+ }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
+ });
+ } catch (_) {}
+})(); // Test _writableState for inheritance to account for Duplex streams,
+// whose prototype chain only points to Readable.
+
+
+var realHasInstance;
+
+if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
+ realHasInstance = Function.prototype[Symbol.hasInstance];
+ Object.defineProperty(Writable, Symbol.hasInstance, {
+ value: function value(object) {
+ if (realHasInstance.call(this, object)) return true;
+ if (this !== Writable) return false;
+ return object && object._writableState instanceof WritableState;
+ }
+ });
+} else {
+ realHasInstance = function realHasInstance(object) {
+ return object instanceof this;
+ };
+}
+
+function Writable(options) {
+ Duplex = Duplex || require('./_stream_duplex'); // Writable ctor is applied to Duplexes, too.
+ // `realHasInstance` is necessary because using plain `instanceof`
+ // would return false, as no `_writableState` property is attached.
+ // Trying to use the custom `instanceof` for Writable here will also break the
+ // Node.js LazyTransform implementation, which has a non-trivial getter for
+ // `_writableState` that would lead to infinite recursion.
+ // Checking for a Stream.Duplex instance is faster here instead of inside
+ // the WritableState constructor, at least with V8 6.5
+
+ var isDuplex = this instanceof Duplex;
+ if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options);
+ this._writableState = new WritableState(options, this, isDuplex); // legacy.
+
+ this.writable = true;
+
+ if (options) {
+ if (typeof options.write === 'function') this._write = options.write;
+ if (typeof options.writev === 'function') this._writev = options.writev;
+ if (typeof options.destroy === 'function') this._destroy = options.destroy;
+ if (typeof options.final === 'function') this._final = options.final;
+ }
+
+ Stream.call(this);
+} // Otherwise people can pipe Writable streams, which is just wrong.
+
+
+Writable.prototype.pipe = function () {
+ errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE());
+};
+
+function writeAfterEnd(stream, cb) {
+ var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb
+
+ errorOrDestroy(stream, er);
+ process.nextTick(cb, er);
+} // Checks that a user-supplied chunk is valid, especially for the particular
+// mode the stream is in. Currently this means that `null` is never accepted
+// and undefined/non-string values are only allowed in object mode.
+
+
+function validChunk(stream, state, chunk, cb) {
+ var er;
+
+ if (chunk === null) {
+ er = new ERR_STREAM_NULL_VALUES();
+ } else if (typeof chunk !== 'string' && !state.objectMode) {
+ er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk);
+ }
+
+ if (er) {
+ errorOrDestroy(stream, er);
+ process.nextTick(cb, er);
+ return false;
+ }
+
+ return true;
+}
+
+Writable.prototype.write = function (chunk, encoding, cb) {
+ var state = this._writableState;
+ var ret = false;
+
+ var isBuf = !state.objectMode && _isUint8Array(chunk);
+
+ if (isBuf && !Buffer.isBuffer(chunk)) {
+ chunk = _uint8ArrayToBuffer(chunk);
+ }
+
+ if (typeof encoding === 'function') {
+ cb = encoding;
+ encoding = null;
+ }
+
+ if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
+ if (typeof cb !== 'function') cb = nop;
+ if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
+ state.pendingcb++;
+ ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
+ }
+ return ret;
+};
+
+Writable.prototype.cork = function () {
+ this._writableState.corked++;
+};
+
+Writable.prototype.uncork = function () {
+ var state = this._writableState;
+
+ if (state.corked) {
+ state.corked--;
+ if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
+ }
+};
+
+Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
+ // node::ParseEncoding() requires lower case.
+ if (typeof encoding === 'string') encoding = encoding.toLowerCase();
+ 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);
+ this._writableState.defaultEncoding = encoding;
+ return this;
+};
+
+Object.defineProperty(Writable.prototype, 'writableBuffer', {
+ // making it explicit this property is not enumerable
+ // because otherwise some prototype manipulation in
+ // userland will fail
+ enumerable: false,
+ get: function get() {
+ return this._writableState && this._writableState.getBuffer();
+ }
+});
+
+function decodeChunk(state, chunk, encoding) {
+ if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
+ chunk = Buffer.from(chunk, encoding);
+ }
+
+ return chunk;
+}
+
+Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
+ // making it explicit this property is not enumerable
+ // because otherwise some prototype manipulation in
+ // userland will fail
+ enumerable: false,
+ get: function get() {
+ return this._writableState.highWaterMark;
+ }
+}); // if we're already writing something, then just put this
+// in the queue, and wait our turn. Otherwise, call _write
+// If we return false, then we need a drain event, so set that flag.
+
+function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
+ if (!isBuf) {
+ var newChunk = decodeChunk(state, chunk, encoding);
+
+ if (chunk !== newChunk) {
+ isBuf = true;
+ encoding = 'buffer';
+ chunk = newChunk;
+ }
+ }
+
+ var len = state.objectMode ? 1 : chunk.length;
+ state.length += len;
+ var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false.
+
+ if (!ret) state.needDrain = true;
+
+ if (state.writing || state.corked) {
+ var last = state.lastBufferedRequest;
+ state.lastBufferedRequest = {
+ chunk: chunk,
+ encoding: encoding,
+ isBuf: isBuf,
+ callback: cb,
+ next: null
+ };
+
+ if (last) {
+ last.next = state.lastBufferedRequest;
+ } else {
+ state.bufferedRequest = state.lastBufferedRequest;
+ }
+
+ state.bufferedRequestCount += 1;
+ } else {
+ doWrite(stream, state, false, len, chunk, encoding, cb);
+ }
+
+ return ret;
+}
+
+function doWrite(stream, state, writev, len, chunk, encoding, cb) {
+ state.writelen = len;
+ state.writecb = cb;
+ state.writing = true;
+ state.sync = true;
+ 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);
+ state.sync = false;
+}
+
+function onwriteError(stream, state, sync, er, cb) {
+ --state.pendingcb;
+
+ if (sync) {
+ // defer the callback if we are being called synchronously
+ // to avoid piling up things on the stack
+ process.nextTick(cb, er); // this can emit finish, and it will always happen
+ // after error
+
+ process.nextTick(finishMaybe, stream, state);
+ stream._writableState.errorEmitted = true;
+ errorOrDestroy(stream, er);
+ } else {
+ // the caller expect this to happen before if
+ // it is async
+ cb(er);
+ stream._writableState.errorEmitted = true;
+ errorOrDestroy(stream, er); // this can emit finish, but finish must
+ // always follow error
+
+ finishMaybe(stream, state);
+ }
+}
+
+function onwriteStateUpdate(state) {
+ state.writing = false;
+ state.writecb = null;
+ state.length -= state.writelen;
+ state.writelen = 0;
+}
+
+function onwrite(stream, er) {
+ var state = stream._writableState;
+ var sync = state.sync;
+ var cb = state.writecb;
+ if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK();
+ onwriteStateUpdate(state);
+ if (er) onwriteError(stream, state, sync, er, cb);else {
+ // Check if we're actually ready to finish, but don't emit yet
+ var finished = needFinish(state) || stream.destroyed;
+
+ if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
+ clearBuffer(stream, state);
+ }
+
+ if (sync) {
+ process.nextTick(afterWrite, stream, state, finished, cb);
+ } else {
+ afterWrite(stream, state, finished, cb);
+ }
+ }
+}
+
+function afterWrite(stream, state, finished, cb) {
+ if (!finished) onwriteDrain(stream, state);
+ state.pendingcb--;
+ cb();
+ finishMaybe(stream, state);
+} // Must force callback to be called on nextTick, so that we don't
+// emit 'drain' before the write() consumer gets the 'false' return
+// value, and has a chance to attach a 'drain' listener.
+
+
+function onwriteDrain(stream, state) {
+ if (state.length === 0 && state.needDrain) {
+ state.needDrain = false;
+ stream.emit('drain');
+ }
+} // if there's something in the buffer waiting, then process it
+
+
+function clearBuffer(stream, state) {
+ state.bufferProcessing = true;
+ var entry = state.bufferedRequest;
+
+ if (stream._writev && entry && entry.next) {
+ // Fast case, write everything using _writev()
+ var l = state.bufferedRequestCount;
+ var buffer = new Array(l);
+ var holder = state.corkedRequestsFree;
+ holder.entry = entry;
+ var count = 0;
+ var allBuffers = true;
+
+ while (entry) {
+ buffer[count] = entry;
+ if (!entry.isBuf) allBuffers = false;
+ entry = entry.next;
+ count += 1;
+ }
+
+ buffer.allBuffers = allBuffers;
+ doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time
+ // as the hot path ends with doWrite
+
+ state.pendingcb++;
+ state.lastBufferedRequest = null;
+
+ if (holder.next) {
+ state.corkedRequestsFree = holder.next;
+ holder.next = null;
+ } else {
+ state.corkedRequestsFree = new CorkedRequest(state);
+ }
+
+ state.bufferedRequestCount = 0;
+ } else {
+ // Slow case, write chunks one-by-one
+ while (entry) {
+ var chunk = entry.chunk;
+ var encoding = entry.encoding;
+ var cb = entry.callback;
+ var len = state.objectMode ? 1 : chunk.length;
+ doWrite(stream, state, false, len, chunk, encoding, cb);
+ entry = entry.next;
+ state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then
+ // it means that we need to wait until it does.
+ // also, that means that the chunk and cb are currently
+ // being processed, so move the buffer counter past them.
+
+ if (state.writing) {
+ break;
+ }
+ }
+
+ if (entry === null) state.lastBufferedRequest = null;
+ }
+
+ state.bufferedRequest = entry;
+ state.bufferProcessing = false;
+}
+
+Writable.prototype._write = function (chunk, encoding, cb) {
+ cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()'));
+};
+
+Writable.prototype._writev = null;
+
+Writable.prototype.end = function (chunk, encoding, cb) {
+ var state = this._writableState;
+
+ if (typeof chunk === 'function') {
+ cb = chunk;
+ chunk = null;
+ encoding = null;
+ } else if (typeof encoding === 'function') {
+ cb = encoding;
+ encoding = null;
+ }
+
+ if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks
+
+ if (state.corked) {
+ state.corked = 1;
+ this.uncork();
+ } // ignore unnecessary end() calls.
+
+
+ if (!state.ending) endWritable(this, state, cb);
+ return this;
+};
+
+Object.defineProperty(Writable.prototype, 'writableLength', {
+ // making it explicit this property is not enumerable
+ // because otherwise some prototype manipulation in
+ // userland will fail
+ enumerable: false,
+ get: function get() {
+ return this._writableState.length;
+ }
+});
+
+function needFinish(state) {
+ return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
+}
+
+function callFinal(stream, state) {
+ stream._final(function (err) {
+ state.pendingcb--;
+
+ if (err) {
+ errorOrDestroy(stream, err);
+ }
+
+ state.prefinished = true;
+ stream.emit('prefinish');
+ finishMaybe(stream, state);
+ });
+}
+
+function prefinish(stream, state) {
+ if (!state.prefinished && !state.finalCalled) {
+ if (typeof stream._final === 'function' && !state.destroyed) {
+ state.pendingcb++;
+ state.finalCalled = true;
+ process.nextTick(callFinal, stream, state);
+ } else {
+ state.prefinished = true;
+ stream.emit('prefinish');
+ }
+ }
+}
+
+function finishMaybe(stream, state) {
+ var need = needFinish(state);
+
+ if (need) {
+ prefinish(stream, state);
+
+ if (state.pendingcb === 0) {
+ state.finished = true;
+ stream.emit('finish');
+
+ if (state.autoDestroy) {
+ // In case of duplex streams we need a way to detect
+ // if the readable side is ready for autoDestroy as well
+ var rState = stream._readableState;
+
+ if (!rState || rState.autoDestroy && rState.endEmitted) {
+ stream.destroy();
+ }
+ }
+ }
+ }
+
+ return need;
+}
+
+function endWritable(stream, state, cb) {
+ state.ending = true;
+ finishMaybe(stream, state);
+
+ if (cb) {
+ if (state.finished) process.nextTick(cb);else stream.once('finish', cb);
+ }
+
+ state.ended = true;
+ stream.writable = false;
+}
+
+function onCorkedFinish(corkReq, state, err) {
+ var entry = corkReq.entry;
+ corkReq.entry = null;
+
+ while (entry) {
+ var cb = entry.callback;
+ state.pendingcb--;
+ cb(err);
+ entry = entry.next;
+ } // reuse the free corkReq.
+
+
+ state.corkedRequestsFree.next = corkReq;
+}
+
+Object.defineProperty(Writable.prototype, 'destroyed', {
+ // making it explicit this property is not enumerable
+ // because otherwise some prototype manipulation in
+ // userland will fail
+ enumerable: false,
+ get: function get() {
+ if (this._writableState === undefined) {
+ return false;
+ }
+
+ return this._writableState.destroyed;
+ },
+ set: function set(value) {
+ // we ignore the value if the stream
+ // has not been initialized yet
+ if (!this._writableState) {
+ return;
+ } // backward compatibility, the user is explicitly
+ // managing destroyed
+
+
+ this._writableState.destroyed = value;
+ }
+});
+Writable.prototype.destroy = destroyImpl.destroy;
+Writable.prototype._undestroy = destroyImpl.undestroy;
+
+Writable.prototype._destroy = function (err, cb) {
+ cb(err);
+};
\ No newline at end of file
diff --git a/temporary_modules/trezor-connect/node_modules/readable-stream/lib/internal/streams/async_iterator.js b/temporary_modules/trezor-connect/node_modules/readable-stream/lib/internal/streams/async_iterator.js
new file mode 100644
index 00000000..9fb615a2
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/readable-stream/lib/internal/streams/async_iterator.js
@@ -0,0 +1,207 @@
+'use strict';
+
+var _Object$setPrototypeO;
+
+function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
+
+var finished = require('./end-of-stream');
+
+var kLastResolve = Symbol('lastResolve');
+var kLastReject = Symbol('lastReject');
+var kError = Symbol('error');
+var kEnded = Symbol('ended');
+var kLastPromise = Symbol('lastPromise');
+var kHandlePromise = Symbol('handlePromise');
+var kStream = Symbol('stream');
+
+function createIterResult(value, done) {
+ return {
+ value: value,
+ done: done
+ };
+}
+
+function readAndResolve(iter) {
+ var resolve = iter[kLastResolve];
+
+ if (resolve !== null) {
+ var data = iter[kStream].read(); // we defer if data is null
+ // we can be expecting either 'end' or
+ // 'error'
+
+ if (data !== null) {
+ iter[kLastPromise] = null;
+ iter[kLastResolve] = null;
+ iter[kLastReject] = null;
+ resolve(createIterResult(data, false));
+ }
+ }
+}
+
+function onReadable(iter) {
+ // we wait for the next tick, because it might
+ // emit an error with process.nextTick
+ process.nextTick(readAndResolve, iter);
+}
+
+function wrapForNext(lastPromise, iter) {
+ return function (resolve, reject) {
+ lastPromise.then(function () {
+ if (iter[kEnded]) {
+ resolve(createIterResult(undefined, true));
+ return;
+ }
+
+ iter[kHandlePromise](resolve, reject);
+ }, reject);
+ };
+}
+
+var AsyncIteratorPrototype = Object.getPrototypeOf(function () {});
+var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = {
+ get stream() {
+ return this[kStream];
+ },
+
+ next: function next() {
+ var _this = this;
+
+ // if we have detected an error in the meanwhile
+ // reject straight away
+ var error = this[kError];
+
+ if (error !== null) {
+ return Promise.reject(error);
+ }
+
+ if (this[kEnded]) {
+ return Promise.resolve(createIterResult(undefined, true));
+ }
+
+ if (this[kStream].destroyed) {
+ // We need to defer via nextTick because if .destroy(err) is
+ // called, the error will be emitted via nextTick, and
+ // we cannot guarantee that there is no error lingering around
+ // waiting to be emitted.
+ return new Promise(function (resolve, reject) {
+ process.nextTick(function () {
+ if (_this[kError]) {
+ reject(_this[kError]);
+ } else {
+ resolve(createIterResult(undefined, true));
+ }
+ });
+ });
+ } // if we have multiple next() calls
+ // we will wait for the previous Promise to finish
+ // this logic is optimized to support for await loops,
+ // where next() is only called once at a time
+
+
+ var lastPromise = this[kLastPromise];
+ var promise;
+
+ if (lastPromise) {
+ promise = new Promise(wrapForNext(lastPromise, this));
+ } else {
+ // fast path needed to support multiple this.push()
+ // without triggering the next() queue
+ var data = this[kStream].read();
+
+ if (data !== null) {
+ return Promise.resolve(createIterResult(data, false));
+ }
+
+ promise = new Promise(this[kHandlePromise]);
+ }
+
+ this[kLastPromise] = promise;
+ return promise;
+ }
+}, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () {
+ return this;
+}), _defineProperty(_Object$setPrototypeO, "return", function _return() {
+ var _this2 = this;
+
+ // destroy(err, cb) is a private API
+ // we can guarantee we have that here, because we control the
+ // Readable class this is attached to
+ return new Promise(function (resolve, reject) {
+ _this2[kStream].destroy(null, function (err) {
+ if (err) {
+ reject(err);
+ return;
+ }
+
+ resolve(createIterResult(undefined, true));
+ });
+ });
+}), _Object$setPrototypeO), AsyncIteratorPrototype);
+
+var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) {
+ var _Object$create;
+
+ var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, {
+ value: stream,
+ writable: true
+ }), _defineProperty(_Object$create, kLastResolve, {
+ value: null,
+ writable: true
+ }), _defineProperty(_Object$create, kLastReject, {
+ value: null,
+ writable: true
+ }), _defineProperty(_Object$create, kError, {
+ value: null,
+ writable: true
+ }), _defineProperty(_Object$create, kEnded, {
+ value: stream._readableState.endEmitted,
+ writable: true
+ }), _defineProperty(_Object$create, kHandlePromise, {
+ value: function value(resolve, reject) {
+ var data = iterator[kStream].read();
+
+ if (data) {
+ iterator[kLastPromise] = null;
+ iterator[kLastResolve] = null;
+ iterator[kLastReject] = null;
+ resolve(createIterResult(data, false));
+ } else {
+ iterator[kLastResolve] = resolve;
+ iterator[kLastReject] = reject;
+ }
+ },
+ writable: true
+ }), _Object$create));
+ iterator[kLastPromise] = null;
+ finished(stream, function (err) {
+ if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') {
+ var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise
+ // returned by next() and store the error
+
+ if (reject !== null) {
+ iterator[kLastPromise] = null;
+ iterator[kLastResolve] = null;
+ iterator[kLastReject] = null;
+ reject(err);
+ }
+
+ iterator[kError] = err;
+ return;
+ }
+
+ var resolve = iterator[kLastResolve];
+
+ if (resolve !== null) {
+ iterator[kLastPromise] = null;
+ iterator[kLastResolve] = null;
+ iterator[kLastReject] = null;
+ resolve(createIterResult(undefined, true));
+ }
+
+ iterator[kEnded] = true;
+ });
+ stream.on('readable', onReadable.bind(null, iterator));
+ return iterator;
+};
+
+module.exports = createReadableStreamAsyncIterator;
\ No newline at end of file
diff --git a/temporary_modules/trezor-connect/node_modules/readable-stream/lib/internal/streams/buffer_list.js b/temporary_modules/trezor-connect/node_modules/readable-stream/lib/internal/streams/buffer_list.js
new file mode 100644
index 00000000..cdea425f
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/readable-stream/lib/internal/streams/buffer_list.js
@@ -0,0 +1,210 @@
+'use strict';
+
+function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
+
+function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
+
+function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
+
+function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
+
+function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
+
+function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
+
+var _require = require('buffer'),
+ Buffer = _require.Buffer;
+
+var _require2 = require('util'),
+ inspect = _require2.inspect;
+
+var custom = inspect && inspect.custom || 'inspect';
+
+function copyBuffer(src, target, offset) {
+ Buffer.prototype.copy.call(src, target, offset);
+}
+
+module.exports =
+/*#__PURE__*/
+function () {
+ function BufferList() {
+ _classCallCheck(this, BufferList);
+
+ this.head = null;
+ this.tail = null;
+ this.length = 0;
+ }
+
+ _createClass(BufferList, [{
+ key: "push",
+ value: function push(v) {
+ var entry = {
+ data: v,
+ next: null
+ };
+ if (this.length > 0) this.tail.next = entry;else this.head = entry;
+ this.tail = entry;
+ ++this.length;
+ }
+ }, {
+ key: "unshift",
+ value: function unshift(v) {
+ var entry = {
+ data: v,
+ next: this.head
+ };
+ if (this.length === 0) this.tail = entry;
+ this.head = entry;
+ ++this.length;
+ }
+ }, {
+ key: "shift",
+ value: function shift() {
+ if (this.length === 0) return;
+ var ret = this.head.data;
+ if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
+ --this.length;
+ return ret;
+ }
+ }, {
+ key: "clear",
+ value: function clear() {
+ this.head = this.tail = null;
+ this.length = 0;
+ }
+ }, {
+ key: "join",
+ value: function join(s) {
+ if (this.length === 0) return '';
+ var p = this.head;
+ var ret = '' + p.data;
+
+ while (p = p.next) {
+ ret += s + p.data;
+ }
+
+ return ret;
+ }
+ }, {
+ key: "concat",
+ value: function concat(n) {
+ if (this.length === 0) return Buffer.alloc(0);
+ var ret = Buffer.allocUnsafe(n >>> 0);
+ var p = this.head;
+ var i = 0;
+
+ while (p) {
+ copyBuffer(p.data, ret, i);
+ i += p.data.length;
+ p = p.next;
+ }
+
+ return ret;
+ } // Consumes a specified amount of bytes or characters from the buffered data.
+
+ }, {
+ key: "consume",
+ value: function consume(n, hasStrings) {
+ var ret;
+
+ if (n < this.head.data.length) {
+ // `slice` is the same for buffers and strings.
+ ret = this.head.data.slice(0, n);
+ this.head.data = this.head.data.slice(n);
+ } else if (n === this.head.data.length) {
+ // First chunk is a perfect match.
+ ret = this.shift();
+ } else {
+ // Result spans more than one buffer.
+ ret = hasStrings ? this._getString(n) : this._getBuffer(n);
+ }
+
+ return ret;
+ }
+ }, {
+ key: "first",
+ value: function first() {
+ return this.head.data;
+ } // Consumes a specified amount of characters from the buffered data.
+
+ }, {
+ key: "_getString",
+ value: function _getString(n) {
+ var p = this.head;
+ var c = 1;
+ var ret = p.data;
+ n -= ret.length;
+
+ while (p = p.next) {
+ var str = p.data;
+ var nb = n > str.length ? str.length : n;
+ if (nb === str.length) ret += str;else ret += str.slice(0, n);
+ n -= nb;
+
+ if (n === 0) {
+ if (nb === str.length) {
+ ++c;
+ if (p.next) this.head = p.next;else this.head = this.tail = null;
+ } else {
+ this.head = p;
+ p.data = str.slice(nb);
+ }
+
+ break;
+ }
+
+ ++c;
+ }
+
+ this.length -= c;
+ return ret;
+ } // Consumes a specified amount of bytes from the buffered data.
+
+ }, {
+ key: "_getBuffer",
+ value: function _getBuffer(n) {
+ var ret = Buffer.allocUnsafe(n);
+ var p = this.head;
+ var c = 1;
+ p.data.copy(ret);
+ n -= p.data.length;
+
+ while (p = p.next) {
+ var buf = p.data;
+ var nb = n > buf.length ? buf.length : n;
+ buf.copy(ret, ret.length - n, 0, nb);
+ n -= nb;
+
+ if (n === 0) {
+ if (nb === buf.length) {
+ ++c;
+ if (p.next) this.head = p.next;else this.head = this.tail = null;
+ } else {
+ this.head = p;
+ p.data = buf.slice(nb);
+ }
+
+ break;
+ }
+
+ ++c;
+ }
+
+ this.length -= c;
+ return ret;
+ } // Make sure the linked list only shows the minimal necessary information.
+
+ }, {
+ key: custom,
+ value: function value(_, options) {
+ return inspect(this, _objectSpread({}, options, {
+ // Only inspect one level.
+ depth: 0,
+ // It should not recurse.
+ customInspect: false
+ }));
+ }
+ }]);
+
+ return BufferList;
+}();
\ No newline at end of file
diff --git a/temporary_modules/trezor-connect/node_modules/readable-stream/lib/internal/streams/destroy.js b/temporary_modules/trezor-connect/node_modules/readable-stream/lib/internal/streams/destroy.js
new file mode 100644
index 00000000..3268a16f
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/readable-stream/lib/internal/streams/destroy.js
@@ -0,0 +1,105 @@
+'use strict'; // undocumented cb() API, needed for core, not for public API
+
+function destroy(err, cb) {
+ var _this = this;
+
+ var readableDestroyed = this._readableState && this._readableState.destroyed;
+ var writableDestroyed = this._writableState && this._writableState.destroyed;
+
+ if (readableDestroyed || writableDestroyed) {
+ if (cb) {
+ cb(err);
+ } else if (err) {
+ if (!this._writableState) {
+ process.nextTick(emitErrorNT, this, err);
+ } else if (!this._writableState.errorEmitted) {
+ this._writableState.errorEmitted = true;
+ process.nextTick(emitErrorNT, this, err);
+ }
+ }
+
+ return this;
+ } // we set destroyed to true before firing error callbacks in order
+ // to make it re-entrance safe in case destroy() is called within callbacks
+
+
+ if (this._readableState) {
+ this._readableState.destroyed = true;
+ } // if this is a duplex stream mark the writable part as destroyed as well
+
+
+ if (this._writableState) {
+ this._writableState.destroyed = true;
+ }
+
+ this._destroy(err || null, function (err) {
+ if (!cb && err) {
+ if (!_this._writableState) {
+ process.nextTick(emitErrorAndCloseNT, _this, err);
+ } else if (!_this._writableState.errorEmitted) {
+ _this._writableState.errorEmitted = true;
+ process.nextTick(emitErrorAndCloseNT, _this, err);
+ } else {
+ process.nextTick(emitCloseNT, _this);
+ }
+ } else if (cb) {
+ process.nextTick(emitCloseNT, _this);
+ cb(err);
+ } else {
+ process.nextTick(emitCloseNT, _this);
+ }
+ });
+
+ return this;
+}
+
+function emitErrorAndCloseNT(self, err) {
+ emitErrorNT(self, err);
+ emitCloseNT(self);
+}
+
+function emitCloseNT(self) {
+ if (self._writableState && !self._writableState.emitClose) return;
+ if (self._readableState && !self._readableState.emitClose) return;
+ self.emit('close');
+}
+
+function undestroy() {
+ if (this._readableState) {
+ this._readableState.destroyed = false;
+ this._readableState.reading = false;
+ this._readableState.ended = false;
+ this._readableState.endEmitted = false;
+ }
+
+ if (this._writableState) {
+ this._writableState.destroyed = false;
+ this._writableState.ended = false;
+ this._writableState.ending = false;
+ this._writableState.finalCalled = false;
+ this._writableState.prefinished = false;
+ this._writableState.finished = false;
+ this._writableState.errorEmitted = false;
+ }
+}
+
+function emitErrorNT(self, err) {
+ self.emit('error', err);
+}
+
+function errorOrDestroy(stream, err) {
+ // We have tests that rely on errors being emitted
+ // in the same tick, so changing this is semver major.
+ // For now when you opt-in to autoDestroy we allow
+ // the error to be emitted nextTick. In a future
+ // semver major update we should change the default to this.
+ var rState = stream._readableState;
+ var wState = stream._writableState;
+ if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err);
+}
+
+module.exports = {
+ destroy: destroy,
+ undestroy: undestroy,
+ errorOrDestroy: errorOrDestroy
+};
\ No newline at end of file
diff --git a/temporary_modules/trezor-connect/node_modules/readable-stream/lib/internal/streams/end-of-stream.js b/temporary_modules/trezor-connect/node_modules/readable-stream/lib/internal/streams/end-of-stream.js
new file mode 100644
index 00000000..831f286d
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/readable-stream/lib/internal/streams/end-of-stream.js
@@ -0,0 +1,104 @@
+// Ported from https://github.com/mafintosh/end-of-stream with
+// permission from the author, Mathias Buus (@mafintosh).
+'use strict';
+
+var ERR_STREAM_PREMATURE_CLOSE = require('../../../errors').codes.ERR_STREAM_PREMATURE_CLOSE;
+
+function once(callback) {
+ var called = false;
+ return function () {
+ if (called) return;
+ called = true;
+
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
+ args[_key] = arguments[_key];
+ }
+
+ callback.apply(this, args);
+ };
+}
+
+function noop() {}
+
+function isRequest(stream) {
+ return stream.setHeader && typeof stream.abort === 'function';
+}
+
+function eos(stream, opts, callback) {
+ if (typeof opts === 'function') return eos(stream, null, opts);
+ if (!opts) opts = {};
+ callback = once(callback || noop);
+ var readable = opts.readable || opts.readable !== false && stream.readable;
+ var writable = opts.writable || opts.writable !== false && stream.writable;
+
+ var onlegacyfinish = function onlegacyfinish() {
+ if (!stream.writable) onfinish();
+ };
+
+ var writableEnded = stream._writableState && stream._writableState.finished;
+
+ var onfinish = function onfinish() {
+ writable = false;
+ writableEnded = true;
+ if (!readable) callback.call(stream);
+ };
+
+ var readableEnded = stream._readableState && stream._readableState.endEmitted;
+
+ var onend = function onend() {
+ readable = false;
+ readableEnded = true;
+ if (!writable) callback.call(stream);
+ };
+
+ var onerror = function onerror(err) {
+ callback.call(stream, err);
+ };
+
+ var onclose = function onclose() {
+ var err;
+
+ if (readable && !readableEnded) {
+ if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();
+ return callback.call(stream, err);
+ }
+
+ if (writable && !writableEnded) {
+ if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();
+ return callback.call(stream, err);
+ }
+ };
+
+ var onrequest = function onrequest() {
+ stream.req.on('finish', onfinish);
+ };
+
+ if (isRequest(stream)) {
+ stream.on('complete', onfinish);
+ stream.on('abort', onclose);
+ if (stream.req) onrequest();else stream.on('request', onrequest);
+ } else if (writable && !stream._writableState) {
+ // legacy streams
+ stream.on('end', onlegacyfinish);
+ stream.on('close', onlegacyfinish);
+ }
+
+ stream.on('end', onend);
+ stream.on('finish', onfinish);
+ if (opts.error !== false) stream.on('error', onerror);
+ stream.on('close', onclose);
+ return function () {
+ stream.removeListener('complete', onfinish);
+ stream.removeListener('abort', onclose);
+ stream.removeListener('request', onrequest);
+ if (stream.req) stream.req.removeListener('finish', onfinish);
+ stream.removeListener('end', onlegacyfinish);
+ stream.removeListener('close', onlegacyfinish);
+ stream.removeListener('finish', onfinish);
+ stream.removeListener('end', onend);
+ stream.removeListener('error', onerror);
+ stream.removeListener('close', onclose);
+ };
+}
+
+module.exports = eos;
\ No newline at end of file
diff --git a/temporary_modules/trezor-connect/node_modules/readable-stream/lib/internal/streams/from-browser.js b/temporary_modules/trezor-connect/node_modules/readable-stream/lib/internal/streams/from-browser.js
new file mode 100644
index 00000000..a4ce56f3
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/readable-stream/lib/internal/streams/from-browser.js
@@ -0,0 +1,3 @@
+module.exports = function () {
+ throw new Error('Readable.from is not available in the browser')
+};
diff --git a/temporary_modules/trezor-connect/node_modules/readable-stream/lib/internal/streams/from.js b/temporary_modules/trezor-connect/node_modules/readable-stream/lib/internal/streams/from.js
new file mode 100644
index 00000000..6c412844
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/readable-stream/lib/internal/streams/from.js
@@ -0,0 +1,64 @@
+'use strict';
+
+function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
+
+function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
+
+function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
+
+function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
+
+function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
+
+var ERR_INVALID_ARG_TYPE = require('../../../errors').codes.ERR_INVALID_ARG_TYPE;
+
+function from(Readable, iterable, opts) {
+ var iterator;
+
+ if (iterable && typeof iterable.next === 'function') {
+ iterator = iterable;
+ } else if (iterable && iterable[Symbol.asyncIterator]) iterator = iterable[Symbol.asyncIterator]();else if (iterable && iterable[Symbol.iterator]) iterator = iterable[Symbol.iterator]();else throw new ERR_INVALID_ARG_TYPE('iterable', ['Iterable'], iterable);
+
+ var readable = new Readable(_objectSpread({
+ objectMode: true
+ }, opts)); // Reading boolean to protect against _read
+ // being called before last iteration completion.
+
+ var reading = false;
+
+ readable._read = function () {
+ if (!reading) {
+ reading = true;
+ next();
+ }
+ };
+
+ function next() {
+ return _next2.apply(this, arguments);
+ }
+
+ function _next2() {
+ _next2 = _asyncToGenerator(function* () {
+ try {
+ var _ref = yield iterator.next(),
+ value = _ref.value,
+ done = _ref.done;
+
+ if (done) {
+ readable.push(null);
+ } else if (readable.push((yield value))) {
+ next();
+ } else {
+ reading = false;
+ }
+ } catch (err) {
+ readable.destroy(err);
+ }
+ });
+ return _next2.apply(this, arguments);
+ }
+
+ return readable;
+}
+
+module.exports = from;
\ No newline at end of file
diff --git a/temporary_modules/trezor-connect/node_modules/readable-stream/lib/internal/streams/pipeline.js b/temporary_modules/trezor-connect/node_modules/readable-stream/lib/internal/streams/pipeline.js
new file mode 100644
index 00000000..65899098
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/readable-stream/lib/internal/streams/pipeline.js
@@ -0,0 +1,97 @@
+// Ported from https://github.com/mafintosh/pump with
+// permission from the author, Mathias Buus (@mafintosh).
+'use strict';
+
+var eos;
+
+function once(callback) {
+ var called = false;
+ return function () {
+ if (called) return;
+ called = true;
+ callback.apply(void 0, arguments);
+ };
+}
+
+var _require$codes = require('../../../errors').codes,
+ ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS,
+ ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED;
+
+function noop(err) {
+ // Rethrow the error if it exists to avoid swallowing it
+ if (err) throw err;
+}
+
+function isRequest(stream) {
+ return stream.setHeader && typeof stream.abort === 'function';
+}
+
+function destroyer(stream, reading, writing, callback) {
+ callback = once(callback);
+ var closed = false;
+ stream.on('close', function () {
+ closed = true;
+ });
+ if (eos === undefined) eos = require('./end-of-stream');
+ eos(stream, {
+ readable: reading,
+ writable: writing
+ }, function (err) {
+ if (err) return callback(err);
+ closed = true;
+ callback();
+ });
+ var destroyed = false;
+ return function (err) {
+ if (closed) return;
+ if (destroyed) return;
+ destroyed = true; // request.destroy just do .end - .abort is what we want
+
+ if (isRequest(stream)) return stream.abort();
+ if (typeof stream.destroy === 'function') return stream.destroy();
+ callback(err || new ERR_STREAM_DESTROYED('pipe'));
+ };
+}
+
+function call(fn) {
+ fn();
+}
+
+function pipe(from, to) {
+ return from.pipe(to);
+}
+
+function popCallback(streams) {
+ if (!streams.length) return noop;
+ if (typeof streams[streams.length - 1] !== 'function') return noop;
+ return streams.pop();
+}
+
+function pipeline() {
+ for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) {
+ streams[_key] = arguments[_key];
+ }
+
+ var callback = popCallback(streams);
+ if (Array.isArray(streams[0])) streams = streams[0];
+
+ if (streams.length < 2) {
+ throw new ERR_MISSING_ARGS('streams');
+ }
+
+ var error;
+ var destroys = streams.map(function (stream, i) {
+ var reading = i < streams.length - 1;
+ var writing = i > 0;
+ return destroyer(stream, reading, writing, function (err) {
+ if (!error) error = err;
+ if (err) destroys.forEach(call);
+ if (reading) return;
+ destroys.forEach(call);
+ callback(error);
+ });
+ });
+ return streams.reduce(pipe);
+}
+
+module.exports = pipeline;
\ No newline at end of file
diff --git a/temporary_modules/trezor-connect/node_modules/readable-stream/lib/internal/streams/state.js b/temporary_modules/trezor-connect/node_modules/readable-stream/lib/internal/streams/state.js
new file mode 100644
index 00000000..19887eb8
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/readable-stream/lib/internal/streams/state.js
@@ -0,0 +1,27 @@
+'use strict';
+
+var ERR_INVALID_OPT_VALUE = require('../../../errors').codes.ERR_INVALID_OPT_VALUE;
+
+function highWaterMarkFrom(options, isDuplex, duplexKey) {
+ return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null;
+}
+
+function getHighWaterMark(state, options, duplexKey, isDuplex) {
+ var hwm = highWaterMarkFrom(options, isDuplex, duplexKey);
+
+ if (hwm != null) {
+ if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) {
+ var name = isDuplex ? duplexKey : 'highWaterMark';
+ throw new ERR_INVALID_OPT_VALUE(name, hwm);
+ }
+
+ return Math.floor(hwm);
+ } // Default value
+
+
+ return state.objectMode ? 16 : 16 * 1024;
+}
+
+module.exports = {
+ getHighWaterMark: getHighWaterMark
+};
\ No newline at end of file
diff --git a/temporary_modules/trezor-connect/node_modules/readable-stream/lib/internal/streams/stream-browser.js b/temporary_modules/trezor-connect/node_modules/readable-stream/lib/internal/streams/stream-browser.js
new file mode 100644
index 00000000..9332a3fd
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/readable-stream/lib/internal/streams/stream-browser.js
@@ -0,0 +1 @@
+module.exports = require('events').EventEmitter;
diff --git a/temporary_modules/trezor-connect/node_modules/readable-stream/lib/internal/streams/stream.js b/temporary_modules/trezor-connect/node_modules/readable-stream/lib/internal/streams/stream.js
new file mode 100644
index 00000000..ce2ad5b6
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/readable-stream/lib/internal/streams/stream.js
@@ -0,0 +1 @@
+module.exports = require('stream');
diff --git a/temporary_modules/trezor-connect/node_modules/readable-stream/package.json b/temporary_modules/trezor-connect/node_modules/readable-stream/package.json
new file mode 100644
index 00000000..0b0c4bd2
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/readable-stream/package.json
@@ -0,0 +1,68 @@
+{
+ "name": "readable-stream",
+ "version": "3.6.0",
+ "description": "Streams3, a user-land copy of the stream library from Node.js",
+ "main": "readable.js",
+ "engines": {
+ "node": ">= 6"
+ },
+ "dependencies": {
+ "inherits": "^2.0.3",
+ "string_decoder": "^1.1.1",
+ "util-deprecate": "^1.0.1"
+ },
+ "devDependencies": {
+ "@babel/cli": "^7.2.0",
+ "@babel/core": "^7.2.0",
+ "@babel/polyfill": "^7.0.0",
+ "@babel/preset-env": "^7.2.0",
+ "airtap": "0.0.9",
+ "assert": "^1.4.0",
+ "bl": "^2.0.0",
+ "deep-strict-equal": "^0.2.0",
+ "events.once": "^2.0.2",
+ "glob": "^7.1.2",
+ "gunzip-maybe": "^1.4.1",
+ "hyperquest": "^2.1.3",
+ "lolex": "^2.6.0",
+ "nyc": "^11.0.0",
+ "pump": "^3.0.0",
+ "rimraf": "^2.6.2",
+ "tap": "^12.0.0",
+ "tape": "^4.9.0",
+ "tar-fs": "^1.16.2",
+ "util-promisify": "^2.1.0"
+ },
+ "scripts": {
+ "test": "tap -J --no-esm test/parallel/*.js test/ours/*.js",
+ "ci": "TAP=1 tap --no-esm test/parallel/*.js test/ours/*.js | tee test.tap",
+ "test-browsers": "airtap --sauce-connect --loopback airtap.local -- test/browser.js",
+ "test-browser-local": "airtap --open --local -- test/browser.js",
+ "cover": "nyc npm test",
+ "report": "nyc report --reporter=lcov",
+ "update-browser-errors": "babel -o errors-browser.js errors.js"
+ },
+ "repository": {
+ "type": "git",
+ "url": "git://github.com/nodejs/readable-stream"
+ },
+ "keywords": [
+ "readable",
+ "stream",
+ "pipe"
+ ],
+ "browser": {
+ "util": false,
+ "worker_threads": false,
+ "./errors": "./errors-browser.js",
+ "./readable.js": "./readable-browser.js",
+ "./lib/internal/streams/from.js": "./lib/internal/streams/from-browser.js",
+ "./lib/internal/streams/stream.js": "./lib/internal/streams/stream-browser.js"
+ },
+ "nyc": {
+ "include": [
+ "lib/**.js"
+ ]
+ },
+ "license": "MIT"
+}
diff --git a/temporary_modules/trezor-connect/node_modules/readable-stream/readable-browser.js b/temporary_modules/trezor-connect/node_modules/readable-stream/readable-browser.js
new file mode 100644
index 00000000..adbf60de
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/readable-stream/readable-browser.js
@@ -0,0 +1,9 @@
+exports = module.exports = require('./lib/_stream_readable.js');
+exports.Stream = exports;
+exports.Readable = exports;
+exports.Writable = require('./lib/_stream_writable.js');
+exports.Duplex = require('./lib/_stream_duplex.js');
+exports.Transform = require('./lib/_stream_transform.js');
+exports.PassThrough = require('./lib/_stream_passthrough.js');
+exports.finished = require('./lib/internal/streams/end-of-stream.js');
+exports.pipeline = require('./lib/internal/streams/pipeline.js');
diff --git a/temporary_modules/trezor-connect/node_modules/readable-stream/readable.js b/temporary_modules/trezor-connect/node_modules/readable-stream/readable.js
new file mode 100644
index 00000000..9e0ca120
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/readable-stream/readable.js
@@ -0,0 +1,16 @@
+var Stream = require('stream');
+if (process.env.READABLE_STREAM === 'disable' && Stream) {
+ module.exports = Stream.Readable;
+ Object.assign(module.exports, Stream);
+ module.exports.Stream = Stream;
+} else {
+ exports = module.exports = require('./lib/_stream_readable.js');
+ exports.Stream = Stream || exports;
+ exports.Readable = exports;
+ exports.Writable = require('./lib/_stream_writable.js');
+ exports.Duplex = require('./lib/_stream_duplex.js');
+ exports.Transform = require('./lib/_stream_transform.js');
+ exports.PassThrough = require('./lib/_stream_passthrough.js');
+ exports.finished = require('./lib/internal/streams/end-of-stream.js');
+ exports.pipeline = require('./lib/internal/streams/pipeline.js');
+}
diff --git a/temporary_modules/trezor-connect/node_modules/regenerator-runtime/LICENSE b/temporary_modules/trezor-connect/node_modules/regenerator-runtime/LICENSE
new file mode 100644
index 00000000..cde61b6c
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/regenerator-runtime/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2014-present, Facebook, Inc.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/temporary_modules/trezor-connect/node_modules/regenerator-runtime/README.md b/temporary_modules/trezor-connect/node_modules/regenerator-runtime/README.md
new file mode 100644
index 00000000..e8702bab
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/regenerator-runtime/README.md
@@ -0,0 +1,31 @@
+# regenerator-runtime
+
+Standalone runtime for
+[Regenerator](https://github.com/facebook/regenerator)-compiled generator
+and `async` functions.
+
+To import the runtime as a module (recommended), either of the following
+import styles will work:
+```js
+// CommonJS
+const regeneratorRuntime = require("regenerator-runtime");
+
+// ECMAScript 2015
+import regeneratorRuntime from "regenerator-runtime";
+```
+
+To ensure that `regeneratorRuntime` is defined globally, either of the
+following styles will work:
+```js
+// CommonJS
+require("regenerator-runtime/runtime");
+
+// ECMAScript 2015
+import "regenerator-runtime/runtime.js";
+```
+
+To get the absolute file system path of `runtime.js`, evaluate the
+following expression:
+```js
+require("regenerator-runtime/path").path
+```
diff --git a/temporary_modules/trezor-connect/node_modules/regenerator-runtime/package.json b/temporary_modules/trezor-connect/node_modules/regenerator-runtime/package.json
new file mode 100644
index 00000000..23575f45
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/regenerator-runtime/package.json
@@ -0,0 +1,19 @@
+{
+ "name": "regenerator-runtime",
+ "author": "Ben Newman ",
+ "description": "Runtime for Regenerator-compiled generator and async functions.",
+ "version": "0.13.9",
+ "main": "runtime.js",
+ "keywords": [
+ "regenerator",
+ "runtime",
+ "generator",
+ "async"
+ ],
+ "sideEffects": true,
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/facebook/regenerator/tree/master/packages/runtime"
+ },
+ "license": "MIT"
+}
diff --git a/temporary_modules/trezor-connect/node_modules/regenerator-runtime/path.js b/temporary_modules/trezor-connect/node_modules/regenerator-runtime/path.js
new file mode 100644
index 00000000..ced878b8
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/regenerator-runtime/path.js
@@ -0,0 +1,11 @@
+/**
+ * Copyright (c) 2014-present, Facebook, Inc.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+exports.path = require("path").join(
+ __dirname,
+ "runtime.js"
+);
diff --git a/temporary_modules/trezor-connect/node_modules/regenerator-runtime/runtime.js b/temporary_modules/trezor-connect/node_modules/regenerator-runtime/runtime.js
new file mode 100644
index 00000000..a64424e6
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/regenerator-runtime/runtime.js
@@ -0,0 +1,754 @@
+/**
+ * Copyright (c) 2014-present, Facebook, Inc.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+var runtime = (function (exports) {
+ "use strict";
+
+ var Op = Object.prototype;
+ var hasOwn = Op.hasOwnProperty;
+ var undefined; // More compressible than void 0.
+ var $Symbol = typeof Symbol === "function" ? Symbol : {};
+ var iteratorSymbol = $Symbol.iterator || "@@iterator";
+ var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator";
+ var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
+
+ function define(obj, key, value) {
+ Object.defineProperty(obj, key, {
+ value: value,
+ enumerable: true,
+ configurable: true,
+ writable: true
+ });
+ return obj[key];
+ }
+ try {
+ // IE 8 has a broken Object.defineProperty that only works on DOM objects.
+ define({}, "");
+ } catch (err) {
+ define = function(obj, key, value) {
+ return obj[key] = value;
+ };
+ }
+
+ function wrap(innerFn, outerFn, self, tryLocsList) {
+ // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.
+ var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;
+ var generator = Object.create(protoGenerator.prototype);
+ var context = new Context(tryLocsList || []);
+
+ // The ._invoke method unifies the implementations of the .next,
+ // .throw, and .return methods.
+ generator._invoke = makeInvokeMethod(innerFn, self, context);
+
+ return generator;
+ }
+ exports.wrap = wrap;
+
+ // Try/catch helper to minimize deoptimizations. Returns a completion
+ // record like context.tryEntries[i].completion. This interface could
+ // have been (and was previously) designed to take a closure to be
+ // invoked without arguments, but in all the cases we care about we
+ // already have an existing method we want to call, so there's no need
+ // to create a new function object. We can even get away with assuming
+ // the method takes exactly one argument, since that happens to be true
+ // in every case, so we don't have to touch the arguments object. The
+ // only additional allocation required is the completion record, which
+ // has a stable shape and so hopefully should be cheap to allocate.
+ function tryCatch(fn, obj, arg) {
+ try {
+ return { type: "normal", arg: fn.call(obj, arg) };
+ } catch (err) {
+ return { type: "throw", arg: err };
+ }
+ }
+
+ var GenStateSuspendedStart = "suspendedStart";
+ var GenStateSuspendedYield = "suspendedYield";
+ var GenStateExecuting = "executing";
+ var GenStateCompleted = "completed";
+
+ // Returning this object from the innerFn has the same effect as
+ // breaking out of the dispatch switch statement.
+ var ContinueSentinel = {};
+
+ // Dummy constructor functions that we use as the .constructor and
+ // .constructor.prototype properties for functions that return Generator
+ // objects. For full spec compliance, you may wish to configure your
+ // minifier not to mangle the names of these two functions.
+ function Generator() {}
+ function GeneratorFunction() {}
+ function GeneratorFunctionPrototype() {}
+
+ // This is a polyfill for %IteratorPrototype% for environments that
+ // don't natively support it.
+ var IteratorPrototype = {};
+ define(IteratorPrototype, iteratorSymbol, function () {
+ return this;
+ });
+
+ var getProto = Object.getPrototypeOf;
+ var NativeIteratorPrototype = getProto && getProto(getProto(values([])));
+ if (NativeIteratorPrototype &&
+ NativeIteratorPrototype !== Op &&
+ hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {
+ // This environment has a native %IteratorPrototype%; use it instead
+ // of the polyfill.
+ IteratorPrototype = NativeIteratorPrototype;
+ }
+
+ var Gp = GeneratorFunctionPrototype.prototype =
+ Generator.prototype = Object.create(IteratorPrototype);
+ GeneratorFunction.prototype = GeneratorFunctionPrototype;
+ define(Gp, "constructor", GeneratorFunctionPrototype);
+ define(GeneratorFunctionPrototype, "constructor", GeneratorFunction);
+ GeneratorFunction.displayName = define(
+ GeneratorFunctionPrototype,
+ toStringTagSymbol,
+ "GeneratorFunction"
+ );
+
+ // Helper for defining the .next, .throw, and .return methods of the
+ // Iterator interface in terms of a single ._invoke method.
+ function defineIteratorMethods(prototype) {
+ ["next", "throw", "return"].forEach(function(method) {
+ define(prototype, method, function(arg) {
+ return this._invoke(method, arg);
+ });
+ });
+ }
+
+ exports.isGeneratorFunction = function(genFun) {
+ var ctor = typeof genFun === "function" && genFun.constructor;
+ return ctor
+ ? ctor === GeneratorFunction ||
+ // For the native GeneratorFunction constructor, the best we can
+ // do is to check its .name property.
+ (ctor.displayName || ctor.name) === "GeneratorFunction"
+ : false;
+ };
+
+ exports.mark = function(genFun) {
+ if (Object.setPrototypeOf) {
+ Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);
+ } else {
+ genFun.__proto__ = GeneratorFunctionPrototype;
+ define(genFun, toStringTagSymbol, "GeneratorFunction");
+ }
+ genFun.prototype = Object.create(Gp);
+ return genFun;
+ };
+
+ // Within the body of any async function, `await x` is transformed to
+ // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test
+ // `hasOwn.call(value, "__await")` to determine if the yielded value is
+ // meant to be awaited.
+ exports.awrap = function(arg) {
+ return { __await: arg };
+ };
+
+ function AsyncIterator(generator, PromiseImpl) {
+ function invoke(method, arg, resolve, reject) {
+ var record = tryCatch(generator[method], generator, arg);
+ if (record.type === "throw") {
+ reject(record.arg);
+ } else {
+ var result = record.arg;
+ var value = result.value;
+ if (value &&
+ typeof value === "object" &&
+ hasOwn.call(value, "__await")) {
+ return PromiseImpl.resolve(value.__await).then(function(value) {
+ invoke("next", value, resolve, reject);
+ }, function(err) {
+ invoke("throw", err, resolve, reject);
+ });
+ }
+
+ return PromiseImpl.resolve(value).then(function(unwrapped) {
+ // When a yielded Promise is resolved, its final value becomes
+ // the .value of the Promise<{value,done}> result for the
+ // current iteration.
+ result.value = unwrapped;
+ resolve(result);
+ }, function(error) {
+ // If a rejected Promise was yielded, throw the rejection back
+ // into the async generator function so it can be handled there.
+ return invoke("throw", error, resolve, reject);
+ });
+ }
+ }
+
+ var previousPromise;
+
+ function enqueue(method, arg) {
+ function callInvokeWithMethodAndArg() {
+ return new PromiseImpl(function(resolve, reject) {
+ invoke(method, arg, resolve, reject);
+ });
+ }
+
+ return previousPromise =
+ // If enqueue has been called before, then we want to wait until
+ // all previous Promises have been resolved before calling invoke,
+ // so that results are always delivered in the correct order. If
+ // enqueue has not been called before, then it is important to
+ // call invoke immediately, without waiting on a callback to fire,
+ // so that the async generator function has the opportunity to do
+ // any necessary setup in a predictable way. This predictability
+ // is why the Promise constructor synchronously invokes its
+ // executor callback, and why async functions synchronously
+ // execute code before the first await. Since we implement simple
+ // async functions in terms of async generators, it is especially
+ // important to get this right, even though it requires care.
+ previousPromise ? previousPromise.then(
+ callInvokeWithMethodAndArg,
+ // Avoid propagating failures to Promises returned by later
+ // invocations of the iterator.
+ callInvokeWithMethodAndArg
+ ) : callInvokeWithMethodAndArg();
+ }
+
+ // Define the unified helper method that is used to implement .next,
+ // .throw, and .return (see defineIteratorMethods).
+ this._invoke = enqueue;
+ }
+
+ defineIteratorMethods(AsyncIterator.prototype);
+ define(AsyncIterator.prototype, asyncIteratorSymbol, function () {
+ return this;
+ });
+ exports.AsyncIterator = AsyncIterator;
+
+ // Note that simple async functions are implemented on top of
+ // AsyncIterator objects; they just return a Promise for the value of
+ // the final result produced by the iterator.
+ exports.async = function(innerFn, outerFn, self, tryLocsList, PromiseImpl) {
+ if (PromiseImpl === void 0) PromiseImpl = Promise;
+
+ var iter = new AsyncIterator(
+ wrap(innerFn, outerFn, self, tryLocsList),
+ PromiseImpl
+ );
+
+ return exports.isGeneratorFunction(outerFn)
+ ? iter // If outerFn is a generator, return the full iterator.
+ : iter.next().then(function(result) {
+ return result.done ? result.value : iter.next();
+ });
+ };
+
+ function makeInvokeMethod(innerFn, self, context) {
+ var state = GenStateSuspendedStart;
+
+ return function invoke(method, arg) {
+ if (state === GenStateExecuting) {
+ throw new Error("Generator is already running");
+ }
+
+ if (state === GenStateCompleted) {
+ if (method === "throw") {
+ throw arg;
+ }
+
+ // Be forgiving, per 25.3.3.3.3 of the spec:
+ // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume
+ return doneResult();
+ }
+
+ context.method = method;
+ context.arg = arg;
+
+ while (true) {
+ var delegate = context.delegate;
+ if (delegate) {
+ var delegateResult = maybeInvokeDelegate(delegate, context);
+ if (delegateResult) {
+ if (delegateResult === ContinueSentinel) continue;
+ return delegateResult;
+ }
+ }
+
+ if (context.method === "next") {
+ // Setting context._sent for legacy support of Babel's
+ // function.sent implementation.
+ context.sent = context._sent = context.arg;
+
+ } else if (context.method === "throw") {
+ if (state === GenStateSuspendedStart) {
+ state = GenStateCompleted;
+ throw context.arg;
+ }
+
+ context.dispatchException(context.arg);
+
+ } else if (context.method === "return") {
+ context.abrupt("return", context.arg);
+ }
+
+ state = GenStateExecuting;
+
+ var record = tryCatch(innerFn, self, context);
+ if (record.type === "normal") {
+ // If an exception is thrown from innerFn, we leave state ===
+ // GenStateExecuting and loop back for another invocation.
+ state = context.done
+ ? GenStateCompleted
+ : GenStateSuspendedYield;
+
+ if (record.arg === ContinueSentinel) {
+ continue;
+ }
+
+ return {
+ value: record.arg,
+ done: context.done
+ };
+
+ } else if (record.type === "throw") {
+ state = GenStateCompleted;
+ // Dispatch the exception by looping back around to the
+ // context.dispatchException(context.arg) call above.
+ context.method = "throw";
+ context.arg = record.arg;
+ }
+ }
+ };
+ }
+
+ // Call delegate.iterator[context.method](context.arg) and handle the
+ // result, either by returning a { value, done } result from the
+ // delegate iterator, or by modifying context.method and context.arg,
+ // setting context.delegate to null, and returning the ContinueSentinel.
+ function maybeInvokeDelegate(delegate, context) {
+ var method = delegate.iterator[context.method];
+ if (method === undefined) {
+ // A .throw or .return when the delegate iterator has no .throw
+ // method always terminates the yield* loop.
+ context.delegate = null;
+
+ if (context.method === "throw") {
+ // Note: ["return"] must be used for ES3 parsing compatibility.
+ if (delegate.iterator["return"]) {
+ // If the delegate iterator has a return method, give it a
+ // chance to clean up.
+ context.method = "return";
+ context.arg = undefined;
+ maybeInvokeDelegate(delegate, context);
+
+ if (context.method === "throw") {
+ // If maybeInvokeDelegate(context) changed context.method from
+ // "return" to "throw", let that override the TypeError below.
+ return ContinueSentinel;
+ }
+ }
+
+ context.method = "throw";
+ context.arg = new TypeError(
+ "The iterator does not provide a 'throw' method");
+ }
+
+ return ContinueSentinel;
+ }
+
+ var record = tryCatch(method, delegate.iterator, context.arg);
+
+ if (record.type === "throw") {
+ context.method = "throw";
+ context.arg = record.arg;
+ context.delegate = null;
+ return ContinueSentinel;
+ }
+
+ var info = record.arg;
+
+ if (! info) {
+ context.method = "throw";
+ context.arg = new TypeError("iterator result is not an object");
+ context.delegate = null;
+ return ContinueSentinel;
+ }
+
+ if (info.done) {
+ // Assign the result of the finished delegate to the temporary
+ // variable specified by delegate.resultName (see delegateYield).
+ context[delegate.resultName] = info.value;
+
+ // Resume execution at the desired location (see delegateYield).
+ context.next = delegate.nextLoc;
+
+ // If context.method was "throw" but the delegate handled the
+ // exception, let the outer generator proceed normally. If
+ // context.method was "next", forget context.arg since it has been
+ // "consumed" by the delegate iterator. If context.method was
+ // "return", allow the original .return call to continue in the
+ // outer generator.
+ if (context.method !== "return") {
+ context.method = "next";
+ context.arg = undefined;
+ }
+
+ } else {
+ // Re-yield the result returned by the delegate method.
+ return info;
+ }
+
+ // The delegate iterator is finished, so forget it and continue with
+ // the outer generator.
+ context.delegate = null;
+ return ContinueSentinel;
+ }
+
+ // Define Generator.prototype.{next,throw,return} in terms of the
+ // unified ._invoke helper method.
+ defineIteratorMethods(Gp);
+
+ define(Gp, toStringTagSymbol, "Generator");
+
+ // A Generator should always return itself as the iterator object when the
+ // @@iterator function is called on it. Some browsers' implementations of the
+ // iterator prototype chain incorrectly implement this, causing the Generator
+ // object to not be returned from this call. This ensures that doesn't happen.
+ // See https://github.com/facebook/regenerator/issues/274 for more details.
+ define(Gp, iteratorSymbol, function() {
+ return this;
+ });
+
+ define(Gp, "toString", function() {
+ return "[object Generator]";
+ });
+
+ function pushTryEntry(locs) {
+ var entry = { tryLoc: locs[0] };
+
+ if (1 in locs) {
+ entry.catchLoc = locs[1];
+ }
+
+ if (2 in locs) {
+ entry.finallyLoc = locs[2];
+ entry.afterLoc = locs[3];
+ }
+
+ this.tryEntries.push(entry);
+ }
+
+ function resetTryEntry(entry) {
+ var record = entry.completion || {};
+ record.type = "normal";
+ delete record.arg;
+ entry.completion = record;
+ }
+
+ function Context(tryLocsList) {
+ // The root entry object (effectively a try statement without a catch
+ // or a finally block) gives us a place to store values thrown from
+ // locations where there is no enclosing try statement.
+ this.tryEntries = [{ tryLoc: "root" }];
+ tryLocsList.forEach(pushTryEntry, this);
+ this.reset(true);
+ }
+
+ exports.keys = function(object) {
+ var keys = [];
+ for (var key in object) {
+ keys.push(key);
+ }
+ keys.reverse();
+
+ // Rather than returning an object with a next method, we keep
+ // things simple and return the next function itself.
+ return function next() {
+ while (keys.length) {
+ var key = keys.pop();
+ if (key in object) {
+ next.value = key;
+ next.done = false;
+ return next;
+ }
+ }
+
+ // To avoid creating an additional object, we just hang the .value
+ // and .done properties off the next function object itself. This
+ // also ensures that the minifier will not anonymize the function.
+ next.done = true;
+ return next;
+ };
+ };
+
+ function values(iterable) {
+ if (iterable) {
+ var iteratorMethod = iterable[iteratorSymbol];
+ if (iteratorMethod) {
+ return iteratorMethod.call(iterable);
+ }
+
+ if (typeof iterable.next === "function") {
+ return iterable;
+ }
+
+ if (!isNaN(iterable.length)) {
+ var i = -1, next = function next() {
+ while (++i < iterable.length) {
+ if (hasOwn.call(iterable, i)) {
+ next.value = iterable[i];
+ next.done = false;
+ return next;
+ }
+ }
+
+ next.value = undefined;
+ next.done = true;
+
+ return next;
+ };
+
+ return next.next = next;
+ }
+ }
+
+ // Return an iterator with no values.
+ return { next: doneResult };
+ }
+ exports.values = values;
+
+ function doneResult() {
+ return { value: undefined, done: true };
+ }
+
+ Context.prototype = {
+ constructor: Context,
+
+ reset: function(skipTempReset) {
+ this.prev = 0;
+ this.next = 0;
+ // Resetting context._sent for legacy support of Babel's
+ // function.sent implementation.
+ this.sent = this._sent = undefined;
+ this.done = false;
+ this.delegate = null;
+
+ this.method = "next";
+ this.arg = undefined;
+
+ this.tryEntries.forEach(resetTryEntry);
+
+ if (!skipTempReset) {
+ for (var name in this) {
+ // Not sure about the optimal order of these conditions:
+ if (name.charAt(0) === "t" &&
+ hasOwn.call(this, name) &&
+ !isNaN(+name.slice(1))) {
+ this[name] = undefined;
+ }
+ }
+ }
+ },
+
+ stop: function() {
+ this.done = true;
+
+ var rootEntry = this.tryEntries[0];
+ var rootRecord = rootEntry.completion;
+ if (rootRecord.type === "throw") {
+ throw rootRecord.arg;
+ }
+
+ return this.rval;
+ },
+
+ dispatchException: function(exception) {
+ if (this.done) {
+ throw exception;
+ }
+
+ var context = this;
+ function handle(loc, caught) {
+ record.type = "throw";
+ record.arg = exception;
+ context.next = loc;
+
+ if (caught) {
+ // If the dispatched exception was caught by a catch block,
+ // then let that catch block handle the exception normally.
+ context.method = "next";
+ context.arg = undefined;
+ }
+
+ return !! caught;
+ }
+
+ for (var i = this.tryEntries.length - 1; i >= 0; --i) {
+ var entry = this.tryEntries[i];
+ var record = entry.completion;
+
+ if (entry.tryLoc === "root") {
+ // Exception thrown outside of any try block that could handle
+ // it, so set the completion value of the entire function to
+ // throw the exception.
+ return handle("end");
+ }
+
+ if (entry.tryLoc <= this.prev) {
+ var hasCatch = hasOwn.call(entry, "catchLoc");
+ var hasFinally = hasOwn.call(entry, "finallyLoc");
+
+ if (hasCatch && hasFinally) {
+ if (this.prev < entry.catchLoc) {
+ return handle(entry.catchLoc, true);
+ } else if (this.prev < entry.finallyLoc) {
+ return handle(entry.finallyLoc);
+ }
+
+ } else if (hasCatch) {
+ if (this.prev < entry.catchLoc) {
+ return handle(entry.catchLoc, true);
+ }
+
+ } else if (hasFinally) {
+ if (this.prev < entry.finallyLoc) {
+ return handle(entry.finallyLoc);
+ }
+
+ } else {
+ throw new Error("try statement without catch or finally");
+ }
+ }
+ }
+ },
+
+ abrupt: function(type, arg) {
+ for (var i = this.tryEntries.length - 1; i >= 0; --i) {
+ var entry = this.tryEntries[i];
+ if (entry.tryLoc <= this.prev &&
+ hasOwn.call(entry, "finallyLoc") &&
+ this.prev < entry.finallyLoc) {
+ var finallyEntry = entry;
+ break;
+ }
+ }
+
+ if (finallyEntry &&
+ (type === "break" ||
+ type === "continue") &&
+ finallyEntry.tryLoc <= arg &&
+ arg <= finallyEntry.finallyLoc) {
+ // Ignore the finally entry if control is not jumping to a
+ // location outside the try/catch block.
+ finallyEntry = null;
+ }
+
+ var record = finallyEntry ? finallyEntry.completion : {};
+ record.type = type;
+ record.arg = arg;
+
+ if (finallyEntry) {
+ this.method = "next";
+ this.next = finallyEntry.finallyLoc;
+ return ContinueSentinel;
+ }
+
+ return this.complete(record);
+ },
+
+ complete: function(record, afterLoc) {
+ if (record.type === "throw") {
+ throw record.arg;
+ }
+
+ if (record.type === "break" ||
+ record.type === "continue") {
+ this.next = record.arg;
+ } else if (record.type === "return") {
+ this.rval = this.arg = record.arg;
+ this.method = "return";
+ this.next = "end";
+ } else if (record.type === "normal" && afterLoc) {
+ this.next = afterLoc;
+ }
+
+ return ContinueSentinel;
+ },
+
+ finish: function(finallyLoc) {
+ for (var i = this.tryEntries.length - 1; i >= 0; --i) {
+ var entry = this.tryEntries[i];
+ if (entry.finallyLoc === finallyLoc) {
+ this.complete(entry.completion, entry.afterLoc);
+ resetTryEntry(entry);
+ return ContinueSentinel;
+ }
+ }
+ },
+
+ "catch": function(tryLoc) {
+ for (var i = this.tryEntries.length - 1; i >= 0; --i) {
+ var entry = this.tryEntries[i];
+ if (entry.tryLoc === tryLoc) {
+ var record = entry.completion;
+ if (record.type === "throw") {
+ var thrown = record.arg;
+ resetTryEntry(entry);
+ }
+ return thrown;
+ }
+ }
+
+ // The context.catch method must only be called with a location
+ // argument that corresponds to a known catch block.
+ throw new Error("illegal catch attempt");
+ },
+
+ delegateYield: function(iterable, resultName, nextLoc) {
+ this.delegate = {
+ iterator: values(iterable),
+ resultName: resultName,
+ nextLoc: nextLoc
+ };
+
+ if (this.method === "next") {
+ // Deliberately forget the last sent value so that we don't
+ // accidentally pass it on to the delegate.
+ this.arg = undefined;
+ }
+
+ return ContinueSentinel;
+ }
+ };
+
+ // Regardless of whether this script is executing as a CommonJS module
+ // or not, return the runtime object so that we can declare the variable
+ // regeneratorRuntime in the outer scope, which allows this module to be
+ // injected easily by `bin/regenerator --include-runtime script.js`.
+ return exports;
+
+}(
+ // If this script is executing as a CommonJS module, use module.exports
+ // as the regeneratorRuntime namespace. Otherwise create a new empty
+ // object. Either way, the resulting object will be used to initialize
+ // the regeneratorRuntime variable at the top of this file.
+ typeof module === "object" ? module.exports : {}
+));
+
+try {
+ regeneratorRuntime = runtime;
+} catch (accidentalStrictMode) {
+ // This module should not be running in strict mode, so the above
+ // assignment should always work unless something is misconfigured. Just
+ // in case runtime.js accidentally runs in strict mode, in modern engines
+ // we can explicitly access globalThis. In older engines we can escape
+ // strict mode using a global Function call. This could conceivably fail
+ // if a Content Security Policy forbids using Function, but in that case
+ // the proper solution is to fix the accidental strict mode problem. If
+ // you've misconfigured your bundler to force strict mode and applied a
+ // CSP to forbid Function, and you're not willing to fix either of those
+ // problems, please detail your unique predicament in a GitHub issue.
+ if (typeof globalThis === "object") {
+ globalThis.regeneratorRuntime = runtime;
+ } else {
+ Function("r", "regeneratorRuntime = r")(runtime);
+ }
+}
diff --git a/temporary_modules/trezor-connect/node_modules/safe-buffer/LICENSE b/temporary_modules/trezor-connect/node_modules/safe-buffer/LICENSE
new file mode 100644
index 00000000..0c068cee
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/safe-buffer/LICENSE
@@ -0,0 +1,21 @@
+The MIT License (MIT)
+
+Copyright (c) Feross Aboukhadijeh
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
diff --git a/temporary_modules/trezor-connect/node_modules/safe-buffer/README.md b/temporary_modules/trezor-connect/node_modules/safe-buffer/README.md
new file mode 100644
index 00000000..e9a81afd
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/safe-buffer/README.md
@@ -0,0 +1,584 @@
+# safe-buffer [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url]
+
+[travis-image]: https://img.shields.io/travis/feross/safe-buffer/master.svg
+[travis-url]: https://travis-ci.org/feross/safe-buffer
+[npm-image]: https://img.shields.io/npm/v/safe-buffer.svg
+[npm-url]: https://npmjs.org/package/safe-buffer
+[downloads-image]: https://img.shields.io/npm/dm/safe-buffer.svg
+[downloads-url]: https://npmjs.org/package/safe-buffer
+[standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg
+[standard-url]: https://standardjs.com
+
+#### Safer Node.js Buffer API
+
+**Use the new Node.js Buffer APIs (`Buffer.from`, `Buffer.alloc`,
+`Buffer.allocUnsafe`, `Buffer.allocUnsafeSlow`) in all versions of Node.js.**
+
+**Uses the built-in implementation when available.**
+
+## install
+
+```
+npm install safe-buffer
+```
+
+## usage
+
+The goal of this package is to provide a safe replacement for the node.js `Buffer`.
+
+It's a drop-in replacement for `Buffer`. You can use it by adding one `require` line to
+the top of your node.js modules:
+
+```js
+var Buffer = require('safe-buffer').Buffer
+
+// Existing buffer code will continue to work without issues:
+
+new Buffer('hey', 'utf8')
+new Buffer([1, 2, 3], 'utf8')
+new Buffer(obj)
+new Buffer(16) // create an uninitialized buffer (potentially unsafe)
+
+// But you can use these new explicit APIs to make clear what you want:
+
+Buffer.from('hey', 'utf8') // convert from many types to a Buffer
+Buffer.alloc(16) // create a zero-filled buffer (safe)
+Buffer.allocUnsafe(16) // create an uninitialized buffer (potentially unsafe)
+```
+
+## api
+
+### Class Method: Buffer.from(array)
+
+
+* `array` {Array}
+
+Allocates a new `Buffer` using an `array` of octets.
+
+```js
+const buf = Buffer.from([0x62,0x75,0x66,0x66,0x65,0x72]);
+ // creates a new Buffer containing ASCII bytes
+ // ['b','u','f','f','e','r']
+```
+
+A `TypeError` will be thrown if `array` is not an `Array`.
+
+### Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]])
+
+
+* `arrayBuffer` {ArrayBuffer} The `.buffer` property of a `TypedArray` or
+ a `new ArrayBuffer()`
+* `byteOffset` {Number} Default: `0`
+* `length` {Number} Default: `arrayBuffer.length - byteOffset`
+
+When passed a reference to the `.buffer` property of a `TypedArray` instance,
+the newly created `Buffer` will share the same allocated memory as the
+TypedArray.
+
+```js
+const arr = new Uint16Array(2);
+arr[0] = 5000;
+arr[1] = 4000;
+
+const buf = Buffer.from(arr.buffer); // shares the memory with arr;
+
+console.log(buf);
+ // Prints:
+
+// changing the TypedArray changes the Buffer also
+arr[1] = 6000;
+
+console.log(buf);
+ // Prints:
+```
+
+The optional `byteOffset` and `length` arguments specify a memory range within
+the `arrayBuffer` that will be shared by the `Buffer`.
+
+```js
+const ab = new ArrayBuffer(10);
+const buf = Buffer.from(ab, 0, 2);
+console.log(buf.length);
+ // Prints: 2
+```
+
+A `TypeError` will be thrown if `arrayBuffer` is not an `ArrayBuffer`.
+
+### Class Method: Buffer.from(buffer)
+
+
+* `buffer` {Buffer}
+
+Copies the passed `buffer` data onto a new `Buffer` instance.
+
+```js
+const buf1 = Buffer.from('buffer');
+const buf2 = Buffer.from(buf1);
+
+buf1[0] = 0x61;
+console.log(buf1.toString());
+ // 'auffer'
+console.log(buf2.toString());
+ // 'buffer' (copy is not changed)
+```
+
+A `TypeError` will be thrown if `buffer` is not a `Buffer`.
+
+### Class Method: Buffer.from(str[, encoding])
+
+
+* `str` {String} String to encode.
+* `encoding` {String} Encoding to use, Default: `'utf8'`
+
+Creates a new `Buffer` containing the given JavaScript string `str`. If
+provided, the `encoding` parameter identifies the character encoding.
+If not provided, `encoding` defaults to `'utf8'`.
+
+```js
+const buf1 = Buffer.from('this is a tést');
+console.log(buf1.toString());
+ // prints: this is a tést
+console.log(buf1.toString('ascii'));
+ // prints: this is a tC)st
+
+const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex');
+console.log(buf2.toString());
+ // prints: this is a tést
+```
+
+A `TypeError` will be thrown if `str` is not a string.
+
+### Class Method: Buffer.alloc(size[, fill[, encoding]])
+
+
+* `size` {Number}
+* `fill` {Value} Default: `undefined`
+* `encoding` {String} Default: `utf8`
+
+Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the
+`Buffer` will be *zero-filled*.
+
+```js
+const buf = Buffer.alloc(5);
+console.log(buf);
+ //
+```
+
+The `size` must be less than or equal to the value of
+`require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is
+`(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will
+be created if a `size` less than or equal to 0 is specified.
+
+If `fill` is specified, the allocated `Buffer` will be initialized by calling
+`buf.fill(fill)`. See [`buf.fill()`][] for more information.
+
+```js
+const buf = Buffer.alloc(5, 'a');
+console.log(buf);
+ //
+```
+
+If both `fill` and `encoding` are specified, the allocated `Buffer` will be
+initialized by calling `buf.fill(fill, encoding)`. For example:
+
+```js
+const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64');
+console.log(buf);
+ //
+```
+
+Calling `Buffer.alloc(size)` can be significantly slower than the alternative
+`Buffer.allocUnsafe(size)` but ensures that the newly created `Buffer` instance
+contents will *never contain sensitive data*.
+
+A `TypeError` will be thrown if `size` is not a number.
+
+### Class Method: Buffer.allocUnsafe(size)
+
+
+* `size` {Number}
+
+Allocates a new *non-zero-filled* `Buffer` of `size` bytes. The `size` must
+be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit
+architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is
+thrown. A zero-length Buffer will be created if a `size` less than or equal to
+0 is specified.
+
+The underlying memory for `Buffer` instances created in this way is *not
+initialized*. The contents of the newly created `Buffer` are unknown and
+*may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such
+`Buffer` instances to zeroes.
+
+```js
+const buf = Buffer.allocUnsafe(5);
+console.log(buf);
+ //
+ // (octets will be different, every time)
+buf.fill(0);
+console.log(buf);
+ //
+```
+
+A `TypeError` will be thrown if `size` is not a number.
+
+Note that the `Buffer` module pre-allocates an internal `Buffer` instance of
+size `Buffer.poolSize` that is used as a pool for the fast allocation of new
+`Buffer` instances created using `Buffer.allocUnsafe(size)` (and the deprecated
+`new Buffer(size)` constructor) only when `size` is less than or equal to
+`Buffer.poolSize >> 1` (floor of `Buffer.poolSize` divided by two). The default
+value of `Buffer.poolSize` is `8192` but can be modified.
+
+Use of this pre-allocated internal memory pool is a key difference between
+calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`.
+Specifically, `Buffer.alloc(size, fill)` will *never* use the internal Buffer
+pool, while `Buffer.allocUnsafe(size).fill(fill)` *will* use the internal
+Buffer pool if `size` is less than or equal to half `Buffer.poolSize`. The
+difference is subtle but can be important when an application requires the
+additional performance that `Buffer.allocUnsafe(size)` provides.
+
+### Class Method: Buffer.allocUnsafeSlow(size)
+
+
+* `size` {Number}
+
+Allocates a new *non-zero-filled* and non-pooled `Buffer` of `size` bytes. The
+`size` must be less than or equal to the value of
+`require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is
+`(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will
+be created if a `size` less than or equal to 0 is specified.
+
+The underlying memory for `Buffer` instances created in this way is *not
+initialized*. The contents of the newly created `Buffer` are unknown and
+*may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such
+`Buffer` instances to zeroes.
+
+When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances,
+allocations under 4KB are, by default, sliced from a single pre-allocated
+`Buffer`. This allows applications to avoid the garbage collection overhead of
+creating many individually allocated Buffers. This approach improves both
+performance and memory usage by eliminating the need to track and cleanup as
+many `Persistent` objects.
+
+However, in the case where a developer may need to retain a small chunk of
+memory from a pool for an indeterminate amount of time, it may be appropriate
+to create an un-pooled Buffer instance using `Buffer.allocUnsafeSlow()` then
+copy out the relevant bits.
+
+```js
+// need to keep around a few small chunks of memory
+const store = [];
+
+socket.on('readable', () => {
+ const data = socket.read();
+ // allocate for retained data
+ const sb = Buffer.allocUnsafeSlow(10);
+ // copy the data into the new allocation
+ data.copy(sb, 0, 0, 10);
+ store.push(sb);
+});
+```
+
+Use of `Buffer.allocUnsafeSlow()` should be used only as a last resort *after*
+a developer has observed undue memory retention in their applications.
+
+A `TypeError` will be thrown if `size` is not a number.
+
+### All the Rest
+
+The rest of the `Buffer` API is exactly the same as in node.js.
+[See the docs](https://nodejs.org/api/buffer.html).
+
+
+## Related links
+
+- [Node.js issue: Buffer(number) is unsafe](https://github.com/nodejs/node/issues/4660)
+- [Node.js Enhancement Proposal: Buffer.from/Buffer.alloc/Buffer.zalloc/Buffer() soft-deprecate](https://github.com/nodejs/node-eps/pull/4)
+
+## Why is `Buffer` unsafe?
+
+Today, the node.js `Buffer` constructor is overloaded to handle many different argument
+types like `String`, `Array`, `Object`, `TypedArrayView` (`Uint8Array`, etc.),
+`ArrayBuffer`, and also `Number`.
+
+The API is optimized for convenience: you can throw any type at it, and it will try to do
+what you want.
+
+Because the Buffer constructor is so powerful, you often see code like this:
+
+```js
+// Convert UTF-8 strings to hex
+function toHex (str) {
+ return new Buffer(str).toString('hex')
+}
+```
+
+***But what happens if `toHex` is called with a `Number` argument?***
+
+### Remote Memory Disclosure
+
+If an attacker can make your program call the `Buffer` constructor with a `Number`
+argument, then they can make it allocate uninitialized memory from the node.js process.
+This could potentially disclose TLS private keys, user data, or database passwords.
+
+When the `Buffer` constructor is passed a `Number` argument, it returns an
+**UNINITIALIZED** block of memory of the specified `size`. When you create a `Buffer` like
+this, you **MUST** overwrite the contents before returning it to the user.
+
+From the [node.js docs](https://nodejs.org/api/buffer.html#buffer_new_buffer_size):
+
+> `new Buffer(size)`
+>
+> - `size` Number
+>
+> The underlying memory for `Buffer` instances created in this way is not initialized.
+> **The contents of a newly created `Buffer` are unknown and could contain sensitive
+> data.** Use `buf.fill(0)` to initialize a Buffer to zeroes.
+
+(Emphasis our own.)
+
+Whenever the programmer intended to create an uninitialized `Buffer` you often see code
+like this:
+
+```js
+var buf = new Buffer(16)
+
+// Immediately overwrite the uninitialized buffer with data from another buffer
+for (var i = 0; i < buf.length; i++) {
+ buf[i] = otherBuf[i]
+}
+```
+
+
+### Would this ever be a problem in real code?
+
+Yes. It's surprisingly common to forget to check the type of your variables in a
+dynamically-typed language like JavaScript.
+
+Usually the consequences of assuming the wrong type is that your program crashes with an
+uncaught exception. But the failure mode for forgetting to check the type of arguments to
+the `Buffer` constructor is more catastrophic.
+
+Here's an example of a vulnerable service that takes a JSON payload and converts it to
+hex:
+
+```js
+// Take a JSON payload {str: "some string"} and convert it to hex
+var server = http.createServer(function (req, res) {
+ var data = ''
+ req.setEncoding('utf8')
+ req.on('data', function (chunk) {
+ data += chunk
+ })
+ req.on('end', function () {
+ var body = JSON.parse(data)
+ res.end(new Buffer(body.str).toString('hex'))
+ })
+})
+
+server.listen(8080)
+```
+
+In this example, an http client just has to send:
+
+```json
+{
+ "str": 1000
+}
+```
+
+and it will get back 1,000 bytes of uninitialized memory from the server.
+
+This is a very serious bug. It's similar in severity to the
+[the Heartbleed bug](http://heartbleed.com/) that allowed disclosure of OpenSSL process
+memory by remote attackers.
+
+
+### Which real-world packages were vulnerable?
+
+#### [`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht)
+
+[Mathias Buus](https://github.com/mafintosh) and I
+([Feross Aboukhadijeh](http://feross.org/)) found this issue in one of our own packages,
+[`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht). The bug would allow
+anyone on the internet to send a series of messages to a user of `bittorrent-dht` and get
+them to reveal 20 bytes at a time of uninitialized memory from the node.js process.
+
+Here's
+[the commit](https://github.com/feross/bittorrent-dht/commit/6c7da04025d5633699800a99ec3fbadf70ad35b8)
+that fixed it. We released a new fixed version, created a
+[Node Security Project disclosure](https://nodesecurity.io/advisories/68), and deprecated all
+vulnerable versions on npm so users will get a warning to upgrade to a newer version.
+
+#### [`ws`](https://www.npmjs.com/package/ws)
+
+That got us wondering if there were other vulnerable packages. Sure enough, within a short
+period of time, we found the same issue in [`ws`](https://www.npmjs.com/package/ws), the
+most popular WebSocket implementation in node.js.
+
+If certain APIs were called with `Number` parameters instead of `String` or `Buffer` as
+expected, then uninitialized server memory would be disclosed to the remote peer.
+
+These were the vulnerable methods:
+
+```js
+socket.send(number)
+socket.ping(number)
+socket.pong(number)
+```
+
+Here's a vulnerable socket server with some echo functionality:
+
+```js
+server.on('connection', function (socket) {
+ socket.on('message', function (message) {
+ message = JSON.parse(message)
+ if (message.type === 'echo') {
+ socket.send(message.data) // send back the user's message
+ }
+ })
+})
+```
+
+`socket.send(number)` called on the server, will disclose server memory.
+
+Here's [the release](https://github.com/websockets/ws/releases/tag/1.0.1) where the issue
+was fixed, with a more detailed explanation. Props to
+[Arnout Kazemier](https://github.com/3rd-Eden) for the quick fix. Here's the
+[Node Security Project disclosure](https://nodesecurity.io/advisories/67).
+
+
+### What's the solution?
+
+It's important that node.js offers a fast way to get memory otherwise performance-critical
+applications would needlessly get a lot slower.
+
+But we need a better way to *signal our intent* as programmers. **When we want
+uninitialized memory, we should request it explicitly.**
+
+Sensitive functionality should not be packed into a developer-friendly API that loosely
+accepts many different types. This type of API encourages the lazy practice of passing
+variables in without checking the type very carefully.
+
+#### A new API: `Buffer.allocUnsafe(number)`
+
+The functionality of creating buffers with uninitialized memory should be part of another
+API. We propose `Buffer.allocUnsafe(number)`. This way, it's not part of an API that
+frequently gets user input of all sorts of different types passed into it.
+
+```js
+var buf = Buffer.allocUnsafe(16) // careful, uninitialized memory!
+
+// Immediately overwrite the uninitialized buffer with data from another buffer
+for (var i = 0; i < buf.length; i++) {
+ buf[i] = otherBuf[i]
+}
+```
+
+
+### How do we fix node.js core?
+
+We sent [a PR to node.js core](https://github.com/nodejs/node/pull/4514) (merged as
+`semver-major`) which defends against one case:
+
+```js
+var str = 16
+new Buffer(str, 'utf8')
+```
+
+In this situation, it's implied that the programmer intended the first argument to be a
+string, since they passed an encoding as a second argument. Today, node.js will allocate
+uninitialized memory in the case of `new Buffer(number, encoding)`, which is probably not
+what the programmer intended.
+
+But this is only a partial solution, since if the programmer does `new Buffer(variable)`
+(without an `encoding` parameter) there's no way to know what they intended. If `variable`
+is sometimes a number, then uninitialized memory will sometimes be returned.
+
+### What's the real long-term fix?
+
+We could deprecate and remove `new Buffer(number)` and use `Buffer.allocUnsafe(number)` when
+we need uninitialized memory. But that would break 1000s of packages.
+
+~~We believe the best solution is to:~~
+
+~~1. Change `new Buffer(number)` to return safe, zeroed-out memory~~
+
+~~2. Create a new API for creating uninitialized Buffers. We propose: `Buffer.allocUnsafe(number)`~~
+
+#### Update
+
+We now support adding three new APIs:
+
+- `Buffer.from(value)` - convert from any type to a buffer
+- `Buffer.alloc(size)` - create a zero-filled buffer
+- `Buffer.allocUnsafe(size)` - create an uninitialized buffer with given size
+
+This solves the core problem that affected `ws` and `bittorrent-dht` which is
+`Buffer(variable)` getting tricked into taking a number argument.
+
+This way, existing code continues working and the impact on the npm ecosystem will be
+minimal. Over time, npm maintainers can migrate performance-critical code to use
+`Buffer.allocUnsafe(number)` instead of `new Buffer(number)`.
+
+
+### Conclusion
+
+We think there's a serious design issue with the `Buffer` API as it exists today. It
+promotes insecure software by putting high-risk functionality into a convenient API
+with friendly "developer ergonomics".
+
+This wasn't merely a theoretical exercise because we found the issue in some of the
+most popular npm packages.
+
+Fortunately, there's an easy fix that can be applied today. Use `safe-buffer` in place of
+`buffer`.
+
+```js
+var Buffer = require('safe-buffer').Buffer
+```
+
+Eventually, we hope that node.js core can switch to this new, safer behavior. We believe
+the impact on the ecosystem would be minimal since it's not a breaking change.
+Well-maintained, popular packages would be updated to use `Buffer.alloc` quickly, while
+older, insecure packages would magically become safe from this attack vector.
+
+
+## links
+
+- [Node.js PR: buffer: throw if both length and enc are passed](https://github.com/nodejs/node/pull/4514)
+- [Node Security Project disclosure for `ws`](https://nodesecurity.io/advisories/67)
+- [Node Security Project disclosure for`bittorrent-dht`](https://nodesecurity.io/advisories/68)
+
+
+## credit
+
+The original issues in `bittorrent-dht`
+([disclosure](https://nodesecurity.io/advisories/68)) and
+`ws` ([disclosure](https://nodesecurity.io/advisories/67)) were discovered by
+[Mathias Buus](https://github.com/mafintosh) and
+[Feross Aboukhadijeh](http://feross.org/).
+
+Thanks to [Adam Baldwin](https://github.com/evilpacket) for helping disclose these issues
+and for his work running the [Node Security Project](https://nodesecurity.io/).
+
+Thanks to [John Hiesey](https://github.com/jhiesey) for proofreading this README and
+auditing the code.
+
+
+## license
+
+MIT. Copyright (C) [Feross Aboukhadijeh](http://feross.org)
diff --git a/temporary_modules/trezor-connect/node_modules/safe-buffer/index.d.ts b/temporary_modules/trezor-connect/node_modules/safe-buffer/index.d.ts
new file mode 100644
index 00000000..e9fed809
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/safe-buffer/index.d.ts
@@ -0,0 +1,187 @@
+declare module "safe-buffer" {
+ export class Buffer {
+ length: number
+ write(string: string, offset?: number, length?: number, encoding?: string): number;
+ toString(encoding?: string, start?: number, end?: number): string;
+ toJSON(): { type: 'Buffer', data: any[] };
+ equals(otherBuffer: Buffer): boolean;
+ compare(otherBuffer: Buffer, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): number;
+ copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number;
+ slice(start?: number, end?: number): Buffer;
+ writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number;
+ writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number;
+ writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number;
+ writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number;
+ readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number;
+ readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number;
+ readIntLE(offset: number, byteLength: number, noAssert?: boolean): number;
+ readIntBE(offset: number, byteLength: number, noAssert?: boolean): number;
+ readUInt8(offset: number, noAssert?: boolean): number;
+ readUInt16LE(offset: number, noAssert?: boolean): number;
+ readUInt16BE(offset: number, noAssert?: boolean): number;
+ readUInt32LE(offset: number, noAssert?: boolean): number;
+ readUInt32BE(offset: number, noAssert?: boolean): number;
+ readInt8(offset: number, noAssert?: boolean): number;
+ readInt16LE(offset: number, noAssert?: boolean): number;
+ readInt16BE(offset: number, noAssert?: boolean): number;
+ readInt32LE(offset: number, noAssert?: boolean): number;
+ readInt32BE(offset: number, noAssert?: boolean): number;
+ readFloatLE(offset: number, noAssert?: boolean): number;
+ readFloatBE(offset: number, noAssert?: boolean): number;
+ readDoubleLE(offset: number, noAssert?: boolean): number;
+ readDoubleBE(offset: number, noAssert?: boolean): number;
+ swap16(): Buffer;
+ swap32(): Buffer;
+ swap64(): Buffer;
+ writeUInt8(value: number, offset: number, noAssert?: boolean): number;
+ writeUInt16LE(value: number, offset: number, noAssert?: boolean): number;
+ writeUInt16BE(value: number, offset: number, noAssert?: boolean): number;
+ writeUInt32LE(value: number, offset: number, noAssert?: boolean): number;
+ writeUInt32BE(value: number, offset: number, noAssert?: boolean): number;
+ writeInt8(value: number, offset: number, noAssert?: boolean): number;
+ writeInt16LE(value: number, offset: number, noAssert?: boolean): number;
+ writeInt16BE(value: number, offset: number, noAssert?: boolean): number;
+ writeInt32LE(value: number, offset: number, noAssert?: boolean): number;
+ writeInt32BE(value: number, offset: number, noAssert?: boolean): number;
+ writeFloatLE(value: number, offset: number, noAssert?: boolean): number;
+ writeFloatBE(value: number, offset: number, noAssert?: boolean): number;
+ writeDoubleLE(value: number, offset: number, noAssert?: boolean): number;
+ writeDoubleBE(value: number, offset: number, noAssert?: boolean): number;
+ fill(value: any, offset?: number, end?: number): this;
+ indexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number;
+ lastIndexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number;
+ includes(value: string | number | Buffer, byteOffset?: number, encoding?: string): boolean;
+
+ /**
+ * Allocates a new buffer containing the given {str}.
+ *
+ * @param str String to store in buffer.
+ * @param encoding encoding to use, optional. Default is 'utf8'
+ */
+ constructor (str: string, encoding?: string);
+ /**
+ * Allocates a new buffer of {size} octets.
+ *
+ * @param size count of octets to allocate.
+ */
+ constructor (size: number);
+ /**
+ * Allocates a new buffer containing the given {array} of octets.
+ *
+ * @param array The octets to store.
+ */
+ constructor (array: Uint8Array);
+ /**
+ * Produces a Buffer backed by the same allocated memory as
+ * the given {ArrayBuffer}.
+ *
+ *
+ * @param arrayBuffer The ArrayBuffer with which to share memory.
+ */
+ constructor (arrayBuffer: ArrayBuffer);
+ /**
+ * Allocates a new buffer containing the given {array} of octets.
+ *
+ * @param array The octets to store.
+ */
+ constructor (array: any[]);
+ /**
+ * Copies the passed {buffer} data onto a new {Buffer} instance.
+ *
+ * @param buffer The buffer to copy.
+ */
+ constructor (buffer: Buffer);
+ prototype: Buffer;
+ /**
+ * Allocates a new Buffer using an {array} of octets.
+ *
+ * @param array
+ */
+ static from(array: any[]): Buffer;
+ /**
+ * When passed a reference to the .buffer property of a TypedArray instance,
+ * the newly created Buffer will share the same allocated memory as the TypedArray.
+ * The optional {byteOffset} and {length} arguments specify a memory range
+ * within the {arrayBuffer} that will be shared by the Buffer.
+ *
+ * @param arrayBuffer The .buffer property of a TypedArray or a new ArrayBuffer()
+ * @param byteOffset
+ * @param length
+ */
+ static from(arrayBuffer: ArrayBuffer, byteOffset?: number, length?: number): Buffer;
+ /**
+ * Copies the passed {buffer} data onto a new Buffer instance.
+ *
+ * @param buffer
+ */
+ static from(buffer: Buffer): Buffer;
+ /**
+ * Creates a new Buffer containing the given JavaScript string {str}.
+ * If provided, the {encoding} parameter identifies the character encoding.
+ * If not provided, {encoding} defaults to 'utf8'.
+ *
+ * @param str
+ */
+ static from(str: string, encoding?: string): Buffer;
+ /**
+ * Returns true if {obj} is a Buffer
+ *
+ * @param obj object to test.
+ */
+ static isBuffer(obj: any): obj is Buffer;
+ /**
+ * Returns true if {encoding} is a valid encoding argument.
+ * Valid string encodings in Node 0.12: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex'
+ *
+ * @param encoding string to test.
+ */
+ static isEncoding(encoding: string): boolean;
+ /**
+ * Gives the actual byte length of a string. encoding defaults to 'utf8'.
+ * This is not the same as String.prototype.length since that returns the number of characters in a string.
+ *
+ * @param string string to test.
+ * @param encoding encoding used to evaluate (defaults to 'utf8')
+ */
+ static byteLength(string: string, encoding?: string): number;
+ /**
+ * Returns a buffer which is the result of concatenating all the buffers in the list together.
+ *
+ * If the list has no items, or if the totalLength is 0, then it returns a zero-length buffer.
+ * If the list has exactly one item, then the first item of the list is returned.
+ * If the list has more than one item, then a new Buffer is created.
+ *
+ * @param list An array of Buffer objects to concatenate
+ * @param totalLength Total length of the buffers when concatenated.
+ * 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.
+ */
+ static concat(list: Buffer[], totalLength?: number): Buffer;
+ /**
+ * The same as buf1.compare(buf2).
+ */
+ static compare(buf1: Buffer, buf2: Buffer): number;
+ /**
+ * Allocates a new buffer of {size} octets.
+ *
+ * @param size count of octets to allocate.
+ * @param fill if specified, buffer will be initialized by calling buf.fill(fill).
+ * If parameter is omitted, buffer will be filled with zeros.
+ * @param encoding encoding used for call to buf.fill while initalizing
+ */
+ static alloc(size: number, fill?: string | Buffer | number, encoding?: string): Buffer;
+ /**
+ * Allocates a new buffer of {size} octets, leaving memory not initialized, so the contents
+ * of the newly created Buffer are unknown and may contain sensitive data.
+ *
+ * @param size count of octets to allocate
+ */
+ static allocUnsafe(size: number): Buffer;
+ /**
+ * Allocates a new non-pooled buffer of {size} octets, leaving memory not initialized, so the contents
+ * of the newly created Buffer are unknown and may contain sensitive data.
+ *
+ * @param size count of octets to allocate
+ */
+ static allocUnsafeSlow(size: number): Buffer;
+ }
+}
\ No newline at end of file
diff --git a/temporary_modules/trezor-connect/node_modules/safe-buffer/index.js b/temporary_modules/trezor-connect/node_modules/safe-buffer/index.js
new file mode 100644
index 00000000..f8d3ec98
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/safe-buffer/index.js
@@ -0,0 +1,65 @@
+/*! safe-buffer. MIT License. Feross Aboukhadijeh */
+/* eslint-disable node/no-deprecated-api */
+var buffer = require('buffer')
+var Buffer = buffer.Buffer
+
+// alternative to using Object.keys for old browsers
+function copyProps (src, dst) {
+ for (var key in src) {
+ dst[key] = src[key]
+ }
+}
+if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
+ module.exports = buffer
+} else {
+ // Copy properties from require('buffer')
+ copyProps(buffer, exports)
+ exports.Buffer = SafeBuffer
+}
+
+function SafeBuffer (arg, encodingOrOffset, length) {
+ return Buffer(arg, encodingOrOffset, length)
+}
+
+SafeBuffer.prototype = Object.create(Buffer.prototype)
+
+// Copy static methods from Buffer
+copyProps(Buffer, SafeBuffer)
+
+SafeBuffer.from = function (arg, encodingOrOffset, length) {
+ if (typeof arg === 'number') {
+ throw new TypeError('Argument must not be a number')
+ }
+ return Buffer(arg, encodingOrOffset, length)
+}
+
+SafeBuffer.alloc = function (size, fill, encoding) {
+ if (typeof size !== 'number') {
+ throw new TypeError('Argument must be a number')
+ }
+ var buf = Buffer(size)
+ if (fill !== undefined) {
+ if (typeof encoding === 'string') {
+ buf.fill(fill, encoding)
+ } else {
+ buf.fill(fill)
+ }
+ } else {
+ buf.fill(0)
+ }
+ return buf
+}
+
+SafeBuffer.allocUnsafe = function (size) {
+ if (typeof size !== 'number') {
+ throw new TypeError('Argument must be a number')
+ }
+ return Buffer(size)
+}
+
+SafeBuffer.allocUnsafeSlow = function (size) {
+ if (typeof size !== 'number') {
+ throw new TypeError('Argument must be a number')
+ }
+ return buffer.SlowBuffer(size)
+}
diff --git a/temporary_modules/trezor-connect/node_modules/safe-buffer/package.json b/temporary_modules/trezor-connect/node_modules/safe-buffer/package.json
new file mode 100644
index 00000000..f2869e25
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/safe-buffer/package.json
@@ -0,0 +1,51 @@
+{
+ "name": "safe-buffer",
+ "description": "Safer Node.js Buffer API",
+ "version": "5.2.1",
+ "author": {
+ "name": "Feross Aboukhadijeh",
+ "email": "feross@feross.org",
+ "url": "https://feross.org"
+ },
+ "bugs": {
+ "url": "https://github.com/feross/safe-buffer/issues"
+ },
+ "devDependencies": {
+ "standard": "*",
+ "tape": "^5.0.0"
+ },
+ "homepage": "https://github.com/feross/safe-buffer",
+ "keywords": [
+ "buffer",
+ "buffer allocate",
+ "node security",
+ "safe",
+ "safe-buffer",
+ "security",
+ "uninitialized"
+ ],
+ "license": "MIT",
+ "main": "index.js",
+ "types": "index.d.ts",
+ "repository": {
+ "type": "git",
+ "url": "git://github.com/feross/safe-buffer.git"
+ },
+ "scripts": {
+ "test": "standard && tape test/*.js"
+ },
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ]
+}
diff --git a/temporary_modules/trezor-connect/node_modules/sax/LICENSE b/temporary_modules/trezor-connect/node_modules/sax/LICENSE
new file mode 100644
index 00000000..ccffa082
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/sax/LICENSE
@@ -0,0 +1,41 @@
+The ISC License
+
+Copyright (c) Isaac Z. Schlueter and Contributors
+
+Permission to use, copy, modify, and/or distribute this software for any
+purpose with or without fee is hereby granted, provided that the above
+copyright notice and this permission notice appear in all copies.
+
+THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
+IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+====
+
+`String.fromCodePoint` by Mathias Bynens used according to terms of MIT
+License, as follows:
+
+ Copyright Mathias Bynens
+
+ Permission is hereby granted, free of charge, to any person obtaining
+ a copy of this software and associated documentation files (the
+ "Software"), to deal in the Software without restriction, including
+ without limitation the rights to use, copy, modify, merge, publish,
+ distribute, sublicense, and/or sell copies of the Software, and to
+ permit persons to whom the Software is furnished to do so, subject to
+ the following conditions:
+
+ The above copyright notice and this permission notice shall be
+ included in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/temporary_modules/trezor-connect/node_modules/sax/LICENSE-W3C.html b/temporary_modules/trezor-connect/node_modules/sax/LICENSE-W3C.html
new file mode 100644
index 00000000..a611e3f9
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/sax/LICENSE-W3C.html
@@ -0,0 +1,188 @@
+
+W3C Software Notice and License
+
+
+
+
+
+
+ W3C
+
+
+
+
+
+
+
+
+
+

+
+
+
+
+
+
W3C Software Notice and License
+
+
+
This work (and included software, documentation such as READMEs, or other
+related items) is being provided by the copyright holders under the following
+license.
+
License
+
+
+By obtaining, using and/or copying this work, you (the licensee)
+agree that you have read, understood, and will comply with the following
+terms and conditions.
+
+
Permission to copy, modify, and distribute this software and its
+documentation, with or without modification, for any purpose and without
+fee or royalty is hereby granted, provided that you include the following on
+ALL copies of the software and documentation or portions thereof, including
+modifications:
+
+
- The full text of this NOTICE in a location viewable to users of the
+ redistributed or derivative work.
- Any pre-existing intellectual property disclaimers, notices, or terms
+ and conditions. If none exist, the W3C Software Short
+ Notice should be included (hypertext is preferred, text is permitted)
+ within the body of any redistributed or derivative code.
- Notice of any changes or modifications to the files, including the date
+ changes were made. (We recommend you provide URIs to the location from
+ which the code is derived.)
+
+
Disclaimers
+
+
THIS SOFTWARE AND DOCUMENTATION IS PROVIDED "AS IS," AND COPYRIGHT HOLDERS
+MAKE NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT
+LIMITED TO, WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR
+PURPOSE OR THAT THE USE OF THE SOFTWARE OR DOCUMENTATION WILL NOT INFRINGE
+ANY THIRD PARTY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS.
+
+
COPYRIGHT HOLDERS WILL NOT BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL OR
+CONSEQUENTIAL DAMAGES ARISING OUT OF ANY USE OF THE SOFTWARE OR
+DOCUMENTATION.
+
+
The name and trademarks of copyright holders may NOT be used in
+advertising or publicity pertaining to the software without specific, written
+prior permission. Title to copyright in this software and any associated
+documentation will at all times remain with copyright holders.
+
+
Notes
+
+
This version: http://www.w3.org/Consortium/Legal/2002/copyright-software-20021231
+
+
This formulation of W3C's notice and license became active on December 31
+2002. This version removes the copyright ownership notice such that this
+license can be used with materials other than those owned by the W3C,
+reflects that ERCIM is now a host of the W3C, includes references to this
+specific dated version of the license, and removes the ambiguous grant of
+"use". Otherwise, this version is the same as the previous
+version and is written so as to preserve the Free
+Software Foundation's assessment of GPL compatibility and OSI's certification
+under the Open Source
+Definition.
+
+
+
+
+
+
+
+
+
+
diff --git a/temporary_modules/trezor-connect/node_modules/sax/README.md b/temporary_modules/trezor-connect/node_modules/sax/README.md
new file mode 100644
index 00000000..91a03143
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/sax/README.md
@@ -0,0 +1,220 @@
+# sax js
+
+A sax-style parser for XML and HTML.
+
+Designed with [node](http://nodejs.org/) in mind, but should work fine in
+the browser or other CommonJS implementations.
+
+## What This Is
+
+* A very simple tool to parse through an XML string.
+* A stepping stone to a streaming HTML parser.
+* A handy way to deal with RSS and other mostly-ok-but-kinda-broken XML
+ docs.
+
+## What This Is (probably) Not
+
+* An HTML Parser - That's a fine goal, but this isn't it. It's just
+ XML.
+* A DOM Builder - You can use it to build an object model out of XML,
+ but it doesn't do that out of the box.
+* XSLT - No DOM = no querying.
+* 100% Compliant with (some other SAX implementation) - Most SAX
+ implementations are in Java and do a lot more than this does.
+* An XML Validator - It does a little validation when in strict mode, but
+ not much.
+* A Schema-Aware XSD Thing - Schemas are an exercise in fetishistic
+ masochism.
+* A DTD-aware Thing - Fetching DTDs is a much bigger job.
+
+## Regarding `Hello, world!').close();
+
+// stream usage
+// takes the same options as the parser
+var saxStream = require("sax").createStream(strict, options)
+saxStream.on("error", function (e) {
+ // unhandled errors will throw, since this is a proper node
+ // event emitter.
+ console.error("error!", e)
+ // clear the error
+ this._parser.error = null
+ this._parser.resume()
+})
+saxStream.on("opentag", function (node) {
+ // same object as above
+})
+// pipe is supported, and it's readable/writable
+// same chunks coming in also go out.
+fs.createReadStream("file.xml")
+ .pipe(saxStream)
+ .pipe(fs.createWriteStream("file-copy.xml"))
+```
+
+
+## Arguments
+
+Pass the following arguments to the parser function. All are optional.
+
+`strict` - Boolean. Whether or not to be a jerk. Default: `false`.
+
+`opt` - Object bag of settings regarding string formatting. All default to `false`.
+
+Settings supported:
+
+* `trim` - Boolean. Whether or not to trim text and comment nodes.
+* `normalize` - Boolean. If true, then turn any whitespace into a single
+ space.
+* `lowercase` - Boolean. If true, then lowercase tag names and attribute names
+ in loose mode, rather than uppercasing them.
+* `xmlns` - Boolean. If true, then namespaces are supported.
+* `position` - Boolean. If false, then don't track line/col/position.
+* `strictEntities` - Boolean. If true, only parse [predefined XML
+ entities](http://www.w3.org/TR/REC-xml/#sec-predefined-ent)
+ (`&`, `'`, `>`, `<`, and `"`)
+
+## Methods
+
+`write` - Write bytes onto the stream. You don't have to do this all at
+once. You can keep writing as much as you want.
+
+`close` - Close the stream. Once closed, no more data may be written until
+it is done processing the buffer, which is signaled by the `end` event.
+
+`resume` - To gracefully handle errors, assign a listener to the `error`
+event. Then, when the error is taken care of, you can call `resume` to
+continue parsing. Otherwise, the parser will not continue while in an error
+state.
+
+## Members
+
+At all times, the parser object will have the following members:
+
+`line`, `column`, `position` - Indications of the position in the XML
+document where the parser currently is looking.
+
+`startTagPosition` - Indicates the position where the current tag starts.
+
+`closed` - Boolean indicating whether or not the parser can be written to.
+If it's `true`, then wait for the `ready` event to write again.
+
+`strict` - Boolean indicating whether or not the parser is a jerk.
+
+`opt` - Any options passed into the constructor.
+
+`tag` - The current tag being dealt with.
+
+And a bunch of other stuff that you probably shouldn't touch.
+
+## Events
+
+All events emit with a single argument. To listen to an event, assign a
+function to `on`. Functions get executed in the this-context of
+the parser object. The list of supported events are also in the exported
+`EVENTS` array.
+
+When using the stream interface, assign handlers using the EventEmitter
+`on` function in the normal fashion.
+
+`error` - Indication that something bad happened. The error will be hanging
+out on `parser.error`, and must be deleted before parsing can continue. By
+listening to this event, you can keep an eye on that kind of stuff. Note:
+this happens *much* more in strict mode. Argument: instance of `Error`.
+
+`text` - Text node. Argument: string of text.
+
+`doctype` - The ``. Argument:
+object with `name` and `body` members. Attributes are not parsed, as
+processing instructions have implementation dependent semantics.
+
+`sgmldeclaration` - Random SGML declarations. Stuff like ``
+would trigger this kind of event. This is a weird thing to support, so it
+might go away at some point. SAX isn't intended to be used to parse SGML,
+after all.
+
+`opentag` - An opening tag. Argument: object with `name` and `attributes`.
+In non-strict mode, tag names are uppercased, unless the `lowercase`
+option is set. If the `xmlns` option is set, then it will contain
+namespace binding information on the `ns` member, and will have a
+`local`, `prefix`, and `uri` member.
+
+`closetag` - A closing tag. In loose mode, tags are auto-closed if their
+parent closes. In strict mode, well-formedness is enforced. Note that
+self-closing tags will have `closeTag` emitted immediately after `openTag`.
+Argument: tag name.
+
+`attribute` - An attribute node. Argument: object with `name` and `value`.
+In non-strict mode, attribute names are uppercased, unless the `lowercase`
+option is set. If the `xmlns` option is set, it will also contains namespace
+information.
+
+`comment` - A comment node. Argument: the string of the comment.
+
+`opencdata` - The opening tag of a ``) of a `` tags trigger a `"script"`
+event, and their contents are not checked for special xml characters.
+If you pass `noscript: true`, then this behavior is suppressed.
+
+## Reporting Problems
+
+It's best to write a failing test if you find an issue. I will always
+accept pull requests with failing tests if they demonstrate intended
+behavior, but it is very hard to figure out what issue you're describing
+without a test. Writing a test is also the best way for you yourself
+to figure out if you really understand the issue you think you have with
+sax-js.
diff --git a/temporary_modules/trezor-connect/node_modules/sax/lib/sax.js b/temporary_modules/trezor-connect/node_modules/sax/lib/sax.js
new file mode 100644
index 00000000..5c08d5f6
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/sax/lib/sax.js
@@ -0,0 +1,1563 @@
+;(function (sax) { // wrapper for non-node envs
+ sax.parser = function (strict, opt) { return new SAXParser(strict, opt) }
+ sax.SAXParser = SAXParser
+ sax.SAXStream = SAXStream
+ sax.createStream = createStream
+
+ // When we pass the MAX_BUFFER_LENGTH position, start checking for buffer overruns.
+ // When we check, schedule the next check for MAX_BUFFER_LENGTH - (max(buffer lengths)),
+ // since that's the earliest that a buffer overrun could occur. This way, checks are
+ // as rare as required, but as often as necessary to ensure never crossing this bound.
+ // Furthermore, buffers are only tested at most once per write(), so passing a very
+ // large string into write() might have undesirable effects, but this is manageable by
+ // the caller, so it is assumed to be safe. Thus, a call to write() may, in the extreme
+ // edge case, result in creating at most one complete copy of the string passed in.
+ // Set to Infinity to have unlimited buffers.
+ sax.MAX_BUFFER_LENGTH = 64 * 1024
+
+ var buffers = [
+ 'comment', 'sgmlDecl', 'textNode', 'tagName', 'doctype',
+ 'procInstName', 'procInstBody', 'entity', 'attribName',
+ 'attribValue', 'cdata', 'script'
+ ]
+
+ sax.EVENTS = [
+ 'text',
+ 'processinginstruction',
+ 'sgmldeclaration',
+ 'doctype',
+ 'comment',
+ 'attribute',
+ 'opentag',
+ 'closetag',
+ 'opencdata',
+ 'cdata',
+ 'closecdata',
+ 'error',
+ 'end',
+ 'ready',
+ 'script',
+ 'opennamespace',
+ 'closenamespace'
+ ]
+
+ function SAXParser (strict, opt) {
+ if (!(this instanceof SAXParser)) {
+ return new SAXParser(strict, opt)
+ }
+
+ var parser = this
+ clearBuffers(parser)
+ parser.q = parser.c = ''
+ parser.bufferCheckPosition = sax.MAX_BUFFER_LENGTH
+ parser.opt = opt || {}
+ parser.opt.lowercase = parser.opt.lowercase || parser.opt.lowercasetags
+ parser.looseCase = parser.opt.lowercase ? 'toLowerCase' : 'toUpperCase'
+ parser.tags = []
+ parser.closed = parser.closedRoot = parser.sawRoot = false
+ parser.tag = parser.error = null
+ parser.strict = !!strict
+ parser.noscript = !!(strict || parser.opt.noscript)
+ parser.state = S.BEGIN
+ parser.strictEntities = parser.opt.strictEntities
+ parser.ENTITIES = parser.strictEntities ? Object.create(sax.XML_ENTITIES) : Object.create(sax.ENTITIES)
+ parser.attribList = []
+
+ // namespaces form a prototype chain.
+ // it always points at the current tag,
+ // which protos to its parent tag.
+ if (parser.opt.xmlns) {
+ parser.ns = Object.create(rootNS)
+ }
+
+ // mostly just for error reporting
+ parser.trackPosition = parser.opt.position !== false
+ if (parser.trackPosition) {
+ parser.position = parser.line = parser.column = 0
+ }
+ emit(parser, 'onready')
+ }
+
+ if (!Object.create) {
+ Object.create = function (o) {
+ function F () {}
+ F.prototype = o
+ var newf = new F()
+ return newf
+ }
+ }
+
+ if (!Object.keys) {
+ Object.keys = function (o) {
+ var a = []
+ for (var i in o) if (o.hasOwnProperty(i)) a.push(i)
+ return a
+ }
+ }
+
+ function checkBufferLength (parser) {
+ var maxAllowed = Math.max(sax.MAX_BUFFER_LENGTH, 10)
+ var maxActual = 0
+ for (var i = 0, l = buffers.length; i < l; i++) {
+ var len = parser[buffers[i]].length
+ if (len > maxAllowed) {
+ // Text/cdata nodes can get big, and since they're buffered,
+ // we can get here under normal conditions.
+ // Avoid issues by emitting the text node now,
+ // so at least it won't get any bigger.
+ switch (buffers[i]) {
+ case 'textNode':
+ closeText(parser)
+ break
+
+ case 'cdata':
+ emitNode(parser, 'oncdata', parser.cdata)
+ parser.cdata = ''
+ break
+
+ case 'script':
+ emitNode(parser, 'onscript', parser.script)
+ parser.script = ''
+ break
+
+ default:
+ error(parser, 'Max buffer length exceeded: ' + buffers[i])
+ }
+ }
+ maxActual = Math.max(maxActual, len)
+ }
+ // schedule the next check for the earliest possible buffer overrun.
+ var m = sax.MAX_BUFFER_LENGTH - maxActual
+ parser.bufferCheckPosition = m + parser.position
+ }
+
+ function clearBuffers (parser) {
+ for (var i = 0, l = buffers.length; i < l; i++) {
+ parser[buffers[i]] = ''
+ }
+ }
+
+ function flushBuffers (parser) {
+ closeText(parser)
+ if (parser.cdata !== '') {
+ emitNode(parser, 'oncdata', parser.cdata)
+ parser.cdata = ''
+ }
+ if (parser.script !== '') {
+ emitNode(parser, 'onscript', parser.script)
+ parser.script = ''
+ }
+ }
+
+ SAXParser.prototype = {
+ end: function () { end(this) },
+ write: write,
+ resume: function () { this.error = null; return this },
+ close: function () { return this.write(null) },
+ flush: function () { flushBuffers(this) }
+ }
+
+ var Stream
+ try {
+ Stream = require('stream').Stream
+ } catch (ex) {
+ Stream = function () {}
+ }
+
+ var streamWraps = sax.EVENTS.filter(function (ev) {
+ return ev !== 'error' && ev !== 'end'
+ })
+
+ function createStream (strict, opt) {
+ return new SAXStream(strict, opt)
+ }
+
+ function SAXStream (strict, opt) {
+ if (!(this instanceof SAXStream)) {
+ return new SAXStream(strict, opt)
+ }
+
+ Stream.apply(this)
+
+ this._parser = new SAXParser(strict, opt)
+ this.writable = true
+ this.readable = true
+
+ var me = this
+
+ this._parser.onend = function () {
+ me.emit('end')
+ }
+
+ this._parser.onerror = function (er) {
+ me.emit('error', er)
+
+ // if didn't throw, then means error was handled.
+ // go ahead and clear error, so we can write again.
+ me._parser.error = null
+ }
+
+ this._decoder = null
+
+ streamWraps.forEach(function (ev) {
+ Object.defineProperty(me, 'on' + ev, {
+ get: function () {
+ return me._parser['on' + ev]
+ },
+ set: function (h) {
+ if (!h) {
+ me.removeAllListeners(ev)
+ me._parser['on' + ev] = h
+ return h
+ }
+ me.on(ev, h)
+ },
+ enumerable: true,
+ configurable: false
+ })
+ })
+ }
+
+ SAXStream.prototype = Object.create(Stream.prototype, {
+ constructor: {
+ value: SAXStream
+ }
+ })
+
+ SAXStream.prototype.write = function (data) {
+ if (typeof Buffer === 'function' &&
+ typeof Buffer.isBuffer === 'function' &&
+ Buffer.isBuffer(data)) {
+ if (!this._decoder) {
+ var SD = require('string_decoder').StringDecoder
+ this._decoder = new SD('utf8')
+ }
+ data = this._decoder.write(data)
+ }
+
+ this._parser.write(data.toString())
+ this.emit('data', data)
+ return true
+ }
+
+ SAXStream.prototype.end = function (chunk) {
+ if (chunk && chunk.length) {
+ this.write(chunk)
+ }
+ this._parser.end()
+ return true
+ }
+
+ SAXStream.prototype.on = function (ev, handler) {
+ var me = this
+ if (!me._parser['on' + ev] && streamWraps.indexOf(ev) !== -1) {
+ me._parser['on' + ev] = function () {
+ var args = arguments.length === 1 ? [arguments[0]] : Array.apply(null, arguments)
+ args.splice(0, 0, ev)
+ me.emit.apply(me, args)
+ }
+ }
+
+ return Stream.prototype.on.call(me, ev, handler)
+ }
+
+ // character classes and tokens
+ var whitespace = '\r\n\t '
+
+ // this really needs to be replaced with character classes.
+ // XML allows all manner of ridiculous numbers and digits.
+ var number = '0124356789'
+ var letter = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
+
+ // (Letter | "_" | ":")
+ var quote = '\'"'
+ var attribEnd = whitespace + '>'
+ var CDATA = '[CDATA['
+ var DOCTYPE = 'DOCTYPE'
+ var XML_NAMESPACE = 'http://www.w3.org/XML/1998/namespace'
+ var XMLNS_NAMESPACE = 'http://www.w3.org/2000/xmlns/'
+ var rootNS = { xml: XML_NAMESPACE, xmlns: XMLNS_NAMESPACE }
+
+ // turn all the string character sets into character class objects.
+ whitespace = charClass(whitespace)
+ number = charClass(number)
+ letter = charClass(letter)
+
+ // http://www.w3.org/TR/REC-xml/#NT-NameStartChar
+ // This implementation works on strings, a single character at a time
+ // as such, it cannot ever support astral-plane characters (10000-EFFFF)
+ // without a significant breaking change to either this parser, or the
+ // JavaScript language. Implementation of an emoji-capable xml parser
+ // is left as an exercise for the reader.
+ var nameStart = /[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/
+
+ var nameBody = /[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040\.\d-]/
+
+ var entityStart = /[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/
+ var entityBody = /[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040\.\d-]/
+
+ quote = charClass(quote)
+ attribEnd = charClass(attribEnd)
+
+ function charClass (str) {
+ return str.split('').reduce(function (s, c) {
+ s[c] = true
+ return s
+ }, {})
+ }
+
+ function isRegExp (c) {
+ return Object.prototype.toString.call(c) === '[object RegExp]'
+ }
+
+ function is (charclass, c) {
+ return isRegExp(charclass) ? !!c.match(charclass) : charclass[c]
+ }
+
+ function not (charclass, c) {
+ return !is(charclass, c)
+ }
+
+ var S = 0
+ sax.STATE = {
+ BEGIN: S++, // leading byte order mark or whitespace
+ BEGIN_WHITESPACE: S++, // leading whitespace
+ TEXT: S++, // general stuff
+ TEXT_ENTITY: S++, // & and such.
+ OPEN_WAKA: S++, // <
+ SGML_DECL: S++, //
+ SCRIPT: S++, //
\ No newline at end of file
diff --git a/temporary_modules/trezor-connect/node_modules/tslib/tslib.es6.js b/temporary_modules/trezor-connect/node_modules/tslib/tslib.es6.js
new file mode 100644
index 00000000..91514ec0
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/tslib/tslib.es6.js
@@ -0,0 +1,248 @@
+/******************************************************************************
+Copyright (c) Microsoft Corporation.
+
+Permission to use, copy, modify, and/or distribute this software for any
+purpose with or without fee is hereby granted.
+
+THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
+REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
+AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
+INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
+LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
+OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
+PERFORMANCE OF THIS SOFTWARE.
+***************************************************************************** */
+/* global Reflect, Promise */
+
+var extendStatics = function(d, b) {
+ extendStatics = Object.setPrototypeOf ||
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
+ function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
+ return extendStatics(d, b);
+};
+
+export function __extends(d, b) {
+ if (typeof b !== "function" && b !== null)
+ throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
+ extendStatics(d, b);
+ function __() { this.constructor = d; }
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+}
+
+export var __assign = function() {
+ __assign = Object.assign || function __assign(t) {
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
+ s = arguments[i];
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
+ }
+ return t;
+ }
+ return __assign.apply(this, arguments);
+}
+
+export function __rest(s, e) {
+ var t = {};
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
+ t[p] = s[p];
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
+ t[p[i]] = s[p[i]];
+ }
+ return t;
+}
+
+export function __decorate(decorators, target, key, desc) {
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
+}
+
+export function __param(paramIndex, decorator) {
+ return function (target, key) { decorator(target, key, paramIndex); }
+}
+
+export function __metadata(metadataKey, metadataValue) {
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
+}
+
+export function __awaiter(thisArg, _arguments, P, generator) {
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
+ return new (P || (P = Promise))(function (resolve, reject) {
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
+ });
+}
+
+export function __generator(thisArg, body) {
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
+ function verb(n) { return function (v) { return step([n, v]); }; }
+ function step(op) {
+ if (f) throw new TypeError("Generator is already executing.");
+ while (_) try {
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
+ if (y = 0, t) op = [op[0] & 2, t.value];
+ switch (op[0]) {
+ case 0: case 1: t = op; break;
+ case 4: _.label++; return { value: op[1], done: false };
+ case 5: _.label++; y = op[1]; op = [0]; continue;
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
+ default:
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
+ if (t[2]) _.ops.pop();
+ _.trys.pop(); continue;
+ }
+ op = body.call(thisArg, _);
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
+ }
+}
+
+export var __createBinding = Object.create ? (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ var desc = Object.getOwnPropertyDescriptor(m, k);
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+ desc = { enumerable: true, get: function() { return m[k]; } };
+ }
+ Object.defineProperty(o, k2, desc);
+}) : (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ o[k2] = m[k];
+});
+
+export function __exportStar(m, o) {
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);
+}
+
+export function __values(o) {
+ var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
+ if (m) return m.call(o);
+ if (o && typeof o.length === "number") return {
+ next: function () {
+ if (o && i >= o.length) o = void 0;
+ return { value: o && o[i++], done: !o };
+ }
+ };
+ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
+}
+
+export function __read(o, n) {
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
+ if (!m) return o;
+ var i = m.call(o), r, ar = [], e;
+ try {
+ while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
+ }
+ catch (error) { e = { error: error }; }
+ finally {
+ try {
+ if (r && !r.done && (m = i["return"])) m.call(i);
+ }
+ finally { if (e) throw e.error; }
+ }
+ return ar;
+}
+
+/** @deprecated */
+export function __spread() {
+ for (var ar = [], i = 0; i < arguments.length; i++)
+ ar = ar.concat(__read(arguments[i]));
+ return ar;
+}
+
+/** @deprecated */
+export function __spreadArrays() {
+ for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
+ for (var r = Array(s), k = 0, i = 0; i < il; i++)
+ for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
+ r[k] = a[j];
+ return r;
+}
+
+export function __spreadArray(to, from, pack) {
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
+ if (ar || !(i in from)) {
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
+ ar[i] = from[i];
+ }
+ }
+ return to.concat(ar || Array.prototype.slice.call(from));
+}
+
+export function __await(v) {
+ return this instanceof __await ? (this.v = v, this) : new __await(v);
+}
+
+export function __asyncGenerator(thisArg, _arguments, generator) {
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
+ var g = generator.apply(thisArg, _arguments || []), i, q = [];
+ return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
+ function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
+ function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
+ function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
+ function fulfill(value) { resume("next", value); }
+ function reject(value) { resume("throw", value); }
+ function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
+}
+
+export function __asyncDelegator(o) {
+ var i, p;
+ return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
+ function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; }
+}
+
+export function __asyncValues(o) {
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
+ var m = o[Symbol.asyncIterator], i;
+ return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
+ function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
+ function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
+}
+
+export function __makeTemplateObject(cooked, raw) {
+ if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
+ return cooked;
+};
+
+var __setModuleDefault = Object.create ? (function(o, v) {
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
+}) : function(o, v) {
+ o["default"] = v;
+};
+
+export function __importStar(mod) {
+ if (mod && mod.__esModule) return mod;
+ var result = {};
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
+ __setModuleDefault(result, mod);
+ return result;
+}
+
+export function __importDefault(mod) {
+ return (mod && mod.__esModule) ? mod : { default: mod };
+}
+
+export function __classPrivateFieldGet(receiver, state, kind, f) {
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
+}
+
+export function __classPrivateFieldSet(receiver, state, value, kind, f) {
+ if (kind === "m") throw new TypeError("Private method is not writable");
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
+}
+
+export function __classPrivateFieldIn(state, receiver) {
+ if (receiver === null || (typeof receiver !== "object" && typeof receiver !== "function")) throw new TypeError("Cannot use 'in' operator on non-object");
+ return typeof state === "function" ? receiver === state : state.has(receiver);
+}
diff --git a/temporary_modules/trezor-connect/node_modules/tslib/tslib.html b/temporary_modules/trezor-connect/node_modules/tslib/tslib.html
new file mode 100644
index 00000000..44c9ba51
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/tslib/tslib.html
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/temporary_modules/trezor-connect/node_modules/tslib/tslib.js b/temporary_modules/trezor-connect/node_modules/tslib/tslib.js
new file mode 100644
index 00000000..228e6a2a
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/tslib/tslib.js
@@ -0,0 +1,317 @@
+/******************************************************************************
+Copyright (c) Microsoft Corporation.
+
+Permission to use, copy, modify, and/or distribute this software for any
+purpose with or without fee is hereby granted.
+
+THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
+REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
+AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
+INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
+LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
+OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
+PERFORMANCE OF THIS SOFTWARE.
+***************************************************************************** */
+/* global global, define, System, Reflect, Promise */
+var __extends;
+var __assign;
+var __rest;
+var __decorate;
+var __param;
+var __metadata;
+var __awaiter;
+var __generator;
+var __exportStar;
+var __values;
+var __read;
+var __spread;
+var __spreadArrays;
+var __spreadArray;
+var __await;
+var __asyncGenerator;
+var __asyncDelegator;
+var __asyncValues;
+var __makeTemplateObject;
+var __importStar;
+var __importDefault;
+var __classPrivateFieldGet;
+var __classPrivateFieldSet;
+var __classPrivateFieldIn;
+var __createBinding;
+(function (factory) {
+ var root = typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : {};
+ if (typeof define === "function" && define.amd) {
+ define("tslib", ["exports"], function (exports) { factory(createExporter(root, createExporter(exports))); });
+ }
+ else if (typeof module === "object" && typeof module.exports === "object") {
+ factory(createExporter(root, createExporter(module.exports)));
+ }
+ else {
+ factory(createExporter(root));
+ }
+ function createExporter(exports, previous) {
+ if (exports !== root) {
+ if (typeof Object.create === "function") {
+ Object.defineProperty(exports, "__esModule", { value: true });
+ }
+ else {
+ exports.__esModule = true;
+ }
+ }
+ return function (id, v) { return exports[id] = previous ? previous(id, v) : v; };
+ }
+})
+(function (exporter) {
+ var extendStatics = Object.setPrototypeOf ||
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
+ function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
+
+ __extends = function (d, b) {
+ if (typeof b !== "function" && b !== null)
+ throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
+ extendStatics(d, b);
+ function __() { this.constructor = d; }
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+ };
+
+ __assign = Object.assign || function (t) {
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
+ s = arguments[i];
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
+ }
+ return t;
+ };
+
+ __rest = function (s, e) {
+ var t = {};
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
+ t[p] = s[p];
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
+ t[p[i]] = s[p[i]];
+ }
+ return t;
+ };
+
+ __decorate = function (decorators, target, key, desc) {
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
+ };
+
+ __param = function (paramIndex, decorator) {
+ return function (target, key) { decorator(target, key, paramIndex); }
+ };
+
+ __metadata = function (metadataKey, metadataValue) {
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
+ };
+
+ __awaiter = function (thisArg, _arguments, P, generator) {
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
+ return new (P || (P = Promise))(function (resolve, reject) {
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
+ });
+ };
+
+ __generator = function (thisArg, body) {
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
+ function verb(n) { return function (v) { return step([n, v]); }; }
+ function step(op) {
+ if (f) throw new TypeError("Generator is already executing.");
+ while (_) try {
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
+ if (y = 0, t) op = [op[0] & 2, t.value];
+ switch (op[0]) {
+ case 0: case 1: t = op; break;
+ case 4: _.label++; return { value: op[1], done: false };
+ case 5: _.label++; y = op[1]; op = [0]; continue;
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
+ default:
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
+ if (t[2]) _.ops.pop();
+ _.trys.pop(); continue;
+ }
+ op = body.call(thisArg, _);
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
+ }
+ };
+
+ __exportStar = function(m, o) {
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);
+ };
+
+ __createBinding = Object.create ? (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ var desc = Object.getOwnPropertyDescriptor(m, k);
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+ desc = { enumerable: true, get: function() { return m[k]; } };
+ }
+ Object.defineProperty(o, k2, desc);
+ }) : (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ o[k2] = m[k];
+ });
+
+ __values = function (o) {
+ var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
+ if (m) return m.call(o);
+ if (o && typeof o.length === "number") return {
+ next: function () {
+ if (o && i >= o.length) o = void 0;
+ return { value: o && o[i++], done: !o };
+ }
+ };
+ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
+ };
+
+ __read = function (o, n) {
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
+ if (!m) return o;
+ var i = m.call(o), r, ar = [], e;
+ try {
+ while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
+ }
+ catch (error) { e = { error: error }; }
+ finally {
+ try {
+ if (r && !r.done && (m = i["return"])) m.call(i);
+ }
+ finally { if (e) throw e.error; }
+ }
+ return ar;
+ };
+
+ /** @deprecated */
+ __spread = function () {
+ for (var ar = [], i = 0; i < arguments.length; i++)
+ ar = ar.concat(__read(arguments[i]));
+ return ar;
+ };
+
+ /** @deprecated */
+ __spreadArrays = function () {
+ for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
+ for (var r = Array(s), k = 0, i = 0; i < il; i++)
+ for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
+ r[k] = a[j];
+ return r;
+ };
+
+ __spreadArray = function (to, from, pack) {
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
+ if (ar || !(i in from)) {
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
+ ar[i] = from[i];
+ }
+ }
+ return to.concat(ar || Array.prototype.slice.call(from));
+ };
+
+ __await = function (v) {
+ return this instanceof __await ? (this.v = v, this) : new __await(v);
+ };
+
+ __asyncGenerator = function (thisArg, _arguments, generator) {
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
+ var g = generator.apply(thisArg, _arguments || []), i, q = [];
+ return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
+ function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
+ function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
+ function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
+ function fulfill(value) { resume("next", value); }
+ function reject(value) { resume("throw", value); }
+ function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
+ };
+
+ __asyncDelegator = function (o) {
+ var i, p;
+ return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
+ function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; }
+ };
+
+ __asyncValues = function (o) {
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
+ var m = o[Symbol.asyncIterator], i;
+ return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
+ function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
+ function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
+ };
+
+ __makeTemplateObject = function (cooked, raw) {
+ if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
+ return cooked;
+ };
+
+ var __setModuleDefault = Object.create ? (function(o, v) {
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
+ }) : function(o, v) {
+ o["default"] = v;
+ };
+
+ __importStar = function (mod) {
+ if (mod && mod.__esModule) return mod;
+ var result = {};
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
+ __setModuleDefault(result, mod);
+ return result;
+ };
+
+ __importDefault = function (mod) {
+ return (mod && mod.__esModule) ? mod : { "default": mod };
+ };
+
+ __classPrivateFieldGet = function (receiver, state, kind, f) {
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
+ };
+
+ __classPrivateFieldSet = function (receiver, state, value, kind, f) {
+ if (kind === "m") throw new TypeError("Private method is not writable");
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
+ };
+
+ __classPrivateFieldIn = function (state, receiver) {
+ if (receiver === null || (typeof receiver !== "object" && typeof receiver !== "function")) throw new TypeError("Cannot use 'in' operator on non-object");
+ return typeof state === "function" ? receiver === state : state.has(receiver);
+ };
+
+ exporter("__extends", __extends);
+ exporter("__assign", __assign);
+ exporter("__rest", __rest);
+ exporter("__decorate", __decorate);
+ exporter("__param", __param);
+ exporter("__metadata", __metadata);
+ exporter("__awaiter", __awaiter);
+ exporter("__generator", __generator);
+ exporter("__exportStar", __exportStar);
+ exporter("__createBinding", __createBinding);
+ exporter("__values", __values);
+ exporter("__read", __read);
+ exporter("__spread", __spread);
+ exporter("__spreadArrays", __spreadArrays);
+ exporter("__spreadArray", __spreadArray);
+ exporter("__await", __await);
+ exporter("__asyncGenerator", __asyncGenerator);
+ exporter("__asyncDelegator", __asyncDelegator);
+ exporter("__asyncValues", __asyncValues);
+ exporter("__makeTemplateObject", __makeTemplateObject);
+ exporter("__importStar", __importStar);
+ exporter("__importDefault", __importDefault);
+ exporter("__classPrivateFieldGet", __classPrivateFieldGet);
+ exporter("__classPrivateFieldSet", __classPrivateFieldSet);
+ exporter("__classPrivateFieldIn", __classPrivateFieldIn);
+});
diff --git a/temporary_modules/trezor-connect/node_modules/universalify/LICENSE b/temporary_modules/trezor-connect/node_modules/universalify/LICENSE
new file mode 100644
index 00000000..514e84e6
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/universalify/LICENSE
@@ -0,0 +1,20 @@
+(The MIT License)
+
+Copyright (c) 2017, Ryan Zimmerman
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of
+this software and associated documentation files (the 'Software'), to deal in
+the Software without restriction, including without limitation the rights to
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software is furnished to do so,
+subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
+FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
+COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
+IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
+CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/temporary_modules/trezor-connect/node_modules/universalify/README.md b/temporary_modules/trezor-connect/node_modules/universalify/README.md
new file mode 100644
index 00000000..aa124747
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/universalify/README.md
@@ -0,0 +1,76 @@
+# universalify
+
+[](https://travis-ci.org/RyanZim/universalify)
+
+
+
+
+Make a callback- or promise-based function support both promises and callbacks.
+
+Uses the native promise implementation.
+
+## Installation
+
+```bash
+npm install universalify
+```
+
+## API
+
+### `universalify.fromCallback(fn)`
+
+Takes a callback-based function to universalify, and returns the universalified function.
+
+Function must take a callback as the last parameter that will be called with the signature `(error, result)`. `universalify` does not support calling the callback with three or more arguments, and does not ensure that the callback is only called once.
+
+```js
+function callbackFn (n, cb) {
+ setTimeout(() => cb(null, n), 15)
+}
+
+const fn = universalify.fromCallback(callbackFn)
+
+// Works with Promises:
+fn('Hello World!')
+.then(result => console.log(result)) // -> Hello World!
+.catch(error => console.error(error))
+
+// Works with Callbacks:
+fn('Hi!', (error, result) => {
+ if (error) return console.error(error)
+ console.log(result)
+ // -> Hi!
+})
+```
+
+### `universalify.fromPromise(fn)`
+
+Takes a promise-based function to universalify, and returns the universalified function.
+
+Function must return a valid JS promise. `universalify` does not ensure that a valid promise is returned.
+
+```js
+function promiseFn (n) {
+ return new Promise(resolve => {
+ setTimeout(() => resolve(n), 15)
+ })
+}
+
+const fn = universalify.fromPromise(promiseFn)
+
+// Works with Promises:
+fn('Hello World!')
+.then(result => console.log(result)) // -> Hello World!
+.catch(error => console.error(error))
+
+// Works with Callbacks:
+fn('Hi!', (error, result) => {
+ if (error) return console.error(error)
+ console.log(result)
+ // -> Hi!
+})
+```
+
+## License
+
+MIT
diff --git a/temporary_modules/trezor-connect/node_modules/universalify/index.js b/temporary_modules/trezor-connect/node_modules/universalify/index.js
new file mode 100644
index 00000000..ba6c6626
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/universalify/index.js
@@ -0,0 +1,24 @@
+'use strict'
+
+exports.fromCallback = function (fn) {
+ return Object.defineProperty(function (...args) {
+ if (typeof args[args.length - 1] === 'function') fn.apply(this, args)
+ else {
+ return new Promise((resolve, reject) => {
+ fn.call(
+ this,
+ ...args,
+ (err, res) => (err != null) ? reject(err) : resolve(res)
+ )
+ })
+ }
+ }, 'name', { value: fn.name })
+}
+
+exports.fromPromise = function (fn) {
+ return Object.defineProperty(function (...args) {
+ const cb = args[args.length - 1]
+ if (typeof cb !== 'function') return fn.apply(this, args)
+ else fn.apply(this, args.slice(0, -1)).then(r => cb(null, r), cb)
+ }, 'name', { value: fn.name })
+}
diff --git a/temporary_modules/trezor-connect/node_modules/universalify/package.json b/temporary_modules/trezor-connect/node_modules/universalify/package.json
new file mode 100644
index 00000000..006d4cc7
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/universalify/package.json
@@ -0,0 +1,34 @@
+{
+ "name": "universalify",
+ "version": "2.0.0",
+ "description": "Make a callback- or promise-based function support both promises and callbacks.",
+ "keywords": [
+ "callback",
+ "native",
+ "promise"
+ ],
+ "homepage": "https://github.com/RyanZim/universalify#readme",
+ "bugs": "https://github.com/RyanZim/universalify/issues",
+ "license": "MIT",
+ "author": "Ryan Zimmerman ",
+ "files": [
+ "index.js"
+ ],
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/RyanZim/universalify.git"
+ },
+ "scripts": {
+ "test": "standard && nyc tape test/*.js | colortape"
+ },
+ "devDependencies": {
+ "colortape": "^0.1.2",
+ "coveralls": "^3.0.1",
+ "nyc": "^15.0.0",
+ "standard": "^14.3.1",
+ "tape": "^5.0.1"
+ },
+ "engines": {
+ "node": ">= 10.0.0"
+ }
+}
diff --git a/temporary_modules/trezor-connect/node_modules/untildify/index.d.ts b/temporary_modules/trezor-connect/node_modules/untildify/index.d.ts
new file mode 100644
index 00000000..8672d9fa
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/untildify/index.d.ts
@@ -0,0 +1,14 @@
+/**
+Convert a tilde path to an absolute path: `~/dev` → `/Users/sindresorhus/dev`.
+
+@example
+```
+import untildify = require('untildify');
+
+untildify('~/dev');
+//=> '/Users/sindresorhus/dev'
+```
+*/
+declare function untildify(pathWithTilde: string): string;
+
+export = untildify;
diff --git a/temporary_modules/trezor-connect/node_modules/untildify/index.js b/temporary_modules/trezor-connect/node_modules/untildify/index.js
new file mode 100644
index 00000000..c82d3c1e
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/untildify/index.js
@@ -0,0 +1,12 @@
+'use strict';
+const os = require('os');
+
+const homeDirectory = os.homedir();
+
+module.exports = pathWithTilde => {
+ if (typeof pathWithTilde !== 'string') {
+ throw new TypeError(`Expected a string, got ${typeof pathWithTilde}`);
+ }
+
+ return homeDirectory ? pathWithTilde.replace(/^~(?=$|\/|\\)/, homeDirectory) : pathWithTilde;
+};
diff --git a/temporary_modules/trezor-connect/node_modules/untildify/license b/temporary_modules/trezor-connect/node_modules/untildify/license
new file mode 100644
index 00000000..e7af2f77
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/untildify/license
@@ -0,0 +1,9 @@
+MIT License
+
+Copyright (c) Sindre Sorhus (sindresorhus.com)
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/temporary_modules/trezor-connect/node_modules/untildify/package.json b/temporary_modules/trezor-connect/node_modules/untildify/package.json
new file mode 100644
index 00000000..bc70c68c
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/untildify/package.json
@@ -0,0 +1,43 @@
+{
+ "name": "untildify",
+ "version": "4.0.0",
+ "description": "Convert a tilde path to an absolute path: `~/dev` → `/Users/sindresorhus/dev`",
+ "license": "MIT",
+ "repository": "sindresorhus/untildify",
+ "author": {
+ "name": "Sindre Sorhus",
+ "email": "sindresorhus@gmail.com",
+ "url": "sindresorhus.com"
+ },
+ "contributors": [
+ "silverwind (https://silverwind.io)"
+ ],
+ "engines": {
+ "node": ">=8"
+ },
+ "scripts": {
+ "test": "xo && ava && tsd"
+ },
+ "files": [
+ "index.js",
+ "index.d.ts"
+ ],
+ "keywords": [
+ "tilde",
+ "expansion",
+ "expand",
+ "untildify",
+ "path",
+ "home",
+ "directory",
+ "user",
+ "shell",
+ "bash"
+ ],
+ "devDependencies": {
+ "ava": "^1.4.1",
+ "rewire": "^4.0.1",
+ "tsd": "^0.7.2",
+ "xo": "^0.24.0"
+ }
+}
diff --git a/temporary_modules/trezor-connect/node_modules/untildify/readme.md b/temporary_modules/trezor-connect/node_modules/untildify/readme.md
new file mode 100644
index 00000000..5f38db2b
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/untildify/readme.md
@@ -0,0 +1,30 @@
+# untildify [](https://travis-ci.org/sindresorhus/untildify)
+
+> Convert a tilde path to an absolute path: `~/dev` → `/Users/sindresorhus/dev`
+
+
+## Install
+
+```
+$ npm install untildify
+```
+
+
+## Usage
+
+```js
+const untildify = require('untildify');
+
+untildify('~/dev');
+//=> '/Users/sindresorhus/dev'
+```
+
+
+## Related
+
+See [tildify](https://github.com/sindresorhus/tildify) for the inverse.
+
+
+## License
+
+MIT © [Sindre Sorhus](https://sindresorhus.com)
diff --git a/temporary_modules/trezor-connect/node_modules/util-deprecate/History.md b/temporary_modules/trezor-connect/node_modules/util-deprecate/History.md
new file mode 100644
index 00000000..acc86753
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/util-deprecate/History.md
@@ -0,0 +1,16 @@
+
+1.0.2 / 2015-10-07
+==================
+
+ * use try/catch when checking `localStorage` (#3, @kumavis)
+
+1.0.1 / 2014-11-25
+==================
+
+ * browser: use `console.warn()` for deprecation calls
+ * browser: more jsdocs
+
+1.0.0 / 2014-04-30
+==================
+
+ * initial commit
diff --git a/temporary_modules/trezor-connect/node_modules/util-deprecate/LICENSE b/temporary_modules/trezor-connect/node_modules/util-deprecate/LICENSE
new file mode 100644
index 00000000..6a60e8c2
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/util-deprecate/LICENSE
@@ -0,0 +1,24 @@
+(The MIT License)
+
+Copyright (c) 2014 Nathan Rajlich
+
+Permission is hereby granted, free of charge, to any person
+obtaining a copy of this software and associated documentation
+files (the "Software"), to deal in the Software without
+restriction, including without limitation the rights to use,
+copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the
+Software is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
+OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+OTHER DEALINGS IN THE SOFTWARE.
diff --git a/temporary_modules/trezor-connect/node_modules/util-deprecate/README.md b/temporary_modules/trezor-connect/node_modules/util-deprecate/README.md
new file mode 100644
index 00000000..75622fa7
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/util-deprecate/README.md
@@ -0,0 +1,53 @@
+util-deprecate
+==============
+### The Node.js `util.deprecate()` function with browser support
+
+In Node.js, this module simply re-exports the `util.deprecate()` function.
+
+In the web browser (i.e. via browserify), a browser-specific implementation
+of the `util.deprecate()` function is used.
+
+
+## API
+
+A `deprecate()` function is the only thing exposed by this module.
+
+``` javascript
+// setup:
+exports.foo = deprecate(foo, 'foo() is deprecated, use bar() instead');
+
+
+// users see:
+foo();
+// foo() is deprecated, use bar() instead
+foo();
+foo();
+```
+
+
+## License
+
+(The MIT License)
+
+Copyright (c) 2014 Nathan Rajlich
+
+Permission is hereby granted, free of charge, to any person
+obtaining a copy of this software and associated documentation
+files (the "Software"), to deal in the Software without
+restriction, including without limitation the rights to use,
+copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the
+Software is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
+OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+OTHER DEALINGS IN THE SOFTWARE.
diff --git a/temporary_modules/trezor-connect/node_modules/util-deprecate/browser.js b/temporary_modules/trezor-connect/node_modules/util-deprecate/browser.js
new file mode 100644
index 00000000..549ae2f0
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/util-deprecate/browser.js
@@ -0,0 +1,67 @@
+
+/**
+ * Module exports.
+ */
+
+module.exports = deprecate;
+
+/**
+ * Mark that a method should not be used.
+ * Returns a modified function which warns once by default.
+ *
+ * If `localStorage.noDeprecation = true` is set, then it is a no-op.
+ *
+ * If `localStorage.throwDeprecation = true` is set, then deprecated functions
+ * will throw an Error when invoked.
+ *
+ * If `localStorage.traceDeprecation = true` is set, then deprecated functions
+ * will invoke `console.trace()` instead of `console.error()`.
+ *
+ * @param {Function} fn - the function to deprecate
+ * @param {String} msg - the string to print to the console when `fn` is invoked
+ * @returns {Function} a new "deprecated" version of `fn`
+ * @api public
+ */
+
+function deprecate (fn, msg) {
+ if (config('noDeprecation')) {
+ return fn;
+ }
+
+ var warned = false;
+ function deprecated() {
+ if (!warned) {
+ if (config('throwDeprecation')) {
+ throw new Error(msg);
+ } else if (config('traceDeprecation')) {
+ console.trace(msg);
+ } else {
+ console.warn(msg);
+ }
+ warned = true;
+ }
+ return fn.apply(this, arguments);
+ }
+
+ return deprecated;
+}
+
+/**
+ * Checks `localStorage` for boolean values for the given `name`.
+ *
+ * @param {String} name
+ * @returns {Boolean}
+ * @api private
+ */
+
+function config (name) {
+ // accessing global.localStorage can trigger a DOMException in sandboxed iframes
+ try {
+ if (!global.localStorage) return false;
+ } catch (_) {
+ return false;
+ }
+ var val = global.localStorage[name];
+ if (null == val) return false;
+ return String(val).toLowerCase() === 'true';
+}
diff --git a/temporary_modules/trezor-connect/node_modules/util-deprecate/node.js b/temporary_modules/trezor-connect/node_modules/util-deprecate/node.js
new file mode 100644
index 00000000..5e6fcff5
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/util-deprecate/node.js
@@ -0,0 +1,6 @@
+
+/**
+ * For Node.js, simply re-export the core `util.deprecate` function.
+ */
+
+module.exports = require('util').deprecate;
diff --git a/temporary_modules/trezor-connect/node_modules/util-deprecate/package.json b/temporary_modules/trezor-connect/node_modules/util-deprecate/package.json
new file mode 100644
index 00000000..2e79f89a
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/util-deprecate/package.json
@@ -0,0 +1,27 @@
+{
+ "name": "util-deprecate",
+ "version": "1.0.2",
+ "description": "The Node.js `util.deprecate()` function with browser support",
+ "main": "node.js",
+ "browser": "browser.js",
+ "scripts": {
+ "test": "echo \"Error: no test specified\" && exit 1"
+ },
+ "repository": {
+ "type": "git",
+ "url": "git://github.com/TooTallNate/util-deprecate.git"
+ },
+ "keywords": [
+ "util",
+ "deprecate",
+ "browserify",
+ "browser",
+ "node"
+ ],
+ "author": "Nathan Rajlich (http://n8.io/)",
+ "license": "MIT",
+ "bugs": {
+ "url": "https://github.com/TooTallNate/util-deprecate/issues"
+ },
+ "homepage": "https://github.com/TooTallNate/util-deprecate"
+}
diff --git a/temporary_modules/trezor-connect/node_modules/whatwg-fetch/LICENSE b/temporary_modules/trezor-connect/node_modules/whatwg-fetch/LICENSE
new file mode 100644
index 00000000..0e319d55
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/whatwg-fetch/LICENSE
@@ -0,0 +1,20 @@
+Copyright (c) 2014-2016 GitHub, Inc.
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/temporary_modules/trezor-connect/node_modules/whatwg-fetch/README.md b/temporary_modules/trezor-connect/node_modules/whatwg-fetch/README.md
new file mode 100644
index 00000000..bfa29ac9
--- /dev/null
+++ b/temporary_modules/trezor-connect/node_modules/whatwg-fetch/README.md
@@ -0,0 +1,354 @@
+# window.fetch polyfill
+
+The `fetch()` function is a Promise-based mechanism for programmatically making
+web requests in the browser. This project is a polyfill that implements a subset
+of the standard [Fetch specification][], enough to make `fetch` a viable
+replacement for most uses of XMLHttpRequest in traditional web applications.
+
+## Table of Contents
+
+* [Read this first](#read-this-first)
+* [Installation](#installation)
+* [Usage](#usage)
+ * [Importing](#importing)
+ * [HTML](#html)
+ * [JSON](#json)
+ * [Response metadata](#response-metadata)
+ * [Post form](#post-form)
+ * [Post JSON](#post-json)
+ * [File upload](#file-upload)
+ * [Caveats](#caveats)
+ * [Handling HTTP error statuses](#handling-http-error-statuses)
+ * [Sending cookies](#sending-cookies)
+ * [Receiving cookies](#receiving-cookies)
+ * [Redirect modes](#redirect-modes)
+ * [Obtaining the Response URL](#obtaining-the-response-url)
+ * [Aborting requests](#aborting-requests)
+* [Browser Support](#browser-support)
+
+## Read this first
+
+* If you believe you found a bug with how `fetch` behaves in your browser,
+ please **don't open an issue in this repository** unless you are testing in
+ an old version of a browser that doesn't support `window.fetch` natively.
+ Make sure you read this _entire_ readme, especially the [Caveats](#caveats)
+ section, as there's probably a known work-around for an issue you've found.
+ This project is a _polyfill_, and since all modern browsers now implement the
+ `fetch` function natively, **no code from this project** actually takes any
+ effect there. See [Browser support](#browser-support) for detailed
+ information.
+
+* If you have trouble **making a request to another domain** (a different
+ subdomain or port number also constitutes another domain), please familiarize
+ yourself with all the intricacies and limitations of [CORS][] requests.
+ Because CORS requires participation of the server by implementing specific
+ HTTP response headers, it is often nontrivial to set up or debug. CORS is
+ exclusively handled by the browser's internal mechanisms which this polyfill
+ cannot influence.
+
+* This project **doesn't work under Node.js environments**. It's meant for web
+ browsers only. You should ensure that your application doesn't try to package
+ and run this on the server.
+
+* If you have an idea for a new feature of `fetch`, **submit your feature
+ requests** to the [specification's repository](https://github.com/whatwg/fetch/issues).
+ We only add features and APIs that are part of the [Fetch specification][].
+
+## Installation
+
+```
+npm install whatwg-fetch --save
+```
+
+As an alternative to using npm, you can obtain `fetch.umd.js` from the
+[Releases][] section. The UMD distribution is compatible with AMD and CommonJS
+module loaders, as well as loading directly into a page via `