diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 0000000000..d4b7310139 --- /dev/null +++ b/.prettierignore @@ -0,0 +1,3 @@ +**/bin/* +**/build/* +**/dist/* \ No newline at end of file diff --git a/.prettierrc b/.prettierrc new file mode 100644 index 0000000000..fcfb9ef5d8 --- /dev/null +++ b/.prettierrc @@ -0,0 +1,8 @@ +{ + "bracketSpacing": true, + "jsxBracketSameLine": true, + "semi": true, + "singleQuote": true, + "tabWidth": 2, + "trailingComma": "none" +} \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index 4ad74d7f8c..7a85d2f23e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -10,9 +10,9 @@ "integrity": "sha512-LIpcKm+2otOOvOvhCbD6wkNYi8aUwHk73uWR+hxBdW2EFht5D0QX89n4me8nyeNGWr5zC3Pvmjq+9MvUof+jkg==", "dev": true, "requires": { - "chalk": "2.3.0", - "esutils": "2.0.2", - "js-tokens": "3.0.2" + "chalk": "^2.0.0", + "esutils": "^2.0.2", + "js-tokens": "^3.0.0" } }, "@types/node": { @@ -29,7 +29,7 @@ "requires": { "@webassemblyjs/helper-wasm-bytecode": "1.4.3", "@webassemblyjs/wast-parser": "1.4.3", - "debug": "3.1.0", + "debug": "^3.1.0", "webassemblyjs": "1.4.3" }, "dependencies": { @@ -56,7 +56,7 @@ "integrity": "sha512-e8+KZHh+RV8MUvoSRtuT1sFXskFnWG9vbDy47Oa166xX+l0dD5sERJ21g5/tcH8Yo95e9IN3u7Jc3NbhnUcSkw==", "dev": true, "requires": { - "debug": "3.1.0" + "debug": "^3.1.0" }, "dependencies": { "debug": { @@ -101,7 +101,7 @@ "@webassemblyjs/helper-buffer": "1.4.3", "@webassemblyjs/helper-wasm-bytecode": "1.4.3", "@webassemblyjs/wasm-gen": "1.4.3", - "debug": "3.1.0" + "debug": "^3.1.0" }, "dependencies": { "debug": { @@ -121,7 +121,7 @@ "integrity": "sha512-4u0LJLSPzuRDWHwdqsrThYn+WqMFVqbI2ltNrHvZZkzFPO8XOZ0HFQ5eVc4jY/TNHgXcnwrHjONhPGYuuf//KQ==", "dev": true, "requires": { - "leb": "0.3.0" + "leb": "^0.3.0" } }, "@webassemblyjs/validation": { @@ -147,7 +147,7 @@ "@webassemblyjs/wasm-opt": "1.4.3", "@webassemblyjs/wasm-parser": "1.4.3", "@webassemblyjs/wast-printer": "1.4.3", - "debug": "3.1.0" + "debug": "^3.1.0" }, "dependencies": { "debug": { @@ -182,7 +182,7 @@ "@webassemblyjs/helper-buffer": "1.4.3", "@webassemblyjs/wasm-gen": "1.4.3", "@webassemblyjs/wasm-parser": "1.4.3", - "debug": "3.1.0" + "debug": "^3.1.0" }, "dependencies": { "debug": { @@ -219,7 +219,7 @@ "@webassemblyjs/floating-point-hex-parser": "1.4.3", "@webassemblyjs/helper-code-frame": "1.4.3", "@webassemblyjs/helper-fsm": "1.4.3", - "long": "3.2.0", + "long": "^3.2.0", "webassemblyjs": "1.4.3" } }, @@ -231,7 +231,7 @@ "requires": { "@webassemblyjs/ast": "1.4.3", "@webassemblyjs/wast-parser": "1.4.3", - "long": "3.2.0" + "long": "^3.2.0" } }, "JSONStream": { @@ -240,8 +240,8 @@ "integrity": "sha1-wQI3G27Dp887hHygDCC7D85Mbeo=", "dev": true, "requires": { - "jsonparse": "1.3.1", - "through": "2.3.8" + "jsonparse": "^1.2.0", + "through": ">=2.2.7 <3" } }, "abab": { @@ -262,7 +262,7 @@ "integrity": "sha512-zVWV8Z8lislJoOKKqdNMOB+s6+XV5WERty8MnKBeFgwA+19XJjJHs2RP5dzM57FftIs+jQnRToLiWazKr6sSWg==", "dev": true, "requires": { - "acorn": "5.3.0" + "acorn": "^5.0.0" } }, "acorn-globals": { @@ -271,7 +271,7 @@ "integrity": "sha512-KjZwU26uG3u6eZcfGbTULzFcsoz6pegNKtHPksZPOUsiKo5bUmiBPa38FuHZ/Eun+XYh/JCCkS9AS3Lu4McQOQ==", "dev": true, "requires": { - "acorn": "5.3.0" + "acorn": "^5.0.0" } }, "add-stream": { @@ -286,10 +286,10 @@ "integrity": "sha1-6yhAdG6dxIvV4GOjbj/UAMXqtak=", "dev": true, "requires": { - "co": "4.6.0", - "fast-deep-equal": "1.0.0", - "fast-json-stable-stringify": "2.0.0", - "json-schema-traverse": "0.3.1" + "co": "^4.6.0", + "fast-deep-equal": "^1.0.0", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.3.0" } }, "ajv-keywords": { @@ -304,9 +304,9 @@ "integrity": "sha1-DNkKVhCT810KmSVsIrcGlDP60Rc=", "dev": true, "requires": { - "kind-of": "3.2.2", - "longest": "1.0.1", - "repeat-string": "1.6.1" + "kind-of": "^3.0.2", + "longest": "^1.0.1", + "repeat-string": "^1.5.2" } }, "amdefine": { @@ -333,7 +333,7 @@ "integrity": "sha512-NnSOmMEYtVR2JVMIGTzynRkkaxtiq1xnFBcdQD/DnNCYPoEPsVJhM98BDyaoNOQIi7p4okdi3E27eN7GQbsUug==", "dev": true, "requires": { - "color-convert": "1.9.1" + "color-convert": "^1.9.0" } }, "anymatch": { @@ -342,8 +342,8 @@ "integrity": "sha512-0XNayC8lTHQ2OI8aljNCN3sSx6hsr/1+rlcDAotXJR7C1oZZHCNsfpbKwMjRA3Uqb5tF1Rae2oloTr4xpq+WjA==", "dev": true, "requires": { - "micromatch": "2.3.11", - "normalize-path": "2.1.1" + "micromatch": "^2.1.5", + "normalize-path": "^2.0.0" } }, "append-transform": { @@ -352,7 +352,7 @@ "integrity": "sha1-126/jKlNJ24keja61EpLdKthGZE=", "dev": true, "requires": { - "default-require-extensions": "1.0.0" + "default-require-extensions": "^1.0.0" } }, "aproba": { @@ -367,8 +367,8 @@ "integrity": "sha1-u13KOCu5TwXhUZQ3PRb9O6HKEQ0=", "dev": true, "requires": { - "delegates": "1.0.0", - "readable-stream": "2.3.3" + "delegates": "^1.0.0", + "readable-stream": "^2.0.6" } }, "argparse": { @@ -377,7 +377,7 @@ "integrity": "sha1-c9g7wmP4bpf4zE9rrhsOkKfSLIY=", "dev": true, "requires": { - "sprintf-js": "1.0.3" + "sprintf-js": "~1.0.2" } }, "arr-diff": { @@ -386,7 +386,7 @@ "integrity": "sha1-jzuCf5Vai9ZpaX5KQlasPOrjVs8=", "dev": true, "requires": { - "arr-flatten": "1.1.0" + "arr-flatten": "^1.0.1" } }, "arr-flatten": { @@ -425,7 +425,7 @@ "integrity": "sha1-mjRBDk9OPaI96jdb5b5w8kd47Dk=", "dev": true, "requires": { - "array-uniq": "1.0.3" + "array-uniq": "^1.0.1" } }, "array-uniq": { @@ -458,9 +458,9 @@ "integrity": "sha512-p32cOF5q0Zqs9uBiONKYLm6BClCoBCM5O9JfeUSlnQLBTxYdTK+pW+nXflm8UkKd2UYlEbYz5qEi0JuZR9ckSw==", "dev": true, "requires": { - "bn.js": "4.11.8", - "inherits": "2.0.3", - "minimalistic-assert": "1.0.1" + "bn.js": "^4.0.0", + "inherits": "^2.0.1", + "minimalistic-assert": "^1.0.0" } }, "assert": { @@ -496,7 +496,7 @@ "integrity": "sha512-xAfGg1/NTLBBKlHFmnd7PlmUW9KhVQIUuSrYem9xzFUZy13ScvtyGGejaae9iAVRiRq9+Cx7DPFaAAhCpyxyPw==", "dev": true, "requires": { - "lodash": "4.17.4" + "lodash": "^4.14.0" } }, "async-each": { @@ -535,9 +535,9 @@ "integrity": "sha1-Y/1D99weO7fONZR9uP42mj9Yx0s=", "dev": true, "requires": { - "chalk": "1.1.3", - "esutils": "2.0.2", - "js-tokens": "3.0.2" + "chalk": "^1.1.3", + "esutils": "^2.0.2", + "js-tokens": "^3.0.2" }, "dependencies": { "ansi-styles": { @@ -552,11 +552,11 @@ "integrity": "sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg=", "dev": true, "requires": { - "ansi-styles": "2.2.1", - "escape-string-regexp": "1.0.5", - "has-ansi": "2.0.0", - "strip-ansi": "3.0.1", - "supports-color": "2.0.0" + "ansi-styles": "^2.2.1", + "escape-string-regexp": "^1.0.2", + "has-ansi": "^2.0.0", + "strip-ansi": "^3.0.0", + "supports-color": "^2.0.0" } }, "strip-ansi": { @@ -565,7 +565,7 @@ "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", "dev": true, "requires": { - "ansi-regex": "2.1.1" + "ansi-regex": "^2.0.0" } }, "supports-color": { @@ -582,25 +582,25 @@ "integrity": "sha1-rzL3izGm/O8RnIew/Y2XU/A6C7g=", "dev": true, "requires": { - "babel-code-frame": "6.26.0", - "babel-generator": "6.26.0", - "babel-helpers": "6.24.1", - "babel-messages": "6.23.0", - "babel-register": "6.26.0", - "babel-runtime": "6.26.0", - "babel-template": "6.26.0", - "babel-traverse": "6.26.0", - "babel-types": "6.26.0", - "babylon": "6.18.0", - "convert-source-map": "1.5.1", - "debug": "2.6.9", - "json5": "0.5.1", - "lodash": "4.17.4", - "minimatch": "3.0.4", - "path-is-absolute": "1.0.1", - "private": "0.1.8", - "slash": "1.0.0", - "source-map": "0.5.7" + "babel-code-frame": "^6.26.0", + "babel-generator": "^6.26.0", + "babel-helpers": "^6.24.1", + "babel-messages": "^6.23.0", + "babel-register": "^6.26.0", + "babel-runtime": "^6.26.0", + "babel-template": "^6.26.0", + "babel-traverse": "^6.26.0", + "babel-types": "^6.26.0", + "babylon": "^6.18.0", + "convert-source-map": "^1.5.0", + "debug": "^2.6.8", + "json5": "^0.5.1", + "lodash": "^4.17.4", + "minimatch": "^3.0.4", + "path-is-absolute": "^1.0.1", + "private": "^0.1.7", + "slash": "^1.0.0", + "source-map": "^0.5.6" } }, "babel-generator": { @@ -609,14 +609,14 @@ "integrity": "sha1-rBriAHC3n248odMmlhMFN3TyDcU=", "dev": true, "requires": { - "babel-messages": "6.23.0", - "babel-runtime": "6.26.0", - "babel-types": "6.26.0", - "detect-indent": "4.0.0", - "jsesc": "1.3.0", - "lodash": "4.17.4", - "source-map": "0.5.7", - "trim-right": "1.0.1" + "babel-messages": "^6.23.0", + "babel-runtime": "^6.26.0", + "babel-types": "^6.26.0", + "detect-indent": "^4.0.0", + "jsesc": "^1.3.0", + "lodash": "^4.17.4", + "source-map": "^0.5.6", + "trim-right": "^1.0.1" } }, "babel-helpers": { @@ -625,8 +625,8 @@ "integrity": "sha1-NHHenK7DiOXIUOWX5Yom3fN2ArI=", "dev": true, "requires": { - "babel-runtime": "6.26.0", - "babel-template": "6.26.0" + "babel-runtime": "^6.22.0", + "babel-template": "^6.24.1" } }, "babel-jest": { @@ -635,8 +635,8 @@ "integrity": "sha512-BgSjmtl3mW3i+VeVHEr9d2zFSAT66G++pJcHQiUjd00pkW+voYXFctIm/indcqOWWXw5a1nUpR1XWszD9fJ1qg==", "dev": true, "requires": { - "babel-plugin-istanbul": "4.1.5", - "babel-preset-jest": "22.4.3" + "babel-plugin-istanbul": "^4.1.5", + "babel-preset-jest": "^22.4.3" } }, "babel-messages": { @@ -645,7 +645,7 @@ "integrity": "sha1-8830cDhYA1sqKVHG7F7fbGLyYw4=", "dev": true, "requires": { - "babel-runtime": "6.26.0" + "babel-runtime": "^6.22.0" } }, "babel-plugin-istanbul": { @@ -654,9 +654,9 @@ "integrity": "sha1-Z2DN2Xf0EdPhdbsGTyvDJ9mbK24=", "dev": true, "requires": { - "find-up": "2.1.0", - "istanbul-lib-instrument": "1.9.1", - "test-exclude": "4.1.1" + "find-up": "^2.1.0", + "istanbul-lib-instrument": "^1.7.5", + "test-exclude": "^4.1.1" } }, "babel-plugin-jest-hoist": { @@ -677,8 +677,8 @@ "integrity": "sha512-a+M3LTEXTq3gxv0uBN9Qm6ahUl7a8pj923nFbCUdqFUSsf3YrX8Uc+C3MEwji5Af3LiQjSC7w4ooYewlz8HRTA==", "dev": true, "requires": { - "babel-plugin-jest-hoist": "22.4.3", - "babel-plugin-syntax-object-rest-spread": "6.13.0" + "babel-plugin-jest-hoist": "^22.4.3", + "babel-plugin-syntax-object-rest-spread": "^6.13.0" } }, "babel-register": { @@ -687,13 +687,13 @@ "integrity": "sha1-btAhFz4vy0htestFxgCahW9kcHE=", "dev": true, "requires": { - "babel-core": "6.26.0", - "babel-runtime": "6.26.0", - "core-js": "2.5.3", - "home-or-tmp": "2.0.0", - "lodash": "4.17.4", - "mkdirp": "0.5.1", - "source-map-support": "0.4.18" + "babel-core": "^6.26.0", + "babel-runtime": "^6.26.0", + "core-js": "^2.5.0", + "home-or-tmp": "^2.0.0", + "lodash": "^4.17.4", + "mkdirp": "^0.5.1", + "source-map-support": "^0.4.15" }, "dependencies": { "source-map-support": { @@ -702,7 +702,7 @@ "integrity": "sha512-try0/JqxPLF9nOjvSta7tVondkP5dwgyLDjVoyMDlmjugT2lRZ1OfsrYTkCd2hkDnJTKRbO/Rl3orm8vlsUzbA==", "dev": true, "requires": { - "source-map": "0.5.7" + "source-map": "^0.5.6" } } } @@ -713,8 +713,8 @@ "integrity": "sha1-llxwWGaOgrVde/4E/yM3vItWR/4=", "dev": true, "requires": { - "core-js": "2.5.3", - "regenerator-runtime": "0.11.1" + "core-js": "^2.4.0", + "regenerator-runtime": "^0.11.0" } }, "babel-template": { @@ -723,11 +723,11 @@ "integrity": "sha1-3gPi0WOWsGn0bdn/+FIfsaDjXgI=", "dev": true, "requires": { - "babel-runtime": "6.26.0", - "babel-traverse": "6.26.0", - "babel-types": "6.26.0", - "babylon": "6.18.0", - "lodash": "4.17.4" + "babel-runtime": "^6.26.0", + "babel-traverse": "^6.26.0", + "babel-types": "^6.26.0", + "babylon": "^6.18.0", + "lodash": "^4.17.4" } }, "babel-traverse": { @@ -736,15 +736,15 @@ "integrity": "sha1-RqnL1+3MYsjlwGTi0tjQ9ANXZu4=", "dev": true, "requires": { - "babel-code-frame": "6.26.0", - "babel-messages": "6.23.0", - "babel-runtime": "6.26.0", - "babel-types": "6.26.0", - "babylon": "6.18.0", - "debug": "2.6.9", - "globals": "9.18.0", - "invariant": "2.2.2", - "lodash": "4.17.4" + "babel-code-frame": "^6.26.0", + "babel-messages": "^6.23.0", + "babel-runtime": "^6.26.0", + "babel-types": "^6.26.0", + "babylon": "^6.18.0", + "debug": "^2.6.8", + "globals": "^9.18.0", + "invariant": "^2.2.2", + "lodash": "^4.17.4" } }, "babel-types": { @@ -753,10 +753,10 @@ "integrity": "sha1-o7Bz+Uq0nrb6Vc1lInozQ4BjJJc=", "dev": true, "requires": { - "babel-runtime": "6.26.0", - "esutils": "2.0.2", - "lodash": "4.17.4", - "to-fast-properties": "1.0.3" + "babel-runtime": "^6.26.0", + "esutils": "^2.0.2", + "lodash": "^4.17.4", + "to-fast-properties": "^1.0.3" } }, "babylon": { @@ -777,13 +777,13 @@ "integrity": "sha512-5T6P4xPgpp0YDFvSWwEZ4NoE3aM4QBQXDzmVbraCkFj8zHM+mba8SyqB5DbZWyR7mYHo6Y7BdQo3MoA4m0TeQg==", "dev": true, "requires": { - "cache-base": "1.0.1", - "class-utils": "0.3.6", - "component-emitter": "1.2.1", - "define-property": "1.0.0", - "isobject": "3.0.1", - "mixin-deep": "1.3.1", - "pascalcase": "0.1.1" + "cache-base": "^1.0.1", + "class-utils": "^0.3.5", + "component-emitter": "^1.2.1", + "define-property": "^1.0.0", + "isobject": "^3.0.1", + "mixin-deep": "^1.2.0", + "pascalcase": "^0.1.1" }, "dependencies": { "define-property": { @@ -792,7 +792,7 @@ "integrity": "sha1-dp66rz9KY6rTr56NMEybvnm/sOY=", "dev": true, "requires": { - "is-descriptor": "1.0.2" + "is-descriptor": "^1.0.0" } }, "is-accessor-descriptor": { @@ -801,7 +801,7 @@ "integrity": "sha512-m5hnHTkcVsPfqx3AKlyttIPb7J+XykHvJP2B9bZDjlhLIoEq4XoK64Vg7boZlVWYK6LUY94dYPEE7Lh0ZkZKcQ==", "dev": true, "requires": { - "kind-of": "6.0.2" + "kind-of": "^6.0.0" } }, "is-data-descriptor": { @@ -810,7 +810,7 @@ "integrity": "sha512-jbRXy1FmtAoCjQkVmIVYwuuqDFUbaOeDjmed1tOGPrsMhtJA4rD9tkgA0F1qJ3gRFRXcHYVkdeaP50Q5rE/jLQ==", "dev": true, "requires": { - "kind-of": "6.0.2" + "kind-of": "^6.0.0" } }, "is-descriptor": { @@ -819,9 +819,9 @@ "integrity": "sha512-2eis5WqQGV7peooDyLmNEPUrps9+SXX5c9pL3xEB+4e9HnGuDa7mB7kHxHw4CbqS9k1T2hOH3miL8n8WtiYVtg==", "dev": true, "requires": { - "is-accessor-descriptor": "1.0.0", - "is-data-descriptor": "1.0.0", - "kind-of": "6.0.2" + "is-accessor-descriptor": "^1.0.0", + "is-data-descriptor": "^1.0.0", + "kind-of": "^6.0.2" } }, "isobject": { @@ -851,7 +851,7 @@ "dev": true, "optional": true, "requires": { - "tweetnacl": "0.14.5" + "tweetnacl": "^0.14.3" } }, "big.js": { @@ -884,7 +884,7 @@ "integrity": "sha1-T4owBctKfjiJ90kDD9JbluAdLjE=", "dev": true, "requires": { - "hoek": "4.2.0" + "hoek": "4.x.x" } }, "brace-expansion": { @@ -893,7 +893,7 @@ "integrity": "sha1-wHshHHyVLsH479Uad+8NHTmQopI=", "dev": true, "requires": { - "balanced-match": "1.0.0", + "balanced-match": "^1.0.0", "concat-map": "0.0.1" } }, @@ -903,9 +903,9 @@ "integrity": "sha1-uneWLhLf+WnWt2cR6RS3N4V79qc=", "dev": true, "requires": { - "expand-range": "1.8.2", - "preserve": "0.2.0", - "repeat-element": "1.1.2" + "expand-range": "^1.8.1", + "preserve": "^0.2.0", + "repeat-element": "^1.1.2" } }, "brorand": { @@ -935,12 +935,12 @@ "integrity": "sha512-+7CHXqGuspUn/Sl5aO7Ea0xWGAtETPXNSAjHo48JfLdPWcMng33Xe4znFvQweqc/uzk5zSOI3H52CYnjCfb5hA==", "dev": true, "requires": { - "buffer-xor": "1.0.3", - "cipher-base": "1.0.4", - "create-hash": "1.2.0", - "evp_bytestokey": "1.0.3", - "inherits": "2.0.3", - "safe-buffer": "5.1.1" + "buffer-xor": "^1.0.3", + "cipher-base": "^1.0.0", + "create-hash": "^1.1.0", + "evp_bytestokey": "^1.0.3", + "inherits": "^2.0.1", + "safe-buffer": "^5.0.1" } }, "browserify-cipher": { @@ -949,9 +949,9 @@ "integrity": "sha512-sPhkz0ARKbf4rRQt2hTpAHqn47X3llLkUGn+xEJzLjwY8LRs2p0v7ljvI5EyoRO/mexrNunNECisZs+gw2zz1w==", "dev": true, "requires": { - "browserify-aes": "1.2.0", - "browserify-des": "1.0.1", - "evp_bytestokey": "1.0.3" + "browserify-aes": "^1.0.4", + "browserify-des": "^1.0.0", + "evp_bytestokey": "^1.0.0" } }, "browserify-des": { @@ -960,9 +960,9 @@ "integrity": "sha512-zy0Cobe3hhgpiOM32Tj7KQ3Vl91m0njwsjzZQK1L+JDf11dzP9qIvjreVinsvXrgfjhStXwUWAEpB9D7Gwmayw==", "dev": true, "requires": { - "cipher-base": "1.0.4", - "des.js": "1.0.0", - "inherits": "2.0.3" + "cipher-base": "^1.0.1", + "des.js": "^1.0.0", + "inherits": "^2.0.1" } }, "browserify-rsa": { @@ -971,8 +971,8 @@ "integrity": "sha1-IeCr+vbyApzy+vsTNWenAdQTVSQ=", "dev": true, "requires": { - "bn.js": "4.11.8", - "randombytes": "2.0.6" + "bn.js": "^4.1.0", + "randombytes": "^2.0.1" } }, "browserify-sign": { @@ -981,13 +981,13 @@ "integrity": "sha1-qk62jl17ZYuqa/alfmMMvXqT0pg=", "dev": true, "requires": { - "bn.js": "4.11.8", - "browserify-rsa": "4.0.1", - "create-hash": "1.2.0", - "create-hmac": "1.1.7", - "elliptic": "6.4.0", - "inherits": "2.0.3", - "parse-asn1": "5.1.1" + "bn.js": "^4.1.1", + "browserify-rsa": "^4.0.0", + "create-hash": "^1.1.0", + "create-hmac": "^1.1.2", + "elliptic": "^6.0.0", + "inherits": "^2.0.1", + "parse-asn1": "^5.0.0" } }, "browserify-zlib": { @@ -996,7 +996,7 @@ "integrity": "sha512-Z942RysHXmJrhqk88FmKBVq/v5tqmSkDz7p54G/MGyjMnCFFnC79XWNbg+Vta8W6Wb2qtSZTSxIGkJrRpCFEiA==", "dev": true, "requires": { - "pako": "1.0.6" + "pako": "~1.0.5" } }, "bser": { @@ -1005,7 +1005,7 @@ "integrity": "sha1-mseNPtXZFYBP2HrLFYvHlxR6Fxk=", "dev": true, "requires": { - "node-int64": "0.4.0" + "node-int64": "^0.4.0" } }, "buffer": { @@ -1014,9 +1014,9 @@ "integrity": "sha1-bRu2AbB6TvztlwlBMgkwJ8lbwpg=", "dev": true, "requires": { - "base64-js": "1.3.0", - "ieee754": "1.1.11", - "isarray": "1.0.0" + "base64-js": "^1.0.2", + "ieee754": "^1.1.4", + "isarray": "^1.0.0" } }, "buffer-xor": { @@ -1049,19 +1049,19 @@ "integrity": "sha512-Dph0MzuH+rTQzGPNT9fAnrPmMmjKfST6trxJeK7NQuHRaVw24VzPRWTmg9MpcwOVQZO0E1FBICUlFeNaKPIfHA==", "dev": true, "requires": { - "bluebird": "3.5.1", - "chownr": "1.0.1", - "glob": "7.1.2", - "graceful-fs": "4.1.11", - "lru-cache": "4.1.1", - "mississippi": "2.0.0", - "mkdirp": "0.5.1", - "move-concurrently": "1.0.1", - "promise-inflight": "1.0.1", - "rimraf": "2.6.2", - "ssri": "5.3.0", - "unique-filename": "1.1.0", - "y18n": "4.0.0" + "bluebird": "^3.5.1", + "chownr": "^1.0.1", + "glob": "^7.1.2", + "graceful-fs": "^4.1.11", + "lru-cache": "^4.1.1", + "mississippi": "^2.0.0", + "mkdirp": "^0.5.1", + "move-concurrently": "^1.0.1", + "promise-inflight": "^1.0.1", + "rimraf": "^2.6.2", + "ssri": "^5.2.4", + "unique-filename": "^1.1.0", + "y18n": "^4.0.0" }, "dependencies": { "y18n": { @@ -1078,15 +1078,15 @@ "integrity": "sha512-AKcdTnFSWATd5/GCPRxr2ChwIJ85CeyrEyjRHlKxQ56d4XJMGym0uAiKn0xbLOGOl3+yRpOTi484dVCEc5AUzQ==", "dev": true, "requires": { - "collection-visit": "1.0.0", - "component-emitter": "1.2.1", - "get-value": "2.0.6", - "has-value": "1.0.0", - "isobject": "3.0.1", - "set-value": "2.0.0", - "to-object-path": "0.3.0", - "union-value": "1.0.0", - "unset-value": "1.0.0" + "collection-visit": "^1.0.0", + "component-emitter": "^1.2.1", + "get-value": "^2.0.6", + "has-value": "^1.0.0", + "isobject": "^3.0.1", + "set-value": "^2.0.0", + "to-object-path": "^0.3.0", + "union-value": "^1.0.0", + "unset-value": "^1.0.0" }, "dependencies": { "isobject": { @@ -1116,8 +1116,8 @@ "integrity": "sha1-MIvur/3ygRkFHvodkyITyRuPkuc=", "dev": true, "requires": { - "camelcase": "2.1.1", - "map-obj": "1.0.1" + "camelcase": "^2.0.0", + "map-obj": "^1.0.0" }, "dependencies": { "camelcase": { @@ -1147,8 +1147,8 @@ "dev": true, "optional": true, "requires": { - "align-text": "0.1.4", - "lazy-cache": "1.0.4" + "align-text": "^0.1.3", + "lazy-cache": "^1.0.3" } }, "chalk": { @@ -1157,9 +1157,9 @@ "integrity": "sha512-Az5zJR2CBujap2rqXGaJKaPHyJ0IrUimvYNX+ncCy8PJP4ltOGTrHUIo097ZaL2zMeKYpiCdqDvS6zdrTFok3Q==", "dev": true, "requires": { - "ansi-styles": "3.2.0", - "escape-string-regexp": "1.0.5", - "supports-color": "4.5.0" + "ansi-styles": "^3.1.0", + "escape-string-regexp": "^1.0.5", + "supports-color": "^4.0.0" } }, "chardet": { @@ -1174,18 +1174,18 @@ "integrity": "sha512-zW8iXYZtXMx4kux/nuZVXjkLP+CyIK5Al5FHnj1OgTKGZfp4Oy6/ymtMSKFv3GD8DviEmUPmJg9eFdJ/JzudMg==", "dev": true, "requires": { - "anymatch": "2.0.0", - "async-each": "1.0.1", - "braces": "2.3.2", - "fsevents": "1.1.3", - "glob-parent": "3.1.0", - "inherits": "2.0.3", - "is-binary-path": "1.0.1", - "is-glob": "4.0.0", - "normalize-path": "2.1.1", - "path-is-absolute": "1.0.1", - "readdirp": "2.1.0", - "upath": "1.1.0" + "anymatch": "^2.0.0", + "async-each": "^1.0.0", + "braces": "^2.3.0", + "fsevents": "^1.1.2", + "glob-parent": "^3.1.0", + "inherits": "^2.0.1", + "is-binary-path": "^1.0.0", + "is-glob": "^4.0.0", + "normalize-path": "^2.1.1", + "path-is-absolute": "^1.0.0", + "readdirp": "^2.0.0", + "upath": "^1.0.0" }, "dependencies": { "anymatch": { @@ -1194,8 +1194,8 @@ "integrity": "sha512-5teOsQWABXHHBFP9y3skS5P3d/WfWXpv3FUpy+LorMrNYaT9pI4oLMQX7jzQ2KklNpGpWHzdCXTDT2Y3XGlZBw==", "dev": true, "requires": { - "micromatch": "3.1.10", - "normalize-path": "2.1.1" + "micromatch": "^3.1.4", + "normalize-path": "^2.1.1" } }, "arr-diff": { @@ -1216,16 +1216,16 @@ "integrity": "sha512-aNdbnj9P8PjdXU4ybaWLK2IF3jc/EoDYbC7AazW6to3TRsfXxscC9UXOB5iDiEQrkyIbWp2SLQda4+QAa7nc3w==", "dev": true, "requires": { - "arr-flatten": "1.1.0", - "array-unique": "0.3.2", - "extend-shallow": "2.0.1", - "fill-range": "4.0.0", - "isobject": "3.0.1", - "repeat-element": "1.1.2", - "snapdragon": "0.8.2", - "snapdragon-node": "2.1.1", - "split-string": "3.1.0", - "to-regex": "3.0.2" + "arr-flatten": "^1.1.0", + "array-unique": "^0.3.2", + "extend-shallow": "^2.0.1", + "fill-range": "^4.0.0", + "isobject": "^3.0.1", + "repeat-element": "^1.1.2", + "snapdragon": "^0.8.1", + "snapdragon-node": "^2.0.1", + "split-string": "^3.0.2", + "to-regex": "^3.0.1" }, "dependencies": { "extend-shallow": { @@ -1234,7 +1234,7 @@ "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", "dev": true, "requires": { - "is-extendable": "0.1.1" + "is-extendable": "^0.1.0" } } } @@ -1245,13 +1245,13 @@ "integrity": "sha1-t3c14xXOMPa27/D4OwQVGiJEliI=", "dev": true, "requires": { - "debug": "2.6.9", - "define-property": "0.2.5", - "extend-shallow": "2.0.1", - "posix-character-classes": "0.1.1", - "regex-not": "1.0.2", - "snapdragon": "0.8.2", - "to-regex": "3.0.2" + "debug": "^2.3.3", + "define-property": "^0.2.5", + "extend-shallow": "^2.0.1", + "posix-character-classes": "^0.1.0", + "regex-not": "^1.0.0", + "snapdragon": "^0.8.1", + "to-regex": "^3.0.1" }, "dependencies": { "define-property": { @@ -1260,7 +1260,7 @@ "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=", "dev": true, "requires": { - "is-descriptor": "0.1.6" + "is-descriptor": "^0.1.0" } }, "extend-shallow": { @@ -1269,7 +1269,7 @@ "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", "dev": true, "requires": { - "is-extendable": "0.1.1" + "is-extendable": "^0.1.0" } }, "is-accessor-descriptor": { @@ -1278,7 +1278,7 @@ "integrity": "sha1-qeEss66Nh2cn7u84Q/igiXtcmNY=", "dev": true, "requires": { - "kind-of": "3.2.2" + "kind-of": "^3.0.2" }, "dependencies": { "kind-of": { @@ -1287,7 +1287,7 @@ "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", "dev": true, "requires": { - "is-buffer": "1.1.6" + "is-buffer": "^1.1.5" } } } @@ -1298,7 +1298,7 @@ "integrity": "sha1-C17mSDiOLIYCgueT8YVv7D8wG1Y=", "dev": true, "requires": { - "kind-of": "3.2.2" + "kind-of": "^3.0.2" }, "dependencies": { "kind-of": { @@ -1307,7 +1307,7 @@ "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", "dev": true, "requires": { - "is-buffer": "1.1.6" + "is-buffer": "^1.1.5" } } } @@ -1318,9 +1318,9 @@ "integrity": "sha512-avDYr0SB3DwO9zsMov0gKCESFYqCnE4hq/4z3TdUlukEy5t9C0YRq7HLrsN52NAcqXKaepeCD0n+B0arnVG3Hg==", "dev": true, "requires": { - "is-accessor-descriptor": "0.1.6", - "is-data-descriptor": "0.1.4", - "kind-of": "5.1.0" + "is-accessor-descriptor": "^0.1.6", + "is-data-descriptor": "^0.1.4", + "kind-of": "^5.0.0" } }, "kind-of": { @@ -1337,14 +1337,14 @@ "integrity": "sha512-Nmb6QXkELsuBr24CJSkilo6UHHgbekK5UiZgfE6UHD3Eb27YC6oD+bhcT+tJ6cl8dmsgdQxnWlcry8ksBIBLpw==", "dev": true, "requires": { - "array-unique": "0.3.2", - "define-property": "1.0.0", - "expand-brackets": "2.1.4", - "extend-shallow": "2.0.1", - "fragment-cache": "0.2.1", - "regex-not": "1.0.2", - "snapdragon": "0.8.2", - "to-regex": "3.0.2" + "array-unique": "^0.3.2", + "define-property": "^1.0.0", + "expand-brackets": "^2.1.4", + "extend-shallow": "^2.0.1", + "fragment-cache": "^0.2.1", + "regex-not": "^1.0.0", + "snapdragon": "^0.8.1", + "to-regex": "^3.0.1" }, "dependencies": { "define-property": { @@ -1353,7 +1353,7 @@ "integrity": "sha1-dp66rz9KY6rTr56NMEybvnm/sOY=", "dev": true, "requires": { - "is-descriptor": "1.0.2" + "is-descriptor": "^1.0.0" } }, "extend-shallow": { @@ -1362,7 +1362,7 @@ "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", "dev": true, "requires": { - "is-extendable": "0.1.1" + "is-extendable": "^0.1.0" } } } @@ -1373,10 +1373,10 @@ "integrity": "sha1-1USBHUKPmOsGpj3EAtJAPDKMOPc=", "dev": true, "requires": { - "extend-shallow": "2.0.1", - "is-number": "3.0.0", - "repeat-string": "1.6.1", - "to-regex-range": "2.1.1" + "extend-shallow": "^2.0.1", + "is-number": "^3.0.0", + "repeat-string": "^1.6.1", + "to-regex-range": "^2.1.0" }, "dependencies": { "extend-shallow": { @@ -1385,7 +1385,7 @@ "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", "dev": true, "requires": { - "is-extendable": "0.1.1" + "is-extendable": "^0.1.0" } } } @@ -1396,8 +1396,8 @@ "integrity": "sha1-nmr2KZ2NO9K9QEMIMr0RPfkGxa4=", "dev": true, "requires": { - "is-glob": "3.1.0", - "path-dirname": "1.0.2" + "is-glob": "^3.1.0", + "path-dirname": "^1.0.0" }, "dependencies": { "is-glob": { @@ -1406,7 +1406,7 @@ "integrity": "sha1-e6WuJCF4BKxwcHuWkiVnSGzD6Eo=", "dev": true, "requires": { - "is-extglob": "2.1.1" + "is-extglob": "^2.1.0" } } } @@ -1417,7 +1417,7 @@ "integrity": "sha512-m5hnHTkcVsPfqx3AKlyttIPb7J+XykHvJP2B9bZDjlhLIoEq4XoK64Vg7boZlVWYK6LUY94dYPEE7Lh0ZkZKcQ==", "dev": true, "requires": { - "kind-of": "6.0.2" + "kind-of": "^6.0.0" } }, "is-data-descriptor": { @@ -1426,7 +1426,7 @@ "integrity": "sha512-jbRXy1FmtAoCjQkVmIVYwuuqDFUbaOeDjmed1tOGPrsMhtJA4rD9tkgA0F1qJ3gRFRXcHYVkdeaP50Q5rE/jLQ==", "dev": true, "requires": { - "kind-of": "6.0.2" + "kind-of": "^6.0.0" } }, "is-descriptor": { @@ -1435,9 +1435,9 @@ "integrity": "sha512-2eis5WqQGV7peooDyLmNEPUrps9+SXX5c9pL3xEB+4e9HnGuDa7mB7kHxHw4CbqS9k1T2hOH3miL8n8WtiYVtg==", "dev": true, "requires": { - "is-accessor-descriptor": "1.0.0", - "is-data-descriptor": "1.0.0", - "kind-of": "6.0.2" + "is-accessor-descriptor": "^1.0.0", + "is-data-descriptor": "^1.0.0", + "kind-of": "^6.0.2" } }, "is-extglob": { @@ -1452,7 +1452,7 @@ "integrity": "sha1-lSHHaEXMJhCoUgPd8ICpWML/q8A=", "dev": true, "requires": { - "is-extglob": "2.1.1" + "is-extglob": "^2.1.1" } }, "is-number": { @@ -1461,7 +1461,7 @@ "integrity": "sha1-JP1iAaR4LPUFYcgQJ2r8fRLXEZU=", "dev": true, "requires": { - "kind-of": "3.2.2" + "kind-of": "^3.0.2" }, "dependencies": { "kind-of": { @@ -1470,7 +1470,7 @@ "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", "dev": true, "requires": { - "is-buffer": "1.1.6" + "is-buffer": "^1.1.5" } } } @@ -1493,19 +1493,19 @@ "integrity": "sha512-MWikgl9n9M3w+bpsY3He8L+w9eF9338xRl8IAO5viDizwSzziFEyUzo2xrrloB64ADbTf8uA8vRqqttDTOmccg==", "dev": true, "requires": { - "arr-diff": "4.0.0", - "array-unique": "0.3.2", - "braces": "2.3.2", - "define-property": "2.0.2", - "extend-shallow": "3.0.2", - "extglob": "2.0.4", - "fragment-cache": "0.2.1", - "kind-of": "6.0.2", - "nanomatch": "1.2.9", - "object.pick": "1.3.0", - "regex-not": "1.0.2", - "snapdragon": "0.8.2", - "to-regex": "3.0.2" + "arr-diff": "^4.0.0", + "array-unique": "^0.3.2", + "braces": "^2.3.1", + "define-property": "^2.0.2", + "extend-shallow": "^3.0.2", + "extglob": "^2.0.4", + "fragment-cache": "^0.2.1", + "kind-of": "^6.0.2", + "nanomatch": "^1.2.9", + "object.pick": "^1.3.0", + "regex-not": "^1.0.0", + "snapdragon": "^0.8.1", + "to-regex": "^3.0.2" } } } @@ -1534,8 +1534,8 @@ "integrity": "sha512-Kkht5ye6ZGmwv40uUDZztayT2ThLQGfnj/T71N/XzeZeo3nf8foyW7zGTsPYkEya3m5f3cAypH+qe7YOrM1U2Q==", "dev": true, "requires": { - "inherits": "2.0.3", - "safe-buffer": "5.1.1" + "inherits": "^2.0.1", + "safe-buffer": "^5.0.1" } }, "class-utils": { @@ -1544,10 +1544,10 @@ "integrity": "sha512-qOhPa/Fj7s6TY8H8esGu5QNpMMQxz79h+urzrNYN6mn+9BnxlDGf5QZ+XeCDsxSjPqsSR56XOZOJmpeurnLMeg==", "dev": true, "requires": { - "arr-union": "3.1.0", - "define-property": "0.2.5", - "isobject": "3.0.1", - "static-extend": "0.1.2" + "arr-union": "^3.1.0", + "define-property": "^0.2.5", + "isobject": "^3.0.0", + "static-extend": "^0.1.1" }, "dependencies": { "define-property": { @@ -1556,7 +1556,7 @@ "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=", "dev": true, "requires": { - "is-descriptor": "0.1.6" + "is-descriptor": "^0.1.0" } }, "isobject": { @@ -1573,7 +1573,7 @@ "integrity": "sha1-s12sN2R5+sw+lHR9QdDQ9SOP/LU=", "dev": true, "requires": { - "restore-cursor": "2.0.0" + "restore-cursor": "^2.0.0" } }, "cli-width": { @@ -1589,8 +1589,8 @@ "dev": true, "optional": true, "requires": { - "center-align": "0.1.3", - "right-align": "0.1.3", + "center-align": "^0.1.1", + "right-align": "^0.1.1", "wordwrap": "0.0.2" }, "dependencies": { @@ -1615,8 +1615,8 @@ "integrity": "sha1-b8vamUg6j9FdfTChlspp1oii79s=", "dev": true, "requires": { - "graceful-fs": "4.1.11", - "mkdirp": "0.5.1" + "graceful-fs": "^4.1.2", + "mkdirp": "~0.5.0" } }, "co": { @@ -1637,8 +1637,8 @@ "integrity": "sha1-S8A3PBZLwykbTTaMgpzxqApZ3KA=", "dev": true, "requires": { - "map-visit": "1.0.0", - "object-visit": "1.0.1" + "map-visit": "^1.0.0", + "object-visit": "^1.0.0" } }, "color-convert": { @@ -1647,7 +1647,7 @@ "integrity": "sha512-mjGanIiwQJskCC18rPR6OmrZ6fm2Lc7PeGFYwCmy5J34wC6F1PzdGL6xeMfmgicfYcNLGuVFA3WzXtIDCQSZxQ==", "dev": true, "requires": { - "color-name": "1.1.3" + "color-name": "^1.1.1" } }, "color-name": { @@ -1662,8 +1662,8 @@ "integrity": "sha1-Rzfd8ce2mop8NAVweC6UfuyOeLs=", "dev": true, "requires": { - "strip-ansi": "3.0.1", - "wcwidth": "1.0.1" + "strip-ansi": "^3.0.0", + "wcwidth": "^1.0.0" }, "dependencies": { "strip-ansi": { @@ -1672,7 +1672,7 @@ "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", "dev": true, "requires": { - "ansi-regex": "2.1.1" + "ansi-regex": "^2.0.0" } } } @@ -1683,7 +1683,7 @@ "integrity": "sha1-k4NwpXtKUd6ix3wV1cX9+JUWQAk=", "dev": true, "requires": { - "delayed-stream": "1.0.0" + "delayed-stream": "~1.0.0" } }, "command-join": { @@ -1710,8 +1710,8 @@ "integrity": "sha1-md0LpFfh+bxyKxLAjsM+6rMfpkg=", "dev": true, "requires": { - "array-ify": "1.0.0", - "dot-prop": "3.0.0" + "array-ify": "^1.0.0", + "dot-prop": "^3.0.0" } }, "component-emitter": { @@ -1732,9 +1732,9 @@ "integrity": "sha1-CqxmL9Ur54lk1VMvaUeE5wEQrPc=", "dev": true, "requires": { - "inherits": "2.0.3", - "readable-stream": "2.3.3", - "typedarray": "0.0.6" + "inherits": "^2.0.3", + "readable-stream": "^2.2.2", + "typedarray": "^0.0.6" } }, "console-browserify": { @@ -1743,7 +1743,7 @@ "integrity": "sha1-8CQcRXMKn8YyOyBtvzjtx0HQuxA=", "dev": true, "requires": { - "date-now": "0.1.4" + "date-now": "^0.1.4" } }, "console-control-strings": { @@ -1770,16 +1770,16 @@ "integrity": "sha1-kVGmKx2O2y2CcR2r9bfPcQQfgrE=", "dev": true, "requires": { - "conventional-changelog-angular": "1.6.0", - "conventional-changelog-atom": "0.1.2", - "conventional-changelog-codemirror": "0.2.1", - "conventional-changelog-core": "1.9.5", - "conventional-changelog-ember": "0.2.10", - "conventional-changelog-eslint": "0.2.1", - "conventional-changelog-express": "0.2.1", - "conventional-changelog-jquery": "0.1.0", - "conventional-changelog-jscs": "0.1.0", - "conventional-changelog-jshint": "0.2.1" + "conventional-changelog-angular": "^1.5.2", + "conventional-changelog-atom": "^0.1.2", + "conventional-changelog-codemirror": "^0.2.1", + "conventional-changelog-core": "^1.9.3", + "conventional-changelog-ember": "^0.2.9", + "conventional-changelog-eslint": "^0.2.1", + "conventional-changelog-express": "^0.2.1", + "conventional-changelog-jquery": "^0.1.0", + "conventional-changelog-jscs": "^0.1.0", + "conventional-changelog-jshint": "^0.2.1" } }, "conventional-changelog-angular": { @@ -1788,8 +1788,8 @@ "integrity": "sha1-CiagcfLJ/PzyuGugz79uYwG3W/o=", "dev": true, "requires": { - "compare-func": "1.3.2", - "q": "1.5.1" + "compare-func": "^1.3.1", + "q": "^1.4.1" } }, "conventional-changelog-atom": { @@ -1798,7 +1798,7 @@ "integrity": "sha1-Ella1SZ6aTfDTPkAKBscZRmKTGM=", "dev": true, "requires": { - "q": "1.5.1" + "q": "^1.4.1" } }, "conventional-changelog-cli": { @@ -1807,11 +1807,11 @@ "integrity": "sha1-RsUUliFrdAZYiIPe+m+sWJ6bsx4=", "dev": true, "requires": { - "add-stream": "1.0.0", - "conventional-changelog": "1.1.7", - "lodash": "4.17.4", - "meow": "3.7.0", - "tempfile": "1.1.1" + "add-stream": "^1.0.0", + "conventional-changelog": "^1.1.7", + "lodash": "^4.1.0", + "meow": "^3.7.0", + "tempfile": "^1.1.1" } }, "conventional-changelog-codemirror": { @@ -1820,7 +1820,7 @@ "integrity": "sha1-KZpPcUe681DmyBWPxUlUopHFzAk=", "dev": true, "requires": { - "q": "1.5.1" + "q": "^1.4.1" } }, "conventional-changelog-core": { @@ -1829,19 +1829,19 @@ "integrity": "sha1-XbdWba18DLddr0f7spdve/mSjB0=", "dev": true, "requires": { - "conventional-changelog-writer": "2.0.3", - "conventional-commits-parser": "2.1.0", - "dateformat": "1.0.12", - "get-pkg-repo": "1.4.0", - "git-raw-commits": "1.3.0", - "git-remote-origin-url": "2.0.0", - "git-semver-tags": "1.2.3", - "lodash": "4.17.4", - "normalize-package-data": "2.4.0", - "q": "1.5.1", - "read-pkg": "1.1.0", - "read-pkg-up": "1.0.1", - "through2": "2.0.3" + "conventional-changelog-writer": "^2.0.3", + "conventional-commits-parser": "^2.1.0", + "dateformat": "^1.0.12", + "get-pkg-repo": "^1.0.0", + "git-raw-commits": "^1.3.0", + "git-remote-origin-url": "^2.0.0", + "git-semver-tags": "^1.2.3", + "lodash": "^4.0.0", + "normalize-package-data": "^2.3.5", + "q": "^1.4.1", + "read-pkg": "^1.1.0", + "read-pkg-up": "^1.0.1", + "through2": "^2.0.0" } }, "conventional-changelog-ember": { @@ -1850,7 +1850,7 @@ "integrity": "sha512-LBBBZO6Q7ib4HhSdyCNVR25OtaXl710UJg1aSHCLmR8AjuXKs3BO8tnbY1MH+D1C+z5IFoEDkpjOddefNTyhCQ==", "dev": true, "requires": { - "q": "1.5.1" + "q": "^1.4.1" } }, "conventional-changelog-eslint": { @@ -1859,7 +1859,7 @@ "integrity": "sha1-LCoRvrIW+AZJunKDQYApO2h8BmI=", "dev": true, "requires": { - "q": "1.5.1" + "q": "^1.4.1" } }, "conventional-changelog-express": { @@ -1868,7 +1868,7 @@ "integrity": "sha1-g42eHmyQmXA7FQucGaoteBdCvWw=", "dev": true, "requires": { - "q": "1.5.1" + "q": "^1.4.1" } }, "conventional-changelog-jquery": { @@ -1877,7 +1877,7 @@ "integrity": "sha1-Agg5cWLjhGmG5xJztsecW1+A9RA=", "dev": true, "requires": { - "q": "1.5.1" + "q": "^1.4.1" } }, "conventional-changelog-jscs": { @@ -1886,7 +1886,7 @@ "integrity": "sha1-BHnrRDzH1yxYvwvPDvHURKkvDlw=", "dev": true, "requires": { - "q": "1.5.1" + "q": "^1.4.1" } }, "conventional-changelog-jshint": { @@ -1895,8 +1895,8 @@ "integrity": "sha1-hhObs6yZiZ8rF36WF+CbN9mbzzo=", "dev": true, "requires": { - "compare-func": "1.3.2", - "q": "1.5.1" + "compare-func": "^1.3.1", + "q": "^1.4.1" } }, "conventional-changelog-writer": { @@ -1905,16 +1905,16 @@ "integrity": "sha512-2E1h7UXL0fhRO5h0CxDZ5EBc5sfBZEQePvuZ+gPvApiRrICUyNDy/NQIP+2TBd4wKZQf2Zm7TxbzXHG5HkPIbA==", "dev": true, "requires": { - "compare-func": "1.3.2", - "conventional-commits-filter": "1.1.1", - "dateformat": "1.0.12", - "handlebars": "4.0.11", - "json-stringify-safe": "5.0.1", - "lodash": "4.17.4", - "meow": "3.7.0", - "semver": "5.4.1", - "split": "1.0.1", - "through2": "2.0.3" + "compare-func": "^1.3.1", + "conventional-commits-filter": "^1.1.1", + "dateformat": "^1.0.11", + "handlebars": "^4.0.2", + "json-stringify-safe": "^5.0.1", + "lodash": "^4.0.0", + "meow": "^3.3.0", + "semver": "^5.0.1", + "split": "^1.0.0", + "through2": "^2.0.0" } }, "conventional-commits-filter": { @@ -1923,8 +1923,8 @@ "integrity": "sha512-bQyatySNKHhcaeKVr9vFxYWA1W1Tdz6ybVMYDmv4/FhOXY1+fchiW07TzRbIQZhVa4cvBwrEaEUQBbCncFSdJQ==", "dev": true, "requires": { - "is-subset": "0.1.1", - "modify-values": "1.0.0" + "is-subset": "^0.1.1", + "modify-values": "^1.0.0" } }, "conventional-commits-parser": { @@ -1933,13 +1933,13 @@ "integrity": "sha512-8MD05yN0Zb6aRsZnFX1ET+8rHWfWJk+my7ANCJZBU2mhz7TSB1fk2vZhkrwVy/PCllcTYAP/1T1NiWQ7Z01mKw==", "dev": true, "requires": { - "JSONStream": "1.3.2", - "is-text-path": "1.0.1", - "lodash": "4.17.4", - "meow": "3.7.0", - "split2": "2.2.0", - "through2": "2.0.3", - "trim-off-newlines": "1.0.1" + "JSONStream": "^1.0.4", + "is-text-path": "^1.0.0", + "lodash": "^4.2.1", + "meow": "^3.3.0", + "split2": "^2.0.0", + "through2": "^2.0.0", + "trim-off-newlines": "^1.0.0" } }, "conventional-recommended-bump": { @@ -1948,13 +1948,13 @@ "integrity": "sha512-WK0HnYnXd9e8J1YezUlfle+Pz7HB1RYvIH6gPLAXoroQTzDSfNfGM1tHHmdrJw0/4BMr+zw0U9V1WzFEfQwE3w==", "dev": true, "requires": { - "concat-stream": "1.6.0", - "conventional-commits-filter": "1.1.1", - "conventional-commits-parser": "2.1.0", - "git-raw-commits": "1.3.0", - "git-semver-tags": "1.2.3", - "meow": "3.7.0", - "object-assign": "4.1.1" + "concat-stream": "^1.4.10", + "conventional-commits-filter": "^1.1.1", + "conventional-commits-parser": "^2.1.0", + "git-raw-commits": "^1.3.0", + "git-semver-tags": "^1.2.3", + "meow": "^3.3.0", + "object-assign": "^4.0.1" } }, "convert-source-map": { @@ -1969,12 +1969,12 @@ "integrity": "sha512-f2domd9fsVDFtaFcbaRZuYXwtdmnzqbADSwhSWYxYB/Q8zsdUUFMXVRwXGDMWmbEzAn1kdRrtI1T/KTFOL4X2A==", "dev": true, "requires": { - "aproba": "1.2.0", - "fs-write-stream-atomic": "1.0.10", - "iferr": "0.1.5", - "mkdirp": "0.5.1", - "rimraf": "2.6.2", - "run-queue": "1.0.3" + "aproba": "^1.1.1", + "fs-write-stream-atomic": "^1.0.8", + "iferr": "^0.1.5", + "mkdirp": "^0.5.1", + "rimraf": "^2.5.4", + "run-queue": "^1.0.0" } }, "copy-descriptor": { @@ -2001,8 +2001,8 @@ "integrity": "sha512-GbEHQPMOswGpKXM9kCWVrremUcBmjteUaQ01T9rkKCPDXfUHX0IoP9LpHYo2NPFampa4e+/pFDc3jQdxrxQLaw==", "dev": true, "requires": { - "bn.js": "4.11.8", - "elliptic": "6.4.0" + "bn.js": "^4.1.0", + "elliptic": "^6.0.0" } }, "create-error-class": { @@ -2011,7 +2011,7 @@ "integrity": "sha1-Br56vvlHo/FKMP1hBnHUAbyot7Y=", "dev": true, "requires": { - "capture-stack-trace": "1.0.0" + "capture-stack-trace": "^1.0.0" } }, "create-hash": { @@ -2020,11 +2020,11 @@ "integrity": "sha512-z00bCGNHDG8mHAkP7CtT1qVu+bFQUPjYq/4Iv3C3kWjTFV10zIjfSoeqXo9Asws8gwSHDGj/hl2u4OGIjapeCg==", "dev": true, "requires": { - "cipher-base": "1.0.4", - "inherits": "2.0.3", - "md5.js": "1.3.4", - "ripemd160": "2.0.2", - "sha.js": "2.4.11" + "cipher-base": "^1.0.1", + "inherits": "^2.0.1", + "md5.js": "^1.3.4", + "ripemd160": "^2.0.1", + "sha.js": "^2.4.0" } }, "create-hmac": { @@ -2033,12 +2033,12 @@ "integrity": "sha512-MJG9liiZ+ogc4TzUwuvbER1JRdgvUFSB5+VR/g5h82fGaIRWMWddtKBHi7/sVhfjQZ6SehlyhvQYrcYkaUIpLg==", "dev": true, "requires": { - "cipher-base": "1.0.4", - "create-hash": "1.2.0", - "inherits": "2.0.3", - "ripemd160": "2.0.2", - "safe-buffer": "5.1.1", - "sha.js": "2.4.11" + "cipher-base": "^1.0.3", + "create-hash": "^1.1.0", + "inherits": "^2.0.1", + "ripemd160": "^2.0.0", + "safe-buffer": "^5.0.1", + "sha.js": "^2.4.8" } }, "cross-spawn": { @@ -2047,9 +2047,9 @@ "integrity": "sha1-6L0O/uWPz/b4+UUQoKVUu/ojVEk=", "dev": true, "requires": { - "lru-cache": "4.1.1", - "shebang-command": "1.2.0", - "which": "1.3.0" + "lru-cache": "^4.0.1", + "shebang-command": "^1.2.0", + "which": "^1.2.9" } }, "cryptiles": { @@ -2058,7 +2058,7 @@ "integrity": "sha1-qJ+7Ig9c4l7FboxKqKT9e1sNKf4=", "dev": true, "requires": { - "boom": "5.2.0" + "boom": "5.x.x" }, "dependencies": { "boom": { @@ -2067,7 +2067,7 @@ "integrity": "sha512-Z5BTk6ZRe4tXXQlkqftmsAUANpXmuwlsF5Oov8ThoMbQRzdGTA1ngYRW160GexgOgjsFOKJz0LYhoNi+2AMBUw==", "dev": true, "requires": { - "hoek": "4.2.0" + "hoek": "4.x.x" } } } @@ -2078,17 +2078,17 @@ "integrity": "sha512-fz4spIh+znjO2VjL+IdhEpRJ3YN6sMzITSBijk6FK2UvTqruSQW+/cCZTSNsMiZNvUeq0CqurF+dAbyiGOY6Wg==", "dev": true, "requires": { - "browserify-cipher": "1.0.1", - "browserify-sign": "4.0.4", - "create-ecdh": "4.0.3", - "create-hash": "1.2.0", - "create-hmac": "1.1.7", - "diffie-hellman": "5.0.3", - "inherits": "2.0.3", - "pbkdf2": "3.0.16", - "public-encrypt": "4.0.2", - "randombytes": "2.0.6", - "randomfill": "1.0.4" + "browserify-cipher": "^1.0.0", + "browserify-sign": "^4.0.0", + "create-ecdh": "^4.0.0", + "create-hash": "^1.1.0", + "create-hmac": "^1.1.0", + "diffie-hellman": "^5.0.0", + "inherits": "^2.0.1", + "pbkdf2": "^3.0.3", + "public-encrypt": "^4.0.0", + "randombytes": "^2.0.0", + "randomfill": "^1.0.3" } }, "cssom": { @@ -2103,7 +2103,7 @@ "integrity": "sha1-VBCXI0yyUTyDzu06zdwn/yeYfVQ=", "dev": true, "requires": { - "cssom": "0.3.2" + "cssom": "0.3.x" } }, "currently-unhandled": { @@ -2112,7 +2112,7 @@ "integrity": "sha1-mI3zP+qxke95mmE2nddsF635V+o=", "dev": true, "requires": { - "array-find-index": "1.0.2" + "array-find-index": "^1.0.1" } }, "cyclist": { @@ -2127,7 +2127,7 @@ "integrity": "sha1-A6nbtLXC8Tm/FK5T8LiipqhvThc=", "dev": true, "requires": { - "number-is-nan": "1.0.1" + "number-is-nan": "^1.0.0" } }, "dashdash": { @@ -2136,7 +2136,7 @@ "integrity": "sha1-hTz6D3y+L+1d4gMmuN1YEDX24vA=", "dev": true, "requires": { - "assert-plus": "1.0.0" + "assert-plus": "^1.0.0" } }, "date-now": { @@ -2151,8 +2151,8 @@ "integrity": "sha1-nxJLZ1lMk3/3BpMuSmQsyo27/uk=", "dev": true, "requires": { - "get-stdin": "4.0.1", - "meow": "3.7.0" + "get-stdin": "^4.0.1", + "meow": "^3.3.0" } }, "debug": { @@ -2200,7 +2200,7 @@ "integrity": "sha1-836hXT4T/9m0N9M+GnW1+5eHTLg=", "dev": true, "requires": { - "strip-bom": "2.0.0" + "strip-bom": "^2.0.0" } }, "defaults": { @@ -2209,7 +2209,7 @@ "integrity": "sha1-xlYFHpgX2f8I7YgUd/P+QBnz730=", "dev": true, "requires": { - "clone": "1.0.3" + "clone": "^1.0.2" } }, "define-properties": { @@ -2218,8 +2218,8 @@ "integrity": "sha1-g6c/L+pWmJj7c3GTyPhzyvbUXJQ=", "dev": true, "requires": { - "foreach": "2.0.5", - "object-keys": "1.0.11" + "foreach": "^2.0.5", + "object-keys": "^1.0.8" } }, "define-property": { @@ -2228,8 +2228,8 @@ "integrity": "sha512-jwK2UV4cnPpbcG7+VRARKTZPUWowwXA8bzH5NP6ud0oeAxyYPuGZUAC7hMugpCdz4BeSZl2Dl9k66CHJ/46ZYQ==", "dev": true, "requires": { - "is-descriptor": "1.0.2", - "isobject": "3.0.1" + "is-descriptor": "^1.0.2", + "isobject": "^3.0.1" }, "dependencies": { "is-accessor-descriptor": { @@ -2238,7 +2238,7 @@ "integrity": "sha512-m5hnHTkcVsPfqx3AKlyttIPb7J+XykHvJP2B9bZDjlhLIoEq4XoK64Vg7boZlVWYK6LUY94dYPEE7Lh0ZkZKcQ==", "dev": true, "requires": { - "kind-of": "6.0.2" + "kind-of": "^6.0.0" } }, "is-data-descriptor": { @@ -2247,7 +2247,7 @@ "integrity": "sha512-jbRXy1FmtAoCjQkVmIVYwuuqDFUbaOeDjmed1tOGPrsMhtJA4rD9tkgA0F1qJ3gRFRXcHYVkdeaP50Q5rE/jLQ==", "dev": true, "requires": { - "kind-of": "6.0.2" + "kind-of": "^6.0.0" } }, "is-descriptor": { @@ -2256,9 +2256,9 @@ "integrity": "sha512-2eis5WqQGV7peooDyLmNEPUrps9+SXX5c9pL3xEB+4e9HnGuDa7mB7kHxHw4CbqS9k1T2hOH3miL8n8WtiYVtg==", "dev": true, "requires": { - "is-accessor-descriptor": "1.0.0", - "is-data-descriptor": "1.0.0", - "kind-of": "6.0.2" + "is-accessor-descriptor": "^1.0.0", + "is-data-descriptor": "^1.0.0", + "kind-of": "^6.0.2" } }, "isobject": { @@ -2293,8 +2293,8 @@ "integrity": "sha1-wHTS4qpqipoH29YfmhXCzYPsjsw=", "dev": true, "requires": { - "inherits": "2.0.3", - "minimalistic-assert": "1.0.1" + "inherits": "^2.0.1", + "minimalistic-assert": "^1.0.0" } }, "detect-indent": { @@ -2303,7 +2303,7 @@ "integrity": "sha1-920GQ1LN9Docts5hnE7jqUdd4gg=", "dev": true, "requires": { - "repeating": "2.0.1" + "repeating": "^2.0.0" } }, "detect-newline": { @@ -2324,9 +2324,9 @@ "integrity": "sha512-kqag/Nl+f3GwyK25fhUMYj81BUOrZ9IuJsjIcDE5icNM9FJHAVm3VcUDxdLPoQtTuUylWm6ZIknYJwwaPxsUzg==", "dev": true, "requires": { - "bn.js": "4.11.8", - "miller-rabin": "4.0.1", - "randombytes": "2.0.6" + "bn.js": "^4.1.0", + "miller-rabin": "^4.0.0", + "randombytes": "^2.0.0" } }, "domain-browser": { @@ -2347,7 +2347,7 @@ "integrity": "sha1-G3CK8JSknJoOfbyteQq6U52sEXc=", "dev": true, "requires": { - "is-obj": "1.0.1" + "is-obj": "^1.0.0" } }, "duplexer": { @@ -2368,10 +2368,10 @@ "integrity": "sha512-fO3Di4tBKJpYTFHAxTU00BcfWMY9w24r/x21a6rZRbsD/ToUgGxsMbiGRmB7uVAXeGKXD9MwiLZa5E97EVgIRQ==", "dev": true, "requires": { - "end-of-stream": "1.4.1", - "inherits": "2.0.3", - "readable-stream": "2.3.3", - "stream-shift": "1.0.0" + "end-of-stream": "^1.0.0", + "inherits": "^2.0.1", + "readable-stream": "^2.0.0", + "stream-shift": "^1.0.0" } }, "ecc-jsbn": { @@ -2381,7 +2381,7 @@ "dev": true, "optional": true, "requires": { - "jsbn": "0.1.1" + "jsbn": "~0.1.0" } }, "elliptic": { @@ -2390,13 +2390,13 @@ "integrity": "sha1-ysmvh2LIWDYYcAPI3+GT5eLq5d8=", "dev": true, "requires": { - "bn.js": "4.11.8", - "brorand": "1.1.0", - "hash.js": "1.1.3", - "hmac-drbg": "1.0.1", - "inherits": "2.0.3", - "minimalistic-assert": "1.0.1", - "minimalistic-crypto-utils": "1.0.1" + "bn.js": "^4.4.0", + "brorand": "^1.0.1", + "hash.js": "^1.0.0", + "hmac-drbg": "^1.0.0", + "inherits": "^2.0.1", + "minimalistic-assert": "^1.0.0", + "minimalistic-crypto-utils": "^1.0.0" } }, "emojis-list": { @@ -2411,7 +2411,7 @@ "integrity": "sha512-1MkrZNvWTKCaigbn+W15elq2BB/L22nqrSY5DKlo3X6+vclJm8Bb5djXJBmEX6fS3+zCh/F4VBK5Z2KxJt4s2Q==", "dev": true, "requires": { - "once": "1.4.0" + "once": "^1.4.0" } }, "enhanced-resolve": { @@ -2420,9 +2420,9 @@ "integrity": "sha512-jox/62b2GofV1qTUQTMPEJSDIGycS43evqYzD/KVtEb9OCoki9cnacUPxCrZa7JfPzZSYOCZhu9O9luaMxAX8g==", "dev": true, "requires": { - "graceful-fs": "4.1.11", - "memory-fs": "0.4.1", - "tapable": "1.0.0" + "graceful-fs": "^4.1.2", + "memory-fs": "^0.4.0", + "tapable": "^1.0.0" } }, "errno": { @@ -2431,7 +2431,7 @@ "integrity": "sha512-MfrRBDWzIWifgq6tJj60gkAwtLNb6sQPlcFrSOflcP1aFmmruKQ2wRnze/8V6kgyz7H3FF8Npzv78mZ7XLLflg==", "dev": true, "requires": { - "prr": "1.0.1" + "prr": "~1.0.1" } }, "error-ex": { @@ -2440,7 +2440,7 @@ "integrity": "sha1-+FWobOYa3E6GIcPNoh56dhLDqNw=", "dev": true, "requires": { - "is-arrayish": "0.2.1" + "is-arrayish": "^0.2.1" } }, "es-abstract": { @@ -2449,11 +2449,11 @@ "integrity": "sha512-/uh/DhdqIOSkAWifU+8nG78vlQxdLckUdI/sPgy0VhuXi2qJ7T8czBmqIYtLQVpCIFYafChnsRsB5pyb1JdmCQ==", "dev": true, "requires": { - "es-to-primitive": "1.1.1", - "function-bind": "1.1.1", - "has": "1.0.1", - "is-callable": "1.1.3", - "is-regex": "1.0.4" + "es-to-primitive": "^1.1.1", + "function-bind": "^1.1.1", + "has": "^1.0.1", + "is-callable": "^1.1.3", + "is-regex": "^1.0.4" } }, "es-to-primitive": { @@ -2462,9 +2462,9 @@ "integrity": "sha1-RTVSSKiJeQNLZ5Lhm7gfK3l13Q0=", "dev": true, "requires": { - "is-callable": "1.1.3", - "is-date-object": "1.0.1", - "is-symbol": "1.0.1" + "is-callable": "^1.1.1", + "is-date-object": "^1.0.1", + "is-symbol": "^1.0.1" } }, "escape-string-regexp": { @@ -2479,11 +2479,11 @@ "integrity": "sha512-v0MYvNQ32bzwoG2OSFzWAkuahDQHK92JBN0pTAALJ4RIxEZe766QJPDR8Hqy7XNUy5K3fnVL76OqYAdc4TZEIw==", "dev": true, "requires": { - "esprima": "3.1.3", - "estraverse": "4.2.0", - "esutils": "2.0.2", - "optionator": "0.8.2", - "source-map": "0.5.7" + "esprima": "^3.1.3", + "estraverse": "^4.2.0", + "esutils": "^2.0.2", + "optionator": "^0.8.1", + "source-map": "~0.5.6" }, "dependencies": { "esprima": { @@ -2500,8 +2500,8 @@ "integrity": "sha1-PWPD7f2gLgbgGkUq2IyqzHzctug=", "dev": true, "requires": { - "esrecurse": "4.2.1", - "estraverse": "4.2.0" + "esrecurse": "^4.1.0", + "estraverse": "^4.1.1" } }, "esprima": { @@ -2516,7 +2516,7 @@ "integrity": "sha512-64RBB++fIOAXPw3P9cy89qfMlvZEXZkqqJkjqqXIvzP5ezRZjW+lPWjw35UX/3EhUPFYbg5ER4JYgDw4007/DQ==", "dev": true, "requires": { - "estraverse": "4.2.0" + "estraverse": "^4.1.0" } }, "estraverse": { @@ -2543,8 +2543,8 @@ "integrity": "sha512-/f2Go4TognH/KvCISP7OUsHn85hT9nUkxxA9BEWxFn+Oj9o8ZNLm/40hdlgSLyuOimsrTKLUMEorQexp/aPQeA==", "dev": true, "requires": { - "md5.js": "1.3.4", - "safe-buffer": "5.1.1" + "md5.js": "^1.3.4", + "safe-buffer": "^5.1.1" } }, "exec-sh": { @@ -2553,7 +2553,7 @@ "integrity": "sha512-aLt95pexaugVtQerpmE51+4QfWrNc304uez7jvj6fWnN8GeEHpttB8F36n8N7uVhUMbH/1enbxQ9HImZ4w/9qg==", "dev": true, "requires": { - "merge": "1.2.0" + "merge": "^1.1.3" } }, "execa": { @@ -2562,13 +2562,13 @@ "integrity": "sha1-lEvs00zEHuMqY6n68nrVpl/Fl3c=", "dev": true, "requires": { - "cross-spawn": "5.1.0", - "get-stream": "3.0.0", - "is-stream": "1.1.0", - "npm-run-path": "2.0.2", - "p-finally": "1.0.0", - "signal-exit": "3.0.2", - "strip-eof": "1.0.0" + "cross-spawn": "^5.0.1", + "get-stream": "^3.0.0", + "is-stream": "^1.1.0", + "npm-run-path": "^2.0.0", + "p-finally": "^1.0.0", + "signal-exit": "^3.0.0", + "strip-eof": "^1.0.0" } }, "exit": { @@ -2583,7 +2583,7 @@ "integrity": "sha1-3wcoTjQqgHzXM6xa9yQR5YHRF3s=", "dev": true, "requires": { - "is-posix-bracket": "0.1.1" + "is-posix-bracket": "^0.1.0" } }, "expand-range": { @@ -2592,7 +2592,7 @@ "integrity": "sha1-opnv/TNf4nIeuujiV+x5ZE/IUzc=", "dev": true, "requires": { - "fill-range": "2.2.3" + "fill-range": "^2.1.0" } }, "expect": { @@ -2601,12 +2601,12 @@ "integrity": "sha512-8K+8TjNnZq73KYtqNWKWTbYbN8z4loeL+Pn2bqpmtTdBtLNXJtpz9vkUcQlFsgKMDRA3VM8GXRA6qbV/oBF7Bw==", "dev": true, "requires": { - "ansi-styles": "3.2.0", - "jest-diff": "22.1.0", - "jest-get-type": "22.1.0", - "jest-matcher-utils": "22.1.0", - "jest-message-util": "22.1.0", - "jest-regex-util": "22.1.0" + "ansi-styles": "^3.2.0", + "jest-diff": "^22.1.0", + "jest-get-type": "^22.1.0", + "jest-matcher-utils": "^22.1.0", + "jest-message-util": "^22.1.0", + "jest-regex-util": "^22.1.0" } }, "extend": { @@ -2621,8 +2621,8 @@ "integrity": "sha1-Jqcarwc7OfshJxcnRhMcJwQCjbg=", "dev": true, "requires": { - "assign-symbols": "1.0.0", - "is-extendable": "1.0.1" + "assign-symbols": "^1.0.0", + "is-extendable": "^1.0.1" }, "dependencies": { "is-extendable": { @@ -2631,7 +2631,7 @@ "integrity": "sha512-arnXMxT1hhoKo9k1LZdmlNyJdDDfy2v0fXjFlmok4+i8ul/6WlbVge9bhM74OpNPQPMGUToDtz+KXa1PneJxOA==", "dev": true, "requires": { - "is-plain-object": "2.0.4" + "is-plain-object": "^2.0.4" } } } @@ -2642,9 +2642,9 @@ "integrity": "sha512-E44iT5QVOUJBKij4IIV3uvxuNlbKS38Tw1HiupxEIHPv9qtC2PrDYohbXV5U+1jnfIXttny8gUhj+oZvflFlzA==", "dev": true, "requires": { - "chardet": "0.4.2", - "iconv-lite": "0.4.19", - "tmp": "0.0.33" + "chardet": "^0.4.0", + "iconv-lite": "^0.4.17", + "tmp": "^0.0.33" } }, "extglob": { @@ -2653,7 +2653,7 @@ "integrity": "sha1-Lhj/PS9JqydlzskCPwEdqo2DSaE=", "dev": true, "requires": { - "is-extglob": "1.0.0" + "is-extglob": "^1.0.0" } }, "extsprintf": { @@ -2686,7 +2686,7 @@ "integrity": "sha1-VOmr99+i8mzZsWNsWIwa/AXeXVg=", "dev": true, "requires": { - "bser": "2.0.0" + "bser": "^2.0.0" } }, "figures": { @@ -2695,7 +2695,7 @@ "integrity": "sha1-OrGi0qYsi/tDGgyUy3l6L84nyWI=", "dev": true, "requires": { - "escape-string-regexp": "1.0.5" + "escape-string-regexp": "^1.0.5" } }, "filename-regex": { @@ -2710,8 +2710,8 @@ "integrity": "sha1-jnVIqW08wjJ+5eZ0FocjozO7oqA=", "dev": true, "requires": { - "glob": "7.1.2", - "minimatch": "3.0.4" + "glob": "^7.0.3", + "minimatch": "^3.0.3" } }, "fill-range": { @@ -2720,11 +2720,11 @@ "integrity": "sha1-ULd9/X5Gm8dJJHCWNpn+eoSFpyM=", "dev": true, "requires": { - "is-number": "2.1.0", - "isobject": "2.1.0", - "randomatic": "1.1.7", - "repeat-element": "1.1.2", - "repeat-string": "1.6.1" + "is-number": "^2.1.0", + "isobject": "^2.0.0", + "randomatic": "^1.1.3", + "repeat-element": "^1.1.2", + "repeat-string": "^1.5.2" } }, "find-cache-dir": { @@ -2733,9 +2733,9 @@ "integrity": "sha1-kojj6ePMN0hxfTnq3hfPcfww7m8=", "dev": true, "requires": { - "commondir": "1.0.1", - "make-dir": "1.1.0", - "pkg-dir": "2.0.0" + "commondir": "^1.0.1", + "make-dir": "^1.0.0", + "pkg-dir": "^2.0.0" } }, "find-up": { @@ -2744,7 +2744,7 @@ "integrity": "sha1-RdG35QbHF93UgndaK3eSCjwMV6c=", "dev": true, "requires": { - "locate-path": "2.0.0" + "locate-path": "^2.0.0" } }, "flush-write-stream": { @@ -2753,8 +2753,8 @@ "integrity": "sha512-calZMC10u0FMUqoiunI2AiGIIUtUIvifNwkHhNupZH4cbNnW1Itkoh/Nf5HFYmDrwWPjrUxpkZT0KhuCq0jmGw==", "dev": true, "requires": { - "inherits": "2.0.3", - "readable-stream": "2.3.3" + "inherits": "^2.0.1", + "readable-stream": "^2.0.4" } }, "for-in": { @@ -2769,7 +2769,7 @@ "integrity": "sha1-UmXGgaTylNq78XyVCbZ2OqhFEM4=", "dev": true, "requires": { - "for-in": "1.0.2" + "for-in": "^1.0.1" } }, "foreach": { @@ -2790,9 +2790,9 @@ "integrity": "sha1-b7lPvXGIUwbXPRXMSX/kzE7NRL8=", "dev": true, "requires": { - "asynckit": "0.4.0", - "combined-stream": "1.0.5", - "mime-types": "2.1.17" + "asynckit": "^0.4.0", + "combined-stream": "^1.0.5", + "mime-types": "^2.1.12" } }, "fragment-cache": { @@ -2801,7 +2801,7 @@ "integrity": "sha1-QpD60n8T6Jvn8zeZxrxaCr//DRk=", "dev": true, "requires": { - "map-cache": "0.2.2" + "map-cache": "^0.2.2" } }, "from2": { @@ -2810,8 +2810,8 @@ "integrity": "sha1-i/tVAr3kpNNs/e6gB/zKIdfjgq8=", "dev": true, "requires": { - "inherits": "2.0.3", - "readable-stream": "2.3.3" + "inherits": "^2.0.1", + "readable-stream": "^2.0.0" } }, "fs-extra": { @@ -2820,9 +2820,9 @@ "integrity": "sha512-q6rbdDd1o2mAnQreO7YADIxf/Whx4AHBiRf6d+/cVT8h44ss+lHgxf1FemcqDnQt9X3ct4McHr+JMGlYSsK7Cg==", "dev": true, "requires": { - "graceful-fs": "4.1.11", - "jsonfile": "4.0.0", - "universalify": "0.1.1" + "graceful-fs": "^4.1.2", + "jsonfile": "^4.0.0", + "universalify": "^0.1.0" } }, "fs-write-stream-atomic": { @@ -2831,10 +2831,10 @@ "integrity": "sha1-tH31NJPvkR33VzHnCp3tAYnbQMk=", "dev": true, "requires": { - "graceful-fs": "4.1.11", - "iferr": "0.1.5", - "imurmurhash": "0.1.4", - "readable-stream": "2.3.3" + "graceful-fs": "^4.1.2", + "iferr": "^0.1.5", + "imurmurhash": "^0.1.4", + "readable-stream": "1 || 2" } }, "fs.realpath": { @@ -2850,8 +2850,8 @@ "dev": true, "optional": true, "requires": { - "nan": "2.8.0", - "node-pre-gyp": "0.6.39" + "nan": "^2.3.0", + "node-pre-gyp": "^0.6.39" }, "dependencies": { "abbrev": { @@ -2866,8 +2866,8 @@ "dev": true, "optional": true, "requires": { - "co": "4.6.0", - "json-stable-stringify": "1.0.1" + "co": "^4.6.0", + "json-stable-stringify": "^1.0.1" } }, "ansi-regex": { @@ -2887,8 +2887,8 @@ "dev": true, "optional": true, "requires": { - "delegates": "1.0.0", - "readable-stream": "2.2.9" + "delegates": "^1.0.0", + "readable-stream": "^2.0.6" } }, "asn1": { @@ -2932,7 +2932,7 @@ "dev": true, "optional": true, "requires": { - "tweetnacl": "0.14.5" + "tweetnacl": "^0.14.3" } }, "block-stream": { @@ -2940,15 +2940,14 @@ "bundled": true, "dev": true, "requires": { - "inherits": "2.0.3" + "inherits": "~2.0.0" } }, "boom": { "version": "2.10.1", "bundled": true, - "dev": true, "requires": { - "hoek": "2.16.3" + "hoek": "2.x.x" } }, "brace-expansion": { @@ -2956,7 +2955,7 @@ "bundled": true, "dev": true, "requires": { - "balanced-match": "0.4.2", + "balanced-match": "^0.4.1", "concat-map": "0.0.1" } }, @@ -2987,7 +2986,7 @@ "bundled": true, "dev": true, "requires": { - "delayed-stream": "1.0.0" + "delayed-stream": "~1.0.0" } }, "concat-map": { @@ -3008,7 +3007,6 @@ "cryptile": { "version": "2.0.5", "bundled": true, - "dev": true, "requires": { "boom": "2.10.1" } @@ -3019,7 +3017,7 @@ "integrity": "sha1-O9/s3GCBR8HGcgL6KR59ylnqo7g=", "dev": true, "requires": { - "boom": "2.10.1" + "boom": "2.x.x" } }, "dashdash": { @@ -3028,7 +3026,7 @@ "dev": true, "optional": true, "requires": { - "assert-plus": "1.0.0" + "assert-plus": "^1.0.0" }, "dependencies": { "assert-plus": { @@ -3077,7 +3075,7 @@ "dev": true, "optional": true, "requires": { - "jsbn": "0.1.1" + "jsbn": "~0.1.0" } }, "extend": { @@ -3103,9 +3101,9 @@ "dev": true, "optional": true, "requires": { - "asynckit": "0.4.0", - "combined-stream": "1.0.5", - "mime-types": "2.1.15" + "asynckit": "^0.4.0", + "combined-stream": "^1.0.5", + "mime-types": "^2.1.12" } }, "fs.realpath": { @@ -3118,10 +3116,10 @@ "bundled": true, "dev": true, "requires": { - "graceful-fs": "4.1.11", - "inherits": "2.0.3", - "mkdirp": "0.5.1", - "rimraf": "2.6.1" + "graceful-fs": "^4.1.2", + "inherits": "~2.0.0", + "mkdirp": ">=0.5 0", + "rimraf": "2" } }, "fstream-ignore": { @@ -3130,9 +3128,9 @@ "dev": true, "optional": true, "requires": { - "fstream": "1.0.11", - "inherits": "2.0.3", - "minimatch": "3.0.4" + "fstream": "^1.0.0", + "inherits": "2", + "minimatch": "^3.0.0" } }, "gauge": { @@ -3141,14 +3139,14 @@ "dev": true, "optional": true, "requires": { - "aproba": "1.1.1", - "console-control-strings": "1.1.0", - "has-unicode": "2.0.1", - "object-assign": "4.1.1", - "signal-exit": "3.0.2", - "string-width": "1.0.2", - "strip-ansi": "3.0.1", - "wide-align": "1.1.2" + "aproba": "^1.0.3", + "console-control-strings": "^1.0.0", + "has-unicode": "^2.0.0", + "object-assign": "^4.1.0", + "signal-exit": "^3.0.0", + "string-width": "^1.0.1", + "strip-ansi": "^3.0.1", + "wide-align": "^1.1.0" } }, "getpass": { @@ -3157,7 +3155,7 @@ "dev": true, "optional": true, "requires": { - "assert-plus": "1.0.0" + "assert-plus": "^1.0.0" }, "dependencies": { "assert-plus": { @@ -3173,12 +3171,12 @@ "bundled": true, "dev": true, "requires": { - "fs.realpath": "1.0.0", - "inflight": "1.0.6", - "inherits": "2.0.3", - "minimatch": "3.0.4", - "once": "1.4.0", - "path-is-absolute": "1.0.1" + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.4", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" } }, "graceful-fs": { @@ -3198,8 +3196,8 @@ "dev": true, "optional": true, "requires": { - "ajv": "4.11.8", - "har-schema": "1.0.5" + "ajv": "^4.9.1", + "har-schema": "^1.0.5" } }, "has-unicode": { @@ -3213,16 +3211,15 @@ "bundled": true, "dev": true, "requires": { - "boom": "2.10.1", - "cryptiles": "2.0.5", - "hoek": "2.16.3", - "sntp": "1.0.9" + "boom": "2.x.x", + "cryptiles": "2.x.x", + "hoek": "2.x.x", + "sntp": "1.x.x" } }, "hoek": { "version": "2.16.3", - "bundled": true, - "dev": true + "bundled": true }, "http-signature": { "version": "1.1.1", @@ -3230,9 +3227,9 @@ "dev": true, "optional": true, "requires": { - "assert-plus": "0.2.0", - "jsprim": "1.4.0", - "sshpk": "1.13.0" + "assert-plus": "^0.2.0", + "jsprim": "^1.2.2", + "sshpk": "^1.7.0" } }, "inflight": { @@ -3240,8 +3237,8 @@ "bundled": true, "dev": true, "requires": { - "once": "1.4.0", - "wrappy": "1.0.2" + "once": "^1.3.0", + "wrappy": "1" } }, "inherits": { @@ -3260,7 +3257,7 @@ "bundled": true, "dev": true, "requires": { - "number-is-nan": "1.0.1" + "number-is-nan": "^1.0.0" } }, "is-typedarray": { @@ -3286,7 +3283,7 @@ "dev": true, "optional": true, "requires": { - "jsbn": "0.1.1" + "jsbn": "~0.1.0" } }, "jsbn": { @@ -3307,7 +3304,7 @@ "dev": true, "optional": true, "requires": { - "jsonify": "0.0.0" + "jsonify": "~0.0.0" } }, "json-stringify-safe": { @@ -3352,7 +3349,7 @@ "bundled": true, "dev": true, "requires": { - "mime-db": "1.27.0" + "mime-db": "~1.27.0" } }, "minimatch": { @@ -3360,7 +3357,7 @@ "bundled": true, "dev": true, "requires": { - "brace-expansion": "1.1.7" + "brace-expansion": "^1.1.7" } }, "minimist": { @@ -3388,17 +3385,17 @@ "dev": true, "optional": true, "requires": { - "detect-libc": "1.0.2", + "detect-libc": "^1.0.2", "hawk": "3.1.3", - "mkdirp": "0.5.1", - "nopt": "4.0.1", - "npmlog": "4.1.0", - "rc": "1.2.1", + "mkdirp": "^0.5.1", + "nopt": "^4.0.1", + "npmlog": "^4.0.2", + "rc": "^1.1.7", "request": "2.81.0", - "rimraf": "2.6.1", - "semver": "5.3.0", - "tar": "2.2.1", - "tar-pack": "3.4.0" + "rimraf": "^2.6.1", + "semver": "^5.3.0", + "tar": "^2.2.1", + "tar-pack": "^3.4.0" } }, "nopt": { @@ -3407,8 +3404,8 @@ "dev": true, "optional": true, "requires": { - "abbrev": "1.1.0", - "osenv": "0.1.4" + "abbrev": "1", + "osenv": "^0.1.4" } }, "npmlog": { @@ -3417,10 +3414,10 @@ "dev": true, "optional": true, "requires": { - "are-we-there-yet": "1.1.4", - "console-control-strings": "1.1.0", - "gauge": "2.7.4", - "set-blocking": "2.0.0" + "are-we-there-yet": "~1.1.2", + "console-control-strings": "~1.1.0", + "gauge": "~2.7.3", + "set-blocking": "~2.0.0" } }, "number-is-nan": { @@ -3445,7 +3442,7 @@ "bundled": true, "dev": true, "requires": { - "wrappy": "1.0.2" + "wrappy": "1" } }, "os-homedir": { @@ -3466,8 +3463,8 @@ "dev": true, "optional": true, "requires": { - "os-homedir": "1.0.2", - "os-tmpdir": "1.0.2" + "os-homedir": "^1.0.0", + "os-tmpdir": "^1.0.0" } }, "path-is-absolute": { @@ -3504,10 +3501,10 @@ "dev": true, "optional": true, "requires": { - "deep-extend": "0.4.2", - "ini": "1.3.4", - "minimist": "1.2.0", - "strip-json-comments": "2.0.1" + "deep-extend": "~0.4.0", + "ini": "~1.3.0", + "minimist": "^1.2.0", + "strip-json-comments": "~2.0.1" }, "dependencies": { "minimist": { @@ -3523,13 +3520,13 @@ "bundled": true, "dev": true, "requires": { - "buffer-shims": "1.0.0", - "core-util-is": "1.0.2", - "inherits": "2.0.3", - "isarray": "1.0.0", - "process-nextick-args": "1.0.7", - "string_decoder": "1.0.1", - "util-deprecate": "1.0.2" + "buffer-shims": "~1.0.0", + "core-util-is": "~1.0.0", + "inherits": "~2.0.1", + "isarray": "~1.0.0", + "process-nextick-args": "~1.0.6", + "string_decoder": "~1.0.0", + "util-deprecate": "~1.0.1" } }, "request": { @@ -3538,28 +3535,28 @@ "dev": true, "optional": true, "requires": { - "aws-sign2": "0.6.0", - "aws4": "1.6.0", - "caseless": "0.12.0", - "combined-stream": "1.0.5", - "extend": "3.0.1", - "forever-agent": "0.6.1", - "form-data": "2.1.4", - "har-validator": "4.2.1", - "hawk": "3.1.3", - "http-signature": "1.1.1", - "is-typedarray": "1.0.0", - "isstream": "0.1.2", - "json-stringify-safe": "5.0.1", - "mime-types": "2.1.15", - "oauth-sign": "0.8.2", - "performance-now": "0.2.0", - "qs": "6.4.0", - "safe-buffer": "5.0.1", - "stringstream": "0.0.5", - "tough-cookie": "2.3.2", - "tunnel-agent": "0.6.0", - "uuid": "3.0.1" + "aws-sign2": "~0.6.0", + "aws4": "^1.2.1", + "caseless": "~0.12.0", + "combined-stream": "~1.0.5", + "extend": "~3.0.0", + "forever-agent": "~0.6.1", + "form-data": "~2.1.1", + "har-validator": "~4.2.1", + "hawk": "~3.1.3", + "http-signature": "~1.1.0", + "is-typedarray": "~1.0.0", + "isstream": "~0.1.2", + "json-stringify-safe": "~5.0.1", + "mime-types": "~2.1.7", + "oauth-sign": "~0.8.1", + "performance-now": "^0.2.0", + "qs": "~6.4.0", + "safe-buffer": "^5.0.1", + "stringstream": "~0.0.4", + "tough-cookie": "~2.3.0", + "tunnel-agent": "^0.6.0", + "uuid": "^3.0.0" } }, "rimraf": { @@ -3567,7 +3564,7 @@ "bundled": true, "dev": true, "requires": { - "glob": "7.1.2" + "glob": "^7.0.5" } }, "safe-buffer": { @@ -3598,7 +3595,7 @@ "bundled": true, "dev": true, "requires": { - "hoek": "2.16.3" + "hoek": "2.x.x" } }, "sshpk": { @@ -3607,15 +3604,15 @@ "dev": true, "optional": true, "requires": { - "asn1": "0.2.3", - "assert-plus": "1.0.0", - "bcrypt-pbkdf": "1.0.1", - "dashdash": "1.14.1", - "ecc-jsbn": "0.1.1", - "getpass": "0.1.7", - "jodid25519": "1.0.2", - "jsbn": "0.1.1", - "tweetnacl": "0.14.5" + "asn1": "~0.2.3", + "assert-plus": "^1.0.0", + "bcrypt-pbkdf": "^1.0.0", + "dashdash": "^1.12.0", + "ecc-jsbn": "~0.1.1", + "getpass": "^0.1.1", + "jodid25519": "^1.0.0", + "jsbn": "~0.1.0", + "tweetnacl": "~0.14.0" }, "dependencies": { "assert-plus": { @@ -3631,9 +3628,9 @@ "bundled": true, "dev": true, "requires": { - "code-point-at": "1.1.0", - "is-fullwidth-code-point": "1.0.0", - "strip-ansi": "3.0.1" + "code-point-at": "^1.0.0", + "is-fullwidth-code-point": "^1.0.0", + "strip-ansi": "^3.0.0" } }, "string_decoder": { @@ -3641,7 +3638,7 @@ "bundled": true, "dev": true, "requires": { - "safe-buffer": "5.0.1" + "safe-buffer": "^5.0.1" } }, "stringstream": { @@ -3655,7 +3652,7 @@ "bundled": true, "dev": true, "requires": { - "ansi-regex": "2.1.1" + "ansi-regex": "^2.0.0" } }, "strip-json-comments": { @@ -3669,9 +3666,9 @@ "bundled": true, "dev": true, "requires": { - "block-stream": "0.0.9", - "fstream": "1.0.11", - "inherits": "2.0.3" + "block-stream": "*", + "fstream": "^1.0.2", + "inherits": "2" } }, "tar-pack": { @@ -3680,14 +3677,14 @@ "dev": true, "optional": true, "requires": { - "debug": "2.6.8", - "fstream": "1.0.11", - "fstream-ignore": "1.0.5", - "once": "1.4.0", - "readable-stream": "2.2.9", - "rimraf": "2.6.1", - "tar": "2.2.1", - "uid-number": "0.0.6" + "debug": "^2.2.0", + "fstream": "^1.0.10", + "fstream-ignore": "^1.0.5", + "once": "^1.3.3", + "readable-stream": "^2.1.4", + "rimraf": "^2.5.1", + "tar": "^2.2.1", + "uid-number": "^0.0.6" } }, "tough-cookie": { @@ -3696,7 +3693,7 @@ "dev": true, "optional": true, "requires": { - "punycode": "1.4.1" + "punycode": "^1.4.1" } }, "tunnel-agent": { @@ -3705,7 +3702,7 @@ "dev": true, "optional": true, "requires": { - "safe-buffer": "5.0.1" + "safe-buffer": "^5.0.1" } }, "tweetnacl": { @@ -3746,7 +3743,7 @@ "dev": true, "optional": true, "requires": { - "string-width": "1.0.2" + "string-width": "^1.0.2" } }, "wrappy": { @@ -3768,14 +3765,14 @@ "integrity": "sha1-LANAXHU4w51+s3sxcCLjJfsBi/c=", "dev": true, "requires": { - "aproba": "1.2.0", - "console-control-strings": "1.1.0", - "has-unicode": "2.0.1", - "object-assign": "4.1.1", - "signal-exit": "3.0.2", - "string-width": "1.0.2", - "strip-ansi": "3.0.1", - "wide-align": "1.1.2" + "aproba": "^1.0.3", + "console-control-strings": "^1.0.0", + "has-unicode": "^2.0.0", + "object-assign": "^4.1.0", + "signal-exit": "^3.0.0", + "string-width": "^1.0.1", + "strip-ansi": "^3.0.1", + "wide-align": "^1.1.0" }, "dependencies": { "string-width": { @@ -3784,9 +3781,9 @@ "integrity": "sha1-EYvfW4zcUaKn5w0hHgfisLmxB9M=", "dev": true, "requires": { - "code-point-at": "1.1.0", - "is-fullwidth-code-point": "1.0.0", - "strip-ansi": "3.0.1" + "code-point-at": "^1.0.0", + "is-fullwidth-code-point": "^1.0.0", + "strip-ansi": "^3.0.0" } }, "strip-ansi": { @@ -3795,7 +3792,7 @@ "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", "dev": true, "requires": { - "ansi-regex": "2.1.1" + "ansi-regex": "^2.0.0" } } } @@ -3812,11 +3809,11 @@ "integrity": "sha1-xztInAbYDMVTbCyFP54FIyBWly0=", "dev": true, "requires": { - "hosted-git-info": "2.5.0", - "meow": "3.7.0", - "normalize-package-data": "2.4.0", - "parse-github-repo-url": "1.4.1", - "through2": "2.0.3" + "hosted-git-info": "^2.1.4", + "meow": "^3.3.0", + "normalize-package-data": "^2.3.0", + "parse-github-repo-url": "^1.3.0", + "through2": "^2.0.0" } }, "get-port": { @@ -3849,7 +3846,7 @@ "integrity": "sha1-Xv+OPmhNVprkyysSgmBOi6YhSfo=", "dev": true, "requires": { - "assert-plus": "1.0.0" + "assert-plus": "^1.0.0" } }, "git-raw-commits": { @@ -3858,11 +3855,11 @@ "integrity": "sha1-C8hZbpDV/+c29/VUa9LRL3OrqsY=", "dev": true, "requires": { - "dargs": "4.1.0", - "lodash.template": "4.4.0", - "meow": "3.7.0", - "split2": "2.2.0", - "through2": "2.0.3" + "dargs": "^4.0.1", + "lodash.template": "^4.0.2", + "meow": "^3.3.0", + "split2": "^2.0.0", + "through2": "^2.0.0" } }, "git-remote-origin-url": { @@ -3871,8 +3868,8 @@ "integrity": "sha1-UoJlna4hBxRaERJhEq0yFuxfpl8=", "dev": true, "requires": { - "gitconfiglocal": "1.0.0", - "pify": "2.3.0" + "gitconfiglocal": "^1.0.0", + "pify": "^2.3.0" } }, "git-semver-tags": { @@ -3881,8 +3878,8 @@ "integrity": "sha1-GItFOIK/nXojr9Mbq6U32rc4jV0=", "dev": true, "requires": { - "meow": "3.7.0", - "semver": "5.4.1" + "meow": "^3.3.0", + "semver": "^5.0.1" } }, "gitconfiglocal": { @@ -3891,7 +3888,7 @@ "integrity": "sha1-QdBF84UaXqiPA/JMocYXgRRGS5s=", "dev": true, "requires": { - "ini": "1.3.5" + "ini": "^1.3.2" } }, "glob": { @@ -3900,12 +3897,12 @@ "integrity": "sha512-MJTUg1kjuLeQCJ+ccE4Vpa6kKVXkPYJ2mOCQyUuKLcLQsdrMCpBPUi8qVE6+YuaJkozeA9NusTAw3hLr8Xe5EQ==", "dev": true, "requires": { - "fs.realpath": "1.0.0", - "inflight": "1.0.6", - "inherits": "2.0.3", - "minimatch": "3.0.4", - "once": "1.4.0", - "path-is-absolute": "1.0.1" + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.4", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" } }, "glob-base": { @@ -3914,8 +3911,8 @@ "integrity": "sha1-27Fk9iIbHAscz4Kuoyi0l98Oo8Q=", "dev": true, "requires": { - "glob-parent": "2.0.0", - "is-glob": "2.0.1" + "glob-parent": "^2.0.0", + "is-glob": "^2.0.0" } }, "glob-parent": { @@ -3924,7 +3921,7 @@ "integrity": "sha1-gTg9ctsFT8zPUzbaqQLxgvbtuyg=", "dev": true, "requires": { - "is-glob": "2.0.1" + "is-glob": "^2.0.0" } }, "globals": { @@ -3939,11 +3936,11 @@ "integrity": "sha1-9abXDoOV4hyFj7BInWTfAkJNUGw=", "dev": true, "requires": { - "array-union": "1.0.2", - "glob": "7.1.2", - "object-assign": "4.1.1", - "pify": "2.3.0", - "pinkie-promise": "2.0.1" + "array-union": "^1.0.1", + "glob": "^7.0.3", + "object-assign": "^4.0.1", + "pify": "^2.0.0", + "pinkie-promise": "^2.0.0" } }, "got": { @@ -3952,17 +3949,17 @@ "integrity": "sha1-JAzQV4WpoY5WHcG0S0HHY+8ejbA=", "dev": true, "requires": { - "create-error-class": "3.0.2", - "duplexer3": "0.1.4", - "get-stream": "3.0.0", - "is-redirect": "1.0.0", - "is-retry-allowed": "1.1.0", - "is-stream": "1.1.0", - "lowercase-keys": "1.0.0", - "safe-buffer": "5.1.1", - "timed-out": "4.0.1", - "unzip-response": "2.0.1", - "url-parse-lax": "1.0.0" + "create-error-class": "^3.0.0", + "duplexer3": "^0.1.4", + "get-stream": "^3.0.0", + "is-redirect": "^1.0.0", + "is-retry-allowed": "^1.0.0", + "is-stream": "^1.0.0", + "lowercase-keys": "^1.0.0", + "safe-buffer": "^5.0.1", + "timed-out": "^4.0.0", + "unzip-response": "^2.0.1", + "url-parse-lax": "^1.0.0" } }, "graceful-fs": { @@ -3983,10 +3980,10 @@ "integrity": "sha1-Ywo13+ApS8KB7a5v/F0yn8eYLcw=", "dev": true, "requires": { - "async": "1.5.2", - "optimist": "0.6.1", - "source-map": "0.4.4", - "uglify-js": "2.8.29" + "async": "^1.4.0", + "optimist": "^0.6.1", + "source-map": "^0.4.4", + "uglify-js": "^2.6" }, "dependencies": { "async": { @@ -4001,7 +3998,7 @@ "integrity": "sha1-66T12pwNyZneaAMti092FzZSA2s=", "dev": true, "requires": { - "amdefine": "1.0.1" + "amdefine": ">=0.0.4" } } } @@ -4018,8 +4015,8 @@ "integrity": "sha1-ukAsJmGU8VlW7xXg/PJCmT9qff0=", "dev": true, "requires": { - "ajv": "5.5.0", - "har-schema": "2.0.0" + "ajv": "^5.1.0", + "har-schema": "^2.0.0" } }, "has": { @@ -4028,7 +4025,7 @@ "integrity": "sha1-hGFzP1OLCDfJNh45qauelwTcLyg=", "dev": true, "requires": { - "function-bind": "1.1.1" + "function-bind": "^1.0.2" } }, "has-ansi": { @@ -4037,7 +4034,7 @@ "integrity": "sha1-NPUEnOHs3ysGSa8+8k5F7TVBbZE=", "dev": true, "requires": { - "ansi-regex": "2.1.1" + "ansi-regex": "^2.0.0" } }, "has-flag": { @@ -4058,9 +4055,9 @@ "integrity": "sha1-GLKB2lhbHFxR3vJMkw7SmgvmsXc=", "dev": true, "requires": { - "get-value": "2.0.6", - "has-values": "1.0.0", - "isobject": "3.0.1" + "get-value": "^2.0.6", + "has-values": "^1.0.0", + "isobject": "^3.0.0" }, "dependencies": { "isobject": { @@ -4077,8 +4074,8 @@ "integrity": "sha1-lbC2P+whRmGab+V/51Yo1aOe/k8=", "dev": true, "requires": { - "is-number": "3.0.0", - "kind-of": "4.0.0" + "is-number": "^3.0.0", + "kind-of": "^4.0.0" }, "dependencies": { "is-number": { @@ -4087,7 +4084,7 @@ "integrity": "sha1-JP1iAaR4LPUFYcgQJ2r8fRLXEZU=", "dev": true, "requires": { - "kind-of": "3.2.2" + "kind-of": "^3.0.2" }, "dependencies": { "kind-of": { @@ -4096,7 +4093,7 @@ "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", "dev": true, "requires": { - "is-buffer": "1.1.6" + "is-buffer": "^1.1.5" } } } @@ -4107,7 +4104,7 @@ "integrity": "sha1-IIE989cSkosgc3hpGkUGb65y3Vc=", "dev": true, "requires": { - "is-buffer": "1.1.6" + "is-buffer": "^1.1.5" } } } @@ -4118,8 +4115,8 @@ "integrity": "sha1-X8hoaEfs1zSZQDMZprCj8/auSRg=", "dev": true, "requires": { - "inherits": "2.0.3", - "safe-buffer": "5.1.1" + "inherits": "^2.0.1", + "safe-buffer": "^5.0.1" } }, "hash.js": { @@ -4128,8 +4125,8 @@ "integrity": "sha512-/UETyP0W22QILqS+6HowevwhEFJ3MBJnwTf75Qob9Wz9t0DPuisL8kW8YZMK62dHAKE1c1p+gY1TtOLY+USEHA==", "dev": true, "requires": { - "inherits": "2.0.3", - "minimalistic-assert": "1.0.1" + "inherits": "^2.0.3", + "minimalistic-assert": "^1.0.0" } }, "hawk": { @@ -4138,10 +4135,10 @@ "integrity": "sha512-miowhl2+U7Qle4vdLqDdPt9m09K6yZhkLDTWGoUiUzrQCn+mHHSmfJgAyGaLRZbPmTqfFFjRV1QWCW0VWUJBbQ==", "dev": true, "requires": { - "boom": "4.3.1", - "cryptiles": "3.1.2", - "hoek": "4.2.0", - "sntp": "2.1.0" + "boom": "4.x.x", + "cryptiles": "3.x.x", + "hoek": "4.x.x", + "sntp": "2.x.x" } }, "hmac-drbg": { @@ -4150,9 +4147,9 @@ "integrity": "sha1-0nRXAQJabHdabFRXk+1QL8DGSaE=", "dev": true, "requires": { - "hash.js": "1.1.3", - "minimalistic-assert": "1.0.1", - "minimalistic-crypto-utils": "1.0.1" + "hash.js": "^1.0.3", + "minimalistic-assert": "^1.0.0", + "minimalistic-crypto-utils": "^1.0.1" } }, "hoek": { @@ -4167,8 +4164,8 @@ "integrity": "sha1-42w/LSyufXRqhX440Y1fMqeILbg=", "dev": true, "requires": { - "os-homedir": "1.0.2", - "os-tmpdir": "1.0.2" + "os-homedir": "^1.0.0", + "os-tmpdir": "^1.0.1" } }, "hosted-git-info": { @@ -4183,7 +4180,7 @@ "integrity": "sha512-71lZziiDnsuabfdYiUeWdCVyKuqwWi23L8YeIgV9jSSZHCtb6wB1BKWooH7L3tn4/FuZJMVWyNaIDr4RGmaSYw==", "dev": true, "requires": { - "whatwg-encoding": "1.0.3" + "whatwg-encoding": "^1.0.1" } }, "http-signature": { @@ -4192,9 +4189,9 @@ "integrity": "sha1-muzZJRFHcvPZW2WmCruPfBj7rOE=", "dev": true, "requires": { - "assert-plus": "1.0.0", - "jsprim": "1.4.1", - "sshpk": "1.13.1" + "assert-plus": "^1.0.0", + "jsprim": "^1.2.2", + "sshpk": "^1.7.0" } }, "https-browserify": { @@ -4227,8 +4224,8 @@ "integrity": "sha512-vAaZHieK9qjGo58agRBg+bhHX3hoTZU/Oa3GESWLz7t1U62fk63aHuDJJEteXoDeTCcPmUT+z38gkHPZkkmpmQ==", "dev": true, "requires": { - "pkg-dir": "2.0.0", - "resolve-cwd": "2.0.0" + "pkg-dir": "^2.0.0", + "resolve-cwd": "^2.0.0" } }, "imurmurhash": { @@ -4243,7 +4240,7 @@ "integrity": "sha1-ji1INIdCEhtKghi3oTfppSBJ3IA=", "dev": true, "requires": { - "repeating": "2.0.1" + "repeating": "^2.0.0" } }, "indexof": { @@ -4258,8 +4255,8 @@ "integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=", "dev": true, "requires": { - "once": "1.4.0", - "wrappy": "1.0.2" + "once": "^1.3.0", + "wrappy": "1" } }, "inherits": { @@ -4280,20 +4277,20 @@ "integrity": "sha512-h+xtnyk4EwKvFWHrUYsWErEVR+igKtLdchu+o0Z1RL7VU/jVMFbYir2bp6bAj8efFNxWqHX0dIss6fJQ+/+qeQ==", "dev": true, "requires": { - "ansi-escapes": "3.0.0", - "chalk": "2.3.0", - "cli-cursor": "2.1.0", - "cli-width": "2.2.0", - "external-editor": "2.1.0", - "figures": "2.0.0", - "lodash": "4.17.4", + "ansi-escapes": "^3.0.0", + "chalk": "^2.0.0", + "cli-cursor": "^2.1.0", + "cli-width": "^2.0.0", + "external-editor": "^2.0.4", + "figures": "^2.0.0", + "lodash": "^4.3.0", "mute-stream": "0.0.7", - "run-async": "2.3.0", - "rx-lite": "4.0.8", - "rx-lite-aggregates": "4.0.8", - "string-width": "2.1.1", - "strip-ansi": "4.0.0", - "through": "2.3.8" + "run-async": "^2.2.0", + "rx-lite": "^4.0.8", + "rx-lite-aggregates": "^4.0.8", + "string-width": "^2.1.0", + "strip-ansi": "^4.0.0", + "through": "^2.3.6" } }, "invariant": { @@ -4302,7 +4299,7 @@ "integrity": "sha1-nh9WrArNtr8wMwbzOL47IErmA2A=", "dev": true, "requires": { - "loose-envify": "1.3.1" + "loose-envify": "^1.0.0" } }, "invert-kv": { @@ -4317,7 +4314,7 @@ "integrity": "sha1-qeEss66Nh2cn7u84Q/igiXtcmNY=", "dev": true, "requires": { - "kind-of": "3.2.2" + "kind-of": "^3.0.2" } }, "is-arrayish": { @@ -4332,7 +4329,7 @@ "integrity": "sha1-dfFmQrSA8YenEcgUFh/TpKdlWJg=", "dev": true, "requires": { - "binary-extensions": "1.11.0" + "binary-extensions": "^1.0.0" } }, "is-buffer": { @@ -4347,7 +4344,7 @@ "integrity": "sha1-VAVy0096wxGfj3bDDLwbHgN6/74=", "dev": true, "requires": { - "builtin-modules": "1.1.1" + "builtin-modules": "^1.0.0" } }, "is-callable": { @@ -4362,7 +4359,7 @@ "integrity": "sha1-9zkzayYyNlBhqdSCcM1WrjNpMY4=", "dev": true, "requires": { - "ci-info": "1.1.2" + "ci-info": "^1.0.0" } }, "is-data-descriptor": { @@ -4371,7 +4368,7 @@ "integrity": "sha1-C17mSDiOLIYCgueT8YVv7D8wG1Y=", "dev": true, "requires": { - "kind-of": "3.2.2" + "kind-of": "^3.0.2" } }, "is-date-object": { @@ -4386,9 +4383,9 @@ "integrity": "sha512-avDYr0SB3DwO9zsMov0gKCESFYqCnE4hq/4z3TdUlukEy5t9C0YRq7HLrsN52NAcqXKaepeCD0n+B0arnVG3Hg==", "dev": true, "requires": { - "is-accessor-descriptor": "0.1.6", - "is-data-descriptor": "0.1.4", - "kind-of": "5.1.0" + "is-accessor-descriptor": "^0.1.6", + "is-data-descriptor": "^0.1.4", + "kind-of": "^5.0.0" }, "dependencies": { "kind-of": { @@ -4411,7 +4408,7 @@ "integrity": "sha1-IjgJj8Ih3gvPpdnqxMRdY4qhxTQ=", "dev": true, "requires": { - "is-primitive": "2.0.0" + "is-primitive": "^2.0.0" } }, "is-extendable": { @@ -4432,7 +4429,7 @@ "integrity": "sha1-zGZ3aVYCvlUO8R6LSqYwU0K20Ko=", "dev": true, "requires": { - "number-is-nan": "1.0.1" + "number-is-nan": "^1.0.0" } }, "is-fullwidth-code-point": { @@ -4441,7 +4438,7 @@ "integrity": "sha1-754xOG8DGn8NZDr4L95QxFfvAMs=", "dev": true, "requires": { - "number-is-nan": "1.0.1" + "number-is-nan": "^1.0.0" } }, "is-generator-fn": { @@ -4456,7 +4453,7 @@ "integrity": "sha1-0Jb5JqPe1WAPP9/ZEZjLCIjC2GM=", "dev": true, "requires": { - "is-extglob": "1.0.0" + "is-extglob": "^1.0.0" } }, "is-number": { @@ -4465,7 +4462,7 @@ "integrity": "sha1-Afy7s5NGOlSPL0ZszhbezknbkI8=", "dev": true, "requires": { - "kind-of": "3.2.2" + "kind-of": "^3.0.2" } }, "is-obj": { @@ -4480,7 +4477,7 @@ "integrity": "sha512-OTiixgpZAT1M4NHgS5IguFp/Vz2VI3U7Goh4/HA1adtwyLtSBrxYlcSYkhpAE07s4fKEcjrFxyvtQBND4vFQyQ==", "dev": true, "requires": { - "is-number": "4.0.0" + "is-number": "^4.0.0" }, "dependencies": { "is-number": { @@ -4503,7 +4500,7 @@ "integrity": "sha512-h5PpgXkWitc38BBMYawTYMWJHFZJVnBquFE57xFpjB8pJFiF6gZ+bU+WyI/yqXiFR5mdLsgYNaPe8uao6Uv9Og==", "dev": true, "requires": { - "isobject": "3.0.1" + "isobject": "^3.0.1" }, "dependencies": { "isobject": { @@ -4544,7 +4541,7 @@ "integrity": "sha1-VRdIm1RwkbCTDglWVM7SXul+lJE=", "dev": true, "requires": { - "has": "1.0.1" + "has": "^1.0.1" } }, "is-retry-allowed": { @@ -4577,7 +4574,7 @@ "integrity": "sha1-Thqg+1G/vLPpJogAE5cgLBd1tm4=", "dev": true, "requires": { - "text-extensions": "1.7.0" + "text-extensions": "^1.0.0" } }, "is-typedarray": { @@ -4631,17 +4628,17 @@ "integrity": "sha512-oFCwXvd65amgaPCzqrR+a2XjanS1MvpXN6l/MlMUTv6uiA1NOgGX+I0uyq8Lg3GDxsxPsaP1049krz3hIJ5+KA==", "dev": true, "requires": { - "async": "2.6.0", - "fileset": "2.0.3", - "istanbul-lib-coverage": "1.1.1", - "istanbul-lib-hook": "1.1.0", - "istanbul-lib-instrument": "1.9.1", - "istanbul-lib-report": "1.1.2", - "istanbul-lib-source-maps": "1.2.2", - "istanbul-reports": "1.1.3", - "js-yaml": "3.10.0", - "mkdirp": "0.5.1", - "once": "1.4.0" + "async": "^2.1.4", + "fileset": "^2.0.2", + "istanbul-lib-coverage": "^1.1.1", + "istanbul-lib-hook": "^1.1.0", + "istanbul-lib-instrument": "^1.9.1", + "istanbul-lib-report": "^1.1.2", + "istanbul-lib-source-maps": "^1.2.2", + "istanbul-reports": "^1.1.3", + "js-yaml": "^3.7.0", + "mkdirp": "^0.5.1", + "once": "^1.4.0" } }, "istanbul-lib-coverage": { @@ -4656,7 +4653,7 @@ "integrity": "sha512-U3qEgwVDUerZ0bt8cfl3dSP3S6opBoOtk3ROO5f2EfBr/SRiD9FQqzwaZBqFORu8W7O0EXpai+k7kxHK13beRg==", "dev": true, "requires": { - "append-transform": "0.4.0" + "append-transform": "^0.4.0" } }, "istanbul-lib-instrument": { @@ -4665,13 +4662,13 @@ "integrity": "sha512-RQmXeQ7sphar7k7O1wTNzVczF9igKpaeGQAG9qR2L+BS4DCJNTI9nytRmIVYevwO0bbq+2CXvJmYDuz0gMrywA==", "dev": true, "requires": { - "babel-generator": "6.26.0", - "babel-template": "6.26.0", - "babel-traverse": "6.26.0", - "babel-types": "6.26.0", - "babylon": "6.18.0", - "istanbul-lib-coverage": "1.1.1", - "semver": "5.4.1" + "babel-generator": "^6.18.0", + "babel-template": "^6.16.0", + "babel-traverse": "^6.18.0", + "babel-types": "^6.18.0", + "babylon": "^6.18.0", + "istanbul-lib-coverage": "^1.1.1", + "semver": "^5.3.0" } }, "istanbul-lib-report": { @@ -4680,10 +4677,10 @@ "integrity": "sha512-UTv4VGx+HZivJQwAo1wnRwe1KTvFpfi/NYwN7DcsrdzMXwpRT/Yb6r4SBPoHWj4VuQPakR32g4PUUeyKkdDkBA==", "dev": true, "requires": { - "istanbul-lib-coverage": "1.1.1", - "mkdirp": "0.5.1", - "path-parse": "1.0.5", - "supports-color": "3.2.3" + "istanbul-lib-coverage": "^1.1.1", + "mkdirp": "^0.5.1", + "path-parse": "^1.0.5", + "supports-color": "^3.1.2" }, "dependencies": { "has-flag": { @@ -4698,7 +4695,7 @@ "integrity": "sha1-ZawFBLOVQXHYpklGsq48u4pfVPY=", "dev": true, "requires": { - "has-flag": "1.0.0" + "has-flag": "^1.0.0" } } } @@ -4709,11 +4706,11 @@ "integrity": "sha512-8BfdqSfEdtip7/wo1RnrvLpHVEd8zMZEDmOFEnpC6dg0vXflHt9nvoAyQUzig2uMSXfF2OBEYBV3CVjIL9JvaQ==", "dev": true, "requires": { - "debug": "3.1.0", - "istanbul-lib-coverage": "1.1.1", - "mkdirp": "0.5.1", - "rimraf": "2.6.2", - "source-map": "0.5.7" + "debug": "^3.1.0", + "istanbul-lib-coverage": "^1.1.1", + "mkdirp": "^0.5.1", + "rimraf": "^2.6.1", + "source-map": "^0.5.3" }, "dependencies": { "debug": { @@ -4733,7 +4730,7 @@ "integrity": "sha512-ZEelkHh8hrZNI5xDaKwPMFwDsUf5wIEI2bXAFGp1e6deR2mnEKBPhLJEgr4ZBt8Gi6Mj38E/C8kcy9XLggVO2Q==", "dev": true, "requires": { - "handlebars": "4.0.11" + "handlebars": "^4.0.3" } }, "jest": { @@ -4742,7 +4739,7 @@ "integrity": "sha512-yOYSMzTqgWcNKSM1ctOJxHXKWndejSD9EtsDb4Wfvqc6Fc+qX4KJ6Dgm2oKvkjKSS6o8Gax1ykQWXxEhv8R7+Q==", "dev": true, "requires": { - "jest-cli": "22.1.1" + "jest-cli": "^22.1.1" }, "dependencies": { "jest-cli": { @@ -4751,39 +4748,39 @@ "integrity": "sha512-QFnt/p+iJFrAKe9rM4D3L2Rw8ckN9kOAQe8jfUZ43gTA99IMDfteub6bDqUAOzzWxRo1aHNDicwGuqqWHdw0yg==", "dev": true, "requires": { - "ansi-escapes": "3.0.0", - "chalk": "2.3.0", - "exit": "0.1.2", - "glob": "7.1.2", - "graceful-fs": "4.1.11", - "import-local": "1.0.0", - "is-ci": "1.0.10", - "istanbul-api": "1.2.1", - "istanbul-lib-coverage": "1.1.1", - "istanbul-lib-instrument": "1.9.1", - "istanbul-lib-source-maps": "1.2.2", - "jest-changed-files": "22.1.0", - "jest-config": "22.1.1", - "jest-environment-jsdom": "22.1.0", - "jest-get-type": "22.1.0", - "jest-haste-map": "22.1.0", - "jest-message-util": "22.1.0", - "jest-regex-util": "22.1.0", - "jest-resolve-dependencies": "22.1.0", - "jest-runner": "22.1.1", - "jest-runtime": "22.1.1", - "jest-snapshot": "22.1.0", - "jest-util": "22.1.0", - "jest-worker": "22.1.0", - "micromatch": "2.3.11", - "node-notifier": "5.2.1", - "realpath-native": "1.0.0", - "rimraf": "2.6.2", - "slash": "1.0.0", - "string-length": "2.0.0", - "strip-ansi": "4.0.0", - "which": "1.3.0", - "yargs": "10.1.1" + "ansi-escapes": "^3.0.0", + "chalk": "^2.0.1", + "exit": "^0.1.2", + "glob": "^7.1.2", + "graceful-fs": "^4.1.11", + "import-local": "^1.0.0", + "is-ci": "^1.0.10", + "istanbul-api": "^1.1.14", + "istanbul-lib-coverage": "^1.1.1", + "istanbul-lib-instrument": "^1.8.0", + "istanbul-lib-source-maps": "^1.2.1", + "jest-changed-files": "^22.1.0", + "jest-config": "^22.1.1", + "jest-environment-jsdom": "^22.1.0", + "jest-get-type": "^22.1.0", + "jest-haste-map": "^22.1.0", + "jest-message-util": "^22.1.0", + "jest-regex-util": "^22.1.0", + "jest-resolve-dependencies": "^22.1.0", + "jest-runner": "^22.1.1", + "jest-runtime": "^22.1.1", + "jest-snapshot": "^22.1.0", + "jest-util": "^22.1.0", + "jest-worker": "^22.1.0", + "micromatch": "^2.3.11", + "node-notifier": "^5.1.2", + "realpath-native": "^1.0.0", + "rimraf": "^2.5.4", + "slash": "^1.0.0", + "string-length": "^2.0.0", + "strip-ansi": "^4.0.0", + "which": "^1.2.12", + "yargs": "^10.0.3" } } } @@ -4794,7 +4791,7 @@ "integrity": "sha512-NGc5HF3zXaMMph1L3HwPw7zVu0uAad2CZ+5QYQaP9QzB9jBioukulg2vcy7gdJRfWAr3D8EGlu4jfUHOtLNVmQ==", "dev": true, "requires": { - "throat": "4.1.0" + "throat": "^4.0.0" } }, "jest-config": { @@ -4803,17 +4800,17 @@ "integrity": "sha512-imzke/YkKXOQKec5cvprqvfcWKNGccZCs3dDk8wTGaqeFnGsx9A9csZ7zzGMlMG8qjlnl+/urRjIdk8XZEXuUg==", "dev": true, "requires": { - "chalk": "2.3.0", - "glob": "7.1.2", - "jest-environment-jsdom": "22.1.0", - "jest-environment-node": "22.1.0", - "jest-get-type": "22.1.0", - "jest-jasmine2": "22.1.1", - "jest-regex-util": "22.1.0", - "jest-resolve": "22.1.0", - "jest-util": "22.1.0", - "jest-validate": "22.1.0", - "pretty-format": "22.1.0" + "chalk": "^2.0.1", + "glob": "^7.1.1", + "jest-environment-jsdom": "^22.1.0", + "jest-environment-node": "^22.1.0", + "jest-get-type": "^22.1.0", + "jest-jasmine2": "^22.1.1", + "jest-regex-util": "^22.1.0", + "jest-resolve": "^22.1.0", + "jest-util": "^22.1.0", + "jest-validate": "^22.1.0", + "pretty-format": "^22.1.0" } }, "jest-diff": { @@ -4822,10 +4819,10 @@ "integrity": "sha512-lowdbU/dzXh+2/MR5QcvU5KPNkO4JdAEYw0PkQCbIQIuy5+g3QZBuVhWh8179Fmpg4CQrz1WgoK/yQHDCHbqqw==", "dev": true, "requires": { - "chalk": "2.3.0", - "diff": "3.4.0", - "jest-get-type": "22.1.0", - "pretty-format": "22.1.0" + "chalk": "^2.0.1", + "diff": "^3.2.0", + "jest-get-type": "^22.1.0", + "pretty-format": "^22.1.0" } }, "jest-docblock": { @@ -4834,7 +4831,7 @@ "integrity": "sha512-/+OGgBVRJb5wCbXrB1LQvibQBz2SdrvDdKRNzY1gL+OISQJZCR9MOewbygdT5rVzbbkfhC4AR2x+qWmNUdJfjw==", "dev": true, "requires": { - "detect-newline": "2.1.0" + "detect-newline": "^2.1.0" } }, "jest-environment-jsdom": { @@ -4843,9 +4840,9 @@ "integrity": "sha512-2R+LlFG+r9l0QK1fb7ywOxrBLu/aC8otBaRRMzPHf3binuumng61g3LxaXhEYstGvMPukMtkVRvX0X6J3wRCqg==", "dev": true, "requires": { - "jest-mock": "22.1.0", - "jest-util": "22.1.0", - "jsdom": "11.5.1" + "jest-mock": "^22.1.0", + "jest-util": "^22.1.0", + "jsdom": "^11.5.1" } }, "jest-environment-node": { @@ -4854,8 +4851,8 @@ "integrity": "sha512-dJnTuEyCUsoY7BE9PbtSxBDkj888VhXUv6Z6yF2OUqJVPLcutiXdBW5luecmNSuKtZ6mMNF+tZBj+iQ2frWslg==", "dev": true, "requires": { - "jest-mock": "22.1.0", - "jest-util": "22.1.0" + "jest-mock": "^22.1.0", + "jest-util": "^22.1.0" } }, "jest-get-type": { @@ -4870,12 +4867,12 @@ "integrity": "sha512-vETdC6GboGlZX6+9SMZkXtYRQSKBbQ47sFF7NGglbMN4eyIZBODply8rlcO01KwBiAeiNCKdjUyfonZzJ93JEg==", "dev": true, "requires": { - "fb-watchman": "2.0.0", - "graceful-fs": "4.1.11", - "jest-docblock": "22.1.0", - "jest-worker": "22.1.0", - "micromatch": "2.3.11", - "sane": "2.2.0" + "fb-watchman": "^2.0.0", + "graceful-fs": "^4.1.11", + "jest-docblock": "^22.1.0", + "jest-worker": "^22.1.0", + "micromatch": "^2.3.11", + "sane": "^2.0.0" } }, "jest-jasmine2": { @@ -4884,17 +4881,17 @@ "integrity": "sha512-AkDEBKTDFU8yKrm+6Gx7uHo++LgcfzRry+mh+/BCy0kxyNxuz+iJSFS2zfW0zpc/LcJONTCTfcNOT1qJ59I3Ow==", "dev": true, "requires": { - "callsites": "2.0.0", - "chalk": "2.3.0", - "co": "4.6.0", - "expect": "22.1.0", - "graceful-fs": "4.1.11", - "is-generator-fn": "1.0.0", - "jest-diff": "22.1.0", - "jest-matcher-utils": "22.1.0", - "jest-message-util": "22.1.0", - "jest-snapshot": "22.1.0", - "source-map-support": "0.5.1" + "callsites": "^2.0.0", + "chalk": "^2.0.1", + "co": "^4.6.0", + "expect": "^22.1.0", + "graceful-fs": "^4.1.11", + "is-generator-fn": "^1.0.0", + "jest-diff": "^22.1.0", + "jest-matcher-utils": "^22.1.0", + "jest-message-util": "^22.1.0", + "jest-snapshot": "^22.1.0", + "source-map-support": "^0.5.0" } }, "jest-leak-detector": { @@ -4903,7 +4900,7 @@ "integrity": "sha512-8QsCWkncWAqdvrXN4yXQp9vgWF6CT3RkRey+d06SIHX913uXzAJhJdZyo6eE+uHVYMxUbxqW93npbUFhAR0YxA==", "dev": true, "requires": { - "pretty-format": "22.1.0" + "pretty-format": "^22.1.0" } }, "jest-matcher-utils": { @@ -4912,9 +4909,9 @@ "integrity": "sha512-Zn1OD9wVjILOdvRxgAnqiCN36OX6KJx+P2FHN+3lzQ0omG2N2OAguxE1QXuJJneG2yndlkXjekXFP254c0cSpw==", "dev": true, "requires": { - "chalk": "2.3.0", - "jest-get-type": "22.1.0", - "pretty-format": "22.1.0" + "chalk": "^2.0.1", + "jest-get-type": "^22.1.0", + "pretty-format": "^22.1.0" } }, "jest-message-util": { @@ -4923,11 +4920,11 @@ "integrity": "sha512-kftcoawOeOVUGuGWmMupJt7FGLK1pqOrh02FlJwtImmPGZ2yTWCTx2D+N/g95qD2jCbQ/ntH1goBixhAIIxL+g==", "dev": true, "requires": { - "@babel/code-frame": "7.0.0-beta.37", - "chalk": "2.3.0", - "micromatch": "2.3.11", - "slash": "1.0.0", - "stack-utils": "1.0.1" + "@babel/code-frame": "^7.0.0-beta.35", + "chalk": "^2.0.1", + "micromatch": "^2.3.11", + "slash": "^1.0.0", + "stack-utils": "^1.0.1" } }, "jest-mock": { @@ -4948,8 +4945,8 @@ "integrity": "sha512-hp4Od9YNEv3A/xNN5pPlNjMuisdZyg3u+XAZOqnGxWPVqnbjvEZ25U2HmYM0eLhOzVTHAAsNnAA8HWDzY1Cwjw==", "dev": true, "requires": { - "browser-resolve": "1.11.2", - "chalk": "2.3.0" + "browser-resolve": "^1.11.2", + "chalk": "^2.0.1" } }, "jest-resolve-dependencies": { @@ -4958,7 +4955,7 @@ "integrity": "sha512-76Ll61bD/Sus8wK8d+lw891EtiBJGJkWG8OuVDTEX0z3z2+jPujvQqSB2eQ+kCHyCsRwJ2PSjhn3UHqae/oEtA==", "dev": true, "requires": { - "jest-regex-util": "22.1.0" + "jest-regex-util": "^22.1.0" } }, "jest-runner": { @@ -4967,17 +4964,17 @@ "integrity": "sha512-SWx2trb5t3HHJegN8m7f8puHpl4XPyGFvdgmPZ74reNgvQVR9bJL3FmJn2/XTYtVLeaqqEP1xpC2shxCqJhBMA==", "dev": true, "requires": { - "exit": "0.1.2", - "jest-config": "22.1.1", - "jest-docblock": "22.1.0", - "jest-haste-map": "22.1.0", - "jest-jasmine2": "22.1.1", - "jest-leak-detector": "22.1.0", - "jest-message-util": "22.1.0", - "jest-runtime": "22.1.1", - "jest-util": "22.1.0", - "jest-worker": "22.1.0", - "throat": "4.1.0" + "exit": "^0.1.2", + "jest-config": "^22.1.1", + "jest-docblock": "^22.1.0", + "jest-haste-map": "^22.1.0", + "jest-jasmine2": "^22.1.1", + "jest-leak-detector": "^22.1.0", + "jest-message-util": "^22.1.0", + "jest-runtime": "^22.1.1", + "jest-util": "^22.1.0", + "jest-worker": "^22.1.0", + "throat": "^4.0.0" } }, "jest-runtime": { @@ -4986,25 +4983,25 @@ "integrity": "sha512-u7vtAciqpdzaNWxGp12XVdCs2FjM/MdoxELdujcQz1VdLiJ3LE7voiVCxfm/gdram/rhwTHeS8BWzXT8IyXjBg==", "dev": true, "requires": { - "babel-core": "6.26.0", - "babel-jest": "22.4.3", - "babel-plugin-istanbul": "4.1.5", - "chalk": "2.3.0", - "convert-source-map": "1.5.1", - "exit": "0.1.2", - "graceful-fs": "4.1.11", - "jest-config": "22.1.1", - "jest-haste-map": "22.1.0", - "jest-regex-util": "22.1.0", - "jest-resolve": "22.1.0", - "jest-util": "22.1.0", - "json-stable-stringify": "1.0.1", - "micromatch": "2.3.11", - "realpath-native": "1.0.0", - "slash": "1.0.0", + "babel-core": "^6.0.0", + "babel-jest": "^22.1.0", + "babel-plugin-istanbul": "^4.1.5", + "chalk": "^2.0.1", + "convert-source-map": "^1.4.0", + "exit": "^0.1.2", + "graceful-fs": "^4.1.11", + "jest-config": "^22.1.1", + "jest-haste-map": "^22.1.0", + "jest-regex-util": "^22.1.0", + "jest-resolve": "^22.1.0", + "jest-util": "^22.1.0", + "json-stable-stringify": "^1.0.1", + "micromatch": "^2.3.11", + "realpath-native": "^1.0.0", + "slash": "^1.0.0", "strip-bom": "3.0.0", - "write-file-atomic": "2.3.0", - "yargs": "10.1.1" + "write-file-atomic": "^2.1.0", + "yargs": "^10.0.3" }, "dependencies": { "strip-bom": { @@ -5021,12 +5018,12 @@ "integrity": "sha512-g5IqCgAC1TaaocL9xMIE2GLpOPP2li5BPVc2Vsa3ti+e7LMhpooXYcd/ouNqtWDThZD8Tp3jDavyqN0LH6hkPA==", "dev": true, "requires": { - "chalk": "2.3.0", - "jest-diff": "22.1.0", - "jest-matcher-utils": "22.1.0", - "mkdirp": "0.5.1", - "natural-compare": "1.4.0", - "pretty-format": "22.1.0" + "chalk": "^2.0.1", + "jest-diff": "^22.1.0", + "jest-matcher-utils": "^22.1.0", + "mkdirp": "^0.5.1", + "natural-compare": "^1.4.0", + "pretty-format": "^22.1.0" } }, "jest-util": { @@ -5035,13 +5032,13 @@ "integrity": "sha512-/IVHOZa7T3sBjzfTKps8QSYf3BS6ugT4fB+612WEjllSTX1fjZNH3TI001TuEhoSz6zLD/BPeteSNCFPHS2O0g==", "dev": true, "requires": { - "callsites": "2.0.0", - "chalk": "2.3.0", - "graceful-fs": "4.1.11", - "is-ci": "1.0.10", - "jest-message-util": "22.1.0", - "jest-validate": "22.1.0", - "mkdirp": "0.5.1" + "callsites": "^2.0.0", + "chalk": "^2.0.1", + "graceful-fs": "^4.1.11", + "is-ci": "^1.0.10", + "jest-message-util": "^22.1.0", + "jest-validate": "^22.1.0", + "mkdirp": "^0.5.1" } }, "jest-validate": { @@ -5050,10 +5047,10 @@ "integrity": "sha512-v9QKiQksA8e0LXRYBhI6c3vuvYyLAm95kR4SVFGj0l2zgzAG3VNT6qpUAxntna6ERf5jydzzmSpOzLpCJYCUvg==", "dev": true, "requires": { - "chalk": "2.3.0", - "jest-get-type": "22.1.0", - "leven": "2.1.0", - "pretty-format": "22.1.0" + "chalk": "^2.0.1", + "jest-get-type": "^22.1.0", + "leven": "^2.1.0", + "pretty-format": "^22.1.0" } }, "jest-worker": { @@ -5062,7 +5059,7 @@ "integrity": "sha512-ezLueYAQowk5N6g2J7bNZfq4NWZvMNB5Qd24EmOZLcM5SXTdiFvxykZIoNiMj9C98cCbPaojX8tfR7b1LJwNig==", "dev": true, "requires": { - "merge-stream": "1.0.1" + "merge-stream": "^1.0.1" } }, "js-tokens": { @@ -5077,8 +5074,8 @@ "integrity": "sha512-O2v52ffjLa9VeM43J4XocZE//WT9N0IiwDa3KSHH7Tu8CtH+1qM8SIZvnsTh6v+4yFy5KUY3BHUVwjpfAWsjIA==", "dev": true, "requires": { - "argparse": "1.0.9", - "esprima": "4.0.0" + "argparse": "^1.0.7", + "esprima": "^4.0.0" } }, "jsbn": { @@ -5094,30 +5091,30 @@ "integrity": "sha512-89ztIZ03aYK9f1uUrLXLsZndRge/JnZjzjpaN+lrse3coqz+8PR/dX4WLHpbF5fIKTXhDjFODOJw2328lPJ90g==", "dev": true, "requires": { - "abab": "1.0.4", - "acorn": "5.3.0", - "acorn-globals": "4.1.0", - "array-equal": "1.0.0", - "browser-process-hrtime": "0.1.2", - "content-type-parser": "1.0.2", - "cssom": "0.3.2", - "cssstyle": "0.2.37", - "domexception": "1.0.0", - "escodegen": "1.9.0", - "html-encoding-sniffer": "1.0.2", - "left-pad": "1.2.0", - "nwmatcher": "1.4.3", - "parse5": "3.0.3", - "pn": "1.1.0", - "request": "2.83.0", - "request-promise-native": "1.0.5", - "sax": "1.2.4", - "symbol-tree": "3.2.2", - "tough-cookie": "2.3.3", - "webidl-conversions": "4.0.2", - "whatwg-encoding": "1.0.3", - "whatwg-url": "6.4.0", - "xml-name-validator": "2.0.1" + "abab": "^1.0.3", + "acorn": "^5.1.2", + "acorn-globals": "^4.0.0", + "array-equal": "^1.0.0", + "browser-process-hrtime": "^0.1.2", + "content-type-parser": "^1.0.1", + "cssom": ">= 0.3.2 < 0.4.0", + "cssstyle": ">= 0.2.37 < 0.3.0", + "domexception": "^1.0.0", + "escodegen": "^1.9.0", + "html-encoding-sniffer": "^1.0.1", + "left-pad": "^1.2.0", + "nwmatcher": "^1.4.3", + "parse5": "^3.0.2", + "pn": "^1.0.0", + "request": "^2.83.0", + "request-promise-native": "^1.0.3", + "sax": "^1.2.1", + "symbol-tree": "^3.2.1", + "tough-cookie": "^2.3.3", + "webidl-conversions": "^4.0.2", + "whatwg-encoding": "^1.0.1", + "whatwg-url": "^6.3.0", + "xml-name-validator": "^2.0.1" } }, "jsesc": { @@ -5150,7 +5147,7 @@ "integrity": "sha1-mnWdOcXy/1A/1TAGRu1EX4jE+a8=", "dev": true, "requires": { - "jsonify": "0.0.0" + "jsonify": "~0.0.0" } }, "json-stringify-safe": { @@ -5171,7 +5168,7 @@ "integrity": "sha1-h3Gq4HmbZAdrdmQPygWPnBDjPss=", "dev": true, "requires": { - "graceful-fs": "4.1.11" + "graceful-fs": "^4.1.6" } }, "jsonify": { @@ -5204,7 +5201,7 @@ "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", "dev": true, "requires": { - "is-buffer": "1.1.6" + "is-buffer": "^1.1.5" } }, "lazy-cache": { @@ -5220,7 +5217,7 @@ "integrity": "sha1-MIrMr6C8SDo4Z7S28rlQYlHRuDU=", "dev": true, "requires": { - "invert-kv": "1.0.0" + "invert-kv": "^1.0.0" } }, "leb": { @@ -5241,45 +5238,45 @@ "integrity": "sha512-kggfoW5Y8uw89spVwCqXeiokNY3kPrYEifHOtRUsvrEVQMj02quzC6IMS4AKcO9LafRWAf4LK064XXHAo7Nt7A==", "dev": true, "requires": { - "async": "1.5.2", - "chalk": "2.3.0", - "cmd-shim": "2.0.2", - "columnify": "1.5.4", - "command-join": "2.0.0", - "conventional-changelog-cli": "1.3.5", - "conventional-recommended-bump": "1.1.0", - "dedent": "0.7.0", - "execa": "0.8.0", - "find-up": "2.1.0", - "fs-extra": "4.0.3", - "get-port": "3.2.0", - "glob": "7.1.2", - "glob-parent": "3.1.0", - "globby": "6.1.0", - "graceful-fs": "4.1.11", - "hosted-git-info": "2.5.0", - "inquirer": "3.3.0", - "is-ci": "1.0.10", - "load-json-file": "4.0.0", - "lodash": "4.17.4", - "minimatch": "3.0.4", - "npmlog": "4.1.2", - "p-finally": "1.0.0", - "package-json": "4.0.1", - "path-exists": "3.0.0", - "read-cmd-shim": "1.0.1", - "read-pkg": "3.0.0", - "rimraf": "2.6.2", - "safe-buffer": "5.1.1", - "semver": "5.4.1", - "signal-exit": "3.0.2", - "slash": "1.0.0", - "strong-log-transformer": "1.0.6", - "temp-write": "3.4.0", - "write-file-atomic": "2.3.0", - "write-json-file": "2.3.0", - "write-pkg": "3.1.0", - "yargs": "8.0.2" + "async": "^1.5.0", + "chalk": "^2.1.0", + "cmd-shim": "^2.0.2", + "columnify": "^1.5.4", + "command-join": "^2.0.0", + "conventional-changelog-cli": "^1.3.2", + "conventional-recommended-bump": "^1.0.1", + "dedent": "^0.7.0", + "execa": "^0.8.0", + "find-up": "^2.1.0", + "fs-extra": "^4.0.1", + "get-port": "^3.2.0", + "glob": "^7.1.2", + "glob-parent": "^3.1.0", + "globby": "^6.1.0", + "graceful-fs": "^4.1.11", + "hosted-git-info": "^2.5.0", + "inquirer": "^3.2.2", + "is-ci": "^1.0.10", + "load-json-file": "^4.0.0", + "lodash": "^4.17.4", + "minimatch": "^3.0.4", + "npmlog": "^4.1.2", + "p-finally": "^1.0.0", + "package-json": "^4.0.1", + "path-exists": "^3.0.0", + "read-cmd-shim": "^1.0.1", + "read-pkg": "^3.0.0", + "rimraf": "^2.6.1", + "safe-buffer": "^5.1.1", + "semver": "^5.4.1", + "signal-exit": "^3.0.2", + "slash": "^1.0.0", + "strong-log-transformer": "^1.0.6", + "temp-write": "^3.3.0", + "write-file-atomic": "^2.3.0", + "write-json-file": "^2.2.0", + "write-pkg": "^3.1.0", + "yargs": "^8.0.2" }, "dependencies": { "async": { @@ -5300,9 +5297,9 @@ "integrity": "sha1-EgYBU3qRbSmUD5NNo7SNWFo5IT0=", "dev": true, "requires": { - "string-width": "1.0.2", - "strip-ansi": "3.0.1", - "wrap-ansi": "2.1.0" + "string-width": "^1.0.1", + "strip-ansi": "^3.0.1", + "wrap-ansi": "^2.0.0" }, "dependencies": { "string-width": { @@ -5311,9 +5308,9 @@ "integrity": "sha1-EYvfW4zcUaKn5w0hHgfisLmxB9M=", "dev": true, "requires": { - "code-point-at": "1.1.0", - "is-fullwidth-code-point": "1.0.0", - "strip-ansi": "3.0.1" + "code-point-at": "^1.0.0", + "is-fullwidth-code-point": "^1.0.0", + "strip-ansi": "^3.0.0" } } } @@ -5324,13 +5321,13 @@ "integrity": "sha1-2NdrvBtVIX7RkP1t1J08d07PyNo=", "dev": true, "requires": { - "cross-spawn": "5.1.0", - "get-stream": "3.0.0", - "is-stream": "1.1.0", - "npm-run-path": "2.0.2", - "p-finally": "1.0.0", - "signal-exit": "3.0.2", - "strip-eof": "1.0.0" + "cross-spawn": "^5.0.1", + "get-stream": "^3.0.0", + "is-stream": "^1.1.0", + "npm-run-path": "^2.0.0", + "p-finally": "^1.0.0", + "signal-exit": "^3.0.0", + "strip-eof": "^1.0.0" } }, "glob-parent": { @@ -5339,8 +5336,8 @@ "integrity": "sha1-nmr2KZ2NO9K9QEMIMr0RPfkGxa4=", "dev": true, "requires": { - "is-glob": "3.1.0", - "path-dirname": "1.0.2" + "is-glob": "^3.1.0", + "path-dirname": "^1.0.0" } }, "is-extglob": { @@ -5355,7 +5352,7 @@ "integrity": "sha1-e6WuJCF4BKxwcHuWkiVnSGzD6Eo=", "dev": true, "requires": { - "is-extglob": "2.1.1" + "is-extglob": "^2.1.0" } }, "load-json-file": { @@ -5364,10 +5361,10 @@ "integrity": "sha1-L19Fq5HjMhYjT9U62rZo607AmTs=", "dev": true, "requires": { - "graceful-fs": "4.1.11", - "parse-json": "4.0.0", - "pify": "3.0.0", - "strip-bom": "3.0.0" + "graceful-fs": "^4.1.2", + "parse-json": "^4.0.0", + "pify": "^3.0.0", + "strip-bom": "^3.0.0" } }, "parse-json": { @@ -5376,8 +5373,8 @@ "integrity": "sha1-vjX1Qlvh9/bHRxhPmKeIy5lHfuA=", "dev": true, "requires": { - "error-ex": "1.3.1", - "json-parse-better-errors": "1.0.1" + "error-ex": "^1.3.1", + "json-parse-better-errors": "^1.0.1" } }, "path-type": { @@ -5386,7 +5383,7 @@ "integrity": "sha512-T2ZUsdZFHgA3u4e5PfPbjd7HDDpxPnQb5jN0SrDsjNSuVXHJqtwTnWqG0B1jZrgmJ/7lj1EmVIByWt1gxGkWvg==", "dev": true, "requires": { - "pify": "3.0.0" + "pify": "^3.0.0" } }, "pify": { @@ -5401,9 +5398,9 @@ "integrity": "sha1-nLxoaXj+5l0WwA4rGcI3/Pbjg4k=", "dev": true, "requires": { - "load-json-file": "4.0.0", - "normalize-package-data": "2.4.0", - "path-type": "3.0.0" + "load-json-file": "^4.0.0", + "normalize-package-data": "^2.3.2", + "path-type": "^3.0.0" } }, "read-pkg-up": { @@ -5412,8 +5409,8 @@ "integrity": "sha1-a3KoBImE4MQeeVEP1en6mbO1Sb4=", "dev": true, "requires": { - "find-up": "2.1.0", - "read-pkg": "2.0.0" + "find-up": "^2.0.0", + "read-pkg": "^2.0.0" }, "dependencies": { "load-json-file": { @@ -5422,10 +5419,10 @@ "integrity": "sha1-eUfkIUmvgNaWy/eXvKq8/h/inKg=", "dev": true, "requires": { - "graceful-fs": "4.1.11", - "parse-json": "2.2.0", - "pify": "2.3.0", - "strip-bom": "3.0.0" + "graceful-fs": "^4.1.2", + "parse-json": "^2.2.0", + "pify": "^2.0.0", + "strip-bom": "^3.0.0" } }, "parse-json": { @@ -5434,7 +5431,7 @@ "integrity": "sha1-9ID0BDTvgHQfhGkJn43qGPVaTck=", "dev": true, "requires": { - "error-ex": "1.3.1" + "error-ex": "^1.2.0" } }, "path-type": { @@ -5443,7 +5440,7 @@ "integrity": "sha1-8BLMuEFbcJb8LaoQVMPXI4lZTHM=", "dev": true, "requires": { - "pify": "2.3.0" + "pify": "^2.0.0" } }, "pify": { @@ -5458,9 +5455,9 @@ "integrity": "sha1-jvHAYjxqbbDcZxPEv6xGMysjaPg=", "dev": true, "requires": { - "load-json-file": "2.0.0", - "normalize-package-data": "2.4.0", - "path-type": "2.0.0" + "load-json-file": "^2.0.0", + "normalize-package-data": "^2.3.2", + "path-type": "^2.0.0" } } } @@ -5471,7 +5468,7 @@ "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", "dev": true, "requires": { - "ansi-regex": "2.1.1" + "ansi-regex": "^2.0.0" } }, "strip-bom": { @@ -5486,19 +5483,19 @@ "integrity": "sha1-YpmpBVsc78lp/355wdkY3Osiw2A=", "dev": true, "requires": { - "camelcase": "4.1.0", - "cliui": "3.2.0", - "decamelize": "1.2.0", - "get-caller-file": "1.0.2", - "os-locale": "2.1.0", - "read-pkg-up": "2.0.0", - "require-directory": "2.1.1", - "require-main-filename": "1.0.1", - "set-blocking": "2.0.0", - "string-width": "2.1.1", - "which-module": "2.0.0", - "y18n": "3.2.1", - "yargs-parser": "7.0.0" + "camelcase": "^4.1.0", + "cliui": "^3.2.0", + "decamelize": "^1.1.1", + "get-caller-file": "^1.0.1", + "os-locale": "^2.0.0", + "read-pkg-up": "^2.0.0", + "require-directory": "^2.1.1", + "require-main-filename": "^1.0.1", + "set-blocking": "^2.0.0", + "string-width": "^2.0.0", + "which-module": "^2.0.0", + "y18n": "^3.2.1", + "yargs-parser": "^7.0.0" } } } @@ -5515,8 +5512,8 @@ "integrity": "sha1-OwmSTt+fCDwEkP3UwLxEIeBHZO4=", "dev": true, "requires": { - "prelude-ls": "1.1.2", - "type-check": "0.3.2" + "prelude-ls": "~1.1.2", + "type-check": "~0.3.2" } }, "load-json-file": { @@ -5525,11 +5522,11 @@ "integrity": "sha1-lWkFcI1YtLq0wiYbBPWfMcmTdMA=", "dev": true, "requires": { - "graceful-fs": "4.1.11", - "parse-json": "2.2.0", - "pify": "2.3.0", - "pinkie-promise": "2.0.1", - "strip-bom": "2.0.0" + "graceful-fs": "^4.1.2", + "parse-json": "^2.2.0", + "pify": "^2.0.0", + "pinkie-promise": "^2.0.0", + "strip-bom": "^2.0.0" }, "dependencies": { "pify": { @@ -5552,9 +5549,9 @@ "integrity": "sha1-yYrvSIvM7aL/teLeZG1qdUQp9c0=", "dev": true, "requires": { - "big.js": "3.2.0", - "emojis-list": "2.1.0", - "json5": "0.5.1" + "big.js": "^3.1.3", + "emojis-list": "^2.0.0", + "json5": "^0.5.0" } }, "locate-path": { @@ -5563,8 +5560,8 @@ "integrity": "sha1-K1aLJl7slExtnA3pw9u7ygNUzY4=", "dev": true, "requires": { - "p-locate": "2.0.0", - "path-exists": "3.0.0" + "p-locate": "^2.0.0", + "path-exists": "^3.0.0" } }, "lodash": { @@ -5591,8 +5588,8 @@ "integrity": "sha1-5zoDhcg1VZF0bgILmWecaQ5o+6A=", "dev": true, "requires": { - "lodash._reinterpolate": "3.0.0", - "lodash.templatesettings": "4.1.0" + "lodash._reinterpolate": "~3.0.0", + "lodash.templatesettings": "^4.0.0" } }, "lodash.templatesettings": { @@ -5601,7 +5598,7 @@ "integrity": "sha1-K01OlbpEDZFf8IvImeRVNmZxMxY=", "dev": true, "requires": { - "lodash._reinterpolate": "3.0.0" + "lodash._reinterpolate": "~3.0.0" } }, "long": { @@ -5622,7 +5619,7 @@ "integrity": "sha1-0aitM/qc4OcT1l/dCsi3SNR4yEg=", "dev": true, "requires": { - "js-tokens": "3.0.2" + "js-tokens": "^3.0.0" } }, "loud-rejection": { @@ -5631,8 +5628,8 @@ "integrity": "sha1-W0b4AUft7leIcPCG0Eghz5mOVR8=", "dev": true, "requires": { - "currently-unhandled": "0.4.1", - "signal-exit": "3.0.2" + "currently-unhandled": "^0.4.1", + "signal-exit": "^3.0.0" } }, "lowercase-keys": { @@ -5647,8 +5644,8 @@ "integrity": "sha512-q4spe4KTfsAS1SUHLO0wz8Qiyf1+vMIAgpRYioFYDMNqKfHQbg+AVDH3i4fvpl71/P1L0dBl+fQi+P37UYf0ew==", "dev": true, "requires": { - "pseudomap": "1.0.2", - "yallist": "2.1.2" + "pseudomap": "^1.0.2", + "yallist": "^2.1.2" } }, "make-dir": { @@ -5657,7 +5654,7 @@ "integrity": "sha512-0Pkui4wLJ7rxvmfUvs87skoEaxmu0hCUApF8nonzpl7q//FWp9zu8W61Scz4sd/kUiqDxvUhtoam2efDyiBzcA==", "dev": true, "requires": { - "pify": "3.0.0" + "pify": "^3.0.0" }, "dependencies": { "pify": { @@ -5674,7 +5671,7 @@ "integrity": "sha1-4BpckQnyr3lmDk6LlYd5AYT1qWw=", "dev": true, "requires": { - "tmpl": "1.0.4" + "tmpl": "1.0.x" } }, "map-cache": { @@ -5695,7 +5692,7 @@ "integrity": "sha1-7Nyo8TFE5mDxtb1B8S80edmN+48=", "dev": true, "requires": { - "object-visit": "1.0.1" + "object-visit": "^1.0.0" } }, "md5.js": { @@ -5704,8 +5701,8 @@ "integrity": "sha1-6b296UogpawYsENA/Fdk1bCdkB0=", "dev": true, "requires": { - "hash-base": "3.0.4", - "inherits": "2.0.3" + "hash-base": "^3.0.0", + "inherits": "^2.0.1" } }, "mem": { @@ -5714,7 +5711,7 @@ "integrity": "sha1-Xt1StIXKHZAP5kiVUFOZoN+kX3Y=", "dev": true, "requires": { - "mimic-fn": "1.1.0" + "mimic-fn": "^1.0.0" } }, "memory-fs": { @@ -5723,8 +5720,8 @@ "integrity": "sha1-OpoguEYlI+RHz7x+i7gO1me/xVI=", "dev": true, "requires": { - "errno": "0.1.7", - "readable-stream": "2.3.3" + "errno": "^0.1.3", + "readable-stream": "^2.0.1" } }, "meow": { @@ -5733,16 +5730,16 @@ "integrity": "sha1-cstmi0JSKCkKu/qFaJJYcwioAfs=", "dev": true, "requires": { - "camelcase-keys": "2.1.0", - "decamelize": "1.2.0", - "loud-rejection": "1.6.0", - "map-obj": "1.0.1", - "minimist": "1.2.0", - "normalize-package-data": "2.4.0", - "object-assign": "4.1.1", - "read-pkg-up": "1.0.1", - "redent": "1.0.0", - "trim-newlines": "1.0.0" + "camelcase-keys": "^2.0.0", + "decamelize": "^1.1.2", + "loud-rejection": "^1.0.0", + "map-obj": "^1.0.1", + "minimist": "^1.1.3", + "normalize-package-data": "^2.3.4", + "object-assign": "^4.0.1", + "read-pkg-up": "^1.0.1", + "redent": "^1.0.0", + "trim-newlines": "^1.0.0" }, "dependencies": { "minimist": { @@ -5765,7 +5762,7 @@ "integrity": "sha1-QEEgLVCKNCugAXQAjfDCUbjBNeE=", "dev": true, "requires": { - "readable-stream": "2.3.3" + "readable-stream": "^2.0.1" } }, "micromatch": { @@ -5774,19 +5771,19 @@ "integrity": "sha1-hmd8l9FyCzY0MdBNDRUpO9OMFWU=", "dev": true, "requires": { - "arr-diff": "2.0.0", - "array-unique": "0.2.1", - "braces": "1.8.5", - "expand-brackets": "0.1.5", - "extglob": "0.3.2", - "filename-regex": "2.0.1", - "is-extglob": "1.0.0", - "is-glob": "2.0.1", - "kind-of": "3.2.2", - "normalize-path": "2.1.1", - "object.omit": "2.0.1", - "parse-glob": "3.0.4", - "regex-cache": "0.4.4" + "arr-diff": "^2.0.0", + "array-unique": "^0.2.1", + "braces": "^1.8.2", + "expand-brackets": "^0.1.4", + "extglob": "^0.3.1", + "filename-regex": "^2.0.0", + "is-extglob": "^1.0.0", + "is-glob": "^2.0.1", + "kind-of": "^3.0.2", + "normalize-path": "^2.0.1", + "object.omit": "^2.0.0", + "parse-glob": "^3.0.4", + "regex-cache": "^0.4.2" } }, "miller-rabin": { @@ -5795,8 +5792,8 @@ "integrity": "sha512-115fLhvZVqWwHPbClyntxEVfVDfl9DLLTuJvq3g2O/Oxi8AiNouAHvDSzHS0viUJc+V5vm3eq91Xwqn9dp4jRA==", "dev": true, "requires": { - "bn.js": "4.11.8", - "brorand": "1.1.0" + "bn.js": "^4.0.0", + "brorand": "^1.0.1" } }, "mime-db": { @@ -5811,7 +5808,7 @@ "integrity": "sha1-Cdejk/A+mVp5+K+Fe3Cp4KsWVXo=", "dev": true, "requires": { - "mime-db": "1.30.0" + "mime-db": "~1.30.0" } }, "mimic-fn": { @@ -5838,7 +5835,7 @@ "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==", "dev": true, "requires": { - "brace-expansion": "1.1.8" + "brace-expansion": "^1.1.7" } }, "minimist": { @@ -5853,16 +5850,16 @@ "integrity": "sha512-zHo8v+otD1J10j/tC+VNoGK9keCuByhKovAvdn74dmxJl9+mWHnx6EMsDN4lgRoMI/eYo2nchAxniIbUPb5onw==", "dev": true, "requires": { - "concat-stream": "1.6.0", - "duplexify": "3.6.0", - "end-of-stream": "1.4.1", - "flush-write-stream": "1.0.3", - "from2": "2.3.0", - "parallel-transform": "1.1.0", - "pump": "2.0.1", - "pumpify": "1.5.1", - "stream-each": "1.2.2", - "through2": "2.0.3" + "concat-stream": "^1.5.0", + "duplexify": "^3.4.2", + "end-of-stream": "^1.1.0", + "flush-write-stream": "^1.0.0", + "from2": "^2.1.0", + "parallel-transform": "^1.1.0", + "pump": "^2.0.1", + "pumpify": "^1.3.3", + "stream-each": "^1.1.0", + "through2": "^2.0.0" } }, "mixin-deep": { @@ -5871,8 +5868,8 @@ "integrity": "sha512-8ZItLHeEgaqEvd5lYBXfm4EZSFCX29Jb9K+lAHhDKzReKBQKj3R+7NOF6tjqYi9t4oI8VUfaWITJQm86wnXGNQ==", "dev": true, "requires": { - "for-in": "1.0.2", - "is-extendable": "1.0.1" + "for-in": "^1.0.2", + "is-extendable": "^1.0.1" }, "dependencies": { "is-extendable": { @@ -5881,7 +5878,7 @@ "integrity": "sha512-arnXMxT1hhoKo9k1LZdmlNyJdDDfy2v0fXjFlmok4+i8ul/6WlbVge9bhM74OpNPQPMGUToDtz+KXa1PneJxOA==", "dev": true, "requires": { - "is-plain-object": "2.0.4" + "is-plain-object": "^2.0.4" } } } @@ -5913,12 +5910,12 @@ "integrity": "sha1-viwAX9oy4LKa8fBdfEszIUxwH5I=", "dev": true, "requires": { - "aproba": "1.2.0", - "copy-concurrently": "1.0.5", - "fs-write-stream-atomic": "1.0.10", - "mkdirp": "0.5.1", - "rimraf": "2.6.2", - "run-queue": "1.0.3" + "aproba": "^1.1.1", + "copy-concurrently": "^1.0.0", + "fs-write-stream-atomic": "^1.0.8", + "mkdirp": "^0.5.1", + "rimraf": "^2.5.4", + "run-queue": "^1.0.3" } }, "ms": { @@ -5946,18 +5943,18 @@ "integrity": "sha512-n8R9bS8yQ6eSXaV6jHUpKzD8gLsin02w1HSFiegwrs9E098Ylhw5jdyKPaYqvHknHaSCKTPp7C8dGCQ0q9koXA==", "dev": true, "requires": { - "arr-diff": "4.0.0", - "array-unique": "0.3.2", - "define-property": "2.0.2", - "extend-shallow": "3.0.2", - "fragment-cache": "0.2.1", - "is-odd": "2.0.0", - "is-windows": "1.0.2", - "kind-of": "6.0.2", - "object.pick": "1.3.0", - "regex-not": "1.0.2", - "snapdragon": "0.8.2", - "to-regex": "3.0.2" + "arr-diff": "^4.0.0", + "array-unique": "^0.3.2", + "define-property": "^2.0.2", + "extend-shallow": "^3.0.2", + "fragment-cache": "^0.2.1", + "is-odd": "^2.0.0", + "is-windows": "^1.0.2", + "kind-of": "^6.0.2", + "object.pick": "^1.3.0", + "regex-not": "^1.0.0", + "snapdragon": "^0.8.1", + "to-regex": "^3.0.1" }, "dependencies": { "arr-diff": { @@ -6004,28 +6001,28 @@ "integrity": "sha512-5AzFzdoIMb89hBGMZglEegffzgRg+ZFoUmisQ8HI4j1KDdpx13J0taNp2y9xPbur6W61gepGDDotGBVQ7mfUCg==", "dev": true, "requires": { - "assert": "1.4.1", - "browserify-zlib": "0.2.0", - "buffer": "4.9.1", - "console-browserify": "1.1.0", - "constants-browserify": "1.0.0", - "crypto-browserify": "3.12.0", - "domain-browser": "1.2.0", - "events": "1.1.1", - "https-browserify": "1.0.0", - "os-browserify": "0.3.0", + "assert": "^1.1.1", + "browserify-zlib": "^0.2.0", + "buffer": "^4.3.0", + "console-browserify": "^1.1.0", + "constants-browserify": "^1.0.0", + "crypto-browserify": "^3.11.0", + "domain-browser": "^1.1.1", + "events": "^1.0.0", + "https-browserify": "^1.0.0", + "os-browserify": "^0.3.0", "path-browserify": "0.0.0", - "process": "0.11.10", - "punycode": "1.4.1", - "querystring-es3": "0.2.1", - "readable-stream": "2.3.3", - "stream-browserify": "2.0.1", - "stream-http": "2.8.2", - "string_decoder": "1.0.3", - "timers-browserify": "2.0.10", + "process": "^0.11.10", + "punycode": "^1.2.4", + "querystring-es3": "^0.2.0", + "readable-stream": "^2.3.3", + "stream-browserify": "^2.0.1", + "stream-http": "^2.7.2", + "string_decoder": "^1.0.0", + "timers-browserify": "^2.0.4", "tty-browserify": "0.0.0", - "url": "0.11.0", - "util": "0.10.3", + "url": "^0.11.0", + "util": "^0.10.3", "vm-browserify": "0.0.4" } }, @@ -6035,10 +6032,10 @@ "integrity": "sha512-MIBs+AAd6dJ2SklbbE8RUDRlIVhU8MaNLh1A9SUZDUHPiZkWLFde6UNwG41yQHZEToHgJMXqyVZ9UcS/ReOVTg==", "dev": true, "requires": { - "growly": "1.3.0", - "semver": "5.4.1", - "shellwords": "0.1.1", - "which": "1.3.0" + "growly": "^1.3.0", + "semver": "^5.4.1", + "shellwords": "^0.1.1", + "which": "^1.3.0" } }, "normalize-package-data": { @@ -6047,10 +6044,10 @@ "integrity": "sha512-9jjUFbTPfEy3R/ad/2oNbKtW9Hgovl5O1FvFWKkKblNXoN/Oou6+9+KKohPK13Yc3/TyunyWhJp6gvRNR/PPAw==", "dev": true, "requires": { - "hosted-git-info": "2.5.0", - "is-builtin-module": "1.0.0", - "semver": "5.4.1", - "validate-npm-package-license": "3.0.1" + "hosted-git-info": "^2.1.4", + "is-builtin-module": "^1.0.0", + "semver": "2 || 3 || 4 || 5", + "validate-npm-package-license": "^3.0.1" } }, "normalize-path": { @@ -6059,7 +6056,7 @@ "integrity": "sha1-GrKLVW4Zg2Oowab35vogE3/mrtk=", "dev": true, "requires": { - "remove-trailing-separator": "1.1.0" + "remove-trailing-separator": "^1.0.1" } }, "npm-run-path": { @@ -6068,7 +6065,7 @@ "integrity": "sha1-NakjLfo11wZ7TLLd8jV7GHFTbF8=", "dev": true, "requires": { - "path-key": "2.0.1" + "path-key": "^2.0.0" } }, "npmlog": { @@ -6077,10 +6074,10 @@ "integrity": "sha512-2uUqazuKlTaSI/dC8AzicUck7+IrEaOnN/e0jd3Xtt1KcGpwx30v50mL7oPyr/h9bL3E4aZccVwpwP+5W9Vjkg==", "dev": true, "requires": { - "are-we-there-yet": "1.1.4", - "console-control-strings": "1.1.0", - "gauge": "2.7.4", - "set-blocking": "2.0.0" + "are-we-there-yet": "~1.1.2", + "console-control-strings": "~1.1.0", + "gauge": "~2.7.3", + "set-blocking": "~2.0.0" } }, "number-is-nan": { @@ -6113,9 +6110,9 @@ "integrity": "sha1-fn2Fi3gb18mRpBupde04EnVOmYw=", "dev": true, "requires": { - "copy-descriptor": "0.1.1", - "define-property": "0.2.5", - "kind-of": "3.2.2" + "copy-descriptor": "^0.1.0", + "define-property": "^0.2.5", + "kind-of": "^3.0.3" }, "dependencies": { "define-property": { @@ -6124,7 +6121,7 @@ "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=", "dev": true, "requires": { - "is-descriptor": "0.1.6" + "is-descriptor": "^0.1.0" } } } @@ -6141,7 +6138,7 @@ "integrity": "sha1-95xEk68MU3e1n+OdOV5BBC3QRbs=", "dev": true, "requires": { - "isobject": "3.0.1" + "isobject": "^3.0.0" }, "dependencies": { "isobject": { @@ -6158,8 +6155,8 @@ "integrity": "sha1-h1jIRvW0B62rDyNuCYbxSwUcqhY=", "dev": true, "requires": { - "define-properties": "1.1.2", - "es-abstract": "1.10.0" + "define-properties": "^1.1.2", + "es-abstract": "^1.5.1" } }, "object.omit": { @@ -6168,8 +6165,8 @@ "integrity": "sha1-Gpx0SCnznbuFjHbKNXmuKlTr0fo=", "dev": true, "requires": { - "for-own": "0.1.5", - "is-extendable": "0.1.1" + "for-own": "^0.1.4", + "is-extendable": "^0.1.1" } }, "object.pick": { @@ -6178,7 +6175,7 @@ "integrity": "sha1-h6EKxMFpS9Lhy/U1kaZhQftd10c=", "dev": true, "requires": { - "isobject": "3.0.1" + "isobject": "^3.0.1" }, "dependencies": { "isobject": { @@ -6195,7 +6192,7 @@ "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=", "dev": true, "requires": { - "wrappy": "1.0.2" + "wrappy": "1" } }, "onetime": { @@ -6204,7 +6201,7 @@ "integrity": "sha1-BnQoIw/WdEOyeUsiu6UotoZ5YtQ=", "dev": true, "requires": { - "mimic-fn": "1.1.0" + "mimic-fn": "^1.0.0" } }, "optimist": { @@ -6213,8 +6210,8 @@ "integrity": "sha1-2j6nRob6IaGaERwybpDrFaAZZoY=", "dev": true, "requires": { - "minimist": "0.0.8", - "wordwrap": "0.0.3" + "minimist": "~0.0.1", + "wordwrap": "~0.0.2" } }, "optionator": { @@ -6223,12 +6220,12 @@ "integrity": "sha1-NkxeQJ0/TWMB1sC0wFu6UBgK62Q=", "dev": true, "requires": { - "deep-is": "0.1.3", - "fast-levenshtein": "2.0.6", - "levn": "0.3.0", - "prelude-ls": "1.1.2", - "type-check": "0.3.2", - "wordwrap": "1.0.0" + "deep-is": "~0.1.3", + "fast-levenshtein": "~2.0.4", + "levn": "~0.3.0", + "prelude-ls": "~1.1.2", + "type-check": "~0.3.2", + "wordwrap": "~1.0.0" }, "dependencies": { "wordwrap": { @@ -6257,9 +6254,9 @@ "integrity": "sha512-3sslG3zJbEYcaC4YVAvDorjGxc7tv6KVATnLPZONiljsUncvihe9BQoVCEs0RZ1kmf4Hk9OBqlZfJZWI4GanKA==", "dev": true, "requires": { - "execa": "0.7.0", - "lcid": "1.0.0", - "mem": "1.1.0" + "execa": "^0.7.0", + "lcid": "^1.0.0", + "mem": "^1.1.0" } }, "os-tmpdir": { @@ -6286,7 +6283,7 @@ "integrity": "sha1-IKAQOyIqcMj9OcwuWAaA893l7EM=", "dev": true, "requires": { - "p-limit": "1.1.0" + "p-limit": "^1.1.0" } }, "package-json": { @@ -6295,10 +6292,10 @@ "integrity": "sha1-iGmgQBJTZhxMTKPabCEh7VVfXu0=", "dev": true, "requires": { - "got": "6.7.1", - "registry-auth-token": "3.3.1", - "registry-url": "3.1.0", - "semver": "5.4.1" + "got": "^6.7.1", + "registry-auth-token": "^3.0.1", + "registry-url": "^3.0.3", + "semver": "^5.1.0" } }, "pako": { @@ -6313,9 +6310,9 @@ "integrity": "sha1-1BDwZbBdojCB/NEPKIVMKb2jOwY=", "dev": true, "requires": { - "cyclist": "0.2.2", - "inherits": "2.0.3", - "readable-stream": "2.3.3" + "cyclist": "~0.2.2", + "inherits": "^2.0.3", + "readable-stream": "^2.1.5" } }, "parse-asn1": { @@ -6324,11 +6321,11 @@ "integrity": "sha512-KPx7flKXg775zZpnp9SxJlz00gTd4BmJ2yJufSc44gMCRrRQ7NSzAcSJQfifuOLgW6bEi+ftrALtsgALeB2Adw==", "dev": true, "requires": { - "asn1.js": "4.10.1", - "browserify-aes": "1.2.0", - "create-hash": "1.2.0", - "evp_bytestokey": "1.0.3", - "pbkdf2": "3.0.16" + "asn1.js": "^4.0.0", + "browserify-aes": "^1.0.0", + "create-hash": "^1.1.0", + "evp_bytestokey": "^1.0.0", + "pbkdf2": "^3.0.3" } }, "parse-github-repo-url": { @@ -6343,10 +6340,10 @@ "integrity": "sha1-ssN2z7EfNVE7rdFz7wu246OIORw=", "dev": true, "requires": { - "glob-base": "0.3.0", - "is-dotfile": "1.0.3", - "is-extglob": "1.0.0", - "is-glob": "2.0.1" + "glob-base": "^0.3.0", + "is-dotfile": "^1.0.0", + "is-extglob": "^1.0.0", + "is-glob": "^2.0.0" } }, "parse-json": { @@ -6355,7 +6352,7 @@ "integrity": "sha1-9ID0BDTvgHQfhGkJn43qGPVaTck=", "dev": true, "requires": { - "error-ex": "1.3.1" + "error-ex": "^1.2.0" } }, "parse5": { @@ -6364,7 +6361,7 @@ "integrity": "sha512-rgO9Zg5LLLkfJF9E6CCmXlSE4UVceloys8JrFqCcHloC3usd/kJCyPDwH2SOlzix2j3xaP9sUX3e8+kvkuleAA==", "dev": true, "requires": { - "@types/node": "9.3.0" + "@types/node": "*" } }, "pascalcase": { @@ -6415,9 +6412,9 @@ "integrity": "sha1-WcRPfuSR2nBNpBXaWkBwuk+P5EE=", "dev": true, "requires": { - "graceful-fs": "4.1.11", - "pify": "2.3.0", - "pinkie-promise": "2.0.1" + "graceful-fs": "^4.1.2", + "pify": "^2.0.0", + "pinkie-promise": "^2.0.0" }, "dependencies": { "pify": { @@ -6434,11 +6431,11 @@ "integrity": "sha512-y4CXP3thSxqf7c0qmOF+9UeOTrifiVTIM+u7NWlq+PRsHbr7r7dpCmvzrZxa96JJUNi0Y5w9VqG5ZNeCVMoDcA==", "dev": true, "requires": { - "create-hash": "1.2.0", - "create-hmac": "1.1.7", - "ripemd160": "2.0.2", - "safe-buffer": "5.1.1", - "sha.js": "2.4.11" + "create-hash": "^1.1.2", + "create-hmac": "^1.1.4", + "ripemd160": "^2.0.1", + "safe-buffer": "^5.0.1", + "sha.js": "^2.4.8" } }, "performance-now": { @@ -6465,7 +6462,7 @@ "integrity": "sha1-ITXW36ejWMBprJsXh3YogihFD/o=", "dev": true, "requires": { - "pinkie": "2.0.4" + "pinkie": "^2.0.0" } }, "pkg-dir": { @@ -6474,7 +6471,7 @@ "integrity": "sha1-9tXREJ4Z1j7fQo4L1X4Sd3YVM0s=", "dev": true, "requires": { - "find-up": "2.1.0" + "find-up": "^2.1.0" } }, "pn": { @@ -6507,14 +6504,20 @@ "integrity": "sha1-gV7R9uvGWSb4ZbMQwHE7yzMVzks=", "dev": true }, + "prettier": { + "version": "1.13.6", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-1.13.6.tgz", + "integrity": "sha512-p5eqCNiohWZN++7aJXUVj0JgLqHCPLf9GLIcLBHGNWs4Y9FJOPs6+KNO2WT0udJIQJTbeZFrJkjzjcb8fkAYYQ==", + "dev": true + }, "pretty-format": { "version": "22.1.0", "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-22.1.0.tgz", "integrity": "sha512-0HHR5hCmjDGU4sez3w5zRDAAwn7V0vT4SgPiYPZ1XDm5sT3Icb+Bh+fsOP3+Y3UwPjMr7TbRj+L7eQyMkPAxAw==", "dev": true, "requires": { - "ansi-regex": "3.0.0", - "ansi-styles": "3.2.0" + "ansi-regex": "^3.0.0", + "ansi-styles": "^3.2.0" }, "dependencies": { "ansi-regex": { @@ -6567,11 +6570,11 @@ "integrity": "sha512-4kJ5Esocg8X3h8YgJsKAuoesBgB7mqH3eowiDzMUPKiRDDE7E/BqqZD1hnTByIaAFiwAw246YEltSq7tdrOH0Q==", "dev": true, "requires": { - "bn.js": "4.11.8", - "browserify-rsa": "4.0.1", - "create-hash": "1.2.0", - "parse-asn1": "5.1.1", - "randombytes": "2.0.6" + "bn.js": "^4.1.0", + "browserify-rsa": "^4.0.0", + "create-hash": "^1.1.0", + "parse-asn1": "^5.0.0", + "randombytes": "^2.0.1" } }, "pump": { @@ -6580,8 +6583,8 @@ "integrity": "sha512-ruPMNRkN3MHP1cWJc9OWr+T/xDP0jhXYCLfJcBuX54hhfIBnaQmAUMfDcG4DM5UMWByBbJY69QSphm3jtDKIkA==", "dev": true, "requires": { - "end-of-stream": "1.4.1", - "once": "1.4.0" + "end-of-stream": "^1.1.0", + "once": "^1.3.1" } }, "pumpify": { @@ -6590,9 +6593,9 @@ "integrity": "sha512-oClZI37HvuUJJxSKKrC17bZ9Cu0ZYhEAGPsPUy9KlMUmv9dKX2o77RUmq7f3XjIxbwyGwYzbzQ1L2Ks8sIradQ==", "dev": true, "requires": { - "duplexify": "3.6.0", - "inherits": "2.0.3", - "pump": "2.0.1" + "duplexify": "^3.6.0", + "inherits": "^2.0.3", + "pump": "^2.0.0" } }, "punycode": { @@ -6631,8 +6634,8 @@ "integrity": "sha512-D5JUjPyJbaJDkuAazpVnSfVkLlpeO3wDlPROTMLGKG1zMFNFRgrciKo1ltz/AzNTkqE0HzDx655QOL51N06how==", "dev": true, "requires": { - "is-number": "3.0.0", - "kind-of": "4.0.0" + "is-number": "^3.0.0", + "kind-of": "^4.0.0" }, "dependencies": { "is-number": { @@ -6641,7 +6644,7 @@ "integrity": "sha1-JP1iAaR4LPUFYcgQJ2r8fRLXEZU=", "dev": true, "requires": { - "kind-of": "3.2.2" + "kind-of": "^3.0.2" }, "dependencies": { "kind-of": { @@ -6650,7 +6653,7 @@ "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", "dev": true, "requires": { - "is-buffer": "1.1.6" + "is-buffer": "^1.1.5" } } } @@ -6661,7 +6664,7 @@ "integrity": "sha1-IIE989cSkosgc3hpGkUGb65y3Vc=", "dev": true, "requires": { - "is-buffer": "1.1.6" + "is-buffer": "^1.1.5" } } } @@ -6672,7 +6675,7 @@ "integrity": "sha512-CIQ5OFxf4Jou6uOKe9t1AOgqpeU5fd70A8NPdHSGeYXqXsPe6peOwI0cUl88RWZ6sP1vPMV3avd/R6cZ5/sP1A==", "dev": true, "requires": { - "safe-buffer": "5.1.1" + "safe-buffer": "^5.1.0" } }, "randomfill": { @@ -6681,8 +6684,8 @@ "integrity": "sha512-87lcbR8+MhcWcUiQ+9e+Rwx8MyR2P7qnt15ynUlbm3TU/fjbgz4GsvfSUDTemtCCtVCqb4ZcEFlyPNTh9bBTLw==", "dev": true, "requires": { - "randombytes": "2.0.6", - "safe-buffer": "5.1.1" + "randombytes": "^2.0.5", + "safe-buffer": "^5.1.0" } }, "rc": { @@ -6691,10 +6694,10 @@ "integrity": "sha1-oPYGyq4qO4YrvQ74VILAElsxX6M=", "dev": true, "requires": { - "deep-extend": "0.4.2", - "ini": "1.3.5", - "minimist": "1.2.0", - "strip-json-comments": "2.0.1" + "deep-extend": "~0.4.0", + "ini": "~1.3.0", + "minimist": "^1.2.0", + "strip-json-comments": "~2.0.1" }, "dependencies": { "minimist": { @@ -6711,7 +6714,7 @@ "integrity": "sha1-LV0Vd4ajfAVdIgd8MsU/gynpHHs=", "dev": true, "requires": { - "graceful-fs": "4.1.11" + "graceful-fs": "^4.1.2" } }, "read-pkg": { @@ -6720,9 +6723,9 @@ "integrity": "sha1-9f+qXs0pyzHAR0vKfXVra7KePyg=", "dev": true, "requires": { - "load-json-file": "1.1.0", - "normalize-package-data": "2.4.0", - "path-type": "1.1.0" + "load-json-file": "^1.0.0", + "normalize-package-data": "^2.3.2", + "path-type": "^1.0.0" } }, "read-pkg-up": { @@ -6731,8 +6734,8 @@ "integrity": "sha1-nWPBMnbAZZGNV/ACpX9AobZD+wI=", "dev": true, "requires": { - "find-up": "1.1.2", - "read-pkg": "1.1.0" + "find-up": "^1.0.0", + "read-pkg": "^1.0.0" }, "dependencies": { "find-up": { @@ -6741,8 +6744,8 @@ "integrity": "sha1-ay6YIrGizgpgq2TWEOzK1TyyTQ8=", "dev": true, "requires": { - "path-exists": "2.1.0", - "pinkie-promise": "2.0.1" + "path-exists": "^2.0.0", + "pinkie-promise": "^2.0.0" } }, "path-exists": { @@ -6751,7 +6754,7 @@ "integrity": "sha1-D+tsZPD8UY2adU3V77YscCJ2H0s=", "dev": true, "requires": { - "pinkie-promise": "2.0.1" + "pinkie-promise": "^2.0.0" } } } @@ -6762,13 +6765,13 @@ "integrity": "sha512-m+qzzcn7KUxEmd1gMbchF+Y2eIUbieUaxkWtptyHywrX0rE8QEYqPC07Vuy4Wm32/xE16NcdBctb8S0Xe/5IeQ==", "dev": true, "requires": { - "core-util-is": "1.0.2", - "inherits": "2.0.3", - "isarray": "1.0.0", - "process-nextick-args": "1.0.7", - "safe-buffer": "5.1.1", - "string_decoder": "1.0.3", - "util-deprecate": "1.0.2" + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~1.0.6", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.0.3", + "util-deprecate": "~1.0.1" } }, "readdirp": { @@ -6777,10 +6780,10 @@ "integrity": "sha1-TtCtBg3zBzMAxIRANz9y0cxkLXg=", "dev": true, "requires": { - "graceful-fs": "4.1.11", - "minimatch": "3.0.4", - "readable-stream": "2.3.3", - "set-immediate-shim": "1.0.1" + "graceful-fs": "^4.1.2", + "minimatch": "^3.0.2", + "readable-stream": "^2.0.2", + "set-immediate-shim": "^1.0.1" } }, "realpath-native": { @@ -6789,7 +6792,7 @@ "integrity": "sha512-XJtlRJ9jf0E1H1SLeJyQ9PGzQD7S65h1pRXEcAeK48doKOnKxcgPeNohJvD5u/2sI9J1oke6E8bZHS/fmW1UiQ==", "dev": true, "requires": { - "util.promisify": "1.0.0" + "util.promisify": "^1.0.0" } }, "redent": { @@ -6798,8 +6801,8 @@ "integrity": "sha1-z5Fqsf1fHxbfsggi3W7H9zDCr94=", "dev": true, "requires": { - "indent-string": "2.1.0", - "strip-indent": "1.0.1" + "indent-string": "^2.1.0", + "strip-indent": "^1.0.1" } }, "regenerator-runtime": { @@ -6814,7 +6817,7 @@ "integrity": "sha512-nVIZwtCjkC9YgvWkpM55B5rBhBYRZhAaJbgcFYXXsHnbZ9UZI9nnVWYZpBlCqv9ho2eZryPnWrZGsOdPwVWXWQ==", "dev": true, "requires": { - "is-equal-shallow": "0.1.3" + "is-equal-shallow": "^0.1.3" } }, "regex-not": { @@ -6823,8 +6826,8 @@ "integrity": "sha512-J6SDjUgDxQj5NusnOtdFxDwN/+HWykR8GELwctJ7mdqhcyy1xEc4SRFHUXvxTp661YaVKAjfRLZ9cCqS6tn32A==", "dev": true, "requires": { - "extend-shallow": "3.0.2", - "safe-regex": "1.1.0" + "extend-shallow": "^3.0.2", + "safe-regex": "^1.1.0" } }, "registry-auth-token": { @@ -6833,8 +6836,8 @@ "integrity": "sha1-+w0yie4Nmtosu1KvXf5mywcNMAY=", "dev": true, "requires": { - "rc": "1.2.4", - "safe-buffer": "5.1.1" + "rc": "^1.1.6", + "safe-buffer": "^5.0.1" } }, "registry-url": { @@ -6843,7 +6846,7 @@ "integrity": "sha1-PU74cPc93h138M+aOBQyRE4XSUI=", "dev": true, "requires": { - "rc": "1.2.4" + "rc": "^1.0.1" } }, "remove-trailing-separator": { @@ -6870,7 +6873,7 @@ "integrity": "sha1-UhTFOpJtNVJwdSf7q0FdvAjQbdo=", "dev": true, "requires": { - "is-finite": "1.0.2" + "is-finite": "^1.0.0" } }, "request": { @@ -6879,28 +6882,28 @@ "integrity": "sha512-lR3gD69osqm6EYLk9wB/G1W/laGWjzH90t1vEa2xuxHD5KUrSzp9pUSfTm+YC5Nxt2T8nMPEvKlhbQayU7bgFw==", "dev": true, "requires": { - "aws-sign2": "0.7.0", - "aws4": "1.6.0", - "caseless": "0.12.0", - "combined-stream": "1.0.5", - "extend": "3.0.1", - "forever-agent": "0.6.1", - "form-data": "2.3.1", - "har-validator": "5.0.3", - "hawk": "6.0.2", - "http-signature": "1.2.0", - "is-typedarray": "1.0.0", - "isstream": "0.1.2", - "json-stringify-safe": "5.0.1", - "mime-types": "2.1.17", - "oauth-sign": "0.8.2", - "performance-now": "2.1.0", - "qs": "6.5.1", - "safe-buffer": "5.1.1", - "stringstream": "0.0.5", - "tough-cookie": "2.3.3", - "tunnel-agent": "0.6.0", - "uuid": "3.1.0" + "aws-sign2": "~0.7.0", + "aws4": "^1.6.0", + "caseless": "~0.12.0", + "combined-stream": "~1.0.5", + "extend": "~3.0.1", + "forever-agent": "~0.6.1", + "form-data": "~2.3.1", + "har-validator": "~5.0.3", + "hawk": "~6.0.2", + "http-signature": "~1.2.0", + "is-typedarray": "~1.0.0", + "isstream": "~0.1.2", + "json-stringify-safe": "~5.0.1", + "mime-types": "~2.1.17", + "oauth-sign": "~0.8.2", + "performance-now": "^2.1.0", + "qs": "~6.5.1", + "safe-buffer": "^5.1.1", + "stringstream": "~0.0.5", + "tough-cookie": "~2.3.3", + "tunnel-agent": "^0.6.0", + "uuid": "^3.1.0" } }, "request-promise-core": { @@ -6909,7 +6912,7 @@ "integrity": "sha1-Pu4AssWqgyOc+wTFcA2jb4HNCLY=", "dev": true, "requires": { - "lodash": "4.17.4" + "lodash": "^4.13.1" } }, "request-promise-native": { @@ -6919,8 +6922,8 @@ "dev": true, "requires": { "request-promise-core": "1.1.1", - "stealthy-require": "1.1.1", - "tough-cookie": "2.3.3" + "stealthy-require": "^1.1.0", + "tough-cookie": ">=2.3.3" } }, "require-directory": { @@ -6947,7 +6950,7 @@ "integrity": "sha1-AKn3OHVW4nA46uIyyqNypqWbZlo=", "dev": true, "requires": { - "resolve-from": "3.0.0" + "resolve-from": "^3.0.0" } }, "resolve-from": { @@ -6968,8 +6971,8 @@ "integrity": "sha1-n37ih/gv0ybU/RYpI9YhKe7g368=", "dev": true, "requires": { - "onetime": "2.0.1", - "signal-exit": "3.0.2" + "onetime": "^2.0.0", + "signal-exit": "^3.0.2" } }, "ret": { @@ -6985,7 +6988,7 @@ "dev": true, "optional": true, "requires": { - "align-text": "0.1.4" + "align-text": "^0.1.1" } }, "rimraf": { @@ -6994,7 +6997,7 @@ "integrity": "sha512-lreewLK/BlghmxtfH36YYVg1i8IAce4TI7oao75I1g245+6BctqTVQiBP3YUJ9C6DQOXJmkYR9X9fCLtCOJc5w==", "dev": true, "requires": { - "glob": "7.1.2" + "glob": "^7.0.5" } }, "ripemd160": { @@ -7003,8 +7006,8 @@ "integrity": "sha512-ii4iagi25WusVoiC4B4lq7pbXfAp3D9v5CwfkY33vffw2+pkDjY1D8GaN7spsxvCSx8dkPqOZCEZyfxcmJG2IA==", "dev": true, "requires": { - "hash-base": "3.0.4", - "inherits": "2.0.3" + "hash-base": "^3.0.0", + "inherits": "^2.0.1" } }, "run-async": { @@ -7013,7 +7016,7 @@ "integrity": "sha1-A3GrSuC91yDUFm19/aZP96RFpsA=", "dev": true, "requires": { - "is-promise": "2.1.0" + "is-promise": "^2.1.0" } }, "run-queue": { @@ -7022,7 +7025,7 @@ "integrity": "sha1-6Eg5bwV9Ij8kOGkkYY4laUFh7Ec=", "dev": true, "requires": { - "aproba": "1.2.0" + "aproba": "^1.1.1" } }, "rx-lite": { @@ -7037,7 +7040,7 @@ "integrity": "sha1-dTuHqJoRyVRnxKwWJsTvxOBcZ74=", "dev": true, "requires": { - "rx-lite": "4.0.8" + "rx-lite": "*" } }, "safe-buffer": { @@ -7052,7 +7055,7 @@ "integrity": "sha1-QKNmnzsHfR6UPURinhV91IAjvy4=", "dev": true, "requires": { - "ret": "0.1.15" + "ret": "~0.1.10" } }, "sane": { @@ -7061,14 +7064,14 @@ "integrity": "sha512-OSJxhHO0CgPUw3lUm3GhfREAfza45smvEI9ozuFrxKG10GHVo0ryW9FK5VYlLvxj0SV7HVKHW0voYJIRu27GWg==", "dev": true, "requires": { - "anymatch": "1.3.2", - "exec-sh": "0.2.1", - "fb-watchman": "2.0.0", - "fsevents": "1.1.3", - "minimatch": "3.0.4", - "minimist": "1.2.0", - "walker": "1.0.7", - "watch": "0.18.0" + "anymatch": "^1.3.0", + "exec-sh": "^0.2.0", + "fb-watchman": "^2.0.0", + "fsevents": "^1.1.1", + "minimatch": "^3.0.2", + "minimist": "^1.1.1", + "walker": "~1.0.5", + "watch": "~0.18.0" }, "dependencies": { "minimist": { @@ -7091,8 +7094,8 @@ "integrity": "sha512-yYrjb9TX2k/J1Y5UNy3KYdZq10xhYcF8nMpAW6o3hy6Q8WSIEf9lJHG/ePnOBfziPM3fvQwfOwa13U/Fh8qTfA==", "dev": true, "requires": { - "ajv": "6.5.0", - "ajv-keywords": "3.2.0" + "ajv": "^6.1.0", + "ajv-keywords": "^3.1.0" }, "dependencies": { "ajv": { @@ -7101,10 +7104,10 @@ "integrity": "sha512-VDUX1oSajablmiyFyED9L1DFndg0P9h7p1F+NO8FkIzei6EPrR6Zu1n18rd5P8PqaSRd/FrWv3G1TVBqpM83gA==", "dev": true, "requires": { - "fast-deep-equal": "2.0.1", - "fast-json-stable-stringify": "2.0.0", - "json-schema-traverse": "0.3.1", - "uri-js": "4.2.1" + "fast-deep-equal": "^2.0.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.3.0", + "uri-js": "^4.2.1" } }, "fast-deep-equal": { @@ -7145,10 +7148,10 @@ "integrity": "sha512-hw0yxk9GT/Hr5yJEYnHNKYXkIA8mVJgd9ditYZCe16ZczcaELYYcfvaXesNACk2O8O0nTiPQcQhGUQj8JLzeeg==", "dev": true, "requires": { - "extend-shallow": "2.0.1", - "is-extendable": "0.1.1", - "is-plain-object": "2.0.4", - "split-string": "3.1.0" + "extend-shallow": "^2.0.1", + "is-extendable": "^0.1.1", + "is-plain-object": "^2.0.3", + "split-string": "^3.0.1" }, "dependencies": { "extend-shallow": { @@ -7157,7 +7160,7 @@ "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", "dev": true, "requires": { - "is-extendable": "0.1.1" + "is-extendable": "^0.1.0" } } } @@ -7174,8 +7177,8 @@ "integrity": "sha512-QMEp5B7cftE7APOjk5Y6xgrbWu+WkLVQwk8JNjZ8nKRciZaByEW6MubieAiToS7+dwvrjGhH8jRXz3MVd0AYqQ==", "dev": true, "requires": { - "inherits": "2.0.3", - "safe-buffer": "5.1.1" + "inherits": "^2.0.1", + "safe-buffer": "^5.0.1" } }, "shebang-command": { @@ -7184,7 +7187,7 @@ "integrity": "sha1-RKrGW2lbAzmJaMOfNj/uXer98eo=", "dev": true, "requires": { - "shebang-regex": "1.0.0" + "shebang-regex": "^1.0.0" } }, "shebang-regex": { @@ -7217,14 +7220,14 @@ "integrity": "sha512-FtyOnWN/wCHTVXOMwvSv26d+ko5vWlIDD6zoUJ7LW8vh+ZBC8QdljveRP+crNrtBwioEUWy/4dMtbBjA4ioNlg==", "dev": true, "requires": { - "base": "0.11.2", - "debug": "2.6.9", - "define-property": "0.2.5", - "extend-shallow": "2.0.1", - "map-cache": "0.2.2", - "source-map": "0.5.7", - "source-map-resolve": "0.5.2", - "use": "3.1.0" + "base": "^0.11.1", + "debug": "^2.2.0", + "define-property": "^0.2.5", + "extend-shallow": "^2.0.1", + "map-cache": "^0.2.2", + "source-map": "^0.5.6", + "source-map-resolve": "^0.5.0", + "use": "^3.1.0" }, "dependencies": { "define-property": { @@ -7233,7 +7236,7 @@ "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=", "dev": true, "requires": { - "is-descriptor": "0.1.6" + "is-descriptor": "^0.1.0" } }, "extend-shallow": { @@ -7242,7 +7245,7 @@ "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", "dev": true, "requires": { - "is-extendable": "0.1.1" + "is-extendable": "^0.1.0" } } } @@ -7253,9 +7256,9 @@ "integrity": "sha512-O27l4xaMYt/RSQ5TR3vpWCAB5Kb/czIcqUFOM/C4fYcLnbZUc1PkjTAMjof2pBWaSTwOUd6qUHcFGVGj7aIwnw==", "dev": true, "requires": { - "define-property": "1.0.0", - "isobject": "3.0.1", - "snapdragon-util": "3.0.1" + "define-property": "^1.0.0", + "isobject": "^3.0.0", + "snapdragon-util": "^3.0.1" }, "dependencies": { "define-property": { @@ -7264,7 +7267,7 @@ "integrity": "sha1-dp66rz9KY6rTr56NMEybvnm/sOY=", "dev": true, "requires": { - "is-descriptor": "1.0.2" + "is-descriptor": "^1.0.0" } }, "is-accessor-descriptor": { @@ -7273,7 +7276,7 @@ "integrity": "sha512-m5hnHTkcVsPfqx3AKlyttIPb7J+XykHvJP2B9bZDjlhLIoEq4XoK64Vg7boZlVWYK6LUY94dYPEE7Lh0ZkZKcQ==", "dev": true, "requires": { - "kind-of": "6.0.2" + "kind-of": "^6.0.0" } }, "is-data-descriptor": { @@ -7282,7 +7285,7 @@ "integrity": "sha512-jbRXy1FmtAoCjQkVmIVYwuuqDFUbaOeDjmed1tOGPrsMhtJA4rD9tkgA0F1qJ3gRFRXcHYVkdeaP50Q5rE/jLQ==", "dev": true, "requires": { - "kind-of": "6.0.2" + "kind-of": "^6.0.0" } }, "is-descriptor": { @@ -7291,9 +7294,9 @@ "integrity": "sha512-2eis5WqQGV7peooDyLmNEPUrps9+SXX5c9pL3xEB+4e9HnGuDa7mB7kHxHw4CbqS9k1T2hOH3miL8n8WtiYVtg==", "dev": true, "requires": { - "is-accessor-descriptor": "1.0.0", - "is-data-descriptor": "1.0.0", - "kind-of": "6.0.2" + "is-accessor-descriptor": "^1.0.0", + "is-data-descriptor": "^1.0.0", + "kind-of": "^6.0.2" } }, "isobject": { @@ -7316,7 +7319,7 @@ "integrity": "sha512-mbKkMdQKsjX4BAL4bRYTj21edOf8cN7XHdYUJEe+Zn99hVEYcMvKPct1IqNe7+AZPirn8BCDOQBHQZknqmKlZQ==", "dev": true, "requires": { - "kind-of": "3.2.2" + "kind-of": "^3.2.0" } }, "sntp": { @@ -7325,7 +7328,7 @@ "integrity": "sha512-FL1b58BDrqS3A11lJ0zEdnJ3UOKqVxawAkF3k7F0CVN7VQ34aZrV+G8BZ1WC9ZL7NyrwsW0oviwsWDgRuVYtJg==", "dev": true, "requires": { - "hoek": "4.2.0" + "hoek": "4.x.x" } }, "sort-keys": { @@ -7334,7 +7337,7 @@ "integrity": "sha1-ZYU1WEhh7JfXMNbPQYIuH1ZoQSg=", "dev": true, "requires": { - "is-plain-obj": "1.1.0" + "is-plain-obj": "^1.0.0" } }, "source-list-map": { @@ -7355,11 +7358,11 @@ "integrity": "sha512-MjqsvNwyz1s0k81Goz/9vRBe9SZdB09Bdw+/zYyO+3CuPk6fouTaxscHkgtE8jKvf01kVfl8riHzERQ/kefaSA==", "dev": true, "requires": { - "atob": "2.1.1", - "decode-uri-component": "0.2.0", - "resolve-url": "0.2.1", - "source-map-url": "0.4.0", - "urix": "0.1.0" + "atob": "^2.1.1", + "decode-uri-component": "^0.2.0", + "resolve-url": "^0.2.1", + "source-map-url": "^0.4.0", + "urix": "^0.1.0" } }, "source-map-support": { @@ -7368,7 +7371,7 @@ "integrity": "sha512-EZNecLNrsdRk9fcdOcjjy+Z/id7cr68sdmsYtR1gA45oQ81Ccea0UvM7DdSRblO0Ie5zWX31bvJTC7Y3QZVujg==", "dev": true, "requires": { - "source-map": "0.6.1" + "source-map": "^0.6.0" }, "dependencies": { "source-map": { @@ -7391,7 +7394,7 @@ "integrity": "sha1-SzBz2TP/UfORLwOsVRlJikFQ20A=", "dev": true, "requires": { - "spdx-license-ids": "1.2.2" + "spdx-license-ids": "^1.0.2" } }, "spdx-expression-parse": { @@ -7412,7 +7415,7 @@ "integrity": "sha512-mTyOoPbrivtXnwnIxZRFYRrPNtEFKlpB2fvjSnCQUiAA6qAZzqwna5envK4uk6OIeP17CsdF3rSBGYVBsU0Tkg==", "dev": true, "requires": { - "through": "2.3.8" + "through": "2" } }, "split-string": { @@ -7421,7 +7424,7 @@ "integrity": "sha512-NzNVhJDYpwceVVii8/Hu6DKfD2G+NrQHlS/V/qgv763EYudVwEcMQNxd2lh+0VrUByXN/oJkl5grOhYWvQUYiw==", "dev": true, "requires": { - "extend-shallow": "3.0.2" + "extend-shallow": "^3.0.0" } }, "split2": { @@ -7430,7 +7433,7 @@ "integrity": "sha512-RAb22TG39LhI31MbreBgIuKiIKhVsawfTgEGqKHTK87aG+ul/PB8Sqoi3I7kVdRWiCfrKxK3uo4/YUkpNvhPbw==", "dev": true, "requires": { - "through2": "2.0.3" + "through2": "^2.0.2" } }, "sprintf-js": { @@ -7445,14 +7448,14 @@ "integrity": "sha1-US322mKHFEMW3EwY/hzx2UBzm+M=", "dev": true, "requires": { - "asn1": "0.2.3", - "assert-plus": "1.0.0", - "bcrypt-pbkdf": "1.0.1", - "dashdash": "1.14.1", - "ecc-jsbn": "0.1.1", - "getpass": "0.1.7", - "jsbn": "0.1.1", - "tweetnacl": "0.14.5" + "asn1": "~0.2.3", + "assert-plus": "^1.0.0", + "bcrypt-pbkdf": "^1.0.0", + "dashdash": "^1.12.0", + "ecc-jsbn": "~0.1.1", + "getpass": "^0.1.1", + "jsbn": "~0.1.0", + "tweetnacl": "~0.14.0" } }, "ssri": { @@ -7461,7 +7464,7 @@ "integrity": "sha512-XRSIPqLij52MtgoQavH/x/dU1qVKtWUAAZeOHsR9c2Ddi4XerFy3mc1alf+dLJKl9EUIm/Ht+EowFkTUOA6GAQ==", "dev": true, "requires": { - "safe-buffer": "5.1.1" + "safe-buffer": "^5.1.1" } }, "stack-utils": { @@ -7476,8 +7479,8 @@ "integrity": "sha1-YICcOcv/VTNyJv1eC1IPNB8ftcY=", "dev": true, "requires": { - "define-property": "0.2.5", - "object-copy": "0.1.0" + "define-property": "^0.2.5", + "object-copy": "^0.1.0" }, "dependencies": { "define-property": { @@ -7486,7 +7489,7 @@ "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=", "dev": true, "requires": { - "is-descriptor": "0.1.6" + "is-descriptor": "^0.1.0" } } } @@ -7503,8 +7506,8 @@ "integrity": "sha1-ZiZu5fm9uZQKTkUUyvtDu3Hlyds=", "dev": true, "requires": { - "inherits": "2.0.3", - "readable-stream": "2.3.3" + "inherits": "~2.0.1", + "readable-stream": "^2.0.2" } }, "stream-each": { @@ -7513,8 +7516,8 @@ "integrity": "sha512-mc1dbFhGBxvTM3bIWmAAINbqiuAk9TATcfIQC8P+/+HJefgaiTlMn2dHvkX8qlI12KeYKSQ1Ua9RrIqrn1VPoA==", "dev": true, "requires": { - "end-of-stream": "1.4.1", - "stream-shift": "1.0.0" + "end-of-stream": "^1.1.0", + "stream-shift": "^1.0.0" } }, "stream-http": { @@ -7523,11 +7526,11 @@ "integrity": "sha512-QllfrBhqF1DPcz46WxKTs6Mz1Bpc+8Qm6vbqOpVav5odAXwbyzwnEczoWqtxrsmlO+cJqtPrp/8gWKWjaKLLlA==", "dev": true, "requires": { - "builtin-status-codes": "3.0.0", - "inherits": "2.0.3", - "readable-stream": "2.3.6", - "to-arraybuffer": "1.0.1", - "xtend": "4.0.1" + "builtin-status-codes": "^3.0.0", + "inherits": "^2.0.1", + "readable-stream": "^2.3.6", + "to-arraybuffer": "^1.0.0", + "xtend": "^4.0.0" }, "dependencies": { "process-nextick-args": { @@ -7542,13 +7545,13 @@ "integrity": "sha512-tQtKA9WIAhBF3+VLAseyMqZeBjW0AHJoxOtYqSUZNJxauErmLbVm2FW1y+J/YA9dUrAC39ITejlZWhVIwawkKw==", "dev": true, "requires": { - "core-util-is": "1.0.2", - "inherits": "2.0.3", - "isarray": "1.0.0", - "process-nextick-args": "2.0.0", - "safe-buffer": "5.1.1", - "string_decoder": "1.1.1", - "util-deprecate": "1.0.2" + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" } }, "string_decoder": { @@ -7557,7 +7560,7 @@ "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", "dev": true, "requires": { - "safe-buffer": "5.1.1" + "safe-buffer": "~5.1.0" } } } @@ -7574,8 +7577,8 @@ "integrity": "sha1-1A27aGo6zpYMHP/KVivyxF+DY+0=", "dev": true, "requires": { - "astral-regex": "1.0.0", - "strip-ansi": "4.0.0" + "astral-regex": "^1.0.0", + "strip-ansi": "^4.0.0" } }, "string-width": { @@ -7584,8 +7587,8 @@ "integrity": "sha512-nOqH59deCq9SRHlxq1Aw85Jnt4w6KvLKqWVik6oA9ZklXLNIOlqg4F2yrT1MVaTjAqvVwdfeZ7w7aCvJD7ugkw==", "dev": true, "requires": { - "is-fullwidth-code-point": "2.0.0", - "strip-ansi": "4.0.0" + "is-fullwidth-code-point": "^2.0.0", + "strip-ansi": "^4.0.0" }, "dependencies": { "is-fullwidth-code-point": { @@ -7602,7 +7605,7 @@ "integrity": "sha512-4AH6Z5fzNNBcH+6XDMfA/BTt87skxqJlO0lAh3Dker5zThcAxG6mKz+iGu308UKoPPQ8Dcqx/4JhujzltRa+hQ==", "dev": true, "requires": { - "safe-buffer": "5.1.1" + "safe-buffer": "~5.1.0" } }, "stringstream": { @@ -7617,7 +7620,7 @@ "integrity": "sha1-qEeQIusaw2iocTibY1JixQXuNo8=", "dev": true, "requires": { - "ansi-regex": "3.0.0" + "ansi-regex": "^3.0.0" }, "dependencies": { "ansi-regex": { @@ -7634,7 +7637,7 @@ "integrity": "sha1-YhmoVhZSBJHzV4i9vxRHqZx+aw4=", "dev": true, "requires": { - "is-utf8": "0.2.1" + "is-utf8": "^0.2.0" } }, "strip-eof": { @@ -7649,7 +7652,7 @@ "integrity": "sha1-DHlipq3vp7vUrDZkYKY4VSrhoKI=", "dev": true, "requires": { - "get-stdin": "4.0.1" + "get-stdin": "^4.0.1" } }, "strip-json-comments": { @@ -7664,11 +7667,11 @@ "integrity": "sha1-9/uTdYpppXEUAYEnfuoMLrEwH6M=", "dev": true, "requires": { - "byline": "5.0.0", - "duplexer": "0.1.1", - "minimist": "0.1.0", - "moment": "2.20.1", - "through": "2.3.8" + "byline": "^5.0.0", + "duplexer": "^0.1.1", + "minimist": "^0.1.0", + "moment": "^2.6.0", + "through": "^2.3.4" }, "dependencies": { "minimist": { @@ -7685,7 +7688,7 @@ "integrity": "sha1-vnoN5ITexcXN34s9WRJQRJEvY1s=", "dev": true, "requires": { - "has-flag": "2.0.0" + "has-flag": "^2.0.0" } }, "symbol-tree": { @@ -7712,12 +7715,12 @@ "integrity": "sha1-jP9jD7fp2gXwR8dM5M5NaFRX1JI=", "dev": true, "requires": { - "graceful-fs": "4.1.11", - "is-stream": "1.1.0", - "make-dir": "1.1.0", - "pify": "3.0.0", - "temp-dir": "1.0.0", - "uuid": "3.1.0" + "graceful-fs": "^4.1.2", + "is-stream": "^1.1.0", + "make-dir": "^1.0.0", + "pify": "^3.0.0", + "temp-dir": "^1.0.0", + "uuid": "^3.0.1" }, "dependencies": { "pify": { @@ -7734,8 +7737,8 @@ "integrity": "sha1-W8xOrsxKsscH2LwR2ZzMmiyyh/I=", "dev": true, "requires": { - "os-tmpdir": "1.0.2", - "uuid": "2.0.3" + "os-tmpdir": "^1.0.0", + "uuid": "^2.0.1" }, "dependencies": { "uuid": { @@ -7752,11 +7755,11 @@ "integrity": "sha512-35+Asrsk3XHJDBgf/VRFexPgh3UyETv8IAn/LRTiZjVy6rjPVqdEk8dJcJYBzl1w0XCJM48lvTy8SfEsCWS4nA==", "dev": true, "requires": { - "arrify": "1.0.1", - "micromatch": "2.3.11", - "object-assign": "4.1.1", - "read-pkg-up": "1.0.1", - "require-main-filename": "1.0.1" + "arrify": "^1.0.1", + "micromatch": "^2.3.11", + "object-assign": "^4.1.0", + "read-pkg-up": "^1.0.1", + "require-main-filename": "^1.0.1" } }, "text-extensions": { @@ -7783,8 +7786,8 @@ "integrity": "sha1-AARWmzfHx0ujnEPzzteNGtlBQL4=", "dev": true, "requires": { - "readable-stream": "2.3.3", - "xtend": "4.0.1" + "readable-stream": "^2.1.5", + "xtend": "~4.0.1" } }, "timed-out": { @@ -7799,7 +7802,7 @@ "integrity": "sha512-YvC1SV1XdOUaL6gx5CoGroT3Gu49pK9+TZ38ErPldOWW4j49GI1HKs9DV+KGq/w6y+LZ72W1c8cKz2vzY+qpzg==", "dev": true, "requires": { - "setimmediate": "1.0.5" + "setimmediate": "^1.0.4" } }, "tmp": { @@ -7808,7 +7811,7 @@ "integrity": "sha512-jRCJlojKnZ3addtTOjdIqoRuPEKBvNXcGYqzO6zWZX8KfKEpnGY5jfggJQ3EjKuu8D4bJRr0y+cYJFmYbImXGw==", "dev": true, "requires": { - "os-tmpdir": "1.0.2" + "os-tmpdir": "~1.0.2" } }, "tmpl": { @@ -7835,7 +7838,7 @@ "integrity": "sha1-KXWIt7Dn4KwI4E5nL4XB9JmeF68=", "dev": true, "requires": { - "kind-of": "3.2.2" + "kind-of": "^3.0.2" } }, "to-regex": { @@ -7844,10 +7847,10 @@ "integrity": "sha512-FWtleNAtZ/Ki2qtqej2CXTOayOH9bHDQF+Q48VpWyDXjbYxA4Yz8iDB31zXOBUlOHHKidDbqGVrTUvQMPmBGBw==", "dev": true, "requires": { - "define-property": "2.0.2", - "extend-shallow": "3.0.2", - "regex-not": "1.0.2", - "safe-regex": "1.1.0" + "define-property": "^2.0.2", + "extend-shallow": "^3.0.2", + "regex-not": "^1.0.2", + "safe-regex": "^1.1.0" } }, "to-regex-range": { @@ -7856,8 +7859,8 @@ "integrity": "sha1-fIDBe53+vlmeJzZ+DU3VWQFB2zg=", "dev": true, "requires": { - "is-number": "3.0.0", - "repeat-string": "1.6.1" + "is-number": "^3.0.0", + "repeat-string": "^1.6.1" }, "dependencies": { "is-number": { @@ -7866,7 +7869,7 @@ "integrity": "sha1-JP1iAaR4LPUFYcgQJ2r8fRLXEZU=", "dev": true, "requires": { - "kind-of": "3.2.2" + "kind-of": "^3.0.2" } } } @@ -7877,7 +7880,7 @@ "integrity": "sha1-C2GKVWW23qkL80JdBNVe3EdadWE=", "dev": true, "requires": { - "punycode": "1.4.1" + "punycode": "^1.4.1" } }, "tr46": { @@ -7886,7 +7889,7 @@ "integrity": "sha1-qLE/1r/SSJUZZ0zN5VujaTtwbQk=", "dev": true, "requires": { - "punycode": "2.1.0" + "punycode": "^2.1.0" }, "dependencies": { "punycode": { @@ -7927,7 +7930,7 @@ "integrity": "sha1-J6XeoGs2sEoKmWZ3SykIaPD8QP0=", "dev": true, "requires": { - "safe-buffer": "5.1.1" + "safe-buffer": "^5.0.1" } }, "tweetnacl": { @@ -7943,7 +7946,7 @@ "integrity": "sha1-WITKtRLPHTVeP7eE8wgEsrUg23I=", "dev": true, "requires": { - "prelude-ls": "1.1.2" + "prelude-ls": "~1.1.2" } }, "typedarray": { @@ -7959,9 +7962,9 @@ "dev": true, "optional": true, "requires": { - "source-map": "0.5.7", - "uglify-to-browserify": "1.0.2", - "yargs": "3.10.0" + "source-map": "~0.5.1", + "uglify-to-browserify": "~1.0.0", + "yargs": "~3.10.0" }, "dependencies": { "yargs": { @@ -7971,9 +7974,9 @@ "dev": true, "optional": true, "requires": { - "camelcase": "1.2.1", - "cliui": "2.1.0", - "decamelize": "1.2.0", + "camelcase": "^1.0.2", + "cliui": "^2.1.0", + "decamelize": "^1.0.0", "window-size": "0.1.0" } } @@ -7992,14 +7995,14 @@ "integrity": "sha512-hIQJ1yxAPhEA2yW/i7Fr+SXZVMp+VEI3d42RTHBgQd2yhp/1UdBcR3QEWPV5ahBxlqQDMEMTuTEvDHSFINfwSw==", "dev": true, "requires": { - "cacache": "10.0.4", - "find-cache-dir": "1.0.0", - "schema-utils": "0.4.5", - "serialize-javascript": "1.5.0", - "source-map": "0.6.1", - "uglify-es": "3.3.9", - "webpack-sources": "1.1.0", - "worker-farm": "1.6.0" + "cacache": "^10.0.4", + "find-cache-dir": "^1.0.0", + "schema-utils": "^0.4.5", + "serialize-javascript": "^1.4.0", + "source-map": "^0.6.1", + "uglify-es": "^3.3.4", + "webpack-sources": "^1.1.0", + "worker-farm": "^1.5.2" }, "dependencies": { "source-map": { @@ -8014,8 +8017,8 @@ "integrity": "sha512-r+MU0rfv4L/0eeW3xZrd16t4NZfK8Ld4SWVglYBb7ez5uXFWHuVRs6xCTrf1yirs9a4j4Y27nn7SRfO6v67XsQ==", "dev": true, "requires": { - "commander": "2.13.0", - "source-map": "0.6.1" + "commander": "~2.13.0", + "source-map": "~0.6.1" } } } @@ -8026,10 +8029,10 @@ "integrity": "sha1-XHHDTLW61dzr4+oM0IIHulqhrqQ=", "dev": true, "requires": { - "arr-union": "3.1.0", - "get-value": "2.0.6", - "is-extendable": "0.1.1", - "set-value": "0.4.3" + "arr-union": "^3.1.0", + "get-value": "^2.0.6", + "is-extendable": "^0.1.1", + "set-value": "^0.4.3" }, "dependencies": { "extend-shallow": { @@ -8038,7 +8041,7 @@ "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", "dev": true, "requires": { - "is-extendable": "0.1.1" + "is-extendable": "^0.1.0" } }, "set-value": { @@ -8047,10 +8050,10 @@ "integrity": "sha1-fbCPnT0i3H945Trzw79GZuzfzPE=", "dev": true, "requires": { - "extend-shallow": "2.0.1", - "is-extendable": "0.1.1", - "is-plain-object": "2.0.4", - "to-object-path": "0.3.0" + "extend-shallow": "^2.0.1", + "is-extendable": "^0.1.1", + "is-plain-object": "^2.0.1", + "to-object-path": "^0.3.0" } } } @@ -8061,7 +8064,7 @@ "integrity": "sha1-0F8v5AMlYIcfMOk8vnNe6iAVFPM=", "dev": true, "requires": { - "unique-slug": "2.0.0" + "unique-slug": "^2.0.0" } }, "unique-slug": { @@ -8070,7 +8073,7 @@ "integrity": "sha1-22Z258fMBimHj/GWCXx4hVrp9Ks=", "dev": true, "requires": { - "imurmurhash": "0.1.4" + "imurmurhash": "^0.1.4" } }, "universalify": { @@ -8085,8 +8088,8 @@ "integrity": "sha1-g3aHP30jNRef+x5vw6jtDfyKtVk=", "dev": true, "requires": { - "has-value": "0.3.1", - "isobject": "3.0.1" + "has-value": "^0.3.1", + "isobject": "^3.0.0" }, "dependencies": { "has-value": { @@ -8095,9 +8098,9 @@ "integrity": "sha1-ex9YutpiyoJ+wKIHgCVlSEWZXh8=", "dev": true, "requires": { - "get-value": "2.0.6", - "has-values": "0.1.4", - "isobject": "2.1.0" + "get-value": "^2.0.3", + "has-values": "^0.1.4", + "isobject": "^2.0.0" }, "dependencies": { "isobject": { @@ -8143,7 +8146,7 @@ "integrity": "sha512-jpKCA3HjsBfSDOEgxRDAxQCNyHfCPSbq57PqCkd3gAyBuPb3IWxw54EHncqESznIdqSetHfw3D7ylThu2Kcc9A==", "dev": true, "requires": { - "punycode": "2.1.0" + "punycode": "^2.1.0" }, "dependencies": { "punycode": { @@ -8184,7 +8187,7 @@ "integrity": "sha1-evjzA2Rem9eaJy56FKxovAYJ2nM=", "dev": true, "requires": { - "prepend-http": "1.0.4" + "prepend-http": "^1.0.1" } }, "use": { @@ -8193,7 +8196,7 @@ "integrity": "sha512-6UJEQM/L+mzC3ZJNM56Q4DFGLX/evKGRg15UJHGB9X5j5Z3AFbgZvjUh2yq/UJUY4U5dh7Fal++XbNg1uzpRAw==", "dev": true, "requires": { - "kind-of": "6.0.2" + "kind-of": "^6.0.2" }, "dependencies": { "kind-of": { @@ -8233,8 +8236,8 @@ "integrity": "sha512-i+6qA2MPhvoKLuxnJNpXAGhg7HphQOSUq2LKMZD0m15EiskXUkMvKdF4Uui0WYeCUGea+o2cw/ZuwehtfsrNkA==", "dev": true, "requires": { - "define-properties": "1.1.2", - "object.getownpropertydescriptors": "2.0.3" + "define-properties": "^1.1.2", + "object.getownpropertydescriptors": "^2.0.3" } }, "uuid": { @@ -8249,8 +8252,8 @@ "integrity": "sha1-KAS6vnEq0zeUWaz74kdGqywwP7w=", "dev": true, "requires": { - "spdx-correct": "1.0.2", - "spdx-expression-parse": "1.0.4" + "spdx-correct": "~1.0.0", + "spdx-expression-parse": "~1.0.0" } }, "verror": { @@ -8259,9 +8262,9 @@ "integrity": "sha1-OhBcoXBTr1XW4nDB+CiGguGNpAA=", "dev": true, "requires": { - "assert-plus": "1.0.0", + "assert-plus": "^1.0.0", "core-util-is": "1.0.2", - "extsprintf": "1.3.0" + "extsprintf": "^1.2.0" } }, "vm-browserify": { @@ -8279,7 +8282,7 @@ "integrity": "sha1-L3+bj9ENZ3JisYqITijRlhjgKPs=", "dev": true, "requires": { - "makeerror": "1.0.11" + "makeerror": "1.0.x" } }, "watch": { @@ -8288,8 +8291,8 @@ "integrity": "sha1-KAlUdsbffJDJYxOJkMClQj60uYY=", "dev": true, "requires": { - "exec-sh": "0.2.1", - "minimist": "1.2.0" + "exec-sh": "^0.2.0", + "minimist": "^1.2.0" }, "dependencies": { "minimist": { @@ -8306,9 +8309,9 @@ "integrity": "sha512-i6dHe3EyLjMmDlU1/bGQpEw25XSjkJULPuAVKCbNRefQVq48yXKUpwg538F7AZTf9kyr57zj++pQFltUa5H7yA==", "dev": true, "requires": { - "chokidar": "2.0.3", - "graceful-fs": "4.1.11", - "neo-async": "2.5.1" + "chokidar": "^2.0.2", + "graceful-fs": "^4.1.2", + "neo-async": "^2.5.0" } }, "wcwidth": { @@ -8317,7 +8320,7 @@ "integrity": "sha1-8LDc+RW8X/FSivrbLA4XtTLaL+g=", "dev": true, "requires": { - "defaults": "1.0.3" + "defaults": "^1.0.3" } }, "webassemblyjs": { @@ -8330,7 +8333,7 @@ "@webassemblyjs/validation": "1.4.3", "@webassemblyjs/wasm-parser": "1.4.3", "@webassemblyjs/wast-parser": "1.4.3", - "long": "3.2.0" + "long": "^3.2.0" } }, "webidl-conversions": { @@ -8348,25 +8351,25 @@ "@webassemblyjs/ast": "1.4.3", "@webassemblyjs/wasm-edit": "1.4.3", "@webassemblyjs/wasm-parser": "1.4.3", - "acorn": "5.3.0", - "acorn-dynamic-import": "3.0.0", - "ajv": "6.5.0", - "ajv-keywords": "3.2.0", - "chrome-trace-event": "0.1.3", - "enhanced-resolve": "4.0.0", - "eslint-scope": "3.7.1", - "loader-runner": "2.3.0", - "loader-utils": "1.1.0", - "memory-fs": "0.4.1", - "micromatch": "3.1.10", - "mkdirp": "0.5.1", - "neo-async": "2.5.1", - "node-libs-browser": "2.1.0", - "schema-utils": "0.4.5", - "tapable": "1.0.0", - "uglifyjs-webpack-plugin": "1.2.5", - "watchpack": "1.6.0", - "webpack-sources": "1.1.0" + "acorn": "^5.0.0", + "acorn-dynamic-import": "^3.0.0", + "ajv": "^6.1.0", + "ajv-keywords": "^3.1.0", + "chrome-trace-event": "^0.1.1", + "enhanced-resolve": "^4.0.0", + "eslint-scope": "^3.7.1", + "loader-runner": "^2.3.0", + "loader-utils": "^1.1.0", + "memory-fs": "~0.4.1", + "micromatch": "^3.1.8", + "mkdirp": "~0.5.0", + "neo-async": "^2.5.0", + "node-libs-browser": "^2.0.0", + "schema-utils": "^0.4.4", + "tapable": "^1.0.0", + "uglifyjs-webpack-plugin": "^1.2.4", + "watchpack": "^1.5.0", + "webpack-sources": "^1.0.1" }, "dependencies": { "ajv": { @@ -8375,10 +8378,10 @@ "integrity": "sha512-VDUX1oSajablmiyFyED9L1DFndg0P9h7p1F+NO8FkIzei6EPrR6Zu1n18rd5P8PqaSRd/FrWv3G1TVBqpM83gA==", "dev": true, "requires": { - "fast-deep-equal": "2.0.1", - "fast-json-stable-stringify": "2.0.0", - "json-schema-traverse": "0.3.1", - "uri-js": "4.2.1" + "fast-deep-equal": "^2.0.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.3.0", + "uri-js": "^4.2.1" } }, "arr-diff": { @@ -8399,16 +8402,16 @@ "integrity": "sha512-aNdbnj9P8PjdXU4ybaWLK2IF3jc/EoDYbC7AazW6to3TRsfXxscC9UXOB5iDiEQrkyIbWp2SLQda4+QAa7nc3w==", "dev": true, "requires": { - "arr-flatten": "1.1.0", - "array-unique": "0.3.2", - "extend-shallow": "2.0.1", - "fill-range": "4.0.0", - "isobject": "3.0.1", - "repeat-element": "1.1.2", - "snapdragon": "0.8.2", - "snapdragon-node": "2.1.1", - "split-string": "3.1.0", - "to-regex": "3.0.2" + "arr-flatten": "^1.1.0", + "array-unique": "^0.3.2", + "extend-shallow": "^2.0.1", + "fill-range": "^4.0.0", + "isobject": "^3.0.1", + "repeat-element": "^1.1.2", + "snapdragon": "^0.8.1", + "snapdragon-node": "^2.0.1", + "split-string": "^3.0.2", + "to-regex": "^3.0.1" }, "dependencies": { "extend-shallow": { @@ -8417,7 +8420,7 @@ "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", "dev": true, "requires": { - "is-extendable": "0.1.1" + "is-extendable": "^0.1.0" } } } @@ -8428,13 +8431,13 @@ "integrity": "sha1-t3c14xXOMPa27/D4OwQVGiJEliI=", "dev": true, "requires": { - "debug": "2.6.9", - "define-property": "0.2.5", - "extend-shallow": "2.0.1", - "posix-character-classes": "0.1.1", - "regex-not": "1.0.2", - "snapdragon": "0.8.2", - "to-regex": "3.0.2" + "debug": "^2.3.3", + "define-property": "^0.2.5", + "extend-shallow": "^2.0.1", + "posix-character-classes": "^0.1.0", + "regex-not": "^1.0.0", + "snapdragon": "^0.8.1", + "to-regex": "^3.0.1" }, "dependencies": { "define-property": { @@ -8443,7 +8446,7 @@ "integrity": "sha1-w1se+RjsPJkPmlvFe+BKrOxcgRY=", "dev": true, "requires": { - "is-descriptor": "0.1.6" + "is-descriptor": "^0.1.0" } }, "extend-shallow": { @@ -8452,7 +8455,7 @@ "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", "dev": true, "requires": { - "is-extendable": "0.1.1" + "is-extendable": "^0.1.0" } }, "is-accessor-descriptor": { @@ -8461,7 +8464,7 @@ "integrity": "sha1-qeEss66Nh2cn7u84Q/igiXtcmNY=", "dev": true, "requires": { - "kind-of": "3.2.2" + "kind-of": "^3.0.2" }, "dependencies": { "kind-of": { @@ -8470,7 +8473,7 @@ "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", "dev": true, "requires": { - "is-buffer": "1.1.6" + "is-buffer": "^1.1.5" } } } @@ -8481,7 +8484,7 @@ "integrity": "sha1-C17mSDiOLIYCgueT8YVv7D8wG1Y=", "dev": true, "requires": { - "kind-of": "3.2.2" + "kind-of": "^3.0.2" }, "dependencies": { "kind-of": { @@ -8490,7 +8493,7 @@ "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", "dev": true, "requires": { - "is-buffer": "1.1.6" + "is-buffer": "^1.1.5" } } } @@ -8501,9 +8504,9 @@ "integrity": "sha512-avDYr0SB3DwO9zsMov0gKCESFYqCnE4hq/4z3TdUlukEy5t9C0YRq7HLrsN52NAcqXKaepeCD0n+B0arnVG3Hg==", "dev": true, "requires": { - "is-accessor-descriptor": "0.1.6", - "is-data-descriptor": "0.1.4", - "kind-of": "5.1.0" + "is-accessor-descriptor": "^0.1.6", + "is-data-descriptor": "^0.1.4", + "kind-of": "^5.0.0" } }, "kind-of": { @@ -8520,14 +8523,14 @@ "integrity": "sha512-Nmb6QXkELsuBr24CJSkilo6UHHgbekK5UiZgfE6UHD3Eb27YC6oD+bhcT+tJ6cl8dmsgdQxnWlcry8ksBIBLpw==", "dev": true, "requires": { - "array-unique": "0.3.2", - "define-property": "1.0.0", - "expand-brackets": "2.1.4", - "extend-shallow": "2.0.1", - "fragment-cache": "0.2.1", - "regex-not": "1.0.2", - "snapdragon": "0.8.2", - "to-regex": "3.0.2" + "array-unique": "^0.3.2", + "define-property": "^1.0.0", + "expand-brackets": "^2.1.4", + "extend-shallow": "^2.0.1", + "fragment-cache": "^0.2.1", + "regex-not": "^1.0.0", + "snapdragon": "^0.8.1", + "to-regex": "^3.0.1" }, "dependencies": { "define-property": { @@ -8536,7 +8539,7 @@ "integrity": "sha1-dp66rz9KY6rTr56NMEybvnm/sOY=", "dev": true, "requires": { - "is-descriptor": "1.0.2" + "is-descriptor": "^1.0.0" } }, "extend-shallow": { @@ -8545,7 +8548,7 @@ "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", "dev": true, "requires": { - "is-extendable": "0.1.1" + "is-extendable": "^0.1.0" } } } @@ -8562,10 +8565,10 @@ "integrity": "sha1-1USBHUKPmOsGpj3EAtJAPDKMOPc=", "dev": true, "requires": { - "extend-shallow": "2.0.1", - "is-number": "3.0.0", - "repeat-string": "1.6.1", - "to-regex-range": "2.1.1" + "extend-shallow": "^2.0.1", + "is-number": "^3.0.0", + "repeat-string": "^1.6.1", + "to-regex-range": "^2.1.0" }, "dependencies": { "extend-shallow": { @@ -8574,7 +8577,7 @@ "integrity": "sha1-Ua99YUrZqfYQ6huvu5idaxxWiQ8=", "dev": true, "requires": { - "is-extendable": "0.1.1" + "is-extendable": "^0.1.0" } } } @@ -8585,7 +8588,7 @@ "integrity": "sha512-m5hnHTkcVsPfqx3AKlyttIPb7J+XykHvJP2B9bZDjlhLIoEq4XoK64Vg7boZlVWYK6LUY94dYPEE7Lh0ZkZKcQ==", "dev": true, "requires": { - "kind-of": "6.0.2" + "kind-of": "^6.0.0" } }, "is-data-descriptor": { @@ -8594,7 +8597,7 @@ "integrity": "sha512-jbRXy1FmtAoCjQkVmIVYwuuqDFUbaOeDjmed1tOGPrsMhtJA4rD9tkgA0F1qJ3gRFRXcHYVkdeaP50Q5rE/jLQ==", "dev": true, "requires": { - "kind-of": "6.0.2" + "kind-of": "^6.0.0" } }, "is-descriptor": { @@ -8603,9 +8606,9 @@ "integrity": "sha512-2eis5WqQGV7peooDyLmNEPUrps9+SXX5c9pL3xEB+4e9HnGuDa7mB7kHxHw4CbqS9k1T2hOH3miL8n8WtiYVtg==", "dev": true, "requires": { - "is-accessor-descriptor": "1.0.0", - "is-data-descriptor": "1.0.0", - "kind-of": "6.0.2" + "is-accessor-descriptor": "^1.0.0", + "is-data-descriptor": "^1.0.0", + "kind-of": "^6.0.2" } }, "is-number": { @@ -8614,7 +8617,7 @@ "integrity": "sha1-JP1iAaR4LPUFYcgQJ2r8fRLXEZU=", "dev": true, "requires": { - "kind-of": "3.2.2" + "kind-of": "^3.0.2" }, "dependencies": { "kind-of": { @@ -8623,7 +8626,7 @@ "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", "dev": true, "requires": { - "is-buffer": "1.1.6" + "is-buffer": "^1.1.5" } } } @@ -8646,19 +8649,19 @@ "integrity": "sha512-MWikgl9n9M3w+bpsY3He8L+w9eF9338xRl8IAO5viDizwSzziFEyUzo2xrrloB64ADbTf8uA8vRqqttDTOmccg==", "dev": true, "requires": { - "arr-diff": "4.0.0", - "array-unique": "0.3.2", - "braces": "2.3.2", - "define-property": "2.0.2", - "extend-shallow": "3.0.2", - "extglob": "2.0.4", - "fragment-cache": "0.2.1", - "kind-of": "6.0.2", - "nanomatch": "1.2.9", - "object.pick": "1.3.0", - "regex-not": "1.0.2", - "snapdragon": "0.8.2", - "to-regex": "3.0.2" + "arr-diff": "^4.0.0", + "array-unique": "^0.3.2", + "braces": "^2.3.1", + "define-property": "^2.0.2", + "extend-shallow": "^3.0.2", + "extglob": "^2.0.4", + "fragment-cache": "^0.2.1", + "kind-of": "^6.0.2", + "nanomatch": "^1.2.9", + "object.pick": "^1.3.0", + "regex-not": "^1.0.0", + "snapdragon": "^0.8.1", + "to-regex": "^3.0.2" } } } @@ -8669,8 +8672,8 @@ "integrity": "sha512-aqYp18kPphgoO5c/+NaUvEeACtZjMESmDChuD3NBciVpah3XpMEU9VAAtIaB1BsfJWWTSdv8Vv1m3T0aRk2dUw==", "dev": true, "requires": { - "source-list-map": "2.0.0", - "source-map": "0.6.1" + "source-list-map": "^2.0.0", + "source-map": "~0.6.1" }, "dependencies": { "source-map": { @@ -8696,9 +8699,9 @@ "integrity": "sha512-Z0CVh/YE217Foyb488eo+iBv+r7eAQ0wSTyApi9n06jhcA3z6Nidg/EGvl0UFkg7kMdKxfBzzr+o9JF+cevgMg==", "dev": true, "requires": { - "lodash.sortby": "4.7.0", - "tr46": "1.0.1", - "webidl-conversions": "4.0.2" + "lodash.sortby": "^4.7.0", + "tr46": "^1.0.0", + "webidl-conversions": "^4.0.1" } }, "which": { @@ -8707,7 +8710,7 @@ "integrity": "sha512-xcJpopdamTuY5duC/KnTTNBraPK54YwpenP4lzxU8H91GudWpFv38u0CKjclE1Wi2EH2EDz5LRcHcKbCIzqGyg==", "dev": true, "requires": { - "isexe": "2.0.0" + "isexe": "^2.0.0" } }, "which-module": { @@ -8722,7 +8725,7 @@ "integrity": "sha512-ijDLlyQ7s6x1JgCLur53osjm/UXUYD9+0PbYKrBsYisYXzCxN+HC3mYDNy/dWdmf3AwqwU3CXwDCvsNgGK1S0w==", "dev": true, "requires": { - "string-width": "1.0.2" + "string-width": "^1.0.2" }, "dependencies": { "string-width": { @@ -8731,9 +8734,9 @@ "integrity": "sha1-EYvfW4zcUaKn5w0hHgfisLmxB9M=", "dev": true, "requires": { - "code-point-at": "1.1.0", - "is-fullwidth-code-point": "1.0.0", - "strip-ansi": "3.0.1" + "code-point-at": "^1.0.0", + "is-fullwidth-code-point": "^1.0.0", + "strip-ansi": "^3.0.0" } }, "strip-ansi": { @@ -8742,7 +8745,7 @@ "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", "dev": true, "requires": { - "ansi-regex": "2.1.1" + "ansi-regex": "^2.0.0" } } } @@ -8766,7 +8769,7 @@ "integrity": "sha512-6w+3tHbM87WnSWnENBUvA2pxJPLhQUg5LKwUQHq3r+XPhIM+Gh2R5ycbwPCyuGbNg+lPgdcnQUhuC02kJCvffQ==", "dev": true, "requires": { - "errno": "0.1.7" + "errno": "~0.1.7" } }, "wrap-ansi": { @@ -8775,8 +8778,8 @@ "integrity": "sha1-2Pw9KE3QV5T+hJc8rs3Rz4JP3YU=", "dev": true, "requires": { - "string-width": "1.0.2", - "strip-ansi": "3.0.1" + "string-width": "^1.0.1", + "strip-ansi": "^3.0.1" }, "dependencies": { "string-width": { @@ -8785,9 +8788,9 @@ "integrity": "sha1-EYvfW4zcUaKn5w0hHgfisLmxB9M=", "dev": true, "requires": { - "code-point-at": "1.1.0", - "is-fullwidth-code-point": "1.0.0", - "strip-ansi": "3.0.1" + "code-point-at": "^1.0.0", + "is-fullwidth-code-point": "^1.0.0", + "strip-ansi": "^3.0.0" } }, "strip-ansi": { @@ -8796,7 +8799,7 @@ "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", "dev": true, "requires": { - "ansi-regex": "2.1.1" + "ansi-regex": "^2.0.0" } } } @@ -8813,9 +8816,9 @@ "integrity": "sha512-xuPeK4OdjWqtfi59ylvVL0Yn35SF3zgcAcv7rBPFHVaEapaDr4GdGgm3j7ckTwH9wHL7fGmgfAnb0+THrHb8tA==", "dev": true, "requires": { - "graceful-fs": "4.1.11", - "imurmurhash": "0.1.4", - "signal-exit": "3.0.2" + "graceful-fs": "^4.1.11", + "imurmurhash": "^0.1.4", + "signal-exit": "^3.0.2" } }, "write-json-file": { @@ -8824,12 +8827,12 @@ "integrity": "sha1-K2TIozAE1UuGmMdtWFp3zrYdoy8=", "dev": true, "requires": { - "detect-indent": "5.0.0", - "graceful-fs": "4.1.11", - "make-dir": "1.1.0", - "pify": "3.0.0", - "sort-keys": "2.0.0", - "write-file-atomic": "2.3.0" + "detect-indent": "^5.0.0", + "graceful-fs": "^4.1.2", + "make-dir": "^1.0.0", + "pify": "^3.0.0", + "sort-keys": "^2.0.0", + "write-file-atomic": "^2.0.0" }, "dependencies": { "detect-indent": { @@ -8852,8 +8855,8 @@ "integrity": "sha1-AwqZlMyZk9JbTnWp8aGSNgcpHOk=", "dev": true, "requires": { - "sort-keys": "2.0.0", - "write-json-file": "2.3.0" + "sort-keys": "^2.0.0", + "write-json-file": "^2.2.0" } }, "xml-name-validator": { @@ -8886,18 +8889,18 @@ "integrity": "sha512-7uRL1HZdCbc1QTP+X8mehOPuCYKC/XTaqAPj7gABLfTt6pgLyVRn3QVte4qhtilZouWCvqd1kipgMKl5tKsFiw==", "dev": true, "requires": { - "cliui": "4.0.0", - "decamelize": "1.2.0", - "find-up": "2.1.0", - "get-caller-file": "1.0.2", - "os-locale": "2.1.0", - "require-directory": "2.1.1", - "require-main-filename": "1.0.1", - "set-blocking": "2.0.0", - "string-width": "2.1.1", - "which-module": "2.0.0", - "y18n": "3.2.1", - "yargs-parser": "8.1.0" + "cliui": "^4.0.0", + "decamelize": "^1.1.1", + "find-up": "^2.1.0", + "get-caller-file": "^1.0.1", + "os-locale": "^2.0.0", + "require-directory": "^2.1.1", + "require-main-filename": "^1.0.1", + "set-blocking": "^2.0.0", + "string-width": "^2.0.0", + "which-module": "^2.0.0", + "y18n": "^3.2.1", + "yargs-parser": "^8.1.0" }, "dependencies": { "camelcase": { @@ -8912,9 +8915,9 @@ "integrity": "sha512-nY3W5Gu2racvdDk//ELReY+dHjb9PlIcVDFXP72nVIhq2Gy3LuVXYwJoPVudwQnv1shtohpgkdCKT2YaKY0CKw==", "dev": true, "requires": { - "string-width": "2.1.1", - "strip-ansi": "4.0.0", - "wrap-ansi": "2.1.0" + "string-width": "^2.1.1", + "strip-ansi": "^4.0.0", + "wrap-ansi": "^2.0.0" } }, "yargs-parser": { @@ -8923,7 +8926,7 @@ "integrity": "sha512-yP+6QqN8BmrgW2ggLtTbdrOyBNSI7zBa4IykmiV5R1wl1JWNxQvWhMfMdmzIYtKU7oP3OOInY/tl2ov3BDjnJQ==", "dev": true, "requires": { - "camelcase": "4.1.0" + "camelcase": "^4.1.0" } } } @@ -8934,7 +8937,7 @@ "integrity": "sha1-jQrELxbqVd69MyyvTEA4s+P139k=", "dev": true, "requires": { - "camelcase": "4.1.0" + "camelcase": "^4.1.0" }, "dependencies": { "camelcase": { diff --git a/package.json b/package.json index 87fc4703a9..2b8861be31 100644 --- a/package.json +++ b/package.json @@ -14,11 +14,13 @@ "test": "lerna run test --stream", "app-start": "lerna run start --stream --scope=insomnia-app", "app-build": "lerna run build --stream --scope=insomnia-app", - "app-package": "lerna run package --stream --scope=insomnia-app" + "app-package": "lerna run package --stream --scope=insomnia-app", + "format-code": "prettier --write \"**/*.js\"" }, "devDependencies": { "jest": "^22.1.1", "lerna": "^2.7.1", + "prettier": "^1.13.6", "webpack": "^4.8.3" }, "dependencies": {} diff --git a/packages/insomnia-app/.eslintrc b/packages/insomnia-app/.eslintrc index 0e439f32ce..4a5000c329 100644 --- a/packages/insomnia-app/.eslintrc +++ b/packages/insomnia-app/.eslintrc @@ -34,6 +34,11 @@ "no-duplicate-imports": "off", "react/jsx-uses-react": "error", "react/jsx-uses-vars": "error", + "space-before-function-paren": ["error", { + "anonymous": "never", + "named": "never", + "asyncArrow": "always" + }], "filenames/match-exported": [ "error", "kebab" diff --git a/packages/insomnia-app/app/__jest__/before-each.js b/packages/insomnia-app/app/__jest__/before-each.js index 56917d2006..20ab20dd16 100644 --- a/packages/insomnia-app/app/__jest__/before-each.js +++ b/packages/insomnia-app/app/__jest__/before-each.js @@ -1,7 +1,7 @@ import * as db from '../common/database'; import * as models from '../models'; -export async function globalBeforeEach () { +export async function globalBeforeEach() { // Setup the local database in case it's used - await db.init(models.types(), {inMemoryOnly: true}, true); + await db.init(models.types(), { inMemoryOnly: true }, true); } diff --git a/packages/insomnia-app/app/__jest__/setup.js b/packages/insomnia-app/app/__jest__/setup.js index e042f1f1f8..379abd718a 100644 --- a/packages/insomnia-app/app/__jest__/setup.js +++ b/packages/insomnia-app/app/__jest__/setup.js @@ -1,16 +1,16 @@ import 'whatwg-fetch'; -const localStorageMock = (function () { +const localStorageMock = (function() { let store = {}; return { - getItem (key) { + getItem(key) { return store[key]; }, - setItem (key, value) { + setItem(key, value) { store[key] = value.toString(); }, - clear () { + clear() { store = {}; } }; diff --git a/packages/insomnia-app/app/__mocks__/electron.js b/packages/insomnia-app/app/__mocks__/electron.js index b2e06464d4..5c3a6666da 100644 --- a/packages/insomnia-app/app/__mocks__/electron.js +++ b/packages/insomnia-app/app/__mocks__/electron.js @@ -1,41 +1,43 @@ import mkdirp from 'mkdirp'; import events from 'events'; -const RANDOM_STRING = Math.random().toString().replace('.', ''); +const RANDOM_STRING = Math.random() + .toString() + .replace('.', ''); const remote = { app: { - getPath (name) { + getPath(name) { const dir = `/tmp/insomnia-tests-${RANDOM_STRING}/${name}`; mkdirp.sync(dir); return dir; }, - getLocale () { + getLocale() { return 'en-US'; } }, net: { - request (url) { + request(url) { const req = new events.EventEmitter(); - req.end = function () {}; + req.end = function() {}; return req; } }, BrowserWindow: { - getAllWindows () { + getAllWindows() { return []; }, - getFocusedWindow () { + getFocusedWindow() { return { - getContentBounds () { - return {width: 1900, height: 1060}; + getContentBounds() { + return { width: 1900, height: 1060 }; } }; } }, screen: { - getPrimaryDisplay () { - return {workAreaSize: {width: 1920, height: 1080}}; + getPrimaryDisplay() { + return { workAreaSize: { width: 1920, height: 1080 } }; } } }; @@ -44,22 +46,12 @@ module.exports = { ...remote, remote: remote, ipcMain: { - on () { - - }, - once () { - - } + on() {}, + once() {} }, ipcRenderer: { - on () { - - }, - once () { - - }, - send () { - - } + on() {}, + once() {}, + send() {} } }; diff --git a/packages/insomnia-app/app/__mocks__/insomnia-libcurl.js b/packages/insomnia-app/app/__mocks__/insomnia-libcurl.js index 8a89cd66cc..adce28aa95 100644 --- a/packages/insomnia-app/app/__mocks__/insomnia-libcurl.js +++ b/packages/insomnia-app/app/__mocks__/insomnia-libcurl.js @@ -1,27 +1,27 @@ -import {EventEmitter} from 'events'; +import { EventEmitter } from 'events'; import fs from 'fs'; class Curl extends EventEmitter { - constructor () { + constructor() { super(); this._options = {}; this._meta = {}; this._features = {}; } - static getVersion () { + static getVersion() { return 'libcurl/7.54.0 LibreSSL/2.0.20 zlib/1.2.11 nghttp2/1.24.0'; } - enable (name) { + enable(name) { this._features[name] = true; } - setUrl (url) { + setUrl(url) { this.setOpt(Curl.option.URL, url); } - setOpt (name, value) { + setOpt(name, value) { if (!name) { throw new Error(`Invalid option ${name} ${value}`); } @@ -51,7 +51,7 @@ class Curl extends EventEmitter { this._options[name] = this._options[name] || []; this._options[name].push(value); } else if (name === Curl.option.READDATA) { - const {size} = fs.fstatSync(value); + const { size } = fs.fstatSync(value); const buffer = Buffer.alloc(size); fs.readSync(value, buffer, 0, size, 0); this._options[name] = buffer.toString(); @@ -60,10 +60,13 @@ class Curl extends EventEmitter { } } - getInfo (name) { + getInfo(name) { switch (name) { case Curl.info.COOKIELIST: - return [`#HttpOnly_.insomnia.rest\tTRUE\t/url/path\tTRUE\t${Date.now() / 1000}\tfoo\tbar`]; + return [ + `#HttpOnly_.insomnia.rest\tTRUE\t/url/path\tTRUE\t${Date.now() / + 1000}\tfoo\tbar` + ]; case Curl.info.EFFECTIVE_URL: return this._options[Curl.option.URL]; case Curl.info.TOTAL_TIME: @@ -75,30 +78,36 @@ class Curl extends EventEmitter { } } - perform () { + perform() { process.nextTick(() => { - const data = Buffer.from(JSON.stringify({ - options: this._options, - meta: this._meta, - features: this._features - })); + const data = Buffer.from( + JSON.stringify({ + options: this._options, + meta: this._meta, + features: this._features + }) + ); this.emit('data', data); this._options.WRITEFUNCTION(data); process.nextTick(() => { - this.emit('end', 'NOT_USED', 'NOT_USED', [ - 'HTTP/1.1 200 OK', - `Content-Length: ${data.length}`, - 'Content-Type: application/json', - '' - ].join('\n')); + this.emit( + 'end', + 'NOT_USED', + 'NOT_USED', + [ + 'HTTP/1.1 200 OK', + `Content-Length: ${data.length}`, + 'Content-Type: application/json', + '' + ].join('\n') + ); }); }); } - close () { - } + close() {} } Curl.info = { diff --git a/packages/insomnia-app/app/__mocks__/node-forge.js b/packages/insomnia-app/app/__mocks__/node-forge.js index f956b8e3c8..20c952df21 100644 --- a/packages/insomnia-app/app/__mocks__/node-forge.js +++ b/packages/insomnia-app/app/__mocks__/node-forge.js @@ -9,35 +9,33 @@ module.exports = { jsbn: forge.jsbn, util: forge.util, pkcs5: { - pbkdf2 () { - - } + pbkdf2() {} }, md: { sha256: { - create () { + create() { return 'TODO'; } } }, rsa: { - setPublicKey () { + setPublicKey() { return { - encrypt (str) { + encrypt(str) { return str; } }; }, - setPrivateKey () { + setPrivateKey() { return { - decrypt (str) { + decrypt(str) { return str; } }; } }, random: { - getBytesSync (n) { + getBytesSync(n) { let s = ''; for (let i = 0; i < n; i++) { s += 'a'; @@ -47,7 +45,7 @@ module.exports = { }, pki: { rsa: { - generateKeyPair () { + generateKeyPair() { return { privateKey: { d: 'a', @@ -68,29 +66,29 @@ module.exports = { } }, cipher: { - createCipher (alg, key) { + createCipher(alg, key) { return { - start (config) { + start(config) { this._config = config; }, - update (buffer) { + update(buffer) { this._data = buffer; }, - finish () { - this.mode = {tag: 'tag'}; + finish() { + this.mode = { tag: 'tag' }; this.output = this._data; } }; }, - createDecipher (alg, key) { + createDecipher(alg, key) { return { - start (config) { + start(config) { this._config = config; }, - update (buffer) { + update(buffer) { this.output = buffer; }, - finish () { + finish() { return true; } }; diff --git a/packages/insomnia-app/app/__tests__/package.test.js b/packages/insomnia-app/app/__tests__/package.test.js index 99ae4c8d3a..6e102d4eef 100644 --- a/packages/insomnia-app/app/__tests__/package.test.js +++ b/packages/insomnia-app/app/__tests__/package.test.js @@ -1,5 +1,5 @@ import * as globalPackage from '../../package.json'; -import {globalBeforeEach} from '../__jest__/before-each'; +import { globalBeforeEach } from '../__jest__/before-each'; describe('package.json', () => { beforeEach(globalBeforeEach); @@ -24,7 +24,9 @@ describe('package.json', () => { it('packages must be included in webpack build or else errors happen', () => { // If this is built by Webpack it fails on multipart/form-data - expect(globalPackage.packedDependencies.includes('httpsnippet')).toBe(false); + expect(globalPackage.packedDependencies.includes('httpsnippet')).toBe( + false + ); }); it('packages must NOT be included in webpack build or else errors happen', () => { diff --git a/packages/insomnia-app/app/__tests__/renderer.test.js b/packages/insomnia-app/app/__tests__/renderer.test.js index b984fd03c0..16809d3cbc 100644 --- a/packages/insomnia-app/app/__tests__/renderer.test.js +++ b/packages/insomnia-app/app/__tests__/renderer.test.js @@ -1,5 +1,5 @@ import * as renderer from '../renderer'; -import {globalBeforeEach} from '../__jest__/before-each'; +import { globalBeforeEach } from '../__jest__/before-each'; describe('imports', () => { beforeEach(globalBeforeEach); diff --git a/packages/insomnia-app/app/common/__fixtures__/nestedfolders.js b/packages/insomnia-app/app/common/__fixtures__/nestedfolders.js index f6d5163826..21fc25c05d 100644 --- a/packages/insomnia-app/app/common/__fixtures__/nestedfolders.js +++ b/packages/insomnia-app/app/common/__fixtures__/nestedfolders.js @@ -1,44 +1,56 @@ import * as models from '../../models'; export const data = { - [models.workspace.type]: [{ - _id: 'wrk_1', - name: 'Wrk 1' - }], + [models.workspace.type]: [ + { + _id: 'wrk_1', + name: 'Wrk 1' + } + ], - [models.requestGroup.type]: [{ - _id: 'fld_1', - parentId: 'wrk_1', - name: 'Fld 1' - }, { - _id: 'fld_2', - parentId: 'wrk_1', - name: 'Fld 2' - }, { - _id: 'fld_3', - parentId: 'fld_1', - name: 'Fld 3' - }], + [models.requestGroup.type]: [ + { + _id: 'fld_1', + parentId: 'wrk_1', + name: 'Fld 1' + }, + { + _id: 'fld_2', + parentId: 'wrk_1', + name: 'Fld 2' + }, + { + _id: 'fld_3', + parentId: 'fld_1', + name: 'Fld 3' + } + ], - [models.request.type]: [{ - _id: 'req_1', - parentId: 'fld_1', - name: 'Req 1' - }, { - _id: 'req_2', - parentId: 'fld_1', - name: 'Req 2' - }, { - _id: 'req_3', - parentId: 'wrk_1', - name: 'Req 3' - }, { - _id: 'req_4', - parentId: 'fld_3', - name: 'Req 4' - }, { - _id: 'req_5', - parentId: 'wrk_1', - name: 'Req 5' - }] + [models.request.type]: [ + { + _id: 'req_1', + parentId: 'fld_1', + name: 'Req 1' + }, + { + _id: 'req_2', + parentId: 'fld_1', + name: 'Req 2' + }, + { + _id: 'req_3', + parentId: 'wrk_1', + name: 'Req 3' + }, + { + _id: 'req_4', + parentId: 'fld_3', + name: 'Req 4' + }, + { + _id: 'req_5', + parentId: 'wrk_1', + name: 'Req 5' + } + ] }; diff --git a/packages/insomnia-app/app/common/__tests__/constants.test.js b/packages/insomnia-app/app/common/__tests__/constants.test.js index 5f7d7729a0..cc5906ddb7 100644 --- a/packages/insomnia-app/app/common/__tests__/constants.test.js +++ b/packages/insomnia-app/app/common/__tests__/constants.test.js @@ -1,5 +1,5 @@ -import {FLEXIBLE_URL_REGEX} from '../constants'; -import {globalBeforeEach} from '../../__jest__/before-each'; +import { FLEXIBLE_URL_REGEX } from '../constants'; +import { globalBeforeEach } from '../../__jest__/before-each'; describe('URL Regex', () => { beforeEach(globalBeforeEach); it('matches valid URLs', () => { @@ -10,7 +10,9 @@ describe('URL Regex', () => { expect('https://google').toMatch(FLEXIBLE_URL_REGEX); expect('https://dash-domain.com').toMatch(FLEXIBLE_URL_REGEX); expect('http://localhost:8000').toMatch(FLEXIBLE_URL_REGEX); - expect('http://localhost:8000/foo/b@@r?hi=there#hello').toMatch(FLEXIBLE_URL_REGEX); + expect('http://localhost:8000/foo/b@@r?hi=there#hello').toMatch( + FLEXIBLE_URL_REGEX + ); }); it('does not match "stop" characters', () => { diff --git a/packages/insomnia-app/app/common/__tests__/database.test.js b/packages/insomnia-app/app/common/__tests__/database.test.js index 3970364326..8117d585ad 100644 --- a/packages/insomnia-app/app/common/__tests__/database.test.js +++ b/packages/insomnia-app/app/common/__tests__/database.test.js @@ -1,13 +1,13 @@ import * as models from '../../models'; import * as db from '../database'; -import {globalBeforeEach} from '../../__jest__/before-each'; +import { globalBeforeEach } from '../../__jest__/before-each'; -function loadFixture (name) { +function loadFixture(name) { const fixtures = require(`../__fixtures__/${name}`).data; const promises = []; for (const type of Object.keys(fixtures)) { for (const doc of fixtures[type]) { - promises.push(db.insert(Object.assign({}, doc, {type}))); + promises.push(db.insert(Object.assign({}, doc, { type }))); } } @@ -17,8 +17,8 @@ function loadFixture (name) { describe('init()', () => { beforeEach(globalBeforeEach); it('handles being initialized twice', async () => { - await db.init(models.types(), {inMemoryOnly: true}); - await db.init(models.types(), {inMemoryOnly: true}); + await db.init(models.types(), { inMemoryOnly: true }); + await db.init(models.types(), { inMemoryOnly: true }); expect((await db.all(models.request.type)).length).toBe(0); }); }); @@ -39,7 +39,7 @@ describe('onChange()', () => { db.onChange(callback); const newDoc = await models.request.create(doc); - const updatedDoc = await models.request.update(newDoc, {name: 'bar'}); + const updatedDoc = await models.request.update(newDoc, { name: 'bar' }); expect(changesSeen.length).toBe(2); expect(changesSeen).toEqual([ @@ -77,17 +77,15 @@ describe('bufferChanges()', () => { // Assert changes seen after flush await db.flushChanges(); - expect(changesSeen).toEqual([[ - [db.CHANGE_INSERT, newDoc, false], - [db.CHANGE_UPDATE, updatedDoc, false] - ]]); + expect(changesSeen).toEqual([ + [[db.CHANGE_INSERT, newDoc, false], [db.CHANGE_UPDATE, updatedDoc, false]] + ]); // Assert no more changes seen after flush again await db.flushChanges(); - expect(changesSeen).toEqual([[ - [db.CHANGE_INSERT, newDoc, false], - [db.CHANGE_UPDATE, updatedDoc, false] - ]]); + expect(changesSeen).toEqual([ + [[db.CHANGE_INSERT, newDoc, false], [db.CHANGE_UPDATE, updatedDoc, false]] + ]); }); }); @@ -120,7 +118,7 @@ describe('requestCreate()', () => { }); it('throws when missing parentID', () => { - const fn = () => models.request.create({name: 'My Request'}); + const fn = () => models.request.create({ name: 'My Request' }); expect(fn).toThrowError('New Requests missing `parentId`'); }); }); @@ -142,9 +140,15 @@ describe('requestGroupDuplicate()', () => { const allRequests = await models.request.all(); const allRequestGroups = await models.requestGroup.all(); const childRequests = await models.request.findByParentId(requestGroup._id); - const childRequestGroups = await models.requestGroup.findByParentId(requestGroup._id); - const newChildRequests = await models.request.findByParentId(newRequestGroup._id); - const newChildRequestGroups = await models.requestGroup.findByParentId(newRequestGroup._id); + const childRequestGroups = await models.requestGroup.findByParentId( + requestGroup._id + ); + const newChildRequests = await models.request.findByParentId( + newRequestGroup._id + ); + const newChildRequestGroups = await models.requestGroup.findByParentId( + newRequestGroup._id + ); // This asserting is pretty garbage but it at least checks // to see that the recursion worked (for the most part) expect(allRequests.length).toBe(8); @@ -162,18 +166,42 @@ describe('_fixThings()', () => { beforeEach(globalBeforeEach); it('fixes duplicate environments', async () => { // Create Workspace with no children - const workspace = await models.workspace.create({_id: 'w1'}); + const workspace = await models.workspace.create({ _id: 'w1' }); expect((await db.withDescendants(workspace)).length).toBe(1); // Create one set of sub environments - await models.environment.create({_id: 'b1', parentId: 'w1', data: {foo: 'b1', b1: true}}); - await models.environment.create({_id: 'b1_sub1', parentId: 'b1', data: {foo: '1'}}); - await models.environment.create({_id: 'b1_sub2', parentId: 'b1', data: {foo: '2'}}); + await models.environment.create({ + _id: 'b1', + parentId: 'w1', + data: { foo: 'b1', b1: true } + }); + await models.environment.create({ + _id: 'b1_sub1', + parentId: 'b1', + data: { foo: '1' } + }); + await models.environment.create({ + _id: 'b1_sub2', + parentId: 'b1', + data: { foo: '2' } + }); // Create second set of sub environments - await models.environment.create({_id: 'b2', parentId: 'w1', data: {foo: 'b2', b2: true}}); - await models.environment.create({_id: 'b2_sub1', parentId: 'b2', data: {foo: '3'}}); - await models.environment.create({_id: 'b2_sub2', parentId: 'b2', data: {foo: '4'}}); + await models.environment.create({ + _id: 'b2', + parentId: 'w1', + data: { foo: 'b2', b2: true } + }); + await models.environment.create({ + _id: 'b2_sub1', + parentId: 'b2', + data: { foo: '3' } + }); + await models.environment.create({ + _id: 'b2_sub2', + parentId: 'b2', + data: { foo: '4' } + }); // Make sure we have everything expect((await db.withDescendants(workspace)).length).toBe(7); @@ -183,40 +211,42 @@ describe('_fixThings()', () => { data: d.data || null })); expect(descendants).toEqual([ - {_id: 'w1', data: null, parentId: null}, - {_id: 'b1', data: {foo: 'b1', b1: true}, parentId: 'w1'}, - {_id: 'b2', data: {foo: 'b2', b2: true}, parentId: 'w1'}, - {_id: 'b1_sub1', data: {foo: '1'}, parentId: 'b1'}, - {_id: 'b1_sub2', data: {foo: '2'}, parentId: 'b1'}, - {_id: 'b2_sub1', data: {foo: '3'}, parentId: 'b2'}, - {_id: 'b2_sub2', data: {foo: '4'}, parentId: 'b2'} + { _id: 'w1', data: null, parentId: null }, + { _id: 'b1', data: { foo: 'b1', b1: true }, parentId: 'w1' }, + { _id: 'b2', data: { foo: 'b2', b2: true }, parentId: 'w1' }, + { _id: 'b1_sub1', data: { foo: '1' }, parentId: 'b1' }, + { _id: 'b1_sub2', data: { foo: '2' }, parentId: 'b1' }, + { _id: 'b2_sub1', data: { foo: '3' }, parentId: 'b2' }, + { _id: 'b2_sub2', data: { foo: '4' }, parentId: 'b2' } ]); // Run the fix algorithm await db._repairDatabase(); // Make sure things get adjusted - const descendants2 = (await db.withDescendants(workspace)).map( - d => ({_id: d._id, parentId: d.parentId, data: d.data || null}) - ); + const descendants2 = (await db.withDescendants(workspace)).map(d => ({ + _id: d._id, + parentId: d.parentId, + data: d.data || null + })); expect(descendants2).toEqual([ - {_id: 'w1', data: null, parentId: null}, - {_id: 'b1', data: {foo: 'b1', b1: true, b2: true}, parentId: 'w1'}, + { _id: 'w1', data: null, parentId: null }, + { _id: 'b1', data: { foo: 'b1', b1: true, b2: true }, parentId: 'w1' }, // Extra base environments should have been deleted // {_id: 'b2', data: {foo: 'bar'}, parentId: 'w1'}, // Sub environments should have been moved to new "master" base environment - {_id: 'b1_sub1', data: {foo: '1'}, parentId: 'b1'}, - {_id: 'b1_sub2', data: {foo: '2'}, parentId: 'b1'}, - {_id: 'b2_sub1', data: {foo: '3'}, parentId: 'b1'}, - {_id: 'b2_sub2', data: {foo: '4'}, parentId: 'b1'} + { _id: 'b1_sub1', data: { foo: '1' }, parentId: 'b1' }, + { _id: 'b1_sub2', data: { foo: '2' }, parentId: 'b1' }, + { _id: 'b2_sub1', data: { foo: '3' }, parentId: 'b1' }, + { _id: 'b2_sub2', data: { foo: '4' }, parentId: 'b1' } ]); }); it('fixes duplicate cookie jars', async () => { // Create Workspace with no children - const workspace = await models.workspace.create({_id: 'w1'}); + const workspace = await models.workspace.create({ _id: 'w1' }); expect((await db.withDescendants(workspace)).length).toBe(1); // Create one set of sub environments @@ -224,8 +254,8 @@ describe('_fixThings()', () => { _id: 'j1', parentId: 'w1', cookies: [ - {id: '1', key: 'foo', value: '1'}, - {id: 'j1_1', key: 'j1', value: '1'} + { id: '1', key: 'foo', value: '1' }, + { id: 'j1_1', key: 'j1', value: '1' } ] }); @@ -233,32 +263,34 @@ describe('_fixThings()', () => { _id: 'j2', parentId: 'w1', cookies: [ - {id: '1', key: 'foo', value: '2'}, - {id: 'j2_1', key: 'j2', value: '2'} + { id: '1', key: 'foo', value: '2' }, + { id: 'j2_1', key: 'j2', value: '2' } ] }); // Make sure we have everything expect((await db.withDescendants(workspace)).length).toBe(3); - const descendants = (await db.withDescendants(workspace)).map( - d => ({_id: d._id, cookies: d.cookies || null, parentId: d.parentId}) - ); + const descendants = (await db.withDescendants(workspace)).map(d => ({ + _id: d._id, + cookies: d.cookies || null, + parentId: d.parentId + })); expect(descendants).toEqual([ - {_id: 'w1', cookies: null, parentId: null}, + { _id: 'w1', cookies: null, parentId: null }, { _id: 'j1', parentId: 'w1', cookies: [ - {id: '1', key: 'foo', value: '1'}, - {id: 'j1_1', key: 'j1', value: '1'} + { id: '1', key: 'foo', value: '1' }, + { id: 'j1_1', key: 'j1', value: '1' } ] }, { _id: 'j2', parentId: 'w1', cookies: [ - {id: '1', key: 'foo', value: '2'}, - {id: 'j2_1', key: 'j2', value: '2'} + { id: '1', key: 'foo', value: '2' }, + { id: 'j2_1', key: 'j2', value: '2' } ] } ]); @@ -267,18 +299,20 @@ describe('_fixThings()', () => { await db._repairDatabase(); // Make sure things get adjusted - const descendants2 = (await db.withDescendants(workspace)).map( - d => ({_id: d._id, cookies: d.cookies || null, parentId: d.parentId}) - ); + const descendants2 = (await db.withDescendants(workspace)).map(d => ({ + _id: d._id, + cookies: d.cookies || null, + parentId: d.parentId + })); expect(descendants2).toEqual([ - {_id: 'w1', cookies: null, parentId: null}, + { _id: 'w1', cookies: null, parentId: null }, { _id: 'j1', parentId: 'w1', cookies: [ - {id: '1', key: 'foo', value: '1'}, - {id: 'j1_1', key: 'j1', value: '1'}, - {id: 'j2_1', key: 'j2', value: '2'} + { id: '1', key: 'foo', value: '1' }, + { id: 'j1_1', key: 'j1', value: '1' }, + { id: 'j2_1', key: 'j2', value: '2' } ] } ]); diff --git a/packages/insomnia-app/app/common/__tests__/har.test.js b/packages/insomnia-app/app/common/__tests__/har.test.js index a66a4d063c..244f45ce91 100644 --- a/packages/insomnia-app/app/common/__tests__/har.test.js +++ b/packages/insomnia-app/app/common/__tests__/har.test.js @@ -2,13 +2,16 @@ import path from 'path'; import * as harUtils from '../har'; import * as render from '../render'; import * as models from '../../models'; -import {AUTH_BASIC} from '../constants'; -import {globalBeforeEach} from '../../__jest__/before-each'; +import { AUTH_BASIC } from '../constants'; +import { globalBeforeEach } from '../../__jest__/before-each'; describe('exportHar()', () => { beforeEach(globalBeforeEach); it('exports single requests', async () => { - const wrk = await models.workspace.create({_id: 'wrk_1', name: 'Workspace'}); + const wrk = await models.workspace.create({ + _id: 'wrk_1', + name: 'Workspace' + }); const req1 = await models.request.create({ _id: 'req_1', name: 'Request 1', @@ -32,15 +35,13 @@ describe('exportHar()', () => { statusCode: 200, statusMessage: 'OK', elapsedTime: 999, - headers: [ - { name: 'Content-Type', value: 'application/json' } - ], + headers: [{ name: 'Content-Type', value: 'application/json' }], contentType: 'application/json', bodyPath: path.join(__dirname, '../__fixtures__/har/test-response.json'), bodyCompression: null }); - const exportRequests = [ { requestId: req1._id, environmentId: 'n/a' } ]; + const exportRequests = [{ requestId: req1._id, environmentId: 'n/a' }]; const harExport = await harUtils.exportHar(exportRequests); expect(harExport).toMatchObject({ @@ -76,9 +77,7 @@ describe('exportHar()', () => { statusText: 'OK', httpVersion: 'HTTP/1.1', cookies: [], - headers: [ - { name: 'Content-Type', value: 'application/json' } - ], + headers: [{ name: 'Content-Type', value: 'application/json' }], content: { size: 15, mimeType: 'application/json', @@ -106,7 +105,10 @@ describe('exportHar()', () => { }); it('exports multiple requests', async () => { - const workspace = await models.workspace.create({_id: 'wrk_1', name: 'Workspace'}); + const workspace = await models.workspace.create({ + _id: 'wrk_1', + name: 'Workspace' + }); const baseReq = await models.request.create({ _id: 'req_0', @@ -117,9 +119,7 @@ describe('exportHar()', () => { url: 'http://localhost', method: 'GET', body: {}, - headers: [ - { name: 'X-Environment', value: '{{ envvalue }}' } - ] + headers: [{ name: 'X-Environment', value: '{{ envvalue }}' }] }); const req1 = await models.request.duplicate(baseReq); req1._id = 'req_1'; @@ -159,13 +159,22 @@ describe('exportHar()', () => { envvalue: '' } }); - const envPublic = await models.environment.create({_id: 'env_1', name: 'Public', parentId: envBase._id}); + const envPublic = await models.environment.create({ + _id: 'env_1', + name: 'Public', + parentId: envBase._id + }); await models.environment.update(envPublic, { data: { envvalue: 'public' } }); - const envPrivate = await models.environment.create({_id: 'env_2', name: 'Private', isPrivate: true, parentId: envBase._id}); + const envPrivate = await models.environment.create({ + _id: 'env_2', + name: 'Private', + isPrivate: true, + parentId: envBase._id + }); await models.environment.update(envPrivate, { data: { envvalue: 'private' @@ -299,18 +308,22 @@ describe('exportHarWithRequest()', () => { beforeEach(globalBeforeEach); it('renders does it correctly', async () => { const workspace = await models.workspace.create(); - const cookies = [{ - creation: new Date('2016-10-05T04:40:49.505Z'), - key: 'foo', - value: 'barrrrr', - expires: new Date('2096-10-12T04:40:49.000Z'), - domain: 'google.com', - path: '/', - hostOnly: true, - lastAccessed: new Date('2096-10-05T04:40:49.505Z') - }]; + const cookies = [ + { + creation: new Date('2016-10-05T04:40:49.505Z'), + key: 'foo', + value: 'barrrrr', + expires: new Date('2096-10-12T04:40:49.000Z'), + domain: 'google.com', + path: '/', + hostOnly: true, + lastAccessed: new Date('2096-10-05T04:40:49.505Z') + } + ]; - const cookieJar = await models.cookieJar.getOrCreateForParentId(workspace._id); + const cookieJar = await models.cookieJar.getOrCreateForParentId( + workspace._id + ); await models.cookieJar.update(cookieJar, { parentId: workspace._id, cookies @@ -319,8 +332,8 @@ describe('exportHarWithRequest()', () => { const request = Object.assign(models.request.init(), { _id: 'req_123', parentId: workspace._id, - headers: [{name: 'Content-Type', value: 'application/json'}], - parameters: [{name: 'foo bar', value: 'hello&world'}], + headers: [{ name: 'Content-Type', value: 'application/json' }], + parameters: [{ name: 'foo bar', value: 'hello&world' }], method: 'POST', body: { text: 'foo bar' @@ -339,16 +352,18 @@ describe('exportHarWithRequest()', () => { expect(har.cookies.length).toBe(1); expect(har).toEqual({ bodySize: -1, - cookies: [{ - domain: 'google.com', - expires: '2096-10-12T04:40:49.000Z', - name: 'foo', - path: '/', - value: 'barrrrr' - }], + cookies: [ + { + domain: 'google.com', + expires: '2096-10-12T04:40:49.000Z', + name: 'foo', + path: '/', + value: 'barrrrr' + } + ], headers: [ - {name: 'Content-Type', value: 'application/json'}, - {name: 'Authorization', value: 'Basic dXNlcjpwYXNz'} + { name: 'Content-Type', value: 'application/json' }, + { name: 'Authorization', value: 'Basic dXNlcjpwYXNz' } ], headersSize: -1, httpVersion: 'HTTP/1.1', @@ -358,7 +373,7 @@ describe('exportHarWithRequest()', () => { params: [], text: 'foo bar' }, - queryString: [{name: 'foo bar', value: 'hello&world'}], + queryString: [{ name: 'foo bar', value: 'hello&world' }], url: 'http://google.com/', settingEncodeUrl: true }); diff --git a/packages/insomnia-app/app/common/__tests__/import.test.js b/packages/insomnia-app/app/common/__tests__/import.test.js index 1b4d4be785..d36107e908 100644 --- a/packages/insomnia-app/app/common/__tests__/import.test.js +++ b/packages/insomnia-app/app/common/__tests__/import.test.js @@ -1,17 +1,20 @@ import * as models from '../../models'; import * as importUtil from '../import'; -import {getAppVersion} from '../constants'; -import {globalBeforeEach} from '../../__jest__/before-each'; +import { getAppVersion } from '../constants'; +import { globalBeforeEach } from '../../__jest__/before-each'; describe('exportHAR()', () => { beforeEach(globalBeforeEach); it('exports a single workspace as an HTTP Archive', async () => { - const wrk1 = await models.workspace.create({_id: 'wrk_1', name: 'Workspace 1'}); + const wrk1 = await models.workspace.create({ + _id: 'wrk_1', + name: 'Workspace 1' + }); const req1 = await models.request.create({ _id: 'req_1', name: 'Request 1', parentId: wrk1._id, - headers: [ { name: 'X-Environment', value: '{{ envvalue }}' } ], + headers: [{ name: 'X-Environment', value: '{{ envvalue }}' }], metaSortKey: 0 }); const req2 = await models.request.create({ @@ -38,7 +41,10 @@ describe('exportHAR()', () => { activeEnvironmentId: env1Private._id }); - const wrk2 = await models.workspace.create({_id: 'wrk_2', name: 'Workspace 2'}); + const wrk2 = await models.workspace.create({ + _id: 'wrk_2', + name: 'Workspace 2' + }); await models.request.create({ _id: 'req_3', name: 'Request 3', @@ -54,9 +60,7 @@ describe('exportHAR()', () => { entries: [ { request: { - headers: [ - { name: 'X-Environment', value: 'private1' } - ] + headers: [{ name: 'X-Environment', value: 'private1' }] }, comment: req1.name }, @@ -69,19 +73,25 @@ describe('exportHAR()', () => { expect(data.log.entries.length).toBe(2); }); it('exports all workspaces as an HTTP Archive', async () => { - const wrk1 = await models.workspace.create({_id: 'wrk_1', name: 'Workspace 1'}); - const wrk2 = await models.workspace.create({_id: 'wrk_2', name: 'Workspace 2'}); + const wrk1 = await models.workspace.create({ + _id: 'wrk_1', + name: 'Workspace 1' + }); + const wrk2 = await models.workspace.create({ + _id: 'wrk_2', + name: 'Workspace 2' + }); await models.request.create({ _id: 'req_1', name: 'Request 1', parentId: wrk1._id, - headers: [ { name: 'X-Environment', value: '{{ envvalue }}' } ] + headers: [{ name: 'X-Environment', value: '{{ envvalue }}' }] }); await models.request.create({ _id: 'req_2', name: 'Request 2', parentId: wrk2._id, - headers: [ { name: 'X-Environment', value: '{{ envvalue }}' } ] + headers: [{ name: 'X-Environment', value: '{{ envvalue }}' }] }); let env1Base = await models.environment.getOrCreateForWorkspace(wrk1); @@ -130,17 +140,13 @@ describe('exportHAR()', () => { entries: [ { request: { - headers: [ - { name: 'X-Environment', value: 'public1' } - ] + headers: [{ name: 'X-Environment', value: 'public1' }] }, comment: 'Request 1' }, { request: { - headers: [ - { name: 'X-Environment', value: 'base2' } - ] + headers: [{ name: 'X-Environment', value: 'base2' }] }, comment: 'Request 2' } @@ -153,20 +159,34 @@ describe('exportHAR()', () => { describe('exportJSON()', () => { beforeEach(globalBeforeEach); it('exports all workspaces', async () => { - const w = await models.workspace.create({name: 'Workspace'}); + const w = await models.workspace.create({ name: 'Workspace' }); const jar = await models.cookieJar.getOrCreateForParentId(w._id); - const r1 = await models.request.create({name: 'Request', parentId: w._id}); + const r1 = await models.request.create({ + name: 'Request', + parentId: w._id + }); const eBase = await models.environment.getOrCreateForWorkspace(w); - const ePub = await models.environment.create({name: 'Public', parentId: eBase._id}); - await models.environment.create({name: 'Private', isPrivate: true, parentId: eBase._id}); + const ePub = await models.environment.create({ + name: 'Public', + parentId: eBase._id + }); + await models.environment.create({ + name: 'Private', + isPrivate: true, + parentId: eBase._id + }); const json = await importUtil.exportJSON(); const data = JSON.parse(json); expect(data._type).toBe('export'); expect(data.__export_format).toBe(3); - expect(data.__export_date).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{3}Z$/); - expect(data.__export_source).toBe(`insomnia.desktop.app:v${getAppVersion()}`); + expect(data.__export_date).toMatch( + /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{3}Z$/ + ); + expect(data.__export_source).toBe( + `insomnia.desktop.app:v${getAppVersion()}` + ); expect(data.resources[0]._id).toBe(w._id); expect(data.resources[1]._id).toBe(eBase._id); expect(data.resources[2]._id).toBe(jar._id); diff --git a/packages/insomnia-app/app/common/__tests__/local-storage.test.js b/packages/insomnia-app/app/common/__tests__/local-storage.test.js index dab0214360..ee96368fa5 100644 --- a/packages/insomnia-app/app/common/__tests__/local-storage.test.js +++ b/packages/insomnia-app/app/common/__tests__/local-storage.test.js @@ -1,7 +1,7 @@ import path from 'path'; import fs from 'fs'; import LocalStorage from '../../main/local-storage'; -import {globalBeforeEach} from '../../__jest__/before-each'; +import { globalBeforeEach } from '../../__jest__/before-each'; describe('LocalStorage()', () => { beforeEach(async () => { @@ -34,8 +34,8 @@ describe('LocalStorage()', () => { expect(localStorage.getItem('foo', 'BAD')).toBe('bar'); // Test Object storage - localStorage.setItem('obj', {foo: 'bar', arr: [1, 2, 3]}); - expect(localStorage.getItem('obj')).toEqual({foo: 'bar', arr: [1, 2, 3]}); + localStorage.setItem('obj', { foo: 'bar', arr: [1, 2, 3] }); + expect(localStorage.getItem('obj')).toEqual({ foo: 'bar', arr: [1, 2, 3] }); // Test default values expect(localStorage.getItem('dne', 'default')).toEqual('default'); @@ -52,7 +52,7 @@ describe('LocalStorage()', () => { // Assert that writing our file actually works fs.writeFileSync(path.join(basePath, 'key'), '{"good": "JSON"}'); - expect(localStorage.getItem('key', 'default')).toEqual({good: 'JSON'}); + expect(localStorage.getItem('key', 'default')).toEqual({ good: 'JSON' }); }); it('does handles failing to write file', () => { @@ -108,7 +108,11 @@ describe('LocalStorage()', () => { // Make sure only one item exists expect(fs.readdirSync(basePath).length).toEqual(2); - expect(fs.readFileSync(path.join(basePath, 'foo'), 'utf8')).toEqual('"bar3"'); - expect(fs.readFileSync(path.join(basePath, 'another'), 'utf8')).toEqual('10'); + expect(fs.readFileSync(path.join(basePath, 'foo'), 'utf8')).toEqual( + '"bar3"' + ); + expect(fs.readFileSync(path.join(basePath, 'another'), 'utf8')).toEqual( + '10' + ); }); }); diff --git a/packages/insomnia-app/app/common/__tests__/misc.test.js b/packages/insomnia-app/app/common/__tests__/misc.test.js index b39efa52b8..1d76dce665 100644 --- a/packages/insomnia-app/app/common/__tests__/misc.test.js +++ b/packages/insomnia-app/app/common/__tests__/misc.test.js @@ -1,12 +1,12 @@ import * as misc from '../misc'; -import {globalBeforeEach} from '../../__jest__/before-each'; +import { globalBeforeEach } from '../../__jest__/before-each'; describe('hasAuthHeader()', () => { beforeEach(globalBeforeEach); it('finds valid header', () => { const yes = misc.hasAuthHeader([ - {name: 'foo', value: 'bar'}, - {name: 'authorization', value: 'foo'} + { name: 'foo', value: 'bar' }, + { name: 'authorization', value: 'foo' } ]); expect(yes).toEqual(true); @@ -14,8 +14,8 @@ describe('hasAuthHeader()', () => { it('finds valid header case insensitive', () => { const yes = misc.hasAuthHeader([ - {name: 'foo', value: 'bar'}, - {name: 'AuthOrizAtiOn', value: 'foo'} + { name: 'foo', value: 'bar' }, + { name: 'AuthOrizAtiOn', value: 'foo' } ]); expect(yes).toEqual(true); @@ -43,9 +43,12 @@ describe('filterHeaders()', () => { expect(misc.filterHeaders(['bad'], null)).toEqual([]); expect(misc.filterHeaders(['bad'], 'good')).toEqual([]); expect(misc.filterHeaders(null, 'good')).toEqual([]); - expect(misc.filterHeaders([{name: 'good', value: 'valid'}], null)).toEqual([]); - expect(misc.filterHeaders([{name: 'good', value: 'valid'}], 'good')) - .toEqual([{name: 'good', value: 'valid'}]); + expect( + misc.filterHeaders([{ name: 'good', value: 'valid' }], null) + ).toEqual([]); + expect( + misc.filterHeaders([{ name: 'good', value: 'valid' }], 'good') + ).toEqual([{ name: 'good', value: 'valid' }]); }); }); @@ -72,11 +75,13 @@ describe('keyedDebounce()', () => { jest.runAllTimers(); - expect(resultsList).toEqual([{ - foo: ['bar3'], - baz: ['bar'], - multi: ['foo', 'bar', 'baz'] - }]); + expect(resultsList).toEqual([ + { + foo: ['bar3'], + baz: ['bar'], + multi: ['foo', 'bar', 'baz'] + } + ]); }); }); @@ -110,9 +115,13 @@ describe('debounce()', () => { describe('fuzzyMatch()', () => { beforeEach(globalBeforeEach); it('can get a positive fuzzy match on a single field', () => { - expect(misc.fuzzyMatch('test', 'testing').searchTermsMatched).toBeGreaterThan(0); + expect( + misc.fuzzyMatch('test', 'testing').searchTermsMatched + ).toBeGreaterThan(0); - expect(misc.fuzzyMatch('tstg', 'testing').searchTermsMatched).toBeGreaterThan(0); + expect( + misc.fuzzyMatch('tstg', 'testing').searchTermsMatched + ).toBeGreaterThan(0); }); it('can get a negative fuzzy match on a single field', () => { @@ -130,12 +139,16 @@ describe('fuzzyMatchAll()', () => { expect(misc.fuzzyMatchAll(' ', ['testing'])).toEqual(true); expect(misc.fuzzyMatchAll('test', ['testing'])).toEqual(true); expect(misc.fuzzyMatchAll('tstg', ['testing'])).toEqual(true); - expect(misc.fuzzyMatchAll('tstg this ou', ['testing', 'this', 'out'])).toEqual(true); + expect( + misc.fuzzyMatchAll('tstg this ou', ['testing', 'this', 'out']) + ).toEqual(true); }); it('can get a negative fuzzy match on multiple fields', () => { expect(misc.fuzzyMatchAll('foo', [undefined])).toEqual(false); expect(misc.fuzzyMatchAll('foo', ['bar'])).toEqual(false); - expect(misc.fuzzyMatchAll('wrong this ou', ['testing', 'this', 'out'])).toEqual(false); + expect( + misc.fuzzyMatchAll('wrong this ou', ['testing', 'this', 'out']) + ).toEqual(false); }); }); diff --git a/packages/insomnia-app/app/common/__tests__/render.test.js b/packages/insomnia-app/app/common/__tests__/render.test.js index 89952b2b20..9acd528d4f 100644 --- a/packages/insomnia-app/app/common/__tests__/render.test.js +++ b/packages/insomnia-app/app/common/__tests__/render.test.js @@ -1,19 +1,23 @@ import * as renderUtils from '../render'; import * as models from '../../models'; -import {globalBeforeEach} from '../../__jest__/before-each'; +import { globalBeforeEach } from '../../__jest__/before-each'; jest.mock('electron'); describe('render()', () => { beforeEach(globalBeforeEach); it('renders hello world', async () => { - const rendered = await renderUtils.render('Hello {{ msg }}!', {msg: 'World'}); + const rendered = await renderUtils.render('Hello {{ msg }}!', { + msg: 'World' + }); expect(rendered).toBe('Hello World!'); }); it('renders custom tag: uuid', async () => { const rendered = await renderUtils.render('Hello {% uuid %}!'); - expect(rendered).toMatch(/Hello [a-z0-9]{8}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{12}!/); + expect(rendered).toMatch( + /Hello [a-z0-9]{8}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{12}!/ + ); }); it('renders custom tag: timestamp', async () => { @@ -23,7 +27,7 @@ describe('render()', () => { it('fails on invalid template', async () => { try { - await renderUtils.render('Hello {{ msg }!', {msg: 'World'}); + await renderUtils.render('Hello {{ msg }!', { msg: 'World' }); fail('Render should have failed'); } catch (err) { expect(err.message).toContain('expected variable end'); @@ -37,22 +41,22 @@ describe('buildRenderContext()', () => { const ancestors = [ { type: models.requestGroup.type, - environment: {foo: 'parent', ancestor: true} + environment: { foo: 'parent', ancestor: true } }, { type: models.requestGroup.type, - environment: {foo: 'grandparent', ancestor: true} + environment: { foo: 'grandparent', ancestor: true } } ]; const rootEnvironment = { type: models.environment.type, - data: {foo: 'root', root: true} + data: { foo: 'root', root: true } }; const subEnvironment = { type: models.environment.type, - data: {foo: 'sub', sub: true} + data: { foo: 'sub', sub: true } }; const context = await renderUtils.buildRenderContext( @@ -70,32 +74,37 @@ describe('buildRenderContext()', () => { }); it('rendered recursive should not infinite loop', async () => { - const ancestors = [{ - // Sub Environment - type: models.requestGroup.type, - environment: {recursive: '{{ recursive }}/hello'} - }]; + const ancestors = [ + { + // Sub Environment + type: models.requestGroup.type, + environment: { recursive: '{{ recursive }}/hello' } + } + ]; const context = await renderUtils.buildRenderContext(ancestors); // This is longer than 3 because it multiplies every time (1 -> 2 -> 4 -> 8) expect(context).toEqual({ - recursive: '{{ recursive }}/hello/hello/hello/hello/hello/hello/hello/hello' + recursive: + '{{ recursive }}/hello/hello/hello/hello/hello/hello/hello/hello' }); }); it('render up to 3 recursion levels', async () => { - const ancestors = [{ - // Sub Environment - type: models.requestGroup.type, - environment: { - d: '/d', - c: '/c{{ d }}', - b: '/b{{ c }}', - a: '/a{{ b }}', - test: 'http://insomnia.rest{{ a }}' + const ancestors = [ + { + // Sub Environment + type: models.requestGroup.type, + environment: { + d: '/d', + c: '/c{{ d }}', + b: '/b{{ c }}', + a: '/a{{ b }}', + test: 'http://insomnia.rest{{ a }}' + } } - }]; + ]; const context = await renderUtils.buildRenderContext(ancestors); @@ -109,109 +118,128 @@ describe('buildRenderContext()', () => { }); it('rendered sibling environment variables', async () => { - const ancestors = [{ - // Sub Environment - type: models.requestGroup.type, - environment: { - sibling: 'sibling', - test: '{{ sibling }}/hello' + const ancestors = [ + { + // Sub Environment + type: models.requestGroup.type, + environment: { + sibling: 'sibling', + test: '{{ sibling }}/hello' + } } - }]; + ]; const context = await renderUtils.buildRenderContext(ancestors); - expect(context).toEqual({sibling: 'sibling', test: 'sibling/hello'}); + expect(context).toEqual({ sibling: 'sibling', test: 'sibling/hello' }); }); it('rendered parent environment variables', async () => { - const ancestors = [{ - name: 'Parent', - type: models.requestGroup.type, - environment: { - test: '{{ grandparent }} parent' + const ancestors = [ + { + name: 'Parent', + type: models.requestGroup.type, + environment: { + test: '{{ grandparent }} parent' + } + }, + { + name: 'Grandparent', + type: models.requestGroup.type, + environment: { + grandparent: 'grandparent' + } } - }, { - name: 'Grandparent', - type: models.requestGroup.type, - environment: { - grandparent: 'grandparent' - } - }]; + ]; const context = await renderUtils.buildRenderContext(ancestors); - expect(context).toEqual({grandparent: 'grandparent', test: 'grandparent parent'}); + expect(context).toEqual({ + grandparent: 'grandparent', + test: 'grandparent parent' + }); }); it('rendered parent same name environment variables', async () => { - const ancestors = [{ - name: 'Parent', - type: models.requestGroup.type, - environment: { - base_url: '{{ base_url }}/resource' + const ancestors = [ + { + name: 'Parent', + type: models.requestGroup.type, + environment: { + base_url: '{{ base_url }}/resource' + } + }, + { + name: 'Grandparent', + type: models.requestGroup.type, + environment: { + base_url: 'https://insomnia.rest' + } } - }, { - name: 'Grandparent', - type: models.requestGroup.type, - environment: { - base_url: 'https://insomnia.rest' - } - }]; + ]; const context = await renderUtils.buildRenderContext(ancestors); - expect(context).toEqual({base_url: 'https://insomnia.rest/resource'}); + expect(context).toEqual({ base_url: 'https://insomnia.rest/resource' }); }); it('rendered parent, ignoring sibling environment variables', async () => { - const ancestors = [{ - name: 'Parent', - type: models.requestGroup.type, - environment: { - host: 'parent.com' - } - }, { - name: 'Grandparent', - type: models.requestGroup.type, - environment: { - host: 'grandparent.com', - node: { - admin: 'admin', - test: 'test', - port: 8080 - }, - urls: { - admin: 'https://{{ host }}/{{ node.admin }}', - test: 'https://{{ host }}/{{ node.test }}' + const ancestors = [ + { + name: 'Parent', + type: models.requestGroup.type, + environment: { + host: 'parent.com' + } + }, + { + name: 'Grandparent', + type: models.requestGroup.type, + environment: { + host: 'grandparent.com', + node: { + admin: 'admin', + test: 'test', + port: 8080 + }, + urls: { + admin: 'https://{{ host }}/{{ node.admin }}', + test: 'https://{{ host }}/{{ node.test }}' + } } } - }]; + ]; const context = await renderUtils.buildRenderContext(ancestors); - expect(await renderUtils.render('{{ urls.admin }}/foo', context)) - .toBe('https://parent.com/admin/foo'); - expect(await renderUtils.render('{{ urls.test }}/foo', context)) - .toBe('https://parent.com/test/foo'); + expect(await renderUtils.render('{{ urls.admin }}/foo', context)).toBe( + 'https://parent.com/admin/foo' + ); + expect(await renderUtils.render('{{ urls.test }}/foo', context)).toBe( + 'https://parent.com/test/foo' + ); }); it('renders child environment variables', async () => { - const ancestors = [{ - name: 'Parent', - type: models.requestGroup.type, - environment: { - parent: 'parent' + const ancestors = [ + { + name: 'Parent', + type: models.requestGroup.type, + environment: { + parent: 'parent' + } + }, + { + name: 'Grandparent', + type: models.requestGroup.type, + environment: { + test: '{{ parent }} grandparent' + } } - }, { - name: 'Grandparent', - type: models.requestGroup.type, - environment: { - test: '{{ parent }} grandparent' - } - }]; + ]; const context = await renderUtils.buildRenderContext(ancestors); - expect(context).toEqual({parent: 'parent', test: 'parent grandparent'}); + expect(context).toEqual({ parent: 'parent', test: 'parent grandparent' }); }); it('cascades properly and renders', async () => { @@ -235,15 +263,16 @@ describe('buildRenderContext()', () => { const subEnvironment = { type: models.environment.type, - data: {winner: 'sub', sub: true, base_url: 'https://insomnia.rest'} + data: { winner: 'sub', sub: true, base_url: 'https://insomnia.rest' } }; const rootEnvironment = { type: models.environment.type, - data: {winner: 'root', root: true, base_url: 'ignore this'} + data: { winner: 'root', root: true, base_url: 'ignore this' } }; - const context = await renderUtils.buildRenderContext(ancestors, + const context = await renderUtils.buildRenderContext( + ancestors, rootEnvironment, subEnvironment ); @@ -277,8 +306,10 @@ describe('buildRenderContext()', () => { hash_input: '123456789012345ThisIsATopSecretValue', hash_input_expected: '123456789012345ThisIsATopSecretValue', orderId: 123456789012345, - password: 'ea84d15f33d3f9e9098fe01659b1ea0599d345770bba20ba98bf9056676a83ffe6b5528b2451ad04badbf690cf3009a94c510121cc6897045f8bb4ba0826134c', - password_expected: 'ea84d15f33d3f9e9098fe01659b1ea0599d345770bba20ba98bf9056676a83ffe6b5528b2451ad04badbf690cf3009a94c510121cc6897045f8bb4ba0826134c', + password: + 'ea84d15f33d3f9e9098fe01659b1ea0599d345770bba20ba98bf9056676a83ffe6b5528b2451ad04badbf690cf3009a94c510121cc6897045f8bb4ba0826134c', + password_expected: + 'ea84d15f33d3f9e9098fe01659b1ea0599d345770bba20ba98bf9056676a83ffe6b5528b2451ad04badbf690cf3009a94c510121cc6897045f8bb4ba0826134c', secret: 'ThisIsATopSecretValue' }); }); @@ -301,11 +332,14 @@ describe('buildRenderContext()', () => { describe('render()', () => { beforeEach(globalBeforeEach); it('correctly renders simple Object', async () => { - const newObj = await renderUtils.render({ - foo: '{{ foo }}', - bar: 'bar', - baz: '{{ bad }}' - }, {foo: 'bar', bad: 'hi'}); + const newObj = await renderUtils.render( + { + foo: '{{ foo }}', + bar: 'bar', + baz: '{{ bad }}' + }, + { foo: 'bar', bad: 'hi' } + ); expect(newObj).toEqual({ foo: 'bar', @@ -329,7 +363,7 @@ describe('render()', () => { } }; - const newObj = await renderUtils.render(obj, {foo: 'bar'}); + const newObj = await renderUtils.render(obj, { foo: 'bar' }); expect(newObj).toEqual({ foo: 'bar', @@ -352,11 +386,14 @@ describe('render()', () => { it('fails on bad template', async () => { try { - await renderUtils.render({ - foo: '{{ foo }', - bar: 'bar', - baz: '{{ bad }}' - }, {foo: 'bar'}); + await renderUtils.render( + { + foo: '{{ foo }', + bar: 'bar', + baz: '{{ bad }}' + }, + { foo: 'bar' } + ); fail('Render should have failed'); } catch (err) { expect(err.message).toContain('expected variable end'); @@ -365,7 +402,7 @@ describe('render()', () => { it('keep on error setting', async () => { const template = '{{ foo }} {% invalid "hi" %}'; - const context = {foo: 'bar'}; + const context = { foo: 'bar' }; const resultOnlyVars = await renderUtils.render( template, @@ -385,7 +422,7 @@ describe('render()', () => { it('outputs correct error path', async () => { const template = { - foo: [{bar: '{% foo %}'}] + foo: [{ bar: '{% foo %}' }] }; try { @@ -398,7 +435,7 @@ describe('render()', () => { it('outputs correct error path when private first node', async () => { const template = { - _foo: {_bar: {baz: '{% foo %}'}} + _foo: { _bar: { baz: '{% foo %}' } } }; try { diff --git a/packages/insomnia-app/app/common/constants.js b/packages/insomnia-app/app/common/constants.js index 0f6600bd7c..9d22502d58 100644 --- a/packages/insomnia-app/app/common/constants.js +++ b/packages/insomnia-app/app/common/constants.js @@ -5,51 +5,51 @@ import mkdirp from 'mkdirp'; // App Stuff -export function getAppVersion () { +export function getAppVersion() { return packageJSON.app.version; } -export function getAppLongName () { +export function getAppLongName() { return packageJSON.app.longName; } -export function getAppName () { +export function getAppName() { return packageJSON.app.productName; } -export function getAppPlatform () { +export function getAppPlatform() { return process.platform; } -export function getAppEnvironment () { +export function getAppEnvironment() { return process.env.INSOMNIA_ENV || 'production'; } -export function getTempDir () { +export function getTempDir() { // NOTE: Using a fairly unique name here because "insomnia" is a common word - const {app} = electron.remote || electron; + const { app } = electron.remote || electron; const dir = path.join(app.getPath('temp'), `insomnia_${getAppVersion()}`); mkdirp.sync(dir); return dir; } -export function isMac () { +export function isMac() { return getAppPlatform() === 'darwin'; } -export function isLinux () { +export function isLinux() { return getAppPlatform() === 'linux'; } -export function isWindows () { +export function isWindows() { return getAppPlatform() === 'win32'; } -export function isDevelopment () { +export function isDevelopment() { return getAppEnvironment() === 'development'; } -export function getClientString () { +export function getClientString() { return `${getAppEnvironment()}::${getAppPlatform()}::${getAppVersion()}`; } @@ -66,14 +66,17 @@ export const LARGE_RESPONSE_MB = 5; export const HUGE_RESPONSE_MB = 100; export const FLEXIBLE_URL_REGEX = /^(http|https):\/\/[\wàâäèéêëîïôóœùûüÿçÀÂÄÈÉÊËÎÏÔŒÙÛÜŸÇ\-_.]+[/\wàâäèéêëîïôóœùûüÿçÀÂÄÈÉÊËÎÏÔŒÙÛÜŸÇ.\-+=:\][@%^*&!#?;$]*/; export const CHECK_FOR_UPDATES_INTERVAL = 1000 * 60 * 60 * 3; // 3 hours -export const PLUGIN_PATH = path.join((electron.remote || electron).app.getPath('userData'), 'plugins'); +export const PLUGIN_PATH = path.join( + (electron.remote || electron).app.getPath('userData'), + 'plugins' +); // Hotkeys export const MOD_SYM = isMac() ? '⌘' : 'Ctrl'; export const ALT_SYM = isMac() ? '⌃' : 'Alt'; export const SHIFT_SYM = isMac() ? '⇧' : 'Shift'; export const CTRL_SYM = isMac() ? '⌃' : 'Ctrl'; -export function joinHotKeys (keys) { +export function joinHotKeys(keys) { return keys.join(isMac() ? '' : '+'); } @@ -175,27 +178,33 @@ const authTypesMap = { [AUTH_NETRC]: ['Netrc', 'Netrc File'] }; -export function getPreviewModeName (previewMode, useLong = false) { +export function getPreviewModeName(previewMode, useLong = false) { if (previewModeMap.hasOwnProperty(previewMode)) { - return useLong ? previewModeMap[previewMode][1] : previewModeMap[previewMode][0]; + return useLong + ? previewModeMap[previewMode][1] + : previewModeMap[previewMode][0]; } else { return ''; } } -export function getContentTypeName (contentType, useLong = false) { +export function getContentTypeName(contentType, useLong = false) { if (typeof contentType !== 'string') { return ''; } if (contentTypesMap.hasOwnProperty(contentType)) { - return useLong ? contentTypesMap[contentType][1] : contentTypesMap[contentType][0]; + return useLong + ? contentTypesMap[contentType][1] + : contentTypesMap[contentType][0]; } - return useLong ? contentTypesMap[CONTENT_TYPE_OTHER][1] : contentTypesMap[CONTENT_TYPE_OTHER][0]; + return useLong + ? contentTypesMap[CONTENT_TYPE_OTHER][1] + : contentTypesMap[CONTENT_TYPE_OTHER][0]; } -export function getAuthTypeName (authType, useLong = false) { +export function getAuthTypeName(authType, useLong = false) { if (authTypesMap.hasOwnProperty(authType)) { return useLong ? authTypesMap[authType][1] : authTypesMap[authType][0]; } else { @@ -203,20 +212,22 @@ export function getAuthTypeName (authType, useLong = false) { } } -export function getContentTypeFromHeaders (headers, defaultValue = null) { +export function getContentTypeFromHeaders(headers, defaultValue = null) { if (!Array.isArray(headers)) { return null; } - const header = headers.find(({name}) => name.toLowerCase() === 'content-type'); + const header = headers.find( + ({ name }) => name.toLowerCase() === 'content-type' + ); return header ? header.value : defaultValue; } // Sourced from https://developer.mozilla.org/en-US/docs/Web/HTTP/Status export const RESPONSE_CODE_DESCRIPTIONS = { - // Special - [STATUS_CODE_PLUGIN_ERROR]: 'An Insomnia plugin threw an error which prevented the request from sending', + [STATUS_CODE_PLUGIN_ERROR]: + 'An Insomnia plugin threw an error which prevented the request from sending', // 100s @@ -256,7 +267,7 @@ export const RESPONSE_CODE_DESCRIPTIONS = { 403: 'Client does not have access rights to the content so server is rejecting to give proper response.', 404: 'Server can not find requested resource. This response code probably is most famous one due to its frequency to occur in web.', 405: 'The request method is known by the server but has been disabled and cannot be used. The two mandatory methods, GET and HEAD, must never be disabled and should not return this error code.', - 406: 'This response is sent when the web server, after performing server-driven content negotiation, doesn\'t find any content following the criteria given by the user agent.', + 406: "This response is sent when the web server, after performing server-driven content negotiation, doesn't find any content following the criteria given by the user agent.", 407: 'This is similar to 401 but authentication is needed to be done by a proxy.', 408: 'This response is sent on an idle connection by some servers, even without any previous request by the client. It means that the server would like to shut down this unused connection. This response is used much more since some browsers, like Chrome or IE9, use HTTP preconnection mechanisms to speed up surfing (see bug 881804, which tracks the future implementation of such a mechanism in Firefox). Also note that some servers merely shut down the connection without sending this message.', 409: 'This response would be sent when a request conflict with current state of server.', @@ -266,22 +277,22 @@ export const RESPONSE_CODE_DESCRIPTIONS = { 413: 'Request entity is larger than limits defined by server; the server might close the connection or return an Retry-After header field.', 414: 'The URI requested by the client is longer than the server is willing to interpret.', 415: 'The media format of the requested data is not supported by the server, so the server is rejecting the request.', - 416: 'The range specified by the Range header field in the request can\'t be fulfilled; it\'s possible that the range is outside the size of the target URI\'s data.', - 417: 'This response code means the expectation indicated by the Expect request header field can\'t be met by the server.', + 416: "The range specified by the Range header field in the request can't be fulfilled; it's possible that the range is outside the size of the target URI's data.", + 417: "This response code means the expectation indicated by the Expect request header field can't be met by the server.", 418: 'Any attempt to brew coffee with a teapot should result in the error code "418 I\'m a teapot". The resulting entity body MAY be short and stout.', 421: 'The request was directed at a server that is not able to produce a response. This can be sent by a server that is not configured to produce responses for the combination of scheme and authority that are included in the request URI.', 422: 'The request was well-formed but was unable to be followed due to semantic errors.', 423: 'The resource that is being accessed is locked.', 424: 'The request failed due to failure of a previous request.', 426: 'The server refuses to perform the request using the current protocol but might be willing to do so after the client upgrades to a different protocol. The server MUST send an Upgrade header field in a 426 response to indicate the required protocol(s) (Section 6.7 of [RFC7230]).', - 428: 'The origin server requires the request to be conditional. Intended to prevent "the \'lost update\' problem, where a client GETs a resource\'s state, modifies it, and PUTs it back to the server, when meanwhile a third party has modified the state on the server, leading to a conflict."', + 428: "The origin server requires the request to be conditional. Intended to prevent \"the 'lost update' problem, where a client GETs a resource's state, modifies it, and PUTs it back to the server, when meanwhile a third party has modified the state on the server, leading to a conflict.\"", 429: 'The user has sent too many requests in a given amount of time ("rate limiting").', 431: 'The server is unwilling to process the request because its header fields are too large. The request MAY be resubmitted after reducing the size of the request header fields.', 451: 'The user requests an illegal resource, such as a web page censored by a government.', // 500s - 500: 'The server has encountered a situation it doesn\'t know how to handle.', + 500: "The server has encountered a situation it doesn't know how to handle.", 501: 'The request method is not supported by the server and cannot be handled. The only methods that servers are required to support (and therefore that must not return this code) are GET and HEAD.', 502: 'This error response means that the server, while working as a gateway to get a response needed to handle the request, got an invalid response.', 503: 'The server is not ready to handle the request. Common causes are a server that is down for maintenance or that is overloaded. Note that together with this response, a user-friendly page explaining the problem should be sent. This responses should be used for temporary conditions and the Retry-After: HTTP header should, if possible, contain the estimated time before the recovery of the service. The webmaster must also take care about the caching-related headers that are sent along with this response, as these temporary condition responses should usually not be cached.', diff --git a/packages/insomnia-app/app/common/database.js b/packages/insomnia-app/app/common/database.js index 3fc0f45b49..92105bb793 100644 --- a/packages/insomnia-app/app/common/database.js +++ b/packages/insomnia-app/app/common/database.js @@ -1,10 +1,10 @@ // @flow -import type {BaseModel} from '../models/index'; +import type { BaseModel } from '../models/index'; import * as models from '../models/index'; import electron from 'electron'; import NeDB from 'nedb'; import fsPath from 'path'; -import {DB_PERSIST_INTERVAL} from './constants'; +import { DB_PERSIST_INTERVAL } from './constants'; import uuid from 'uuid'; export const CHANGE_INSERT = 'insert'; @@ -20,18 +20,18 @@ const db = { // HELPERS // // ~~~~~~~ // -function allTypes () { +function allTypes() { return Object.keys(db); } -function getDBFilePath (modelType) { +function getDBFilePath(modelType) { // NOTE: Do not EVER change this. EVER! - const {app} = electron.remote || electron; + const { app } = electron.remote || electron; const basePath = app.getPath('userData'); return fsPath.join(basePath, `insomnia.${modelType}.db`); } -export async function initClient () { +export async function initClient() { electron.ipcRenderer.on('db.changes', async (e, changes) => { for (const fn of changeListeners) { await fn(changes); @@ -40,7 +40,7 @@ export async function initClient () { console.log('[db] Initialized DB client'); } -export async function init ( +export async function init( types: Array, config: Object = {}, forceReset: boolean = false @@ -64,10 +64,15 @@ export async function init ( } const filePath = getDBFilePath(modelType); - const collection = new NeDB(Object.assign({ - autoload: true, - filename: filePath - }, config)); + const collection = new NeDB( + Object.assign( + { + autoload: true, + filename: filePath + }, + config + ) + ); collection.persistence.setAutocompactionInterval(DB_PERSIST_INTERVAL); @@ -106,7 +111,9 @@ export async function init ( try { await m.hookRemove(doc); } catch (err) { - console.log(`[db] Delete hook failed for ${type} ${doc._id}: ${err.message}`); + console.log( + `[db] Delete hook failed for ${type} ${doc._id}: ${err.message}` + ); } } @@ -114,7 +121,9 @@ export async function init ( try { await m.hookInsert(doc); } catch (err) { - console.log(`[db] Insert hook failed for ${type} ${doc._id}: ${err.message}`); + console.log( + `[db] Insert hook failed for ${type} ${doc._id}: ${err.message}` + ); } } @@ -122,7 +131,9 @@ export async function init ( try { await m.hookUpdate(doc); } catch (err) { - console.log(`[db] Update hook failed for ${type} ${doc._id}: ${err.message}`); + console.log( + `[db] Update hook failed for ${type} ${doc._id}: ${err.message}` + ); } } } @@ -137,28 +148,30 @@ let bufferingChanges = false; let changeBuffer = []; let changeListeners = []; -export function onChange (callback: Function): void { +export function onChange(callback: Function): void { changeListeners.push(callback); } -export function offChange (callback: Function): void { +export function offChange(callback: Function): void { changeListeners = changeListeners.filter(l => l !== callback); } -export const bufferChanges = database.bufferChanges = async function (millis: number = 1000): Promise { +export const bufferChanges = (database.bufferChanges = async function( + millis: number = 1000 +): Promise { if (db._empty) return _send('bufferChanges', ...arguments); bufferingChanges = true; setTimeout(database.flushChanges, millis); -}; +}); -export const flushChangesAsync = database.flushChangesAsync = async function (): Promise { +export const flushChangesAsync = (database.flushChangesAsync = async function() { process.nextTick(async () => { await flushChanges(); }); -}; +}); -export const flushChanges = database.flushChanges = async function (): Promise { +export const flushChanges = (database.flushChanges = async function() { if (db._empty) return _send('flushChanges', ...arguments); bufferingChanges = false; @@ -180,9 +193,13 @@ export const flushChanges = database.flushChanges = async function (): Promise { +async function notifyOfChange( + event: string, + doc: BaseModel, + fromSync: boolean +): Promise { changeBuffer.push([event, doc, fromSync]); // Flush right away if we're not buffering @@ -195,7 +212,7 @@ async function notifyOfChange (event: string, doc: BaseModel, fromSync: boolean) // Helpers // // ~~~~~~~ // -export const getMostRecentlyModified = database.getMostRecentlyModified = async function ( +export const getMostRecentlyModified = (database.getMostRecentlyModified = async function( type: string, query: Object = {} ): Promise { @@ -203,9 +220,9 @@ export const getMostRecentlyModified = database.getMostRecentlyModified = async const docs = await database.findMostRecentlyModified(type, query, 1); return docs.length ? docs[0] : null; -}; +}); -export const findMostRecentlyModified = database.findMostRecentlyModified = async function ( +export const findMostRecentlyModified = (database.findMostRecentlyModified = async function( type: string, query: Object = {}, limit: number | null = null @@ -213,53 +230,62 @@ export const findMostRecentlyModified = database.findMostRecentlyModified = asyn if (db._empty) return _send('findMostRecentlyModified', ...arguments); return new Promise(resolve => { - db[type].find(query).sort({modified: -1}).limit(limit).exec(async (err, rawDocs) => { - if (err) { - console.warn('[db] Failed to find docs', err); - resolve([]); - return; - } + db[type] + .find(query) + .sort({ modified: -1 }) + .limit(limit) + .exec(async (err, rawDocs) => { + if (err) { + console.warn('[db] Failed to find docs', err); + resolve([]); + return; + } - const docs = []; - for (const rawDoc of rawDocs) { - docs.push(await models.initModel(type, rawDoc)); - } + const docs = []; + for (const rawDoc of rawDocs) { + docs.push(await models.initModel(type, rawDoc)); + } - resolve(docs); - }); + resolve(docs); + }); }); -}; +}); -export const find = database.find = async function ( +export const find = (database.find = async function( type: string, query: Object = {}, - sort: Object = {created: 1} + sort: Object = { created: 1 } ): Promise> { if (db._empty) return _send('find', ...arguments); return new Promise((resolve, reject) => { - db[type].find(query).sort(sort).exec(async (err, rawDocs) => { - if (err) { - return reject(err); - } + db[type] + .find(query) + .sort(sort) + .exec(async (err, rawDocs) => { + if (err) { + return reject(err); + } - const docs = []; - for (const rawDoc of rawDocs) { - docs.push(await models.initModel(type, rawDoc)); - } + const docs = []; + for (const rawDoc of rawDocs) { + docs.push(await models.initModel(type, rawDoc)); + } - resolve(docs); - }); + resolve(docs); + }); }); -}; +}); -export const all = database.all = async function (type: string): Promise> { +export const all = (database.all = async function( + type: string +): Promise> { if (db._empty) return _send('all', ...arguments); return database.find(type); -}; +}); -export const getWhere = database.getWhere = async function ( +export const getWhere = (database.getWhere = async function( type: string, query: Object ): Promise { @@ -267,9 +293,9 @@ export const getWhere = database.getWhere = async function ( const docs = await database.find(type, query); return docs.length ? docs[0] : null; -}; +}); -export const get = database.get = async function ( +export const get = (database.get = async function( type: string, id: string ): Promise { @@ -279,11 +305,11 @@ export const get = database.get = async function ( if (!id || id === 'n/a') { return null; } else { - return database.getWhere(type, {_id: id}); + return database.getWhere(type, { _id: id }); } -}; +}); -export const count = database.count = async function ( +export const count = (database.count = async function( type: string, query: Object = {} ): Promise { @@ -298,9 +324,9 @@ export const count = database.count = async function ( resolve(count); }); }); -}; +}); -export const upsert = database.upsert = async function ( +export const upsert = (database.upsert = async function( doc: BaseModel, fromSync: boolean = false ): Promise { @@ -312,9 +338,9 @@ export const upsert = database.upsert = async function ( } else { return database.insert(doc, fromSync); } -}; +}); -export const insert = database.insert = async function ( +export const insert = (database.insert = async function( doc: T, fromSync: boolean = false ): Promise { @@ -333,9 +359,9 @@ export const insert = database.insert = async function ( notifyOfChange(CHANGE_INSERT, newDoc, fromSync); }); }); -}; +}); -export const update = database.update = async function ( +export const update = (database.update = async function( doc: T, fromSync: boolean = false ): Promise { @@ -343,7 +369,7 @@ export const update = database.update = async function ( return new Promise(async (resolve, reject) => { const docWithDefaults = await models.initModel(doc.type, doc); - db[doc.type].update({_id: docWithDefaults._id}, docWithDefaults, err => { + db[doc.type].update({ _id: docWithDefaults._id }, docWithDefaults, err => { if (err) { return reject(err); } @@ -354,9 +380,9 @@ export const update = database.update = async function ( notifyOfChange(CHANGE_UPDATE, docWithDefaults, fromSync); }); }); -}; +}); -export const remove = database.remove = async function ( +export const remove = (database.remove = async function( doc: T, fromSync: boolean = false ): Promise { @@ -369,14 +395,14 @@ export const remove = database.remove = async function ( const types = [...new Set(docs.map(d => d.type))]; // Don't really need to wait for this to be over; - types.map(t => db[t].remove({_id: {$in: docIds}}, {multi: true})); + types.map(t => db[t].remove({ _id: { $in: docIds } }, { multi: true })); docs.map(d => notifyOfChange(CHANGE_REMOVE, d, fromSync)); await database.flushChanges(); -}; +}); -export const removeWhere = database.removeWhere = async function ( +export const removeWhere = (database.removeWhere = async function( type: string, query: Object ): Promise { @@ -390,25 +416,28 @@ export const removeWhere = database.removeWhere = async function ( const types = [...new Set(docs.map(d => d.type))]; // Don't really need to wait for this to be over; - types.map(t => db[t].remove({_id: {$in: docIds}}, {multi: true})); + types.map(t => db[t].remove({ _id: { $in: docIds } }, { multi: true })); docs.map(d => notifyOfChange(CHANGE_REMOVE, d, false)); } await database.flushChanges(); -}; +}); // ~~~~~~~~~~~~~~~~~~~ // // DEFAULT MODEL STUFF // // ~~~~~~~~~~~~~~~~~~~ // -export async function docUpdate (originalDoc: T, ...patches: Array): Promise { +export async function docUpdate( + originalDoc: T, + ...patches: Array +): Promise { const doc = await models.initModel( originalDoc.type, originalDoc, // NOTE: This is before `patch` because we want `patch.modified` to win if it has it - {modified: Date.now()}, + { modified: Date.now() }, ...patches ); @@ -416,7 +445,7 @@ export async function docUpdate (originalDoc: T, ...patches: Array return database.update(doc); } -export async function docCreate ( +export async function docCreate( type: string, ...patches: Array ): Promise { @@ -425,7 +454,7 @@ export async function docCreate ( ...patches, // Fields that the user can't touch - {type: type} + { type: type } ); return database.insert(doc); @@ -435,7 +464,7 @@ export async function docCreate ( // GENERAL // // ~~~~~~~ // -export const withDescendants = database.withDescendants = async function ( +export const withDescendants = (database.withDescendants = async function( doc: BaseModel | null, stopType: string | null = null ): Promise> { @@ -443,7 +472,9 @@ export const withDescendants = database.withDescendants = async function ( let docsToReturn = doc ? [doc] : []; - async function next (docs: Array): Promise> { + async function next( + docs: Array + ): Promise> { let foundDocs = []; for (const d of docs) { @@ -454,7 +485,7 @@ export const withDescendants = database.withDescendants = async function ( for (const type of allTypes()) { // If the doc is null, we want to search for parentId === null const parentId = d ? d._id : null; - const more = await database.find(type, {parentId}); + const more = await database.find(type, { parentId }); foundDocs = [...foundDocs, ...more]; } } @@ -470,9 +501,9 @@ export const withDescendants = database.withDescendants = async function ( } return next([doc]); -}; +}); -export const withAncestors = database.withAncestors = async function ( +export const withAncestors = (database.withAncestors = async function( doc: BaseModel | null, types: Array = allTypes() ): Promise> { @@ -484,7 +515,7 @@ export const withAncestors = database.withAncestors = async function ( let docsToReturn = doc ? [doc] : []; - async function next (docs: Array): Promise> { + async function next(docs: Array): Promise> { let foundDocs = []; for (const d: BaseModel of docs) { for (const type of types) { @@ -505,9 +536,9 @@ export const withAncestors = database.withAncestors = async function ( } return next([doc]); -}; +}); -export const duplicate = database.duplicate = async function ( +export const duplicate = (database.duplicate = async function( originalDoc: T, patch: Object = {} ): Promise { @@ -515,7 +546,7 @@ export const duplicate = database.duplicate = async function ( await database.bufferChanges(); - async function next (docToCopy: T, patch: Object): Promise { + async function next(docToCopy: T, patch: Object): Promise { // 1. Copy the doc const newDoc = Object.assign({}, docToCopy, patch); delete newDoc._id; @@ -532,9 +563,9 @@ export const duplicate = database.duplicate = async function ( } const parentId = docToCopy._id; - const children = await database.find(type, {parentId}); + const children = await database.find(type, { parentId }); for (const doc of children) { - await next(doc, {parentId: createdDoc._id}); + await next(doc, { parentId: createdDoc._id }); } } @@ -546,13 +577,13 @@ export const duplicate = database.duplicate = async function ( await database.flushChanges(); return createdDoc; -}; +}); // ~~~~~~~ // // Helpers // // ~~~~~~~ // -async function _send (fnName: string, ...args: Array): Promise { +async function _send(fnName: string, ...args: Array): Promise { return new Promise((resolve, reject) => { const replyChannel = `db.fn.reply:${uuid.v4()}`; electron.ipcRenderer.send('db.fn', fnName, replyChannel, ...args); @@ -565,7 +596,7 @@ async function _send (fnName: string, ...args: Array): Promise { /** * Run various database repair scripts */ -export async function _repairDatabase () { +export async function _repairDatabase() { console.log(`[fix] Running database repairs`); for (const workspace of await find(models.workspace.type)) { await _repairBaseEnvironments(workspace); @@ -578,8 +609,10 @@ export async function _repairDatabase () { * can only have one, this function walks over all base environments, merges the data, and * moves all children as well. */ -async function _repairBaseEnvironments (workspace) { - const baseEnvironments = await find(models.environment.type, {parentId: workspace._id}); +async function _repairBaseEnvironments(workspace) { + const baseEnvironments = await find(models.environment.type, { + parentId: workspace._id + }); // Nothing to do here if (baseEnvironments.length <= 1) { @@ -593,10 +626,12 @@ async function _repairBaseEnvironments (workspace) { } chosenBase.data = Object.assign(baseEnvironment.data, chosenBase.data); - const subEnvironments = await find(models.environment.type, {parentId: baseEnvironment._id}); + const subEnvironments = await find(models.environment.type, { + parentId: baseEnvironment._id + }); for (const subEnvironment of subEnvironments) { - await docUpdate(subEnvironment, {parentId: chosenBase._id}); + await docUpdate(subEnvironment, { parentId: chosenBase._id }); } // Remove unnecessary base env @@ -606,7 +641,11 @@ async function _repairBaseEnvironments (workspace) { // Update remaining base env await update(chosenBase); - console.log(`[fix] Merged ${baseEnvironments.length} base environments under ${workspace.name}`); + console.log( + `[fix] Merged ${baseEnvironments.length} base environments under ${ + workspace.name + }` + ); } /** @@ -614,8 +653,10 @@ async function _repairBaseEnvironments (workspace) { * can only have one, this function walks over all jars and merges them and their cookies * together. */ -async function _fixMultipleCookieJars (workspace) { - const cookieJars = await find(models.cookieJar.type, {parentId: workspace._id}); +async function _fixMultipleCookieJars(workspace) { + const cookieJars = await find(models.cookieJar.type, { + parentId: workspace._id + }); // Nothing to do here if (cookieJars.length <= 1) { @@ -643,5 +684,7 @@ async function _fixMultipleCookieJars (workspace) { // Update remaining jar await update(chosenJar); - console.log(`[fix] Merged ${cookieJars.length} cookie jars under ${workspace.name}`); + console.log( + `[fix] Merged ${cookieJars.length} cookie jars under ${workspace.name}` + ); } diff --git a/packages/insomnia-app/app/common/fetch.js b/packages/insomnia-app/app/common/fetch.js index 649d3b854a..7ea0058f42 100644 --- a/packages/insomnia-app/app/common/fetch.js +++ b/packages/insomnia-app/app/common/fetch.js @@ -1,40 +1,40 @@ import 'whatwg-fetch'; -import {parse as urlParse} from 'url'; -import {getClientString} from './constants'; +import { parse as urlParse } from 'url'; +import { getClientString } from './constants'; import * as session from '../sync/session'; import * as zlib from 'zlib'; let commandListeners = []; -export function onCommand (callback) { +export function onCommand(callback) { commandListeners.push(callback); } -export function offCommand (callback) { +export function offCommand(callback) { commandListeners = commandListeners.filter(l => l !== callback); } -export function post (path, obj) { +export function post(path, obj) { return _fetch('POST', path, obj); } -export function get (path, sessionId = null) { +export function get(path, sessionId = null) { return _fetch('GET', path, null, sessionId); } -export function del (path, sessionId = null) { +export function del(path, sessionId = null) { return _fetch('DELETE', path, null, sessionId); } -export function put (path, sessionId = null) { +export function put(path, sessionId = null) { return _fetch('PUT', path, null, sessionId); } -export function rawFetch (...args) { +export function rawFetch(...args) { return window.fetch(...args); } -async function _fetch (method, path, obj, sessionId = null) { +async function _fetch(method, path, obj, sessionId = null) { const config = { method: method, headers: new window.Headers() @@ -65,19 +65,22 @@ async function _fetch (method, path, obj, sessionId = null) { throw err; } - if (response.headers.get('content-type') === 'application/json' || path.match(/\.json$/)) { + if ( + response.headers.get('content-type') === 'application/json' || + path.match(/\.json$/) + ) { return response.json(); } else { return response.text(); } } -function _getUrl (path) { +function _getUrl(path) { const baseUrl = process.env.INSOMNIA_SYNC_URL || 'https://api.insomnia.rest'; return `${baseUrl}${path}`; } -function _notifyCommandListeners (uri) { +function _notifyCommandListeners(uri) { const parsed = urlParse(uri, true); const command = `${parsed.hostname}${parsed.pathname}`; diff --git a/packages/insomnia-app/app/common/har.js b/packages/insomnia-app/app/common/har.js index 9e483a67d0..9d3608c802 100644 --- a/packages/insomnia-app/app/common/har.js +++ b/packages/insomnia-app/app/common/har.js @@ -1,21 +1,21 @@ // @flow import fs from 'fs'; import clone from 'clone'; -import {Cookie as toughCookie} from 'tough-cookie'; +import { Cookie as toughCookie } from 'tough-cookie'; import * as models from '../models'; -import type {RenderedRequest} from './render'; -import {getRenderedRequestAndContext} from './render'; -import {jarFromCookies} from 'insomnia-cookies'; +import type { RenderedRequest } from './render'; +import { getRenderedRequestAndContext } from './render'; +import { jarFromCookies } from 'insomnia-cookies'; import * as pluginContexts from '../plugins/context/index'; import * as misc from './misc'; -import type {Cookie} from '../models/cookie-jar'; -import type {Request} from '../models/request'; -import {newBodyRaw} from '../models/request'; -import type {Response as ResponseModel} from '../models/response'; -import {getAuthHeader} from '../network/authentication'; -import {getAppVersion} from './constants'; -import {RenderError} from '../templating/index'; -import {smartEncodeUrl} from 'insomnia-url'; +import type { Cookie } from '../models/cookie-jar'; +import type { Request } from '../models/request'; +import { newBodyRaw } from '../models/request'; +import type { Response as ResponseModel } from '../models/response'; +import { getAuthHeader } from '../network/authentication'; +import { getAppVersion } from './constants'; +import { RenderError } from '../templating/index'; +import { smartEncodeUrl } from 'insomnia-url'; import * as plugins from '../plugins'; export type HarCookie = { @@ -33,13 +33,13 @@ export type HarHeader = { name: string, value: string, comment?: string -} +}; export type HarQueryString = { name: string, value: string, comment?: string -} +}; export type HarPostParam = { name: string, @@ -98,7 +98,7 @@ export type HarRequestCache = { eTag: string, hitCount: number, comment?: string -} +}; export type HarCache = { beforeRequest?: HarRequestCache, @@ -142,7 +142,7 @@ export type HarPage = { title: string, pageTimings: HarPageTimings, comment?: string -} +}; export type HarCreator = { name: string, @@ -172,24 +172,33 @@ export type Har = { export type ExportRequest = { requestId: string, environmentId: string -} +}; -export async function exportHar (exportRequests: Array): Promise { +export async function exportHar( + exportRequests: Array +): Promise { // Export HAR entries with the same start time in order to keep their workspace sort order. const startedDateTime = new Date().toISOString(); const entries: Array = []; for (let exportRequest of exportRequests) { - const request: Request | null = await models.request.getById(exportRequest.requestId); + const request: Request | null = await models.request.getById( + exportRequest.requestId + ); if (!request) { continue; } - const harRequest = await exportHarWithRequest(request, exportRequest.environmentId); + const harRequest = await exportHarWithRequest( + request, + exportRequest.environmentId + ); if (!harRequest) { continue; } - const response: ResponseModel | null = await models.response.getLatestForRequest(exportRequest.requestId); + const response: ResponseModel | null = await models.response.getLatestForRequest( + exportRequest.requestId + ); const harResponse = await exportHarResponse(response); if (!harResponse) { continue; @@ -228,7 +237,9 @@ export async function exportHar (exportRequests: Array): Promise< }; } -export async function exportHarResponse (response: ResponseModel | null): Promise { +export async function exportHarResponse( + response: ResponseModel | null +): Promise { if (!response) { return { status: 0, @@ -259,7 +270,7 @@ export async function exportHarResponse (response: ResponseModel | null): Promis }; } -export async function exportHarRequest ( +export async function exportHarRequest( requestId: string, environmentId: string, addContentLength: boolean = false @@ -272,13 +283,16 @@ export async function exportHarRequest ( return exportHarWithRequest(request, environmentId, addContentLength); } -export async function exportHarWithRequest ( +export async function exportHarWithRequest( request: Request, environmentId: string, addContentLength: boolean = false ): Promise { try { - const renderResult = await getRenderedRequestAndContext(request, environmentId); + const renderResult = await getRenderedRequestAndContext( + request, + environmentId + ); const renderedRequest = await _applyRequestPluginHooks( renderResult.request, renderResult.context @@ -286,19 +300,23 @@ export async function exportHarWithRequest ( return exportHarWithRenderedRequest(renderedRequest, addContentLength); } catch (err) { if (err instanceof RenderError) { - throw new Error(`Failed to render "${request.name}:${err.path}"\n ${err.message}`); + throw new Error( + `Failed to render "${request.name}:${err.path}"\n ${err.message}` + ); } else { - throw new Error(`Failed to export request "${request.name}"\n ${err.message}`); + throw new Error( + `Failed to export request "${request.name}"\n ${err.message}` + ); } } } -async function _applyRequestPluginHooks ( +async function _applyRequestPluginHooks( renderedRequest: RenderedRequest, renderedContext: Object ): Promise { let newRenderedRequest = renderedRequest; - for (const {plugin, hook} of await plugins.getRequestHooks()) { + for (const { plugin, hook } of await plugins.getRequestHooks()) { newRenderedRequest = clone(newRenderedRequest); const context = { @@ -317,22 +335,25 @@ async function _applyRequestPluginHooks ( return newRenderedRequest; } -export async function exportHarWithRenderedRequest ( +export async function exportHarWithRenderedRequest( renderedRequest: RenderedRequest, addContentLength: boolean = false ): Promise { - const url = smartEncodeUrl(renderedRequest.url, renderedRequest.settingEncodeUrl); + const url = smartEncodeUrl( + renderedRequest.url, + renderedRequest.settingEncodeUrl + ); if (addContentLength) { - const hasContentLengthHeader = misc.filterHeaders( - renderedRequest.headers, - 'Content-Length' - ).length > 0; + const hasContentLengthHeader = + misc.filterHeaders(renderedRequest.headers, 'Content-Length').length > 0; if (!hasContentLengthHeader) { const name = 'Content-Length'; - const value = Buffer.byteLength((renderedRequest.body || {}).text || '').toString(); - renderedRequest.headers.push({name, value}); + const value = Buffer.byteLength( + (renderedRequest.body || {}).text || '' + ).toString(); + renderedRequest.headers.push({ name, value }); } } @@ -366,28 +387,30 @@ export async function exportHarWithRenderedRequest ( }; } -function getRequestCookies (renderedRequest: RenderedRequest): Array { +function getRequestCookies(renderedRequest: RenderedRequest): Array { const jar = jarFromCookies(renderedRequest.cookieJar.cookies); const domainCookies = jar.getCookiesSync(renderedRequest.url); return domainCookies.map(mapCookie); } -function getReponseCookies (response: ResponseModel): Array { - return misc.getSetCookieHeaders(response.headers).map(h => { - let cookie; - try { - cookie = toughCookie.parse(h.value || ''); - } catch (error) { - } - if (!cookie) { - return null; - } +function getReponseCookies(response: ResponseModel): Array { + return misc + .getSetCookieHeaders(response.headers) + .map(h => { + let cookie; + try { + cookie = toughCookie.parse(h.value || ''); + } catch (error) {} + if (!cookie) { + return null; + } - return mapCookie(cookie); - }).filter(Boolean); + return mapCookie(cookie); + }) + .filter(Boolean); } -function mapCookie (cookie: Cookie): HarCookie { +function mapCookie(cookie: Cookie): HarCookie { const harCookie: HarCookie = { name: cookie.key, value: cookie.value @@ -428,7 +451,7 @@ function mapCookie (cookie: Cookie): HarCookie { return harCookie; } -function getResponseContent (response: ResponseModel): HarContent { +function getResponseContent(response: ResponseModel): HarContent { let body: Buffer | null = models.response.getBodyBuffer(response); if (body === null) { @@ -442,29 +465,27 @@ function getResponseContent (response: ResponseModel): HarContent { }; } -function getResponseHeaders (response: ResponseModel): Array { - return response.headers - .filter(header => (header.name)) - .map(h => { - return { - name: h.name, - value: h.value - }; - }); +function getResponseHeaders(response: ResponseModel): Array { + return response.headers.filter(header => header.name).map(h => { + return { + name: h.name, + value: h.value + }; + }); } -function getRequestHeaders (renderedRequest: RenderedRequest): Array { - return renderedRequest.headers - .filter(header => (header.name)) - .map(header => { - return { - name: header.name, - value: header.value - }; - }); +function getRequestHeaders(renderedRequest: RenderedRequest): Array { + return renderedRequest.headers.filter(header => header.name).map(header => { + return { + name: header.name, + value: header.value + }; + }); } -function getRequestQueryString (renderedRequest: RenderedRequest): Array { +function getRequestQueryString( + renderedRequest: RenderedRequest +): Array { return renderedRequest.parameters.map(parameter => { return { name: parameter.name, @@ -473,11 +494,15 @@ function getRequestQueryString (renderedRequest: RenderedRequest): Array, - metaIsCtrl?: boolean, + metaIsCtrl?: boolean }; export const SHOW_WORKSPACE_SETTINGS: Hotkey = { @@ -212,12 +212,12 @@ export const CLOSE_MODAL: Hotkey = { keycode: keycodes.esc }; -export function pressedHotKey (e: KeyboardEvent, definition: Hotkey): boolean { +export function pressedHotKey(e: KeyboardEvent, definition: Hotkey): boolean { const isMetaPressed = isMac() ? e.metaKey : e.ctrlKey; const isAltPressed = isMac() ? e.ctrlKey : e.altKey; const isShiftPressed = e.shiftKey; - const {meta, alt, shift, keycode} = definition; + const { meta, alt, shift, keycode } = definition; const codes = Array.isArray(keycode) ? keycode : [keycode]; for (const code of codes) { @@ -243,7 +243,7 @@ export function pressedHotKey (e: KeyboardEvent, definition: Hotkey): boolean { return false; } -export function executeHotKey ( +export function executeHotKey( e: KeyboardEvent, definition: Hotkey, callback: Function @@ -253,8 +253,10 @@ export function executeHotKey ( } } -export function getChar (hotkey: Hotkey) { - const codes = Array.isArray(hotkey.keycode) ? hotkey.keycode : [hotkey.keycode]; +export function getChar(hotkey: Hotkey) { + const codes = Array.isArray(hotkey.keycode) + ? hotkey.keycode + : [hotkey.keycode]; const chars = []; for (const keycode of codes) { diff --git a/packages/insomnia-app/app/common/import.js b/packages/insomnia-app/app/common/import.js index 47b1af7432..866fc425ad 100644 --- a/packages/insomnia-app/app/common/import.js +++ b/packages/insomnia-app/app/common/import.js @@ -1,17 +1,17 @@ // @flow -import {convert} from 'insomnia-importers'; +import { convert } from 'insomnia-importers'; import * as db from './database'; import * as har from './har'; -import type {BaseModel} from '../models/index'; +import type { BaseModel } from '../models/index'; import * as models from '../models/index'; -import {getAppVersion} from './constants'; -import {showModal} from '../ui/components/modals/index'; +import { getAppVersion } from './constants'; +import { showModal } from '../ui/components/modals/index'; import AlertModal from '../ui/components/modals/alert-modal'; import * as fetch from './fetch'; import fs from 'fs'; -import type {Workspace} from '../models/workspace'; -import type {Environment} from '../models/environment'; -import {fnOrString, generateId} from './misc'; +import type { Workspace } from '../models/workspace'; +import type { Environment } from '../models/environment'; +import { fnOrString, generateId } from './misc'; const EXPORT_FORMAT = 3; @@ -32,7 +32,10 @@ const MODELS = { [EXPORT_TYPE_ENVIRONMENT]: models.environment }; -export async function importUri (workspaceId: string | null, uri: string): Promise { +export async function importUri( + workspaceId: string | null, + uri: string +): Promise { let rawText; if (uri.match(/^(http|https):\/\//)) { const response = await fetch.rawFetch(uri); @@ -45,18 +48,20 @@ export async function importUri (workspaceId: string | null, uri: string): Promi } const result = await importRaw(workspaceId, rawText); - const {summary, error} = result; + const { summary, error } = result; if (error) { - showModal(AlertModal, {title: 'Import Failed', message: error}); + showModal(AlertModal, { title: 'Import Failed', message: error }); return; } - let statements = Object.keys(summary).map(type => { - const count = summary[type].length; - const name = models.getModelName(type, count); - return count === 0 ? null : `${count} ${name}`; - }).filter(s => s !== null); + let statements = Object.keys(summary) + .map(type => { + const count = summary[type].length; + const name = models.getModelName(type, count); + return count === 0 ? null : `${count} ${name}`; + }) + .filter(s => s !== null); let message; if (statements.length === 0) { @@ -64,14 +69,18 @@ export async function importUri (workspaceId: string | null, uri: string): Promi } else { message = `You imported ${statements.join(', ')}!`; } - showModal(AlertModal, {title: 'Import Succeeded', message}); + showModal(AlertModal, { title: 'Import Succeeded', message }); } -export async function importRaw ( +export async function importRaw( workspaceId: string | null, rawContent: string, generateNewIds: boolean = false -): Promise<{source: string, error: string | null, summary: {[string]: Array}}> { +): Promise<{ + source: string, + error: string | null, + summary: { [string]: Array } +}> { let results; try { results = await convert(rawContent); @@ -84,9 +93,11 @@ export async function importRaw ( }; } - const {data} = results; + const { data } = results; - let workspace: Workspace | null = await models.workspace.getById(workspaceId || 'n/a'); + let workspace: Workspace | null = await models.workspace.getById( + workspaceId || 'n/a' + ); // Fetch the base environment in case we need it let baseEnvironment: Environment | null = await models.environment.getOrCreateForWorkspaceId( @@ -94,7 +105,7 @@ export async function importRaw ( ); // Generate all the ids we may need - const generatedIds: {[string]: string | Function} = {}; + const generatedIds: { [string]: string | Function } = {}; for (const r of data.resources) { if (generateNewIds || r._id.match(REPLACE_ID_REGEX)) { generatedIds[r._id] = generateId(MODELS[r._type].prefix); @@ -104,7 +115,7 @@ export async function importRaw ( // Always replace these "constants" generatedIds['__WORKSPACE_ID__'] = async () => { if (!workspace) { - workspace = await models.workspace.create({name: 'Imported Workspace'}); + workspace = await models.workspace.create({ name: 'Imported Workspace' }); } return workspace._id; @@ -113,9 +124,13 @@ export async function importRaw ( generatedIds['__BASE_ENVIRONMENT_ID__'] = async () => { if (!baseEnvironment) { if (!workspace) { - workspace = await models.workspace.create({name: 'Imported Workspace'}); + workspace = await models.workspace.create({ + name: 'Imported Workspace' + }); } - baseEnvironment = await models.environment.getOrCreateForWorkspace(workspace); + baseEnvironment = await models.environment.getOrCreateForWorkspace( + workspace + ); } return baseEnvironment._id; }; @@ -163,8 +178,10 @@ export async function importRaw ( // Mark as not seen if we created a new workspace from sync if (newDoc.type === models.workspace.type) { - const workspaceMeta = await models.workspaceMeta.getOrCreateByParentId(newDoc._id); - await models.workspaceMeta.update(workspaceMeta, {hasSeen: false}); + const workspaceMeta = await models.workspaceMeta.getOrCreateByParentId( + newDoc._id + ); + await models.workspaceMeta.update(workspaceMeta, { hasSeen: false }); } } @@ -174,15 +191,16 @@ export async function importRaw ( await db.flushChanges(); return { - source: (results.type && typeof results.type.id === 'string') - ? results.type.id - : 'unknown', + source: + results.type && typeof results.type.id === 'string' + ? results.type.id + : 'unknown', summary: importedDocs, error: null }; } -export async function exportHAR ( +export async function exportHAR( parentDoc: BaseModel | null = null, includePrivateDocs: boolean = false ): Promise { @@ -195,9 +213,15 @@ export async function exportHAR ( const workspaceEnvironmentLookup = {}; for (let workspace of workspaces) { - const workspaceMeta = await models.workspaceMeta.getByParentId(workspace._id); - let environmentId = workspaceMeta ? workspaceMeta.activeEnvironmentId : null; - const environment = await models.environment.getById(environmentId || 'n/a'); + const workspaceMeta = await models.workspaceMeta.getByParentId( + workspace._id + ); + let environmentId = workspaceMeta + ? workspaceMeta.activeEnvironmentId + : null; + const environment = await models.environment.getById( + environmentId || 'n/a' + ); if (!environment || (environment.isPrivate && !includePrivateDocs)) { environmentId = 'n/a'; } @@ -206,10 +230,13 @@ export async function exportHAR ( const requests = []; for (let workspace of workspaces) { - const docs: Array = await getDocWithDescendants(workspace, includePrivateDocs); + const docs: Array = await getDocWithDescendants( + workspace, + includePrivateDocs + ); const workspaceRequests = docs - .filter(d => (d.type === models.request.type)) - .sort((a: Object, b: Object) => a.metaSortKey < b.metaSortKey ? -1 : 1) + .filter(d => d.type === models.request.type) + .sort((a: Object, b: Object) => (a.metaSortKey < b.metaSortKey ? -1 : 1)) .map((request: BaseModel) => { return { requestId: request._id, @@ -225,7 +252,7 @@ export async function exportHAR ( return JSON.stringify(data, null, '\t'); } -export async function exportJSON ( +export async function exportJSON( parentDoc: BaseModel | null = null, includePrivateDocs: boolean = false ): Promise { @@ -237,17 +264,21 @@ export async function exportJSON ( resources: [] }; - const docs: Array = await getDocWithDescendants(parentDoc, includePrivateDocs); + const docs: Array = await getDocWithDescendants( + parentDoc, + includePrivateDocs + ); data.resources = docs - .filter(d => ( - // Only export these model types - d.type === models.request.type || - d.type === models.requestGroup.type || - d.type === models.workspace.type || - d.type === models.cookieJar.type || - d.type === models.environment.type - )) + .filter( + d => + // Only export these model types + d.type === models.request.type || + d.type === models.requestGroup.type || + d.type === models.workspace.type || + d.type === models.cookieJar.type || + d.type === models.environment.type + ) .map((d: Object) => { if (d.type === models.workspace.type) { d._type = EXPORT_TYPE_WORKSPACE; @@ -269,13 +300,14 @@ export async function exportJSON ( return JSON.stringify(data, null, '\t'); } -async function getDocWithDescendants ( +async function getDocWithDescendants( parentDoc: BaseModel | null = null, includePrivateDocs: boolean = false ): Promise> { const docs = await db.withDescendants(parentDoc); - return docs.filter(d => ( - // Don't include if private, except if we want to - !(d: any).isPrivate || includePrivateDocs - )); + return docs.filter( + d => + // Don't include if private, except if we want to + !(d: any).isPrivate || includePrivateDocs + ); } diff --git a/packages/insomnia-app/app/common/markdown-to-html.js b/packages/insomnia-app/app/common/markdown-to-html.js index 6fb14faba4..815e34ec22 100644 --- a/packages/insomnia-app/app/common/markdown-to-html.js +++ b/packages/insomnia-app/app/common/markdown-to-html.js @@ -11,6 +11,6 @@ marked.setOptions({ smartypants: false }); -export function markdownToHTML (markdown) { +export function markdownToHTML(markdown) { return marked(markdown); } diff --git a/packages/insomnia-app/app/common/misc.js b/packages/insomnia-app/app/common/misc.js index 809e8b2620..e0c3568109 100644 --- a/packages/insomnia-app/app/common/misc.js +++ b/packages/insomnia-app/app/common/misc.js @@ -1,11 +1,11 @@ // @flow import * as electron from 'electron'; -import {Readable, Writable} from 'stream'; +import { Readable, Writable } from 'stream'; import fuzzysort from 'fuzzysort'; import uuid from 'uuid'; import zlib from 'zlib'; -import {join as pathJoin} from 'path'; -import {DEBOUNCE_MILLIS} from './constants'; +import { join as pathJoin } from 'path'; +import { DEBOUNCE_MILLIS } from './constants'; const ESCAPE_REGEX_MATCH = /[-[\]/{}()*+?.\\^$|]/g; @@ -19,15 +19,21 @@ type Parameter = { value: string }; -export function filterParameters (parameters: Array, name: string): Array { +export function filterParameters( + parameters: Array, + name: string +): Array { if (!Array.isArray(parameters) || !name) { return []; } - return parameters.filter(h => !h || !h.name ? false : h.name === name); + return parameters.filter(h => (!h || !h.name ? false : h.name === name)); } -export function filterHeaders (headers: Array, name: string): Array { +export function filterHeaders( + headers: Array, + name: string +): Array { if (!Array.isArray(headers) || !name) { return []; } @@ -41,55 +47,57 @@ export function filterHeaders (headers: Array, name: string): Arra }); } -export function hasContentTypeHeader (headers: Array): boolean { +export function hasContentTypeHeader(headers: Array): boolean { return filterHeaders(headers, 'content-type').length > 0; } -export function hasContentLengthHeader (headers: Array): boolean { +export function hasContentLengthHeader(headers: Array): boolean { return filterHeaders(headers, 'content-length').length > 0; } -export function hasAuthHeader (headers: Array): boolean { +export function hasAuthHeader(headers: Array): boolean { return filterHeaders(headers, 'authorization').length > 0; } -export function hasAcceptHeader (headers: Array): boolean { +export function hasAcceptHeader(headers: Array): boolean { return filterHeaders(headers, 'accept').length > 0; } -export function hasUserAgentHeader (headers: Array): boolean { +export function hasUserAgentHeader(headers: Array): boolean { return filterHeaders(headers, 'user-agent').length > 0; } -export function hasAcceptEncodingHeader (headers: Array): boolean { +export function hasAcceptEncodingHeader(headers: Array): boolean { return filterHeaders(headers, 'accept-encoding').length > 0; } -export function getSetCookieHeaders (headers: Array): Array { +export function getSetCookieHeaders(headers: Array): Array { return filterHeaders(headers, 'set-cookie'); } -export function getLocationHeader (headers: Array): T | null { +export function getLocationHeader(headers: Array): T | null { const matches = filterHeaders(headers, 'location'); return matches.length ? matches[0] : null; } -export function getContentTypeHeader (headers: Array): T | null { +export function getContentTypeHeader(headers: Array): T | null { const matches = filterHeaders(headers, 'content-type'); return matches.length ? matches[0] : null; } -export function getHostHeader (headers: Array): T | null { +export function getHostHeader(headers: Array): T | null { const matches = filterHeaders(headers, 'host'); return matches.length ? matches[0] : null; } -export function getContentDispositionHeader (headers: Array): T | null { +export function getContentDispositionHeader( + headers: Array +): T | null { const matches = filterHeaders(headers, 'content-disposition'); return matches.length ? matches[0] : null; } -export function getContentLengthHeader (headers: Array): T | null { +export function getContentLengthHeader(headers: Array): T | null { const matches = filterHeaders(headers, 'content-length'); return matches.length ? matches[0] : null; } @@ -99,7 +107,7 @@ export function getContentLengthHeader (headers: Array): T | null * @param prefix * @returns {string} */ -export function generateId (prefix: string): string { +export function generateId(prefix: string): string { const id = uuid.v4().replace(/-/g, ''); if (prefix) { @@ -109,19 +117,22 @@ export function generateId (prefix: string): string { } } -export function delay (milliseconds: number = DEBOUNCE_MILLIS): Promise { +export function delay(milliseconds: number = DEBOUNCE_MILLIS): Promise { return new Promise(resolve => setTimeout(resolve, milliseconds)); } -export function removeVowels (str: string): string { +export function removeVowels(str: string): string { return str.replace(/[aeiouyAEIOUY]/g, ''); } -export function keyedDebounce (callback: Function, millis: number = DEBOUNCE_MILLIS): Function { +export function keyedDebounce( + callback: Function, + millis: number = DEBOUNCE_MILLIS +): Function { let timeout; let results = {}; - return function (key, ...args) { + return function(key, ...args) { results[key] = args; clearTimeout(timeout); @@ -136,14 +147,17 @@ export function keyedDebounce (callback: Function, millis: number = DEBOUNCE_MIL }; } -export function debounce (callback: Function, millis: number = DEBOUNCE_MILLIS): Function { +export function debounce( + callback: Function, + millis: number = DEBOUNCE_MILLIS +): Function { // For regular debounce, just use a keyed debounce with a fixed key return keyedDebounce(results => { callback.apply(null, results['__key__']); }, millis).bind(null, '__key__'); } -export function describeByteSize (bytes: number, long: boolean = false): string { +export function describeByteSize(bytes: number, long: boolean = false): string { bytes = Math.round(bytes * 10) / 10; let size; @@ -165,23 +179,23 @@ export function describeByteSize (bytes: number, long: boolean = false): string unit = long ? 'gigabytes' : 'GB'; } - const rounded = (Math.round(size * 10) / 10); + const rounded = Math.round(size * 10) / 10; return `${rounded} ${unit}`; } -export function nullFn (): void { +export function nullFn(): void { // Do nothing } -export function preventDefault (e: Event): void { +export function preventDefault(e: Event): void { e.preventDefault(); } -export function clickLink (href: string): void { +export function clickLink(href: string): void { electron.shell.openExternal(href); } -export function fnOrString (v: string | Function, ...args: Array) { +export function fnOrString(v: string | Function, ...args: Array) { if (typeof v === 'string') { return v; } else { @@ -189,17 +203,17 @@ export function fnOrString (v: string | Function, ...args: Array) { } } -export function compressObject (obj: any): string { +export function compressObject(obj: any): string { const compressed = zlib.gzipSync(JSON.stringify(obj)); return compressed.toString('base64'); } -export function decompressObject (input: string): any { +export function decompressObject(input: string): any { const jsonBuffer = zlib.gunzipSync(Buffer.from(input, 'base64')); return JSON.parse(jsonBuffer.toString('utf8')); } -export function resolveHomePath (p: string): string { +export function resolveHomePath(p: string): string { if (p.indexOf('~/') === 0) { return pathJoin(process.env.HOME || '/', p.slice(1)); } else { @@ -207,7 +221,7 @@ export function resolveHomePath (p: string): string { } } -export function jsonParseOr (str: string, fallback: any): any { +export function jsonParseOr(str: string, fallback: any): any { try { return JSON.parse(str); } catch (err) { @@ -220,11 +234,14 @@ export function jsonParseOr (str: string, fallback: any): any { * @param str - string to escape * @returns {string} escaped string */ -export function escapeRegex (str: string): string { +export function escapeRegex(str: string): string { return str.replace(ESCAPE_REGEX_MATCH, '\\$&'); } -export function fuzzyMatch (searchString: string, text: string): { +export function fuzzyMatch( + searchString: string, + text: string +): { searchTermsMatched: number, indexes: number[] } { @@ -235,7 +252,12 @@ export function fuzzyMatch (searchString: string, text: string): { indexes: [] }; - if (!searchString || !searchString.trim() || !searchTerms || searchTerms.length === 0) { + if ( + !searchString || + !searchString.trim() || + !searchTerms || + searchTerms.length === 0 + ) { return emptyResults; } @@ -259,10 +281,7 @@ export function fuzzyMatch (searchString: string, text: string): { searchTermsMatched: prevResult.searchTermsMatched + 1, - indexes: sort(uniq([ - ...prevResult.indexes, - ...nextResult.indexes - ])) + indexes: sort(uniq([...prevResult.indexes, ...nextResult.indexes])) }; }, emptyResults); @@ -273,7 +292,10 @@ export function fuzzyMatch (searchString: string, text: string): { return results; } -export function fuzzyMatchAll (searchString: string, allText: Array): boolean { +export function fuzzyMatchAll( + searchString: string, + allText: Array +): boolean { if (!searchString || !searchString.trim()) { return true; } @@ -283,17 +305,17 @@ export function fuzzyMatchAll (searchString: string, allText: Array): bo .map(searchTerm => searchTerm.trim()) .filter(searchTerm => !!searchTerm) .every(searchTerm => - allText.some(text => - fuzzyMatch(searchTerm, text).searchTermsMatched > 0)); + allText.some(text => fuzzyMatch(searchTerm, text).searchTermsMatched > 0) + ); } -export function getViewportSize (): string | null { - const {BrowserWindow} = electron.remote || electron; - const w = BrowserWindow.getFocusedWindow() || - BrowserWindow.getAllWindows()[0]; +export function getViewportSize(): string | null { + const { BrowserWindow } = electron.remote || electron; + const w = + BrowserWindow.getFocusedWindow() || BrowserWindow.getAllWindows()[0]; if (w) { - const {width, height} = w.getContentBounds(); + const { width, height } = w.getContentBounds(); return `${width}x${height}`; } else { // No windows open @@ -301,18 +323,20 @@ export function getViewportSize (): string | null { } } -export function getScreenResolution (): string { - const {screen} = electron.remote || electron; - const {width, height} = screen.getPrimaryDisplay().workAreaSize; +export function getScreenResolution(): string { + const { screen } = electron.remote || electron; + const { width, height } = screen.getPrimaryDisplay().workAreaSize; return `${width}x${height}`; } -export function getUserLanguage (): string { - const {app} = electron.remote || electron; +export function getUserLanguage(): string { + const { app } = electron.remote || electron; return app.getLocale(); } -export async function waitForStreamToFinish (s: Readable | Writable): Promise { +export async function waitForStreamToFinish( + s: Readable | Writable +): Promise { return new Promise(resolve => { if ((s: any)._readableState && (s: any)._readableState.finished) { return resolve(); diff --git a/packages/insomnia-app/app/common/render.js b/packages/insomnia-app/app/common/render.js index 5ad1803d3c..5e3a012cf6 100644 --- a/packages/insomnia-app/app/common/render.js +++ b/packages/insomnia-app/app/common/render.js @@ -1,14 +1,14 @@ // @flow -import type {Request} from '../models/request'; -import type {BaseModel} from '../models/index'; +import type { Request } from '../models/request'; +import type { BaseModel } from '../models/index'; -import {setDefaultProtocol} from 'insomnia-url'; +import { setDefaultProtocol } from 'insomnia-url'; import clone from 'clone'; import * as models from '../models'; import * as db from './database'; import * as templating from '../templating'; -import type {CookieJar} from '../models/cookie-jar'; -import type {Environment} from '../models/environment'; +import type { CookieJar } from '../models/cookie-jar'; +import type { Environment } from '../models/environment'; export const KEEP_ON_ERROR = 'keep'; export const THROW_ON_ERROR = 'throw'; @@ -19,11 +19,11 @@ export const RENDER_PURPOSE_SEND: RenderPurpose = 'send'; export const RENDER_PURPOSE_GENERAL: RenderPurpose = 'general'; export type RenderedRequest = Request & { - cookies: Array<{name: string, value: string, disabled?: boolean}>, + cookies: Array<{ name: string, value: string, disabled?: boolean }>, cookieJar: CookieJar }; -export async function buildRenderContext ( +export async function buildRenderContext( ancestors: Array | null, rootEnvironment: Environment | null, subEnvironment: Environment | null, @@ -108,7 +108,7 @@ export async function buildRenderContext ( * @param name - name to include in error message * @return {Promise.<*>} */ -export async function render ( +export async function render( obj: T, context: Object = {}, blacklistPathRegex: RegExp | null = null, @@ -118,7 +118,11 @@ export async function render ( // Make a deep copy so no one gets mad :) const newObj = clone(obj); - async function next (x: any, path: string, first: boolean = false): Promise { + async function next( + x: any, + path: string, + first: boolean = false + ): Promise { if (blacklistPathRegex && path.match(blacklistPathRegex)) { return x; } @@ -138,13 +142,13 @@ export async function render ( // Do nothing to these types } else if (typeof x === 'string') { try { - x = await templating.render(x, {context, path}); + x = await templating.render(x, { context, path }); // If the variable outputs a tag, render it again. This is a common use // case for environment variables: // {{ foo }} => {% uuid 'v4' %} => dd265685-16a3-4d76-a59c-e8264c16835a if (x.includes('{%')) { - x = await templating.render(x, {context, path}); + x = await templating.render(x, { context, path }); } } catch (err) { if (errorMode !== KEEP_ON_ERROR) { @@ -179,7 +183,7 @@ export async function render ( return next(newObj, name, true); } -export async function getRenderContext ( +export async function getRenderContext( request: Request, environmentId: string, ancestors: Array | null = null, @@ -202,7 +206,9 @@ export async function getRenderContext ( throw new Error('Failed to render. Could not find workspace'); } - const rootEnvironment = await models.environment.getOrCreateForWorkspaceId(workspace ? workspace._id : 'n/a'); + const rootEnvironment = await models.environment.getOrCreateForWorkspaceId( + workspace ? workspace._id : 'n/a' + ); const subEnvironment = await models.environment.getById(environmentId); // Add meta data helper function @@ -223,11 +229,11 @@ export async function getRenderContext ( ); } -export async function getRenderedRequestAndContext ( +export async function getRenderedRequestAndContext( request: Request, environmentId: string, purpose?: string -): Promise<{request: RenderedRequest, context: Object}> { +): Promise<{ request: RenderedRequest, context: Object }> { const ancestors = await db.withAncestors(request, [ models.request.type, models.requestGroup.type, @@ -237,11 +243,16 @@ export async function getRenderedRequestAndContext ( const parentId = workspace ? workspace._id : 'n/a'; const cookieJar = await models.cookieJar.getOrCreateForParentId(parentId); - const renderContext = await getRenderContext(request, environmentId, ancestors, purpose); + const renderContext = await getRenderContext( + request, + environmentId, + ancestors, + purpose + ); // Render all request properties const renderResult = await render( - {_request: request, _cookieJar: cookieJar}, + { _request: request, _cookieJar: cookieJar }, renderContext, request.settingDisableRenderRequestBody ? /^body.*/ : null ); @@ -250,18 +261,25 @@ export async function getRenderedRequestAndContext ( const renderedCookieJar = renderResult._cookieJar; // Remove disabled params - renderedRequest.parameters = renderedRequest.parameters.filter(p => !p.disabled); + renderedRequest.parameters = renderedRequest.parameters.filter( + p => !p.disabled + ); // Remove disabled headers renderedRequest.headers = renderedRequest.headers.filter(p => !p.disabled); // Remove disabled body params if (renderedRequest.body && Array.isArray(renderedRequest.body.params)) { - renderedRequest.body.params = renderedRequest.body.params.filter(p => !p.disabled); + renderedRequest.body.params = renderedRequest.body.params.filter( + p => !p.disabled + ); } // Remove disabled authentication - if (renderedRequest.authentication && renderedRequest.authentication.disabled) { + if ( + renderedRequest.authentication && + renderedRequest.authentication.disabled + ) { renderedRequest.authentication = {}; } @@ -291,7 +309,8 @@ export async function getRenderedRequestAndContext ( name: renderedRequest.name, parameters: renderedRequest.parameters, parentId: renderedRequest.parentId, - settingDisableRenderRequestBody: renderedRequest.settingDisableRenderRequestBody, + settingDisableRenderRequestBody: + renderedRequest.settingDisableRenderRequestBody, settingEncodeUrl: renderedRequest.settingEncodeUrl, settingSendCookies: renderedRequest.settingSendCookies, settingStoreCookies: renderedRequest.settingStoreCookies, @@ -303,12 +322,16 @@ export async function getRenderedRequestAndContext ( }; } -export async function getRenderedRequest ( +export async function getRenderedRequest( request: Request, environmentId: string, purpose?: string ): Promise { - const result = await getRenderedRequestAndContext(request, environmentId, purpose); + const result = await getRenderedRequestAndContext( + request, + environmentId, + purpose + ); return result.request; } @@ -320,7 +343,7 @@ export async function getRenderedRequest ( * @param v * @returns {number} */ -function _nunjucksSortValue (v) { +function _nunjucksSortValue(v) { if (v && v.match && v.match(/({%)/)) { return 3; } else if (v && v.match && v.match(/({{)/)) { @@ -330,7 +353,7 @@ function _nunjucksSortValue (v) { } } -function _getOrderedEnvironmentKeys (finalRenderContext: Object): Array { +function _getOrderedEnvironmentKeys(finalRenderContext: Object): Array { return Object.keys(finalRenderContext).sort((k1, k2) => { const k1Sort = _nunjucksSortValue(finalRenderContext[k1]); const k2Sort = _nunjucksSortValue(finalRenderContext[k2]); diff --git a/packages/insomnia-app/app/datasets/encodings.js b/packages/insomnia-app/app/datasets/encodings.js index 7f42744170..4a32ffb177 100644 --- a/packages/insomnia-app/app/datasets/encodings.js +++ b/packages/insomnia-app/app/datasets/encodings.js @@ -1,8 +1 @@ -export default [ - 'gzip', - 'compress', - 'deflate', - 'br', - 'identity', - '*' -]; +export default ['gzip', 'compress', 'deflate', 'br', 'identity', '*']; diff --git a/packages/insomnia-app/app/main.development.js b/packages/insomnia-app/app/main.development.js index e20a64f975..ded219079e 100644 --- a/packages/insomnia-app/app/main.development.js +++ b/packages/insomnia-app/app/main.development.js @@ -6,16 +6,21 @@ import * as updates from './main/updates'; import * as windowUtils from './main/window-utils'; import * as models from './models/index'; import * as database from './common/database'; -import {CHANGELOG_BASE_URL, getAppVersion, isDevelopment, isMac} from './common/constants'; -import type {ToastNotification} from './ui/components/toast'; -import type {Stats} from './models/stats'; +import { + CHANGELOG_BASE_URL, + getAppVersion, + isDevelopment, + isMac +} from './common/constants'; +import type { ToastNotification } from './ui/components/toast'; +import type { Stats } from './models/stats'; // Handle potential auto-update if (needsRestart) { process.exit(0); } -const {app, ipcMain, session} = electron; +const { app, ipcMain, session } = electron; const commandLineArgs = process.argv.slice(1); // So if (window) checks don't throw @@ -39,7 +44,7 @@ app.on('ready', async () => { // Set as default protocol app.setAsDefaultProtocolClient(`insomnia${isDevelopment() ? 'dev' : ''}`); -function _addUrlToOpen (e, url) { +function _addUrlToOpen(e, url) { e.preventDefault(); commandLineArgs.push(url); } @@ -70,7 +75,7 @@ app.on('activate', (e, hasVisibleWindows) => { } }); -function _launchApp () { +function _launchApp() { app.removeListener('open-url', _addUrlToOpen); const window = windowUtils.createWindow(); @@ -97,11 +102,11 @@ function _launchApp () { // Don't send origin header from Insomnia app because we're not technically using CORS session.defaultSession.webRequest.onBeforeSendHeaders((details, fn) => { delete details.requestHeaders['Origin']; - fn({cancel: false, requestHeaders: details.requestHeaders}); + fn({ cancel: false, requestHeaders: details.requestHeaders }); }); } -async function _trackStats () { +async function _trackStats() { // Handle the stats const oldStats = await models.stats.get(); const stats: Stats = await models.stats.update({ @@ -114,19 +119,20 @@ async function _trackStats () { // Update Stats Object const firstLaunch = stats.launches === 1; - const justUpdated = !firstLaunch && stats.currentVersion !== stats.lastVersion; + const justUpdated = + !firstLaunch && stats.currentVersion !== stats.lastVersion; ipcMain.once('window-ready', () => { - const {currentVersion} = stats; + const { currentVersion } = stats; if (!justUpdated || !currentVersion) { return; } - const {BrowserWindow} = electron; + const { BrowserWindow } = electron; const notification: ToastNotification = { key: `updated-${currentVersion}`, url: `${CHANGELOG_BASE_URL}/${currentVersion}/`, - cta: 'See What\'s New', + cta: "See What's New", message: `Updated to ${currentVersion}`, email: 'support@insomnia.rest' }; diff --git a/packages/insomnia-app/app/main/error-handling.js b/packages/insomnia-app/app/main/error-handling.js index 49c5eee975..e1a3f31ebf 100644 --- a/packages/insomnia-app/app/main/error-handling.js +++ b/packages/insomnia-app/app/main/error-handling.js @@ -1,4 +1,4 @@ -export function init () { +export function init() { process.on('uncaughtException', err => { console.error('[catcher] Uncaught exception:', err.stack); }); diff --git a/packages/insomnia-app/app/main/local-storage.js b/packages/insomnia-app/app/main/local-storage.js index efa48f2c18..7b732911b0 100644 --- a/packages/insomnia-app/app/main/local-storage.js +++ b/packages/insomnia-app/app/main/local-storage.js @@ -3,7 +3,7 @@ import fs from 'fs'; import path from 'path'; class LocalStorage { - constructor (basePath) { + constructor(basePath) { this._basePath = basePath; // Debounce writes on a per key basis @@ -14,13 +14,13 @@ class LocalStorage { console.log(`[localstorage] Initialized at ${basePath}`); } - setItem (key, obj) { + setItem(key, obj) { clearTimeout(this._timeouts[key]); this._buffer[key] = JSON.stringify(obj); this._timeouts[key] = setTimeout(this._flush.bind(this), 100); } - getItem (key, defaultObj) { + getItem(key, defaultObj) { // Make sure things are flushed before we read this._flush(); @@ -38,12 +38,14 @@ class LocalStorage { try { return JSON.parse(contents); } catch (e) { - console.error(`[localstorage] Failed to parse item from LocalStorage: ${e}`); + console.error( + `[localstorage] Failed to parse item from LocalStorage: ${e}` + ); return defaultObj; } } - _flush () { + _flush() { const keys = Object.keys(this._buffer); if (!keys.length) { @@ -64,7 +66,7 @@ class LocalStorage { } } - _getKeyPath (key) { + _getKeyPath(key) { return path.join(this._basePath, key); } } diff --git a/packages/insomnia-app/app/main/updates.js b/packages/insomnia-app/app/main/updates.js index 9e118dce4c..73bfea5c18 100644 --- a/packages/insomnia-app/app/main/updates.js +++ b/packages/insomnia-app/app/main/updates.js @@ -1,13 +1,22 @@ // @flow import electron from 'electron'; -import {CHECK_FOR_UPDATES_INTERVAL, getAppVersion, isDevelopment, UPDATE_URL_MAC, UPDATE_URL_WINDOWS} from '../common/constants'; +import { + CHECK_FOR_UPDATES_INTERVAL, + getAppVersion, + isDevelopment, + UPDATE_URL_MAC, + UPDATE_URL_WINDOWS +} from '../common/constants'; import * as models from '../models/index'; -import {buildQueryStringFromParams, joinUrlAndQueryString} from 'insomnia-url'; -import {delay} from '../common/misc'; +import { + buildQueryStringFromParams, + joinUrlAndQueryString +} from 'insomnia-url'; +import { delay } from '../common/misc'; -const {autoUpdater, BrowserWindow, ipcMain} = electron; +const { autoUpdater, BrowserWindow, ipcMain } = electron; -async function getUpdateUrl (force: boolean): Promise { +async function getUpdateUrl(force: boolean): Promise { const platform = process.platform; const settings = await models.settings.getOrCreate(); let updateUrl = null; @@ -21,8 +30,8 @@ async function getUpdateUrl (force: boolean): Promise { } const params = [ - {name: 'v', value: getAppVersion()}, - {name: 'channel', value: settings.updateChannel} + { name: 'v', value: getAppVersion() }, + { name: 'channel', value: settings.updateChannel } ]; const qs = buildQueryStringFromParams(params); @@ -30,7 +39,9 @@ async function getUpdateUrl (force: boolean): Promise { console.log(`[updater] Using url ${fullUrl}`); if (process.env.INSOMNIA_DISABLE_AUTOMATIC_UPDATES) { - console.log(`[updater] Disabled by INSOMNIA_DISABLE_AUTOMATIC_UPDATES environment variable`); + console.log( + `[updater] Disabled by INSOMNIA_DISABLE_AUTOMATIC_UPDATES environment variable` + ); return null; } @@ -45,14 +56,14 @@ async function getUpdateUrl (force: boolean): Promise { return fullUrl; } -function _sendUpdateStatus (status) { +function _sendUpdateStatus(status) { const windows = BrowserWindow.getAllWindows(); for (const w of windows) { w.send('updater.check.status', status); } } -function _sendUpdateComplete (success: boolean, msg: string) { +function _sendUpdateComplete(success: boolean, msg: string) { const windows = BrowserWindow.getAllWindows(); for (const w of windows) { w.send('updater.check.complete', success, msg); @@ -61,7 +72,7 @@ function _sendUpdateComplete (success: boolean, msg: string) { let hasPromptedForUpdates = false; -export async function init () { +export async function init() { autoUpdater.on('error', e => { console.warn(`[updater] Error: ${e.message}`); }); @@ -76,11 +87,14 @@ export async function init () { _sendUpdateStatus('Downloading...'); }); - autoUpdater.on('update-downloaded', (e, releaseNotes, releaseName, releaseDate, updateUrl) => { - console.log(`[updater] Downloaded ${releaseName}`); - _sendUpdateComplete(true, 'Updated (Restart Required)'); - _showUpdateNotification(); - }); + autoUpdater.on( + 'update-downloaded', + (e, releaseNotes, releaseName, releaseDate, updateUrl) => { + console.log(`[updater] Downloaded ${releaseName}`); + _sendUpdateComplete(true, 'Updated (Restart Required)'); + _showUpdateNotification(); + } + ); ipcMain.on('updater.check', async e => { await _checkForUpdates(true); @@ -95,7 +109,7 @@ export async function init () { await _checkForUpdates(false); } -function _showUpdateNotification () { +function _showUpdateNotification() { if (hasPromptedForUpdates) { return; } @@ -108,7 +122,7 @@ function _showUpdateNotification () { hasPromptedForUpdates = true; } -async function _checkForUpdates (force: boolean) { +async function _checkForUpdates(force: boolean) { _sendUpdateStatus('Checking'); await delay(500); @@ -124,7 +138,11 @@ async function _checkForUpdates (force: boolean) { const updateUrl = await getUpdateUrl(force); if (updateUrl === null) { - console.log(`[updater] Updater not running platform=${process.platform} dev=${isDevelopment()}`); + console.log( + `[updater] Updater not running platform=${ + process.platform + } dev=${isDevelopment()}` + ); _sendUpdateComplete(false, 'Updates Not Supported'); return; } diff --git a/packages/insomnia-app/app/main/window-utils.js b/packages/insomnia-app/app/main/window-utils.js index 218200fa93..e06bf3899f 100644 --- a/packages/insomnia-app/app/main/window-utils.js +++ b/packages/insomnia-app/app/main/window-utils.js @@ -1,12 +1,19 @@ import electron from 'electron'; import path from 'path'; -import {Curl} from 'insomnia-libcurl'; +import { Curl } from 'insomnia-libcurl'; import fs from 'fs'; import LocalStorage from './local-storage'; -import {CHANGELOG_BASE_URL, getAppLongName, getAppName, getAppVersion, isDevelopment, isMac} from '../common/constants'; +import { + CHANGELOG_BASE_URL, + getAppLongName, + getAppName, + getAppVersion, + isDevelopment, + isMac +} from '../common/constants'; import * as misc from '../common/misc'; -const {app, Menu, BrowserWindow, shell, dialog} = electron; +const { app, Menu, BrowserWindow, shell, dialog } = electron; const DEFAULT_WIDTH = 1100; const DEFAULT_HEIGHT = 550; @@ -16,15 +23,15 @@ const MINIMUM_HEIGHT = 400; let mainWindow = null; let localStorage = null; -export function init () { +export function init() { initLocalStorage(); initContextMenus(); } -export function createWindow () { +export function createWindow() { const zoomFactor = getZoomFactor(); - const {bounds, fullscreen, maximize} = getBounds(); - const {x, y, width, height} = bounds; + const { bounds, fullscreen, maximize } = getBounds(); + const { x, y, width, height } = bounds; // Make sure we don't place the window outside of the visible space let maxX = 0; @@ -89,14 +96,16 @@ export function createWindow () { const applicationMenu = { label: 'Application', submenu: [ - ...(isMac() ? [ - {label: `About ${getAppName()}`, role: 'about'}, - {type: 'separator'} - ] : []), + ...(isMac() + ? [ + { label: `About ${getAppName()}`, role: 'about' }, + { type: 'separator' } + ] + : []), { label: 'Preferences', accelerator: 'CmdOrCtrl+,', - click: function (menuItem, window, e) { + click: function(menuItem, window, e) { if (!window || !window.webContents) { return; } @@ -105,40 +114,42 @@ export function createWindow () { }, { label: 'Changelog', - click: function (menuItem, window, e) { + click: function(menuItem, window, e) { if (!window || !window.webContents) { return; } misc.clickLink(`${CHANGELOG_BASE_URL}/${getAppVersion()}/`); } }, - ...(isMac() ? [ - {type: 'separator'}, - {role: 'hide'}, - {role: 'hideothers'} - ] : []), - {type: 'separator'}, - {label: 'Quit', accelerator: 'CmdOrCtrl+Q', click: () => app.quit()} + ...(isMac() + ? [{ type: 'separator' }, { role: 'hide' }, { role: 'hideothers' }] + : []), + { type: 'separator' }, + { label: 'Quit', accelerator: 'CmdOrCtrl+Q', click: () => app.quit() } ] }; const editMenu = { label: 'Edit', submenu: [ - {label: 'Undo', accelerator: 'CmdOrCtrl+Z', selector: 'undo:'}, - {label: 'Redo', accelerator: 'Shift+CmdOrCtrl+Z', selector: 'redo:'}, - {type: 'separator'}, - {label: 'Cut', accelerator: 'CmdOrCtrl+X', selector: 'cut:'}, - {label: 'Copy', accelerator: 'CmdOrCtrl+C', selector: 'copy:'}, - {label: 'Paste', accelerator: 'CmdOrCtrl+V', selector: 'paste:'}, - {label: 'Select All', accelerator: 'CmdOrCtrl+A', selector: 'selectAll:'} + { label: 'Undo', accelerator: 'CmdOrCtrl+Z', selector: 'undo:' }, + { label: 'Redo', accelerator: 'Shift+CmdOrCtrl+Z', selector: 'redo:' }, + { type: 'separator' }, + { label: 'Cut', accelerator: 'CmdOrCtrl+X', selector: 'cut:' }, + { label: 'Copy', accelerator: 'CmdOrCtrl+C', selector: 'copy:' }, + { label: 'Paste', accelerator: 'CmdOrCtrl+V', selector: 'paste:' }, + { + label: 'Select All', + accelerator: 'CmdOrCtrl+A', + selector: 'selectAll:' + } ] }; const viewMenu = { label: 'View', submenu: [ - {role: 'togglefullscreen'}, + { role: 'togglefullscreen' }, { label: 'Actual Size', accelerator: 'CmdOrCtrl+0', @@ -204,10 +215,7 @@ export function createWindow () { const windowMenu = { label: 'Window', role: 'window', - submenu: [ - {role: 'minimize'}, - ...(isMac() ? [{role: 'close'}] : []) - ] + submenu: [{ role: 'minimize' }, ...(isMac() ? [{ role: 'close' }] : [])] }; const helpMenu = { @@ -272,48 +280,59 @@ export function createWindow () { const developerMenu = { label: 'Developer', position: 'before=help', - submenu: [{ - label: 'Reload', - accelerator: 'Shift+F5', - click: () => mainWindow.reload() - }, { - label: 'Toggle DevTools', - accelerator: 'Alt+CmdOrCtrl+I', - click: () => mainWindow.toggleDevTools() - }, { - label: 'Resize to Default', - click: () => mainWindow.setBounds({ - x: 100, - y: 100, - width: DEFAULT_WIDTH, - height: DEFAULT_HEIGHT - }) - }, { - label: 'Take Screenshot', - click: function () { - mainWindow.capturePage(image => { - const buffer = image.toPNG(); - const dir = app.getPath('desktop'); - fs.writeFileSync(path.join(dir, `Screenshot-${new Date()}.png`), buffer); - }); + submenu: [ + { + label: 'Reload', + accelerator: 'Shift+F5', + click: () => mainWindow.reload() + }, + { + label: 'Toggle DevTools', + accelerator: 'Alt+CmdOrCtrl+I', + click: () => mainWindow.toggleDevTools() + }, + { + label: 'Resize to Default', + click: () => + mainWindow.setBounds({ + x: 100, + y: 100, + width: DEFAULT_WIDTH, + height: DEFAULT_HEIGHT + }) + }, + { + label: 'Take Screenshot', + click: function() { + mainWindow.capturePage(image => { + const buffer = image.toPNG(); + const dir = app.getPath('desktop'); + fs.writeFileSync( + path.join(dir, `Screenshot-${new Date()}.png`), + buffer + ); + }); + } } - }] + ] }; const toolsMenu = { label: 'Tools', - submenu: [{ - label: 'Reload Plugins', - accelerator: 'CmdOrCtrl+Shift+R', - click: () => { - const window = BrowserWindow.getFocusedWindow(); - if (!window || !window.webContents) { - return; - } + submenu: [ + { + label: 'Reload Plugins', + accelerator: 'CmdOrCtrl+Shift+R', + click: () => { + const window = BrowserWindow.getFocusedWindow(); + if (!window || !window.webContents) { + return; + } - window.webContents.send('reload-plugins'); + window.webContents.send('reload-plugins'); + } } - }] + ] }; let template = []; @@ -334,23 +353,26 @@ export function createWindow () { return mainWindow; } -function showUnresponsiveModal () { - dialog.showMessageBox({ - type: 'info', - buttons: ['Cancel', 'Reload'], - defaultId: 1, - cancelId: 0, - title: 'Unresponsive', - message: 'Insomnia has become unresponsive. Do you want to reload?' - }, id => { - if (id === 1) { - mainWindow.destroy(); - createWindow(); +function showUnresponsiveModal() { + dialog.showMessageBox( + { + type: 'info', + buttons: ['Cancel', 'Reload'], + defaultId: 1, + cancelId: 0, + title: 'Unresponsive', + message: 'Insomnia has become unresponsive. Do you want to reload?' + }, + id => { + if (id === 1) { + mainWindow.destroy(); + createWindow(); + } } - }); + ); } -function saveBounds () { +function saveBounds() { if (!mainWindow) { return; } @@ -367,7 +389,7 @@ function saveBounds () { } } -function getBounds () { +function getBounds() { let bounds = {}; let fullscreen = false; let maximize = false; @@ -380,14 +402,14 @@ function getBounds () { console.error('Failed to parse window bounds', e); } - return {bounds, fullscreen, maximize}; + return { bounds, fullscreen, maximize }; } -function saveZoomFactor (zoomFactor) { +function saveZoomFactor(zoomFactor) { localStorage.setItem('zoomFactor', zoomFactor); } -function getZoomFactor () { +function getZoomFactor() { let zoomFactor = 1; try { zoomFactor = localStorage.getItem('zoomFactor', 1); @@ -399,11 +421,11 @@ function getZoomFactor () { return zoomFactor; } -function initLocalStorage () { +function initLocalStorage() { const localStoragePath = path.join(app.getPath('userData'), 'localStorage'); localStorage = new LocalStorage(localStoragePath); } -function initContextMenus () { +function initContextMenus() { require('electron-context-menu')({}); } diff --git a/packages/insomnia-app/app/models/__mocks__/uuid.js b/packages/insomnia-app/app/models/__mocks__/uuid.js index ed5ddf77b8..c4b0496cab 100644 --- a/packages/insomnia-app/app/models/__mocks__/uuid.js +++ b/packages/insomnia-app/app/models/__mocks__/uuid.js @@ -192,7 +192,7 @@ const v4UUIDs = [ '966e9995-938a-4a5e-813c-de3691dddb3a' ]; -function v1 () { +function v1() { const uuid = v1UUIDs[v1Counter++]; if (!uuid) { throw new Error('Not enough mocked v1 UUIDs to go around'); @@ -201,7 +201,7 @@ function v1 () { return uuid; } -function v4 () { +function v4() { const uuid = v4UUIDs[v4Counter++]; if (!uuid) { throw new Error('Not enough mocked v4 UUIDs to go around'); diff --git a/packages/insomnia-app/app/models/__tests__/request.test.js b/packages/insomnia-app/app/models/__tests__/request.test.js index 9d802fec91..de5b77dca0 100644 --- a/packages/insomnia-app/app/models/__tests__/request.test.js +++ b/packages/insomnia-app/app/models/__tests__/request.test.js @@ -1,5 +1,5 @@ import * as models from '../index'; -import {globalBeforeEach} from '../../__jest__/before-each'; +import { globalBeforeEach } from '../../__jest__/before-each'; describe('init()', () => { beforeEach(globalBeforeEach); @@ -66,18 +66,28 @@ describe('create()', async () => { it('fails when missing parentId', async () => { Date.now = jest.fn().mockReturnValue(1478795580200); - expect(() => models.request.create({name: 'Test Request'})).toThrow('New Requests missing `parentId`'); + expect(() => models.request.create({ name: 'Test Request' })).toThrow( + 'New Requests missing `parentId`' + ); }); }); describe('updateMimeType()', async () => { beforeEach(globalBeforeEach); it('adds header when does not exist', async () => { - const request = await models.request.create({name: 'My Request', parentId: 'fld_1'}); + const request = await models.request.create({ + name: 'My Request', + parentId: 'fld_1' + }); expect(request).not.toBeNull(); - const newRequest = await models.request.updateMimeType(request, 'text/html'); - expect(newRequest.headers).toEqual([{name: 'Content-Type', value: 'text/html'}]); + const newRequest = await models.request.updateMimeType( + request, + 'text/html' + ); + expect(newRequest.headers).toEqual([ + { name: 'Content-Type', value: 'text/html' } + ]); }); it('replaces header when exists', async () => { @@ -85,19 +95,22 @@ describe('updateMimeType()', async () => { name: 'My Request', parentId: 'fld_1', headers: [ - {name: 'content-tYPE', value: 'application/json'}, - {name: 'foo', value: 'bar'}, - {bad: true}, + { name: 'content-tYPE', value: 'application/json' }, + { name: 'foo', value: 'bar' }, + { bad: true }, null ] }); expect(request).not.toBeNull(); - const newRequest = await models.request.updateMimeType(request, 'text/html'); + const newRequest = await models.request.updateMimeType( + request, + 'text/html' + ); expect(newRequest.headers).toEqual([ - {name: 'content-tYPE', value: 'text/html'}, - {name: 'foo', value: 'bar'}, - {bad: true}, + { name: 'content-tYPE', value: 'text/html' }, + { name: 'foo', value: 'bar' }, + { bad: true }, null ]); }); @@ -106,25 +119,32 @@ describe('updateMimeType()', async () => { const request = await models.request.create({ name: 'My Request', parentId: 'fld_1', - headers: [{name: 'content-tYPE', value: 'application/json'}] + headers: [{ name: 'content-tYPE', value: 'application/json' }] }); expect(request).not.toBeNull(); - const newRequest = await models.request.updateMimeType(request, 'text/html'); - expect(newRequest.headers).toEqual([{name: 'content-tYPE', value: 'text/html'}]); + const newRequest = await models.request.updateMimeType( + request, + 'text/html' + ); + expect(newRequest.headers).toEqual([ + { name: 'content-tYPE', value: 'text/html' } + ]); }); it('keeps content-type', async () => { const request = await models.request.create({ name: 'My Request', parentId: 'fld_1', - headers: [{name: 'content-tYPE', value: 'application/json'}] + headers: [{ name: 'content-tYPE', value: 'application/json' }] }); expect(request).not.toBeNull(); const newRequest = await models.request.updateMimeType(request, null); expect(newRequest.body).toEqual({}); - expect(newRequest.headers).toEqual([{name: 'content-tYPE', value: 'application/json'}]); + expect(newRequest.headers).toEqual([ + { name: 'content-tYPE', value: 'application/json' } + ]); }); it('uses saved body when provided', async () => { @@ -137,7 +157,12 @@ describe('updateMimeType()', async () => { }); expect(request).not.toBeNull(); - const newRequest = await models.request.updateMimeType(request, 'application/json', false, {text: 'Saved Data'}); + const newRequest = await models.request.updateMimeType( + request, + 'application/json', + false, + { text: 'Saved Data' } + ); expect(newRequest.body.text).toEqual('Saved Data'); }); @@ -151,7 +176,12 @@ describe('updateMimeType()', async () => { }); expect(request).not.toBeNull(); - const newRequest = await models.request.updateMimeType(request, 'application/json', false, {}); + const newRequest = await models.request.updateMimeType( + request, + 'application/json', + false, + {} + ); expect(newRequest.body.text).toEqual('My Data'); }); }); @@ -166,7 +196,7 @@ describe('migrate()', () => { const expected = { headers: [], - body: {mimeType: '', text: 'hello world!'}, + body: { mimeType: '', text: 'hello world!' }, url: '' }; @@ -175,17 +205,21 @@ describe('migrate()', () => { it('migrates form-urlencoded', () => { const original = { - headers: [{name: 'content-type', value: 'application/x-www-form-urlencoded'}], + headers: [ + { name: 'content-type', value: 'application/x-www-form-urlencoded' } + ], body: 'foo=bar&baz={{ hello }}' }; const expected = { - headers: [{name: 'content-type', value: 'application/x-www-form-urlencoded'}], + headers: [ + { name: 'content-type', value: 'application/x-www-form-urlencoded' } + ], body: { mimeType: 'application/x-www-form-urlencoded', params: [ - {name: 'foo', value: 'bar'}, - {name: 'baz', value: '{{ hello }}'} + { name: 'foo', value: 'bar' }, + { name: 'baz', value: '{{ hello }}' } ] }, url: '' @@ -196,17 +230,27 @@ describe('migrate()', () => { it('migrates form-urlencoded with charset', () => { const original = { - headers: [{name: 'content-type', value: 'application/x-www-form-urlencoded; charset=utf-8'}], + headers: [ + { + name: 'content-type', + value: 'application/x-www-form-urlencoded; charset=utf-8' + } + ], body: 'foo=bar&baz={{ hello }}' }; const expected = { - headers: [{name: 'content-type', value: 'application/x-www-form-urlencoded; charset=utf-8'}], + headers: [ + { + name: 'content-type', + value: 'application/x-www-form-urlencoded; charset=utf-8' + } + ], body: { mimeType: 'application/x-www-form-urlencoded', params: [ - {name: 'foo', value: 'bar'}, - {name: 'baz', value: '{{ hello }}'} + { name: 'foo', value: 'bar' }, + { name: 'baz', value: '{{ hello }}' } ] }, url: '' @@ -217,17 +261,19 @@ describe('migrate()', () => { it('migrates form-urlencoded malformed', () => { const original = { - headers: [{name: 'content-type', value: 'application/x-www-form-urlencoded'}], + headers: [ + { name: 'content-type', value: 'application/x-www-form-urlencoded' } + ], body: '{"foo": "bar"}' }; const expected = { - headers: [{name: 'content-type', value: 'application/x-www-form-urlencoded'}], + headers: [ + { name: 'content-type', value: 'application/x-www-form-urlencoded' } + ], body: { mimeType: 'application/x-www-form-urlencoded', - params: [ - {name: '{"foo": "bar"}', value: ''} - ] + params: [{ name: '{"foo": "bar"}', value: '' }] }, url: '' }; @@ -239,18 +285,18 @@ describe('migrate()', () => { const contentToMimeMap = { 'application/json; charset=utf-8': 'application/json', 'text/plain': 'text/plain', - 'malformed': 'malformed' + malformed: 'malformed' }; for (const contentType of Object.keys(contentToMimeMap)) { const original = { - headers: [{name: 'content-type', value: contentType}], + headers: [{ name: 'content-type', value: contentType }], body: '' }; const expected = { - headers: [{name: 'content-type', value: contentType}], - body: {mimeType: contentToMimeMap[contentType], text: ''}, + headers: [{ name: 'content-type', value: contentType }], + body: { mimeType: contentToMimeMap[contentType], text: '' }, url: '' }; @@ -260,16 +306,16 @@ describe('migrate()', () => { it('skips migrate for schema 1', () => { const original = { - body: {mimeType: 'text/plain', text: 'foo'} + body: { mimeType: 'text/plain', text: 'foo' } }; expect(models.request.migrate(original)).toBe(original); }); it('migrates with weird data', () => { - const newBody = {body: {mimeType: '', text: 'foo bar!'}}; - const stringBody = {body: 'foo bar!'}; - const nullBody = {body: null}; + const newBody = { body: { mimeType: '', text: 'foo bar!' } }; + const stringBody = { body: 'foo bar!' }; + const nullBody = { body: null }; const noBody = {}; const expected = { @@ -315,7 +361,7 @@ describe('migrate()', () => { authentication: {}, parameters: [], parentId: null, - body: {mimeType: '', text: 'hello world!'}, + body: { mimeType: '', text: 'hello world!' }, settingStoreCookies: true, settingSendCookies: true, settingDisableRenderRequestBody: false, diff --git a/packages/insomnia-app/app/models/__tests__/response.test.js b/packages/insomnia-app/app/models/__tests__/response.test.js index 3e74648dbf..99d9058498 100644 --- a/packages/insomnia-app/app/models/__tests__/response.test.js +++ b/packages/insomnia-app/app/models/__tests__/response.test.js @@ -3,7 +3,7 @@ import zlib from 'zlib'; import fs from 'fs'; import * as electron from 'electron'; import * as models from '../../models'; -import {globalBeforeEach} from '../../__jest__/before-each'; +import { globalBeforeEach } from '../../__jest__/before-each'; describe('migrate()', () => { beforeEach(async () => { @@ -13,7 +13,7 @@ describe('migrate()', () => { }); it('migrates utf8 body correctly', async () => { - const initialModel = {body: 'hello world!', encoding: 'utf8'}; + const initialModel = { body: 'hello world!', encoding: 'utf8' }; const newModel = await models.initModel(models.response.type, initialModel); const expectedBodyPath = path.join( @@ -32,7 +32,7 @@ describe('migrate()', () => { }); it('migrates base64 body correctly', async () => { - const initialModel = {body: 'aGVsbG8gd29ybGQh', encoding: 'base64'}; + const initialModel = { body: 'aGVsbG8gd29ybGQh', encoding: 'base64' }; const newModel = await models.initModel(models.response.type, initialModel); jest.runAllTimers(); @@ -52,7 +52,7 @@ describe('migrate()', () => { }); it('migrates empty body', async () => { - const initialModel = {body: ''}; + const initialModel = { body: '' }; const newModel = await models.initModel(models.response.type, initialModel); jest.runAllTimers(); @@ -74,7 +74,7 @@ describe('migrate()', () => { }); it('does not migrate body again', async () => { - const initialModel = {bodyPath: '/foo/bar'}; + const initialModel = { bodyPath: '/foo/bar' }; const newModel = await models.initModel(models.response.type, initialModel); @@ -87,10 +87,13 @@ describe('migrate()', () => { }); it('does it', async () => { - const bodyPath = path.join(electron.remote.app.getPath('userData'), 'foo.zip'); + const bodyPath = path.join( + electron.remote.app.getPath('userData'), + 'foo.zip' + ); fs.writeFileSync(bodyPath, zlib.gzipSync('Hello World!')); - const response = await models.initModel(models.response.type, {bodyPath}); + const response = await models.initModel(models.response.type, { bodyPath }); const body = await models.response.getBodyBuffer(response).toString(); expect(response.bodyCompression).toBe('zip'); @@ -109,22 +112,28 @@ describe('migrate()', () => { }); it('migrates leaves bodyCompression for null', async () => { - expect((await models.initModel(models.response.type, { - bodyPath: '/foo/bar', - bodyCompression: null - })).bodyCompression).toBe(null); + expect( + (await models.initModel(models.response.type, { + bodyPath: '/foo/bar', + bodyCompression: null + })).bodyCompression + ).toBe(null); }); it('migrates sets bodyCompression to zip if does not have one yet', async () => { - expect((await models.initModel(models.response.type, { - bodyPath: '/foo/bar' - })).bodyCompression).toBe('zip'); + expect( + (await models.initModel(models.response.type, { + bodyPath: '/foo/bar' + })).bodyCompression + ).toBe('zip'); }); it('migrates leaves bodyCompression if string', async () => { - expect((await models.initModel(models.response.type, { - bodyPath: '/foo/bar', - bodyCompression: 'zip' - })).bodyCompression).toBe('zip'); + expect( + (await models.initModel(models.response.type, { + bodyPath: '/foo/bar', + bodyCompression: 'zip' + })).bodyCompression + ).toBe('zip'); }); }); diff --git a/packages/insomnia-app/app/models/__tests__/workspace.test.js b/packages/insomnia-app/app/models/__tests__/workspace.test.js index 85b740375f..92812a3cc6 100644 --- a/packages/insomnia-app/app/models/__tests__/workspace.test.js +++ b/packages/insomnia-app/app/models/__tests__/workspace.test.js @@ -1,5 +1,5 @@ import * as models from '../index'; -import {globalBeforeEach} from '../../__jest__/before-each'; +import { globalBeforeEach } from '../../__jest__/before-each'; describe('migrate()', () => { beforeEach(globalBeforeEach); @@ -7,8 +7,8 @@ describe('migrate()', () => { const workspace = await models.workspace.create({ name: 'My Workspace', certificates: [ - {key: 'key', passphrase: 'mypass'}, - {disabled: true, cert: 'cert'} + { key: 'key', passphrase: 'mypass' }, + { disabled: true, cert: 'cert' } ] }); @@ -24,35 +24,40 @@ describe('migrate()', () => { } expect(certs.length).toBe(2); - expect(certs.sort((c1, c2) => c1._id > c2._id ? -1 : 1)).toEqual([{ - _id: 'crt_e3e96e5fdd6842298b66dee1f0940f3d', - cert: 'cert', - disabled: false, - isPrivate: false, - host: '', - key: null, - parentId: 'wrk_cc1dd2ca4275747aa88199e8efd42403', - passphrase: null, - pfx: null, - type: 'ClientCertificate' - }, { - _id: 'crt_dd2ccc1a2745477a881a9e8ef9d42403', - cert: null, - disabled: false, - isPrivate: false, - host: '', - key: 'key', - parentId: 'wrk_cc1dd2ca4275747aa88199e8efd42403', - passphrase: 'mypass', - pfx: null, - type: 'ClientCertificate' - }]); + expect(certs.sort((c1, c2) => (c1._id > c2._id ? -1 : 1))).toEqual([ + { + _id: 'crt_e3e96e5fdd6842298b66dee1f0940f3d', + cert: 'cert', + disabled: false, + isPrivate: false, + host: '', + key: null, + parentId: 'wrk_cc1dd2ca4275747aa88199e8efd42403', + passphrase: null, + pfx: null, + type: 'ClientCertificate' + }, + { + _id: 'crt_dd2ccc1a2745477a881a9e8ef9d42403', + cert: null, + disabled: false, + isPrivate: false, + host: '', + key: 'key', + parentId: 'wrk_cc1dd2ca4275747aa88199e8efd42403', + passphrase: 'mypass', + pfx: null, + type: 'ClientCertificate' + } + ]); expect(migratedWorkspace.certificates).toBeUndefined(); // Make sure we don't create new certs if we migrate again await models.workspace.migrate(migratedWorkspace); - const certsAgain = await models.clientCertificate.findByParentId(workspace._id); + const certsAgain = await models.clientCertificate.findByParentId( + workspace._id + ); expect(certsAgain.length).toBe(2); }); }); diff --git a/packages/insomnia-app/app/models/client-certificate.js b/packages/insomnia-app/app/models/client-certificate.js index ecd3dd45b4..af8ed660c9 100644 --- a/packages/insomnia-app/app/models/client-certificate.js +++ b/packages/insomnia-app/app/models/client-certificate.js @@ -1,6 +1,6 @@ // @flow import * as db from '../common/database'; -import type {BaseModel} from './index'; +import type { BaseModel } from './index'; export const name = 'Client Certificate'; export const type = 'ClientCertificate'; @@ -22,7 +22,7 @@ type BaseClientCertificate = { export type ClientCertificate = BaseModel & BaseClientCertificate; -export function init (): BaseClientCertificate { +export function init(): BaseClientCertificate { return { parentId: '', host: '', @@ -35,34 +35,41 @@ export function init (): BaseClientCertificate { }; } -export async function migrate (doc: ClientCertificate) { +export async function migrate(doc: ClientCertificate) { return doc; } -export function create (patch: Object = {}): Promise { +export function create(patch: Object = {}): Promise { if (!patch.parentId) { - throw new Error('New ClientCertificate missing `parentId`: ' + JSON.stringify(patch)); + throw new Error( + 'New ClientCertificate missing `parentId`: ' + JSON.stringify(patch) + ); } return db.docCreate(type, patch); } -export function update (cert: ClientCertificate, patch: Object = {}): Promise { +export function update( + cert: ClientCertificate, + patch: Object = {} +): Promise { return db.docUpdate(cert, patch); } -export function getById (id: string): Promise { +export function getById(id: string): Promise { return db.get(type, id); } -export function findByParentId (parentId: string): Promise> { - return db.find(type, {parentId}); +export function findByParentId( + parentId: string +): Promise> { + return db.find(type, { parentId }); } -export function remove (cert: ClientCertificate): Promise { +export function remove(cert: ClientCertificate): Promise { return db.remove(cert); } -export function all (): Promise> { +export function all(): Promise> { return db.all(type); } diff --git a/packages/insomnia-app/app/models/cookie-jar.js b/packages/insomnia-app/app/models/cookie-jar.js index 3d90c70f47..1664b0ffde 100644 --- a/packages/insomnia-app/app/models/cookie-jar.js +++ b/packages/insomnia-app/app/models/cookie-jar.js @@ -1,6 +1,6 @@ // @flow import * as db from '../common/database'; -import type {BaseModel} from './index'; +import type { BaseModel } from './index'; export const name = 'Cookie Jar'; export const type = 'CookieJar'; @@ -23,7 +23,7 @@ export type Cookie = { hostOnly?: boolean, pathIsDefault?: boolean, lastAccessed?: Date -} +}; type BaseCookieJar = { name: string, @@ -32,52 +32,56 @@ type BaseCookieJar = { export type CookieJar = BaseModel & BaseCookieJar; -export function init () { +export function init() { return { name: 'Default Jar', cookies: [] }; } -export function migrate (doc: CookieJar): CookieJar { +export function migrate(doc: CookieJar): CookieJar { doc = migrateCookieId(doc); return doc; } -export function create (patch: Object = {}) { +export function create(patch: Object = {}) { if (!patch.parentId) { - throw new Error(`New CookieJar missing \`parentId\`: ${JSON.stringify(patch)}`); + throw new Error( + `New CookieJar missing \`parentId\`: ${JSON.stringify(patch)}` + ); } return db.docCreate(type, patch); } -export async function getOrCreateForParentId (parentId: string) { - const cookieJars = await db.find(type, {parentId}); +export async function getOrCreateForParentId(parentId: string) { + const cookieJars = await db.find(type, { parentId }); if (cookieJars.length === 0) { - return create({parentId}); + return create({ parentId }); } else { return cookieJars[0]; } } -export function all () { +export function all() { return db.all(type); } -export function getById (id: string) { +export function getById(id: string) { return db.get(type, id); } -export function update (cookieJar: CookieJar, patch: Object = {}) { +export function update(cookieJar: CookieJar, patch: Object = {}) { return db.docUpdate(cookieJar, patch); } /** Ensure every cookie has an ID property */ -function migrateCookieId (cookieJar: CookieJar) { +function migrateCookieId(cookieJar: CookieJar) { for (const cookie of cookieJar.cookies) { if (!cookie.id) { - cookie.id = Math.random().toString().replace('0.', ''); + cookie.id = Math.random() + .toString() + .replace('0.', ''); } } return cookieJar; diff --git a/packages/insomnia-app/app/models/environment.js b/packages/insomnia-app/app/models/environment.js index 0dce14d289..058f1228fb 100644 --- a/packages/insomnia-app/app/models/environment.js +++ b/packages/insomnia-app/app/models/environment.js @@ -1,7 +1,7 @@ // @flow import * as db from '../common/database'; -import type {BaseModel} from './index'; -import type {Workspace} from './workspace'; +import type { BaseModel } from './index'; +import type { Workspace } from './workspace'; export const name = 'Environment'; export const type = 'Environment'; @@ -20,7 +20,7 @@ type BaseEnvironment = { export type Environment = BaseModel & BaseEnvironment; -export function init () { +export function init() { return { name: 'New Environment', data: {}, @@ -30,28 +30,35 @@ export function init () { }; } -export function migrate (doc: Environment): Environment { +export function migrate(doc: Environment): Environment { return doc; } -export function create (patch: Object = {}): Promise { +export function create(patch: Object = {}): Promise { if (!patch.parentId) { - throw new Error(`New Environment missing \`parentId\`: ${JSON.stringify(patch)}`); + throw new Error( + `New Environment missing \`parentId\`: ${JSON.stringify(patch)}` + ); } return db.docCreate(type, patch); } -export function update (environment: Environment, patch: Object): Promise { +export function update( + environment: Environment, + patch: Object +): Promise { return db.docUpdate(environment, patch); } -export function findByParentId (parentId: string): Promise> { - return db.find(type, {parentId}, {metaSortKey: 1}); +export function findByParentId(parentId: string): Promise> { + return db.find(type, { parentId }, { metaSortKey: 1 }); } -export async function getOrCreateForWorkspaceId (workspaceId: string): Promise { - const environments = await db.find(type, {parentId: workspaceId}); +export async function getOrCreateForWorkspaceId( + workspaceId: string +): Promise { + const environments = await db.find(type, { parentId: workspaceId }); if (!environments.length) { return create({ @@ -63,18 +70,20 @@ export async function getOrCreateForWorkspaceId (workspaceId: string): Promise { +export async function getOrCreateForWorkspace( + workspace: Workspace +): Promise { return getOrCreateForWorkspaceId(workspace._id); } -export function getById (id: string): Promise { +export function getById(id: string): Promise { return db.get(type, id); } -export function remove (environment: Environment): Promise { +export function remove(environment: Environment): Promise { return db.remove(environment); } -export function all (): Promise> { +export function all(): Promise> { return db.all(type); } diff --git a/packages/insomnia-app/app/models/index.js b/packages/insomnia-app/app/models/index.js index 12b8dda9bf..a3c30584ef 100644 --- a/packages/insomnia-app/app/models/index.js +++ b/packages/insomnia-app/app/models/index.js @@ -14,7 +14,7 @@ import * as _settings from './settings'; import * as _stats from './stats'; import * as _workspace from './workspace'; import * as _workspaceMeta from './workspace-meta'; -import {generateId} from '../common/misc'; +import { generateId } from '../common/misc'; export type BaseModel = { _id: string, @@ -22,7 +22,7 @@ export type BaseModel = { parentId: string, modified: number, created: number -} +}; // Reference to each model export const clientCertificate = _clientCertificate; @@ -41,7 +41,7 @@ export const stats = _stats; export const workspace = _workspace; export const workspaceMeta = _workspaceMeta; -export function all () { +export function all() { return [ stats, settings, @@ -61,20 +61,20 @@ export function all () { ]; } -export function types () { +export function types() { return all().map(model => model.type); } -export function getModel (type: string): Object | null { +export function getModel(type: string): Object | null { return all().find(m => m.type === type) || null; } -export function canDuplicate (type: string) { +export function canDuplicate(type: string) { const model = getModel(type); return model ? model.canDuplicate : false; } -export function getModelName (type: string, count: number = 1) { +export function getModelName(type: string, count: number = 1) { const model = getModel(type); if (!model) { return 'Unknown'; @@ -88,25 +88,33 @@ export function getModelName (type: string, count: number = 1) { } } -export async function initModel ( +export async function initModel( type: string, ...sources: Array ): Promise { const model = getModel(type); if (!model) { - const choices = all().map(m => m.type).join(', '); - throw new Error(`Tried to init invalid model "${type}". Choices are ${choices}`); + const choices = all() + .map(m => m.type) + .join(', '); + throw new Error( + `Tried to init invalid model "${type}". Choices are ${choices}` + ); } // Define global default fields - const objectDefaults = Object.assign({}, { - _id: null, - type: type, - parentId: null, - modified: Date.now(), - created: Date.now() - }, model.init()); + const objectDefaults = Object.assign( + {}, + { + _id: null, + type: type, + parentId: null, + modified: Date.now(), + created: Date.now() + }, + model.init() + ); const fullObject = Object.assign({}, objectDefaults, ...sources); diff --git a/packages/insomnia-app/app/models/o-auth-2-token.js b/packages/insomnia-app/app/models/o-auth-2-token.js index b76b33574c..86a5e2a5ba 100644 --- a/packages/insomnia-app/app/models/o-auth-2-token.js +++ b/packages/insomnia-app/app/models/o-auth-2-token.js @@ -1,5 +1,5 @@ // @flow -import type {BaseModel} from './index'; +import type { BaseModel } from './index'; import * as db from '../common/database'; @@ -21,7 +21,7 @@ export const type = 'OAuth2Token'; export const prefix = 'oa2'; export const canDuplicate = false; -export function init (): BaseOAuth2Token { +export function init(): BaseOAuth2Token { return { refreshToken: '', accessToken: '', @@ -34,40 +34,47 @@ export function init (): BaseOAuth2Token { }; } -export function migrate (doc: T): T { +export function migrate(doc: T): T { return doc; } -export function create (patch: Object = {}): Promise { +export function create(patch: Object = {}): Promise { if (!patch.parentId) { - throw new Error(`New OAuth2Token missing \`parentId\` ${JSON.stringify(patch)}`); + throw new Error( + `New OAuth2Token missing \`parentId\` ${JSON.stringify(patch)}` + ); } return db.docCreate(type, patch); } -export function update (token: OAuth2Token, patch: Object): Promise { +export function update( + token: OAuth2Token, + patch: Object +): Promise { return db.docUpdate(token, patch); } -export function remove (token: OAuth2Token): Promise { +export function remove(token: OAuth2Token): Promise { return db.remove(token); } -export function getByParentId (parentId: string): Promise { - return db.getWhere(type, {parentId}); +export function getByParentId(parentId: string): Promise { + return db.getWhere(type, { parentId }); } -export async function getOrCreateByParentId (parentId: string): Promise { - let token = await db.getWhere(type, {parentId}); +export async function getOrCreateByParentId( + parentId: string +): Promise { + let token = await db.getWhere(type, { parentId }); if (!token) { - token = await create({parentId}); + token = await create({ parentId }); } return token; } -export function all (): Promise> { +export function all(): Promise> { return db.all(type); } diff --git a/packages/insomnia-app/app/models/plugin-data.js b/packages/insomnia-app/app/models/plugin-data.js index a27a33c5aa..beebb3af95 100644 --- a/packages/insomnia-app/app/models/plugin-data.js +++ b/packages/insomnia-app/app/models/plugin-data.js @@ -1,6 +1,6 @@ // @flow import * as db from '../common/database'; -import type {BaseModel} from './index'; +import type { BaseModel } from './index'; export const name = 'PluginData'; export const type = 'PluginData'; @@ -10,12 +10,12 @@ export const canDuplicate = false; type BasePluginData = { plugin: string, key: string, - value: string, + value: string }; export type PluginData = BaseModel & BasePluginData; -export function init (): BasePluginData { +export function init(): BasePluginData { return { plugin: '', key: '', @@ -23,27 +23,37 @@ export function init (): BasePluginData { }; } -export function migrate (doc: PluginData): PluginData { +export function migrate(doc: PluginData): PluginData { return doc; } -export function create (patch: Object = {}): Promise { +export function create(patch: Object = {}): Promise { return db.docCreate(type, patch); } -export async function update (doc: PluginData, patch: Object): Promise { +export async function update( + doc: PluginData, + patch: Object +): Promise { return db.docUpdate(doc, patch); } -export async function upsertByKey (plugin: string, key: string, value: string): Promise { +export async function upsertByKey( + plugin: string, + key: string, + value: string +): Promise { const doc = await getByKey(plugin, key); - return doc ? update(doc, {value}) : create({plugin, key, value}); + return doc ? update(doc, { value }) : create({ plugin, key, value }); } -export async function removeByKey (plugin: string, key: string): Promise { - return db.removeWhere(type, {plugin, key}); +export async function removeByKey(plugin: string, key: string): Promise { + return db.removeWhere(type, { plugin, key }); } -export async function getByKey (plugin: string, key: string): Promise { - return db.getWhere(type, {plugin, key}); +export async function getByKey( + plugin: string, + key: string +): Promise { + return db.getWhere(type, { plugin, key }); } diff --git a/packages/insomnia-app/app/models/request-group-meta.js b/packages/insomnia-app/app/models/request-group-meta.js index 38d4251d63..08090c8273 100644 --- a/packages/insomnia-app/app/models/request-group-meta.js +++ b/packages/insomnia-app/app/models/request-group-meta.js @@ -5,18 +5,18 @@ export const type = 'RequestGroupMeta'; export const prefix = 'fldm'; export const canDuplicate = false; -export function init () { +export function init() { return { parentId: null, collapsed: false }; } -export function migrate (doc) { +export function migrate(doc) { return doc; } -export function create (patch = {}) { +export function create(patch = {}) { if (!patch.parentId) { throw new Error('New RequestGroupMeta missing `parentId`', patch); } @@ -24,14 +24,14 @@ export function create (patch = {}) { return db.docCreate(type, patch); } -export function update (requestGroupMeta, patch) { +export function update(requestGroupMeta, patch) { return db.docUpdate(requestGroupMeta, patch); } -export function getByParentId (parentId) { - return db.getWhere(type, {parentId}); +export function getByParentId(parentId) { + return db.getWhere(type, { parentId }); } -export function all () { +export function all() { return db.all(type); } diff --git a/packages/insomnia-app/app/models/request-group.js b/packages/insomnia-app/app/models/request-group.js index dba1b8f762..f2730554e9 100644 --- a/packages/insomnia-app/app/models/request-group.js +++ b/packages/insomnia-app/app/models/request-group.js @@ -1,6 +1,6 @@ // @flow import * as db from '../common/database'; -import type {BaseModel} from './index'; +import type { BaseModel } from './index'; export const name = 'Folder'; export const type = 'RequestGroup'; @@ -16,7 +16,7 @@ type BaseRequestGroup = { export type RequestGroup = BaseModel & BaseRequestGroup; -export function init () { +export function init() { return { name: 'New Folder', description: '', @@ -25,44 +25,51 @@ export function init () { }; } -export function migrate (doc: RequestGroup) { +export function migrate(doc: RequestGroup) { return doc; } -export function create (patch: Object = {}): Promise { +export function create(patch: Object = {}): Promise { if (!patch.parentId) { - throw new Error('New RequestGroup missing `parentId`: ' + JSON.stringify(patch)); + throw new Error( + 'New RequestGroup missing `parentId`: ' + JSON.stringify(patch) + ); } return db.docCreate(type, patch); } -export function update (requestGroup: RequestGroup, patch: Object = {}): Promise { +export function update( + requestGroup: RequestGroup, + patch: Object = {} +): Promise { return db.docUpdate(requestGroup, patch); } -export function getById (id: string): Promise { +export function getById(id: string): Promise { return db.get(type, id); } -export function findByParentId (parentId: string): Promise> { - return db.find(type, {parentId}); +export function findByParentId(parentId: string): Promise> { + return db.find(type, { parentId }); } -export function remove (requestGroup: RequestGroup): Promise { +export function remove(requestGroup: RequestGroup): Promise { return db.remove(requestGroup); } -export function all (): Promise> { +export function all(): Promise> { return db.all(type); } -export async function duplicate (requestGroup: RequestGroup): Promise { +export async function duplicate( + requestGroup: RequestGroup +): Promise { const name = `${requestGroup.name} (Copy)`; // Get sort key of next request - const q = {metaSortKey: {$gt: requestGroup.metaSortKey}}; - const [nextRequestGroup] = await db.find(type, q, {metaSortKey: 1}); + const q = { metaSortKey: { $gt: requestGroup.metaSortKey } }; + const [nextRequestGroup] = await db.find(type, q, { metaSortKey: 1 }); const nextSortKey = nextRequestGroup ? nextRequestGroup.metaSortKey : requestGroup.metaSortKey + 100; @@ -71,5 +78,5 @@ export async function duplicate (requestGroup: RequestGroup): Promise | null): RequestBody { +export function newBodyFormUrlEncoded( + parameters: Array | null +): RequestBody { return { mimeType: CONTENT_TYPE_FORM_URLENCODED, params: parameters || [] }; } -export function newBodyFile (path: string): RequestBody { +export function newBodyFile(path: string): RequestBody { return { mimeType: CONTENT_TYPE_FILE, fileName: path }; } -export function newBodyForm (parameters: Array): RequestBody { +export function newBodyForm( + parameters: Array +): RequestBody { return { mimeType: CONTENT_TYPE_FORM_DATA, params: parameters || [] }; } -export function migrate (doc: Request): Request { +export function migrate(doc: Request): Request { doc = migrateBody(doc); doc = migrateWeirdUrls(doc); doc = migrateAuthType(doc); return doc; } -export function create (patch: Object = {}): Promise { +export function create(patch: Object = {}): Promise { if (!patch.parentId) { - throw new Error(`New Requests missing \`parentId\`: ${JSON.stringify(patch)}`); + throw new Error( + `New Requests missing \`parentId\`: ${JSON.stringify(patch)}` + ); } return db.docCreate(type, patch); } -export function getById (id: string): Promise { +export function getById(id: string): Promise { return db.get(type, id); } -export function findByParentId (parentId: string): Promise> { - return db.find(type, {parentId: parentId}); +export function findByParentId(parentId: string): Promise> { + return db.find(type, { parentId: parentId }); } -export function update (request: Request, patch: Object): Promise { +export function update(request: Request, patch: Object): Promise { return db.docUpdate(request, patch); } -export function updateMimeType ( +export function updateMimeType( request: Request, mimeType: string, doCreate: boolean = false, @@ -238,9 +271,8 @@ export function updateMimeType ( const contentTypeHeader = getContentTypeHeader(headers); // GraphQL uses JSON content-type - const contentTypeHeaderValue = mimeType === CONTENT_TYPE_GRAPHQL - ? CONTENT_TYPE_JSON - : mimeType; + const contentTypeHeaderValue = + mimeType === CONTENT_TYPE_GRAPHQL ? CONTENT_TYPE_JSON : mimeType; // GraphQL must be POST if (mimeType === CONTENT_TYPE_GRAPHQL) { @@ -268,7 +300,7 @@ export function updateMimeType ( } else if (mimeType && contentTypeHeader && !leaveContentTypeAlone) { contentTypeHeader.value = contentTypeHeaderValue; } else if (mimeType && !contentTypeHeader) { - headers.push({name: 'Content-Type', value: contentTypeHeaderValue}); + headers.push({ name: 'Content-Type', value: contentTypeHeaderValue }); } // ~~~~~~~~~~~~~~~~~~~~~~~~~~ // @@ -277,9 +309,8 @@ export function updateMimeType ( let body; - const oldBody = Object.keys(savedBody).length === 0 - ? request.body - : savedBody; + const oldBody = + Object.keys(savedBody).length === 0 ? request.body : savedBody; if (mimeType === CONTENT_TYPE_FORM_URLENCODED) { // Urlencoded @@ -314,33 +345,35 @@ export function updateMimeType ( // ~~~~~~~~~~~~~~~~~~~~~~~~ // if (doCreate) { - const newRequest: Request = Object.assign({}, request, {headers, body}); + const newRequest: Request = Object.assign({}, request, { headers, body }); return create(newRequest); } else { - return update(request, {headers, body}); + return update(request, { headers, body }); } } -export async function duplicate (request: Request): Promise { +export async function duplicate(request: Request): Promise { const name = `${request.name} (Copy)`; // Get sort key of next request - const q = {metaSortKey: {$gt: request.metaSortKey}}; - const [nextRequest] = await db.find(type, q, {metaSortKey: 1}); - const nextSortKey = nextRequest ? nextRequest.metaSortKey : request.metaSortKey + 100; + const q = { metaSortKey: { $gt: request.metaSortKey } }; + const [nextRequest] = await db.find(type, q, { metaSortKey: 1 }); + const nextSortKey = nextRequest + ? nextRequest.metaSortKey + : request.metaSortKey + 100; // Calculate new sort key const sortKeyIncrement = (nextSortKey - request.metaSortKey) / 2; const metaSortKey = request.metaSortKey + sortKeyIncrement; - return db.duplicate(request, {name, metaSortKey}); + return db.duplicate(request, { name, metaSortKey }); } -export function remove (request: Request): Promise { +export function remove(request: Request): Promise { return db.remove(request); } -export function all () { +export function all() { return db.all(type); } @@ -353,19 +386,23 @@ export function all () { * @param request * @returns {*} */ -function migrateBody (request: Request): Request { +function migrateBody(request: Request): Request { if (request.body && typeof request.body === 'object') { return request; } // Second, convert all existing urlencoded bodies to new format const contentType = getContentTypeFromHeaders(request.headers) || ''; - const wasFormUrlEncoded = !!contentType.match(/^application\/x-www-form-urlencoded/i); + const wasFormUrlEncoded = !!contentType.match( + /^application\/x-www-form-urlencoded/i + ); if (wasFormUrlEncoded) { // Convert old-style form-encoded request bodies to new style const body = typeof request.body === 'string' ? request.body : ''; - request.body = newBodyFormUrlEncoded(deconstructQueryStringToParams(body, false)); + request.body = newBodyFormUrlEncoded( + deconstructQueryStringToParams(body, false) + ); } else if (!request.body && !contentType) { request.body = {}; } else { @@ -381,7 +418,7 @@ function migrateBody (request: Request): Request { * @param request * @returns {*} */ -function migrateWeirdUrls (request: Request): Request { +function migrateWeirdUrls(request: Request): Request { // Some people seem to have requests with URLs that don't have the indexOf // function. This should clear that up. This can be removed at a later date. @@ -397,7 +434,7 @@ function migrateWeirdUrls (request: Request): Request { * @param request * @returns {*} */ -function migrateAuthType (request: Request): Request { +function migrateAuthType(request: Request): Request { const isAuthSet = request.authentication && request.authentication.username; if (isAuthSet && !request.authentication.type) { diff --git a/packages/insomnia-app/app/models/response.js b/packages/insomnia-app/app/models/response.js index 423f4f52c2..2ef5b41ff1 100644 --- a/packages/insomnia-app/app/models/response.js +++ b/packages/insomnia-app/app/models/response.js @@ -1,7 +1,7 @@ // @flow -import type {BaseModel} from './index'; +import type { BaseModel } from './index'; import * as models from './index'; -import {Readable} from 'stream'; +import { Readable } from 'stream'; import fs from 'fs'; import crypto from 'crypto'; @@ -9,7 +9,7 @@ import path from 'path'; import zlib from 'zlib'; import mkdirp from 'mkdirp'; import * as electron from 'electron'; -import {MAX_RESPONSES} from '../common/constants'; +import { MAX_RESPONSES } from '../common/constants'; import * as db from '../common/database'; export const name = 'Response'; @@ -20,12 +20,12 @@ export const canDuplicate = false; export type ResponseHeader = { name: string, value: string -} +}; export type ResponseTimelineEntry = { name: string, value: string -} +}; type BaseResponse = { statusCode: number, @@ -50,7 +50,7 @@ type BaseResponse = { export type Response = BaseModel & BaseResponse; -export function init (): BaseResponse { +export function init(): BaseResponse { return { statusCode: 0, statusMessage: '', @@ -73,13 +73,13 @@ export function init (): BaseResponse { }; } -export async function migrate (doc: Object) { +export async function migrate(doc: Object) { doc = await migrateBodyToFileSystem(doc); doc = await migrateBodyCompression(doc); return doc; } -export function hookRemove (doc: Response) { +export function hookRemove(doc: Response) { if (!doc.bodyPath) { return; } @@ -87,73 +87,96 @@ export function hookRemove (doc: Response) { fs.unlinkSync(doc.bodyPath); } -export function getById (id: string) { +export function getById(id: string) { return db.get(type, id); } -export function all () { +export function all() { return db.all(type); } -export async function removeForRequest (parentId: string) { - await db.removeWhere(type, {parentId}); +export async function removeForRequest(parentId: string) { + await db.removeWhere(type, { parentId }); } -export function remove (response: Response) { +export function remove(response: Response) { return db.remove(response); } -export async function findRecentForRequest ( +export async function findRecentForRequest( requestId: string, limit: number ): Promise> { - const responses = await db.findMostRecentlyModified(type, {parentId: requestId}, limit); + const responses = await db.findMostRecentlyModified( + type, + { parentId: requestId }, + limit + ); return responses; } -export async function getLatestForRequest (requestId: string): Promise { +export async function getLatestForRequest( + requestId: string +): Promise { const responses = await findRecentForRequest(requestId, 1); const response = (responses[0]: ?Response); return response || null; } -export async function create (patch: Object = {}) { +export async function create(patch: Object = {}) { if (!patch.parentId) { throw new Error('New Response missing `parentId`'); } - const {parentId} = patch; + const { parentId } = patch; // Create request version snapshot const request = await models.request.getById(parentId); - const requestVersion = request ? await models.requestVersion.create(request) : null; + const requestVersion = request + ? await models.requestVersion.create(request) + : null; patch.requestVersionId = requestVersion ? requestVersion._id : null; // Delete all other responses before creating the new one - const allResponses = await db.findMostRecentlyModified(type, {parentId}, MAX_RESPONSES); + const allResponses = await db.findMostRecentlyModified( + type, + { parentId }, + MAX_RESPONSES + ); const recentIds = allResponses.map(r => r._id); - await db.removeWhere(type, {parentId, _id: {$nin: recentIds}}); + await db.removeWhere(type, { parentId, _id: { $nin: recentIds } }); // Actually create the new response return db.docCreate(type, patch); } -export function getLatestByParentId (parentId: string) { - return db.getMostRecentlyModified(type, {parentId}); +export function getLatestByParentId(parentId: string) { + return db.getMostRecentlyModified(type, { parentId }); } -export function getBodyStream ( +export function getBodyStream( response: Object, readFailureValue: ?T ): Readable | null | T { - return getBodyStreamFromPath(response.bodyPath || '', response.bodyCompression, readFailureValue); + return getBodyStreamFromPath( + response.bodyPath || '', + response.bodyCompression, + readFailureValue + ); } -export function getBodyBuffer (response: Object, readFailureValue: ?T): Buffer | T | null { - return getBodyBufferFromPath(response.bodyPath || '', response.bodyCompression, readFailureValue); +export function getBodyBuffer( + response: Object, + readFailureValue: ?T +): Buffer | T | null { + return getBodyBufferFromPath( + response.bodyPath || '', + response.bodyCompression, + readFailureValue + ); } -function getBodyStreamFromPath ( +function getBodyStreamFromPath( bodyPath: string, compression: string | null, readFailureValue: ?T @@ -178,7 +201,7 @@ function getBodyStreamFromPath ( } } -function getBodyBufferFromPath ( +function getBodyBufferFromPath( bodyPath: string, compression: string | null, readFailureValue: ?T @@ -201,16 +224,19 @@ function getBodyBufferFromPath ( } } -async function migrateBodyToFileSystem (doc: Object) { +async function migrateBodyToFileSystem(doc: Object) { if (doc.hasOwnProperty('body') && doc._id && !doc.bodyPath) { const bodyBuffer = Buffer.from(doc.body, doc.encoding || 'utf8'); - const {app} = electron.remote || electron; + const { app } = electron.remote || electron; const root = app.getPath('userData'); const dir = path.join(root, 'responses'); mkdirp.sync(dir); - const hash = crypto.createHash('md5').update(bodyBuffer || '').digest('hex'); + const hash = crypto + .createHash('md5') + .update(bodyBuffer || '') + .digest('hex'); const bodyPath = path.join(dir, `${hash}.zip`); try { @@ -220,13 +246,13 @@ async function migrateBodyToFileSystem (doc: Object) { console.warn('Failed to write response body to file', err.message); } - return db.docUpdate(doc, {bodyPath, bodyCompression: null}); + return db.docUpdate(doc, { bodyPath, bodyCompression: null }); } else { return doc; } } -function migrateBodyCompression (doc: Object) { +function migrateBodyCompression(doc: Object) { if (doc.bodyCompression === '__NEEDS_MIGRATION__') { doc.bodyCompression = 'zip'; } diff --git a/packages/insomnia-app/app/models/settings.js b/packages/insomnia-app/app/models/settings.js index bb4ce43ab9..9eb30af204 100644 --- a/packages/insomnia-app/app/models/settings.js +++ b/packages/insomnia-app/app/models/settings.js @@ -1,7 +1,7 @@ // @flow -import type {BaseModel} from './index'; +import type { BaseModel } from './index'; import * as db from '../common/database'; -import {UPDATE_CHANNEL_STABLE} from '../common/constants'; +import { UPDATE_CHANNEL_STABLE } from '../common/constants'; type BaseSettings = { showPasswords: boolean, @@ -35,7 +35,7 @@ export const type = 'Settings'; export const prefix = 'set'; export const canDuplicate = false; -export function init (): BaseSettings { +export function init(): BaseSettings { return { showPasswords: false, useBulkHeaderEditor: false, @@ -62,11 +62,11 @@ export function init (): BaseSettings { }; } -export function migrate (doc: Settings): Settings { +export function migrate(doc: Settings): Settings { return doc; } -export async function all (patch: Object = {}): Promise> { +export async function all(patch: Object = {}): Promise> { const settings = await db.all(type); if (settings.length === 0) { return [await getOrCreate()]; @@ -75,15 +75,18 @@ export async function all (patch: Object = {}): Promise> { } } -export async function create (patch: Object = {}): Promise { +export async function create(patch: Object = {}): Promise { return db.docCreate(type, patch); } -export async function update (settings: Settings, patch: Object): Promise { +export async function update( + settings: Settings, + patch: Object +): Promise { return db.docUpdate(settings, patch); } -export async function getOrCreate (patch: Object = {}): Promise { +export async function getOrCreate(patch: Object = {}): Promise { const results = await db.all(type); if (results.length === 0) { return create(patch); diff --git a/packages/insomnia-app/app/models/stats.js b/packages/insomnia-app/app/models/stats.js index 4ac40dc931..4bae757208 100644 --- a/packages/insomnia-app/app/models/stats.js +++ b/packages/insomnia-app/app/models/stats.js @@ -1,6 +1,6 @@ // @flow import * as db from '../common/database'; -import type {BaseModel} from './index'; +import type { BaseModel } from './index'; export const name = 'Stats'; export const type = 'Stats'; @@ -17,7 +17,7 @@ type BaseStats = { export type Stats = BaseModel & BaseStats; -export function init (): BaseStats { +export function init(): BaseStats { return { currentLaunch: null, lastLaunch: null, @@ -27,20 +27,20 @@ export function init (): BaseStats { }; } -export function migrate (doc: Stats): Stats { +export function migrate(doc: Stats): Stats { return doc; } -export function create (patch: Object = {}): Promise { +export function create(patch: Object = {}): Promise { return db.docCreate(type, patch); } -export async function update (patch: Object): Promise { +export async function update(patch: Object): Promise { const stats = await get(); return db.docUpdate(stats, patch); } -export async function get (): Promise { +export async function get(): Promise { const results = await db.all(type); if (results.length === 0) { return create(); diff --git a/packages/insomnia-app/app/models/workspace-meta.js b/packages/insomnia-app/app/models/workspace-meta.js index f3fa166967..63fb342913 100644 --- a/packages/insomnia-app/app/models/workspace-meta.js +++ b/packages/insomnia-app/app/models/workspace-meta.js @@ -1,7 +1,11 @@ // @flow -import type {BaseModel} from './index'; +import type { BaseModel } from './index'; import * as db from '../common/database'; -import {DEFAULT_SIDEBAR_WIDTH, DEFAULT_PANE_WIDTH, DEFAULT_PANE_HEIGHT} from '../common/constants'; +import { + DEFAULT_SIDEBAR_WIDTH, + DEFAULT_PANE_WIDTH, + DEFAULT_PANE_HEIGHT +} from '../common/constants'; export const name = 'Workspace Meta'; export const type = 'WorkspaceMeta'; @@ -21,7 +25,7 @@ type BaseWorkspaceMeta = { export type WorkspaceMeta = BaseWorkspaceMeta & BaseModel; -export function init (): BaseWorkspaceMeta { +export function init(): BaseWorkspaceMeta { return { parentId: null, activeRequestId: null, @@ -35,31 +39,40 @@ export function init (): BaseWorkspaceMeta { }; } -export function migrate (doc: WorkspaceMeta): WorkspaceMeta { +export function migrate(doc: WorkspaceMeta): WorkspaceMeta { return doc; } -export function create (patch: Object = {}): Promise { +export function create(patch: Object = {}): Promise { if (!patch.parentId) { - throw new Error(`New WorkspaceMeta missing parentId ${JSON.stringify(patch)}`); + throw new Error( + `New WorkspaceMeta missing parentId ${JSON.stringify(patch)}` + ); } return db.docCreate(type, patch); } -export function update (workspaceMeta: WorkspaceMeta, patch: Object = {}): Promise { +export function update( + workspaceMeta: WorkspaceMeta, + patch: Object = {} +): Promise { return db.docUpdate(workspaceMeta, patch); } -export async function getByParentId (parentId: string): Promise { - return db.getWhere(type, {parentId}); +export async function getByParentId( + parentId: string +): Promise { + return db.getWhere(type, { parentId }); } -export async function getOrCreateByParentId (parentId: string): Promise { +export async function getOrCreateByParentId( + parentId: string +): Promise { const doc = await getByParentId(parentId); - return doc || this.create({parentId}); + return doc || this.create({ parentId }); } -export function all (): Promise> { +export function all(): Promise> { return db.all(type); } diff --git a/packages/insomnia-app/app/models/workspace.js b/packages/insomnia-app/app/models/workspace.js index 5cc44358f4..056036a4db 100644 --- a/packages/insomnia-app/app/models/workspace.js +++ b/packages/insomnia-app/app/models/workspace.js @@ -1,5 +1,5 @@ // @flow -import type {BaseModel} from './index'; +import type { BaseModel } from './index'; import * as db from '../common/database'; import * as models from './index'; @@ -15,49 +15,54 @@ type BaseWorkspace = { export type Workspace = BaseModel & BaseWorkspace; -export function init () { +export function init() { return { name: 'New Workspace', description: '' }; } -export async function migrate (doc: Workspace): Promise { +export async function migrate(doc: Workspace): Promise { return _migrateExtractClientCertificates(doc); } -export function getById (id: string): Promise { +export function getById(id: string): Promise { return db.get(type, id); } -export async function create (patch: Object = {}): Promise { +export async function create(patch: Object = {}): Promise { return db.docCreate(type, patch); } -export async function all (): Promise> { +export async function all(): Promise> { const workspaces = await db.all(type); if (workspaces.length === 0) { - await create({name: 'Insomnia'}); + await create({ name: 'Insomnia' }); return all(); } else { return workspaces; } } -export function count () { +export function count() { return db.count(type); } -export function update (workspace: Workspace, patch: Object): Promise { +export function update( + workspace: Workspace, + patch: Object +): Promise { return db.docUpdate(workspace, patch); } -export function remove (workspace: Workspace): Promise { +export function remove(workspace: Workspace): Promise { return db.remove(workspace); } -async function _migrateExtractClientCertificates (workspace: Workspace): Promise { +async function _migrateExtractClientCertificates( + workspace: Workspace +): Promise { const certificates = (workspace: Object).certificates || null; if (!Array.isArray(certificates)) { // Already migrated diff --git a/packages/insomnia-app/app/network/__tests__/authentication.test.js b/packages/insomnia-app/app/network/__tests__/authentication.test.js index 2f717ad267..d9f2aef3b2 100644 --- a/packages/insomnia-app/app/network/__tests__/authentication.test.js +++ b/packages/insomnia-app/app/network/__tests__/authentication.test.js @@ -1,5 +1,5 @@ -import {getAuthHeader} from '../authentication'; -import {AUTH_OAUTH_1} from '../../common/constants'; +import { getAuthHeader } from '../authentication'; +import { AUTH_OAUTH_1 } from '../../common/constants'; describe('OAuth 1.0', () => { it('Does OAuth 1.0', async () => { @@ -23,8 +23,7 @@ describe('OAuth 1.0', () => { expect(header).toEqual({ name: 'Authorization', value: [ - 'OAuth ' + - 'oauth_callback="https%3A%2F%2Finsomnia.rest%2Fcallback%2F"', + 'OAuth ' + 'oauth_callback="https%3A%2F%2Finsomnia.rest%2Fcallback%2F"', 'oauth_consumer_key="consumerKey"', 'oauth_nonce="nonce"', 'oauth_signature="muJumAG6rOEUuJmhx5zOcBquqk8%3D"', @@ -49,21 +48,22 @@ describe('OAuth 1.0', () => { tokenKey: 'tokenKey', tokenSecret: 'tokenSecret', signatureMethod: 'RSA-SHA1', - privateKey: '-----BEGIN RSA PRIVATE KEY-----\n' + - 'MIICXgIBAAKBgQC6jwJjt/KywX4N4ZA3YOLcNFrS9S2+TcArdMyo89yqLZWzC9x9\n' + - 'MY4gA+1+iOpG+S/jlDM3WuJSCnEzQhzDo9UGtNODC+Qr8nStRcKdjSOhywRXPd4d\n' + - '+u6TOae/Flukwqzl0Pw3fsMWqwp0dni6OIc7E2gm2jj4MTLsd4oq/0igCQIDAQAB\n' + - 'AoGBAJCdHusRwo6SsxYrjdF/xxuPcgApkmX8e0S0a5lkP9+jKnH6ddaOPW/P25/E\n' + - 'nmaZ72dokDMOvnV+JrXnP8jgDNatJsBqS2aLBNpSI4TsOQDfhB3rPoafc5s2bNVY\n' + - '5SRp2kr3QL74BZzLzAsIJzGDpRyKQGRPzMFiPzkQcfJuO7rpAkEA3gZq2v2OUzcV\n' + - 'iQIoCy7bkvxaKZUlkj6xT0msExqrAt9mtVE6XW3GsHUSyB2ePOzDz6zcKeX90nTq\n' + - '79PAGTAm1wJBANcbO+xt9By9Omq8K51RuKkvlESHH8j+meAWW6DoKJvHdy2/+xnA\n' + - 'XEcDcWb9cV9V5FNWmJ+mMF1jfu/GxTMp9B8CQQDazaQ80KiUZbK5ZQCllLYbcspA\n' + - 'NJXkPBhtNQN5iEyD9jm38qb8MBUhDR9HS7kH/aUzYv1N5TRxVXu6ggnMSOHdAkBI\n' + - 'Gojrp6+8MnHydUDpawtLKve4QNMWvME3rEbqmOeD0EjSvReeeix0YWMR8sKeAlyW\n' + - '0uA2I67ynvddyHMxw05hAkEAyXuG1xpqs3VYQeHRC67dQjkKw0YbcOeeWHpo1+cn\n' + - 'F29dI2yG3Ti+28/WlSdfYGe9P9SfeYM7RQbNbUp1MHWrkg==\n' + - '-----END RSA PRIVATE KEY-----', + privateKey: + '-----BEGIN RSA PRIVATE KEY-----\n' + + 'MIICXgIBAAKBgQC6jwJjt/KywX4N4ZA3YOLcNFrS9S2+TcArdMyo89yqLZWzC9x9\n' + + 'MY4gA+1+iOpG+S/jlDM3WuJSCnEzQhzDo9UGtNODC+Qr8nStRcKdjSOhywRXPd4d\n' + + '+u6TOae/Flukwqzl0Pw3fsMWqwp0dni6OIc7E2gm2jj4MTLsd4oq/0igCQIDAQAB\n' + + 'AoGBAJCdHusRwo6SsxYrjdF/xxuPcgApkmX8e0S0a5lkP9+jKnH6ddaOPW/P25/E\n' + + 'nmaZ72dokDMOvnV+JrXnP8jgDNatJsBqS2aLBNpSI4TsOQDfhB3rPoafc5s2bNVY\n' + + '5SRp2kr3QL74BZzLzAsIJzGDpRyKQGRPzMFiPzkQcfJuO7rpAkEA3gZq2v2OUzcV\n' + + 'iQIoCy7bkvxaKZUlkj6xT0msExqrAt9mtVE6XW3GsHUSyB2ePOzDz6zcKeX90nTq\n' + + '79PAGTAm1wJBANcbO+xt9By9Omq8K51RuKkvlESHH8j+meAWW6DoKJvHdy2/+xnA\n' + + 'XEcDcWb9cV9V5FNWmJ+mMF1jfu/GxTMp9B8CQQDazaQ80KiUZbK5ZQCllLYbcspA\n' + + 'NJXkPBhtNQN5iEyD9jm38qb8MBUhDR9HS7kH/aUzYv1N5TRxVXu6ggnMSOHdAkBI\n' + + 'Gojrp6+8MnHydUDpawtLKve4QNMWvME3rEbqmOeD0EjSvReeeix0YWMR8sKeAlyW\n' + + '0uA2I67ynvddyHMxw05hAkEAyXuG1xpqs3VYQeHRC67dQjkKw0YbcOeeWHpo1+cn\n' + + 'F29dI2yG3Ti+28/WlSdfYGe9P9SfeYM7RQbNbUp1MHWrkg==\n' + + '-----END RSA PRIVATE KEY-----', nonce: 'nonce', timestamp: '1234567890' } @@ -72,8 +72,7 @@ describe('OAuth 1.0', () => { expect(header).toEqual({ name: 'Authorization', value: [ - 'OAuth ' + - 'oauth_callback="https%3A%2F%2Finsomnia.rest%2Fcallback%2F"', + 'OAuth ' + 'oauth_callback="https%3A%2F%2Finsomnia.rest%2Fcallback%2F"', 'oauth_consumer_key="consumerKey"', 'oauth_nonce="nonce"', 'oauth_signature="cuJlDLQcyQkIdfs8sIE9Y1769hrPy%2Fkwq8D%2BSQxl5azvk1TimWSgUECf3vJoF7DkgnvcYhFYTnduldj%2FJ9ttaOh8xmfE7krGm8Yh%2FDqYfvLPKnw%2F%2BAaKjd43Y6ulZqptTaf4q5D0%2FM9MhqI8pNRcblk30fI%2FR6JYRyjHVm3YNZo%3D"', @@ -99,14 +98,17 @@ describe('OAuth 1.0', () => { ); expect(header.name).toBe('Authorization'); - expect(header.value).toMatch(new RegExp([ - 'OAuth ' + - 'oauth_consumer_key="consumerKey"', - 'oauth_nonce="[\\w\\d]*"', - 'oauth_signature="[\\w\\d%]*"', - 'oauth_signature_method="HMAC-SHA1"', - 'oauth_timestamp="\\d*"', - 'oauth_version="1\\.0"' - ].join(', '))); + expect(header.value).toMatch( + new RegExp( + [ + 'OAuth ' + 'oauth_consumer_key="consumerKey"', + 'oauth_nonce="[\\w\\d]*"', + 'oauth_signature="[\\w\\d%]*"', + 'oauth_signature_method="HMAC-SHA1"', + 'oauth_timestamp="\\d*"', + 'oauth_version="1\\.0"' + ].join(', ') + ) + ); }); }); diff --git a/packages/insomnia-app/app/network/__tests__/certificate-url-parse.test.js b/packages/insomnia-app/app/network/__tests__/certificate-url-parse.test.js index a29c209ef2..22ccc1eac2 100644 --- a/packages/insomnia-app/app/network/__tests__/certificate-url-parse.test.js +++ b/packages/insomnia-app/app/network/__tests__/certificate-url-parse.test.js @@ -1,11 +1,12 @@ import certificateUrlParse from '../certificate-url-parse'; -import {parse as urlParse} from 'url'; -import {globalBeforeEach} from '../../__jest__/before-each'; +import { parse as urlParse } from 'url'; +import { globalBeforeEach } from '../../__jest__/before-each'; describe('certificateUrlParse', () => { beforeEach(globalBeforeEach); it('should return the result of url.parse if no wildcard paths are supplied', () => { - const url = 'https://www.example.org:80/some/resources?query=1&other=2#myfragment'; + const url = + 'https://www.example.org:80/some/resources?query=1&other=2#myfragment'; const expected = urlParse(url); expect(certificateUrlParse(url)).toEqual(expected); }); diff --git a/packages/insomnia-app/app/network/__tests__/multipart.test.js b/packages/insomnia-app/app/network/__tests__/multipart.test.js index dbebbba1a1..33687cbf51 100644 --- a/packages/insomnia-app/app/network/__tests__/multipart.test.js +++ b/packages/insomnia-app/app/network/__tests__/multipart.test.js @@ -1,83 +1,89 @@ import fs from 'fs'; -import {globalBeforeEach} from '../../__jest__/before-each'; -import {buildMultipart, DEFAULT_BOUNDARY} from '../multipart'; +import { globalBeforeEach } from '../../__jest__/before-each'; +import { buildMultipart, DEFAULT_BOUNDARY } from '../multipart'; import path from 'path'; describe('buildMultipart()', () => { beforeEach(globalBeforeEach); it('builds a simple request', async () => { - const {filePath, boundary, contentLength} = await buildMultipart([ - {name: 'foo', value: 'bar'}, - {name: 'multi-line', value: 'Hello\nWorld!'} + const { filePath, boundary, contentLength } = await buildMultipart([ + { name: 'foo', value: 'bar' }, + { name: 'multi-line', value: 'Hello\nWorld!' } ]); expect(boundary).toBe(DEFAULT_BOUNDARY); expect(contentLength).toBe(189); - expect(fs.readFileSync(filePath, 'utf8')).toBe([ - `--${boundary}`, - 'Content-Disposition: form-data; name="foo"', - '', - 'bar', - `--${boundary}`, - 'Content-Disposition: form-data; name="multi-line"', - '', - 'Hello\nWorld!', - `--${boundary}--`, - '' - ].join('\r\n')); + expect(fs.readFileSync(filePath, 'utf8')).toBe( + [ + `--${boundary}`, + 'Content-Disposition: form-data; name="foo"', + '', + 'bar', + `--${boundary}`, + 'Content-Disposition: form-data; name="multi-line"', + '', + 'Hello\nWorld!', + `--${boundary}--`, + '' + ].join('\r\n') + ); }); it('builds with file', async () => { const fileName = path.resolve(path.join(__dirname, './testfile.txt')); - const {filePath, boundary, contentLength} = await buildMultipart([ - {name: 'foo', value: 'bar'}, - {name: 'file', type: 'file', fileName: fileName}, - {name: 'baz', value: 'qux'} + const { filePath, boundary, contentLength } = await buildMultipart([ + { name: 'foo', value: 'bar' }, + { name: 'file', type: 'file', fileName: fileName }, + { name: 'baz', value: 'qux' } ]); expect(boundary).toBe(DEFAULT_BOUNDARY); expect(contentLength).toBe(322); - expect(fs.readFileSync(filePath, 'utf8')).toBe([ - `--${boundary}`, - 'Content-Disposition: form-data; name="foo"', - '', - 'bar', - `--${boundary}`, - 'Content-Disposition: form-data; name="file"; filename="testfile.txt"', - 'Content-Type: text/plain', - '', - 'Hello World!\n\nHow are you?', - `--${boundary}`, - 'Content-Disposition: form-data; name="baz"', - '', - 'qux', - `--${boundary}--`, - '' - ].join('\r\n')); + expect(fs.readFileSync(filePath, 'utf8')).toBe( + [ + `--${boundary}`, + 'Content-Disposition: form-data; name="foo"', + '', + 'bar', + `--${boundary}`, + 'Content-Disposition: form-data; name="file"; filename="testfile.txt"', + 'Content-Type: text/plain', + '', + 'Hello World!\n\nHow are you?', + `--${boundary}`, + 'Content-Disposition: form-data; name="baz"', + '', + 'qux', + `--${boundary}--`, + '' + ].join('\r\n') + ); }); it('skips entries with no name or value', async () => { - const {filePath, boundary, contentLength} = await buildMultipart([ - {value: 'bar'}, - {name: 'foo'}, - {name: '', value: ''}, - {name: '', type: 'file', fileName: ''} + const { filePath, boundary, contentLength } = await buildMultipart([ + { value: 'bar' }, + { name: 'foo' }, + { name: '', value: '' }, + { name: '', type: 'file', fileName: '' } ]); expect(boundary).toBe(DEFAULT_BOUNDARY); expect(contentLength).toBe(167); - expect(fs.readFileSync(filePath, 'utf8')).toBe([ - `--${boundary}`, - 'Content-Disposition: form-data; name=""', - '', - 'bar', - `--${boundary}`, - 'Content-Disposition: form-data; name="foo"', - '', - '', - `--${boundary}--`, - '' - ].join('\r\n')); + expect(fs.readFileSync(filePath, 'utf8')).toBe( + [ + `--${boundary}`, + 'Content-Disposition: form-data; name=""', + '', + 'bar', + `--${boundary}`, + 'Content-Disposition: form-data; name="foo"', + '', + '', + `--${boundary}--`, + '' + ].join('\r\n') + ); }); }); diff --git a/packages/insomnia-app/app/network/__tests__/network.test.js b/packages/insomnia-app/app/network/__tests__/network.test.js index 725206ab0a..7252ffe115 100644 --- a/packages/insomnia-app/app/network/__tests__/network.test.js +++ b/packages/insomnia-app/app/network/__tests__/network.test.js @@ -1,7 +1,7 @@ import * as networkUtils from '../network'; import fs from 'fs'; -import {join as pathJoin, resolve as pathResolve} from 'path'; -import {getRenderedRequest} from '../../common/render'; +import { join as pathJoin, resolve as pathResolve } from 'path'; +import { getRenderedRequest } from '../../common/render'; import * as models from '../../models'; import { AUTH_AWS_IAM, @@ -12,9 +12,9 @@ import { CONTENT_TYPE_FORM_URLENCODED, getAppVersion } from '../../common/constants'; -import {filterHeaders} from '../../common/misc'; -import {globalBeforeEach} from '../../__jest__/before-each'; -import {DEFAULT_BOUNDARY} from '../multipart'; +import { filterHeaders } from '../../common/misc'; +import { globalBeforeEach } from '../../__jest__/before-each'; +import { DEFAULT_BOUNDARY } from '../multipart'; const CONTEXT = {}; @@ -23,27 +23,32 @@ describe('actuallySend()', () => { it('sends a generic request', async () => { const workspace = await models.workspace.create(); const settings = await models.settings.create(); - const cookies = [{ - creation: new Date('2016-10-05T04:40:49.505Z'), - key: 'foo', - value: 'barrrrr', - expires: new Date('2096-10-12T04:40:49.000Z'), - domain: 'notlocalhost', - path: '/', - hostOnly: true, - lastAccessed: new Date('2096-10-05T04:40:49.505Z') - }, { - creation: new Date('2016-10-05T04:40:49.505Z'), - key: 'foo', - value: 'bar', - expires: new Date('2096-10-12T04:40:49.000Z'), - domain: 'localhost', - path: '/', - hostOnly: true, - lastAccessed: new Date('2096-10-05T04:40:49.505Z') - }]; + const cookies = [ + { + creation: new Date('2016-10-05T04:40:49.505Z'), + key: 'foo', + value: 'barrrrr', + expires: new Date('2096-10-12T04:40:49.000Z'), + domain: 'notlocalhost', + path: '/', + hostOnly: true, + lastAccessed: new Date('2096-10-05T04:40:49.505Z') + }, + { + creation: new Date('2016-10-05T04:40:49.505Z'), + key: 'foo', + value: 'bar', + expires: new Date('2096-10-12T04:40:49.000Z'), + domain: 'localhost', + path: '/', + hostOnly: true, + lastAccessed: new Date('2096-10-05T04:40:49.505Z') + } + ]; - const cookieJar = await models.cookieJar.getOrCreateForParentId(workspace._id); + const cookieJar = await models.cookieJar.getOrCreateForParentId( + workspace._id + ); await models.cookieJar.update(cookieJar, { parentId: workspace._id, cookies @@ -52,12 +57,15 @@ describe('actuallySend()', () => { const request = Object.assign(models.request.init(), { _id: 'req_123', parentId: workspace._id, - headers: [{name: 'Content-Type', value: 'application/json'}, {name: 'Empty', value: ''}], - parameters: [{name: 'foo bar', value: 'hello&world'}], + headers: [ + { name: 'Content-Type', value: 'application/json' }, + { name: 'Empty', value: '' } + ], + parameters: [{ name: 'foo bar', value: 'hello&world' }], method: 'POST', body: { mimeType: CONTENT_TYPE_FORM_URLENCODED, - params: [{name: 'foo', value: 'bar'}] + params: [{ name: 'foo', value: 'bar' }] }, url: 'http://localhost', authentication: { @@ -119,14 +127,14 @@ describe('actuallySend()', () => { const request = Object.assign(models.request.init(), { _id: 'req_123', parentId: workspace._id, - headers: [{name: 'Content-Type', value: CONTENT_TYPE_FORM_URLENCODED}], + headers: [{ name: 'Content-Type', value: CONTENT_TYPE_FORM_URLENCODED }], method: 'POST', body: { mimeType: CONTENT_TYPE_FORM_URLENCODED, params: [ - {name: 'foo', value: 'bar'}, - {name: 'bar', value: ''}, - {name: '', value: 'value'} + { name: 'foo', value: 'bar' }, + { name: 'bar', value: '' }, + { name: '', value: 'value' } ] }, url: 'http://localhost' @@ -174,25 +182,28 @@ describe('actuallySend()', () => { it('skips sending and storing cookies with setting', async () => { const workspace = await models.workspace.create(); const settings = await models.settings.create(); - const cookies = [{ - creation: new Date('2016-10-05T04:40:49.505Z'), - key: 'foo', - value: 'barrrrr', - expires: new Date('2096-10-12T04:40:49.000Z'), - domain: 'notlocalhost', - path: '/', - hostOnly: true, - lastAccessed: new Date('2096-10-05T04:40:49.505Z') - }, { - creation: new Date('2016-10-05T04:40:49.505Z'), - key: 'foo', - value: 'barrrrr', - expires: new Date('2096-10-12T04:40:49.000Z'), - domain: 'localhost', - path: '/', - hostOnly: true, - lastAccessed: new Date('2096-10-05T04:40:49.505Z') - }]; + const cookies = [ + { + creation: new Date('2016-10-05T04:40:49.505Z'), + key: 'foo', + value: 'barrrrr', + expires: new Date('2096-10-12T04:40:49.000Z'), + domain: 'notlocalhost', + path: '/', + hostOnly: true, + lastAccessed: new Date('2096-10-05T04:40:49.505Z') + }, + { + creation: new Date('2016-10-05T04:40:49.505Z'), + key: 'foo', + value: 'barrrrr', + expires: new Date('2096-10-12T04:40:49.000Z'), + domain: 'localhost', + path: '/', + hostOnly: true, + lastAccessed: new Date('2096-10-05T04:40:49.505Z') + } + ]; await models.cookieJar.create({ parentId: workspace._id, @@ -202,12 +213,12 @@ describe('actuallySend()', () => { const request = Object.assign(models.request.init(), { _id: 'req_123', parentId: workspace._id, - headers: [{name: 'Content-Type', value: 'application/json'}], - parameters: [{name: 'foo bar', value: 'hello&world'}], + headers: [{ name: 'Content-Type', value: 'application/json' }], + parameters: [{ name: 'foo bar', value: 'hello&world' }], method: 'GET', body: { mimeType: CONTENT_TYPE_FORM_URLENCODED, - params: [{name: 'foo', value: 'bar'}] + params: [{ name: 'foo', value: 'bar' }] }, url: 'http://localhost', authentication: { @@ -262,16 +273,16 @@ describe('actuallySend()', () => { it('sends a file', async () => { const workspace = await models.workspace.create(); const settings = await models.settings.create(); - await models.cookieJar.create({parentId: workspace._id}); + await models.cookieJar.create({ parentId: workspace._id }); const fileName = pathResolve(pathJoin(__dirname, './testfile.txt')); const request = Object.assign(models.request.init(), { _id: 'req_123', parentId: workspace._id, - headers: [{name: 'Content-Type', value: 'application/octet-stream'}], + headers: [{ name: 'Content-Type', value: 'application/octet-stream' }], url: 'http://localhost', method: 'POST', - body: {mimeType: CONTENT_TYPE_FILE, fileName} + body: { mimeType: CONTENT_TYPE_FILE, fileName } }); const renderedRequest = await getRenderedRequest(request); @@ -320,24 +331,24 @@ describe('actuallySend()', () => { it('sends multipart form data', async () => { const workspace = await models.workspace.create(); const settings = await models.settings.create(); - await models.cookieJar.create({parentId: workspace._id}); + await models.cookieJar.create({ parentId: workspace._id }); const fileName = pathResolve(pathJoin(__dirname, './testfile.txt')); const request = Object.assign(models.request.init(), { _id: 'req_123', parentId: workspace._id, - headers: [{name: 'Content-Type', value: 'multipart/form-data'}], + headers: [{ name: 'Content-Type', value: 'multipart/form-data' }], url: 'http://localhost', method: 'POST', body: { mimeType: CONTENT_TYPE_FORM_DATA, params: [ // Should ignore value and send the file since type is set to file - {name: 'foo', fileName: fileName, value: 'bar', type: 'file'}, + { name: 'foo', fileName: fileName, value: 'bar', type: 'file' }, // Some extra params - {name: 'a', value: 'AA'}, - {name: 'baz', value: 'qux', disabled: true} + { name: 'a', value: 'AA' }, + { name: 'baz', value: 'qux', disabled: true } ] } }); @@ -427,11 +438,7 @@ describe('actuallySend()', () => { ACCEPT_ENCODING: '', COOKIEFILE: '', FOLLOWLOCATION: true, - HTTPHEADER: [ - 'Accept: */*', - 'Accept-Encoding:', - 'content-type:' - ], + HTTPHEADER: ['Accept: */*', 'Accept-Encoding:', 'content-type:'], NOPROGRESS: false, PROXY: '', TIMEOUT_MS: 0, @@ -475,11 +482,7 @@ describe('actuallySend()', () => { ACCEPT_ENCODING: '', COOKIEFILE: '', FOLLOWLOCATION: true, - HTTPHEADER: [ - 'Accept: */*', - 'Accept-Encoding:', - 'content-type:' - ], + HTTPHEADER: ['Accept: */*', 'Accept-Encoding:', 'content-type:'], NOPROGRESS: false, PROXY: '', TIMEOUT_MS: 0, @@ -522,11 +525,7 @@ describe('actuallySend()', () => { ACCEPT_ENCODING: '', COOKIEFILE: '', FOLLOWLOCATION: true, - HTTPHEADER: [ - 'Accept: */*', - 'Accept-Encoding:', - 'content-type:' - ], + HTTPHEADER: ['Accept: */*', 'Accept-Encoding:', 'content-type:'], NOPROGRESS: false, PROXY: '', TIMEOUT_MS: 0, @@ -570,11 +569,7 @@ describe('actuallySend()', () => { ACCEPT_ENCODING: '', COOKIEFILE: '', FOLLOWLOCATION: true, - HTTPHEADER: [ - 'Accept: */*', - 'Accept-Encoding:', - 'content-type:' - ], + HTTPHEADER: ['Accept: */*', 'Accept-Encoding:', 'content-type:'], NOPROGRESS: false, PROXY: '', TIMEOUT_MS: 0, @@ -597,8 +592,8 @@ describe('_getAwsAuthHeaders', () => { secretAccessKey: 'SAK9999999999999', sessionToken: 'ST9999999999999999' }, - headers: [{name: 'content-type', value: 'application/json'}], - body: {text: '{}'}, + headers: [{ name: 'content-type', value: 'application/json' }], + body: { text: '{}' }, method: 'POST', url: 'https://ec2.us-west-2.amazonaws.com/path?query=q1' }; @@ -614,13 +609,16 @@ describe('_getAwsAuthHeaders', () => { req.url, req.method ); - expect(filterHeaders(headers, 'x-amz-date')[0].value) - .toMatch(/^\d{8}T\d{6}Z$/); - expect(filterHeaders(headers, 'host')[0].value).toEqual('ec2.us-west-2.amazonaws.com'); - expect(filterHeaders(headers, 'authorization')[0].value) - .toMatch(/^AWS4-HMAC-SHA256 Credential=AKIA99999999\/\d{8}\/us-west-2\/ec2\/aws4_request, SignedHeaders=content-length;content-type;host;x-amz-date;x-amz-security-token, Signature=[a-z0-9]*$/); - expect(filterHeaders(headers, 'content-type')) - .toHaveLength(0); + expect(filterHeaders(headers, 'x-amz-date')[0].value).toMatch( + /^\d{8}T\d{6}Z$/ + ); + expect(filterHeaders(headers, 'host')[0].value).toEqual( + 'ec2.us-west-2.amazonaws.com' + ); + expect(filterHeaders(headers, 'authorization')[0].value).toMatch( + /^AWS4-HMAC-SHA256 Credential=AKIA99999999\/\d{8}\/us-west-2\/ec2\/aws4_request, SignedHeaders=content-length;content-type;host;x-amz-date;x-amz-security-token, Signature=[a-z0-9]*$/ + ); + expect(filterHeaders(headers, 'content-type')).toHaveLength(0); }); it('should handle sparse request', () => { @@ -631,10 +629,7 @@ describe('_getAwsAuthHeaders', () => { secretAccessKey: 'SAK9999999999999', sessionToken: 'ST99999999999999' }, - headers: [ - 'Accept: */*', - 'Accept-Encoding:' - ], + headers: ['Accept: */*', 'Accept-Encoding:'], url: 'https://example.com', method: 'GET' }; @@ -653,13 +648,14 @@ describe('_getAwsAuthHeaders', () => { 'ec2' ); - expect(filterHeaders(headers, 'x-amz-date')[0].value) - .toMatch(/^\d{8}T\d{6}Z$/); + expect(filterHeaders(headers, 'x-amz-date')[0].value).toMatch( + /^\d{8}T\d{6}Z$/ + ); expect(filterHeaders(headers, 'host')[0].value).toEqual('example.com'); - expect(filterHeaders(headers, 'authorization')[0].value) - .toMatch(/^AWS4-HMAC-SHA256 Credential=AKIA99999999\/\d{8}\/us-west-2\/ec2\/aws4_request, SignedHeaders=content-type;host;x-amz-date;x-amz-security-token, Signature=[a-z0-9]*$/); - expect(filterHeaders(headers, 'content-type')) - .toHaveLength(0); + expect(filterHeaders(headers, 'authorization')[0].value).toMatch( + /^AWS4-HMAC-SHA256 Credential=AKIA99999999\/\d{8}\/us-west-2\/ec2\/aws4_request, SignedHeaders=content-type;host;x-amz-date;x-amz-security-token, Signature=[a-z0-9]*$/ + ); + expect(filterHeaders(headers, 'content-type')).toHaveLength(0); }); }); @@ -678,48 +674,49 @@ describe('_parseHeaders', () => { '' ]; - const minimalHeaders = [ - 'HTTP/1.1 301', - '' - ]; + const minimalHeaders = ['HTTP/1.1 301', '']; it('Parses single response headers', () => { - expect(networkUtils._parseHeaders(Buffer.from(basicHeaders.join('\n')))).toEqual([ + expect( + networkUtils._parseHeaders(Buffer.from(basicHeaders.join('\n'))) + ).toEqual([ { code: 301, version: 'HTTP/1.1', reason: 'Moved Permanently', headers: [ - {name: 'X-Powered-By', value: 'Express'}, - {name: 'location', value: 'http://localhost:3000/'}, - {name: 'Content-Type', value: 'text/plain; charset=utf-8'}, - {name: 'Content-Length', value: '17'}, - {name: 'ETag', value: 'W/"11-WKzg6oYof0o8Mliwrz5pkw"'}, - {name: 'Duplicate', value: 'foo'}, - {name: 'Duplicate', value: 'bar'}, - {name: 'Date', value: 'Mon, 13 Nov 2017 22:06:28 GMT'}, - {name: 'Foo', value: ''} + { name: 'X-Powered-By', value: 'Express' }, + { name: 'location', value: 'http://localhost:3000/' }, + { name: 'Content-Type', value: 'text/plain; charset=utf-8' }, + { name: 'Content-Length', value: '17' }, + { name: 'ETag', value: 'W/"11-WKzg6oYof0o8Mliwrz5pkw"' }, + { name: 'Duplicate', value: 'foo' }, + { name: 'Duplicate', value: 'bar' }, + { name: 'Date', value: 'Mon, 13 Nov 2017 22:06:28 GMT' }, + { name: 'Foo', value: '' } ] } ]); }); it('Parses Windows newlines', () => { - expect(networkUtils._parseHeaders(Buffer.from(basicHeaders.join('\r\n')))).toEqual([ + expect( + networkUtils._parseHeaders(Buffer.from(basicHeaders.join('\r\n'))) + ).toEqual([ { code: 301, version: 'HTTP/1.1', reason: 'Moved Permanently', headers: [ - {name: 'X-Powered-By', value: 'Express'}, - {name: 'location', value: 'http://localhost:3000/'}, - {name: 'Content-Type', value: 'text/plain; charset=utf-8'}, - {name: 'Content-Length', value: '17'}, - {name: 'ETag', value: 'W/"11-WKzg6oYof0o8Mliwrz5pkw"'}, - {name: 'Duplicate', value: 'foo'}, - {name: 'Duplicate', value: 'bar'}, - {name: 'Date', value: 'Mon, 13 Nov 2017 22:06:28 GMT'}, - {name: 'Foo', value: ''} + { name: 'X-Powered-By', value: 'Express' }, + { name: 'location', value: 'http://localhost:3000/' }, + { name: 'Content-Type', value: 'text/plain; charset=utf-8' }, + { name: 'Content-Length', value: '17' }, + { name: 'ETag', value: 'W/"11-WKzg6oYof0o8Mliwrz5pkw"' }, + { name: 'Duplicate', value: 'foo' }, + { name: 'Duplicate', value: 'bar' }, + { name: 'Date', value: 'Mon, 13 Nov 2017 22:06:28 GMT' }, + { name: 'Foo', value: '' } ] } ]); @@ -733,15 +730,15 @@ describe('_parseHeaders', () => { version: 'HTTP/1.1', reason: 'Moved Permanently', headers: [ - {name: 'X-Powered-By', value: 'Express'}, - {name: 'location', value: 'http://localhost:3000/'}, - {name: 'Content-Type', value: 'text/plain; charset=utf-8'}, - {name: 'Content-Length', value: '17'}, - {name: 'ETag', value: 'W/"11-WKzg6oYof0o8Mliwrz5pkw"'}, - {name: 'Duplicate', value: 'foo'}, - {name: 'Duplicate', value: 'bar'}, - {name: 'Date', value: 'Mon, 13 Nov 2017 22:06:28 GMT'}, - {name: 'Foo', value: ''} + { name: 'X-Powered-By', value: 'Express' }, + { name: 'location', value: 'http://localhost:3000/' }, + { name: 'Content-Type', value: 'text/plain; charset=utf-8' }, + { name: 'Content-Length', value: '17' }, + { name: 'ETag', value: 'W/"11-WKzg6oYof0o8Mliwrz5pkw"' }, + { name: 'Duplicate', value: 'foo' }, + { name: 'Duplicate', value: 'bar' }, + { name: 'Date', value: 'Mon, 13 Nov 2017 22:06:28 GMT' }, + { name: 'Foo', value: '' } ] }, { diff --git a/packages/insomnia-app/app/network/__tests__/url-matches-cert-host.test.js b/packages/insomnia-app/app/network/__tests__/url-matches-cert-host.test.js index 5ba800ce0c..6a2e43c566 100644 --- a/packages/insomnia-app/app/network/__tests__/url-matches-cert-host.test.js +++ b/packages/insomnia-app/app/network/__tests__/url-matches-cert-host.test.js @@ -1,5 +1,5 @@ -import {urlMatchesCertHost} from '../url-matches-cert-host'; -import {globalBeforeEach} from '../../__jest__/before-each'; +import { urlMatchesCertHost } from '../url-matches-cert-host'; +import { globalBeforeEach } from '../../__jest__/before-each'; describe('urlMatchesCertHost', () => { beforeEach(globalBeforeEach); diff --git a/packages/insomnia-app/app/network/authentication.js b/packages/insomnia-app/app/network/authentication.js index d7ef30bec9..3ca7c70720 100644 --- a/packages/insomnia-app/app/network/authentication.js +++ b/packages/insomnia-app/app/network/authentication.js @@ -1,19 +1,26 @@ // @flow -import {AUTH_ASAP, AUTH_BASIC, AUTH_BEARER, AUTH_HAWK, AUTH_OAUTH_1, AUTH_OAUTH_2} from '../common/constants'; +import { + AUTH_ASAP, + AUTH_BASIC, + AUTH_BEARER, + AUTH_HAWK, + AUTH_OAUTH_1, + AUTH_OAUTH_2 +} from '../common/constants'; import getOAuth2Token from './o-auth-2/get-token'; import getOAuth1Token from './o-auth-1/get-token'; import * as Hawk from 'hawk'; import jwtAuthentication from 'jwt-authentication'; -import type {RequestAuthentication} from '../models/request'; -import {getBasicAuthHeader} from './basic-auth/get-header'; -import {getBearerAuthHeader} from './bearer-auth/get-header'; +import type { RequestAuthentication } from '../models/request'; +import { getBasicAuthHeader } from './basic-auth/get-header'; +import { getBearerAuthHeader } from './bearer-auth/get-header'; type Header = { name: string, value: string }; -export async function getAuthHeader ( +export async function getAuthHeader( requestId: string, url: string, method: string, @@ -24,12 +31,12 @@ export async function getAuthHeader ( } if (authentication.type === AUTH_BASIC) { - const {username, password} = authentication; + const { username, password } = authentication; return getBasicAuthHeader(username, password); } if (authentication.type === AUTH_BEARER) { - const {token, prefix} = authentication; + const { token, prefix } = authentication; return getBearerAuthHeader(token, prefix); } @@ -64,8 +71,10 @@ export async function getAuthHeader ( } if (authentication.type === AUTH_HAWK) { - const {id, key, algorithm} = authentication; - const header = Hawk.client.header(url, method, {credentials: {id, key, algorithm}}); + const { id, key, algorithm } = authentication; + const header = Hawk.client.header(url, method, { + credentials: { id, key, algorithm } + }); return { name: 'Authorization', value: header.field @@ -73,10 +82,17 @@ export async function getAuthHeader ( } if (authentication.type === AUTH_ASAP) { - const {issuer, subject, audience, keyId, additionalClaims, privateKey} = authentication; + const { + issuer, + subject, + audience, + keyId, + additionalClaims, + privateKey + } = authentication; const generator = jwtAuthentication.client.create(); - let claims = {iss: issuer, sub: subject, aud: audience}; + let claims = { iss: issuer, sub: subject, aud: audience }; let parsedAdditionalClaims; @@ -88,7 +104,9 @@ export async function getAuthHeader ( if (parsedAdditionalClaims) { if (typeof parsedAdditionalClaims !== 'object') { - throw new Error(`additional-claims must be an object received: '${typeof parsedAdditionalClaims}' instead`); + throw new Error( + `additional-claims must be an object received: '${typeof parsedAdditionalClaims}' instead` + ); } claims = Object.assign(parsedAdditionalClaims, claims); @@ -100,23 +118,27 @@ export async function getAuthHeader ( }; return new Promise((resolve, reject) => { - generator.generateAuthorizationHeader(claims, options, (error, headerValue) => { - if (error) { - reject(error); - } else { - resolve({ - name: 'Authorization', - value: headerValue - }); + generator.generateAuthorizationHeader( + claims, + options, + (error, headerValue) => { + if (error) { + reject(error); + } else { + resolve({ + name: 'Authorization', + value: headerValue + }); + } } - }); + ); }); } return null; } -function _buildBearerHeader (accessToken, prefix) { +function _buildBearerHeader(accessToken, prefix) { if (!accessToken) { return null; } @@ -124,5 +146,5 @@ function _buildBearerHeader (accessToken, prefix) { const name = 'Authorization'; const value = `${prefix || 'Bearer'} ${accessToken}`; - return {name, value}; + return { name, value }; } diff --git a/packages/insomnia-app/app/network/basic-auth/__tests__/get-header.test.js b/packages/insomnia-app/app/network/basic-auth/__tests__/get-header.test.js index eee7c99714..c723009329 100644 --- a/packages/insomnia-app/app/network/basic-auth/__tests__/get-header.test.js +++ b/packages/insomnia-app/app/network/basic-auth/__tests__/get-header.test.js @@ -1,5 +1,5 @@ -import {globalBeforeEach} from '../../../__jest__/before-each'; -import {getBasicAuthHeader} from '../get-header'; +import { globalBeforeEach } from '../../../__jest__/before-each'; +import { getBasicAuthHeader } from '../get-header'; describe('getBasicAuthHeader()', () => { beforeEach(globalBeforeEach); diff --git a/packages/insomnia-app/app/network/basic-auth/get-header.js b/packages/insomnia-app/app/network/basic-auth/get-header.js index 7e9b8ded93..e3144b69d2 100644 --- a/packages/insomnia-app/app/network/basic-auth/get-header.js +++ b/packages/insomnia-app/app/network/basic-auth/get-header.js @@ -1,11 +1,14 @@ // @flow -import type {RequestHeader} from '../../models/request'; +import type { RequestHeader } from '../../models/request'; -export function getBasicAuthHeader (username: ?string, password: ?string): RequestHeader { +export function getBasicAuthHeader( + username: ?string, + password: ?string +): RequestHeader { const name = 'Authorization'; const header = `${username || ''}:${password || ''}`; const authString = Buffer.from(header, 'utf8').toString('base64'); const value = `Basic ${authString}`; - return {name, value}; + return { name, value }; } diff --git a/packages/insomnia-app/app/network/bearer-auth/get-header.js b/packages/insomnia-app/app/network/bearer-auth/get-header.js index 4d3cec3613..bc177869d3 100644 --- a/packages/insomnia-app/app/network/bearer-auth/get-header.js +++ b/packages/insomnia-app/app/network/bearer-auth/get-header.js @@ -1,8 +1,11 @@ // @flow -import type {RequestHeader} from '../../models/request'; +import type { RequestHeader } from '../../models/request'; -export function getBearerAuthHeader (token: string, prefix: string): RequestHeader { +export function getBearerAuthHeader( + token: string, + prefix: string +): RequestHeader { const name = 'Authorization'; const value = `${prefix || 'Bearer'} ${token}`; - return {name, value}; + return { name, value }; } diff --git a/packages/insomnia-app/app/network/certificate-url-parse.js b/packages/insomnia-app/app/network/certificate-url-parse.js index 5bd9ca5918..dafb49a1c5 100644 --- a/packages/insomnia-app/app/network/certificate-url-parse.js +++ b/packages/insomnia-app/app/network/certificate-url-parse.js @@ -1,10 +1,15 @@ -import {parse as urlParse} from 'url'; +import { parse as urlParse } from 'url'; const WILDCARD_CHARACTER = '*'; -const WILDCARD_SUBSTITUTION = Math.random().toString().split('.')[1]; -const WILDCARD_SUBSTITUTION_PATTERN = new RegExp(`${WILDCARD_SUBSTITUTION}`, 'g'); +const WILDCARD_SUBSTITUTION = Math.random() + .toString() + .split('.')[1]; +const WILDCARD_SUBSTITUTION_PATTERN = new RegExp( + `${WILDCARD_SUBSTITUTION}`, + 'g' +); -export default function certificateUrlParse (url) { +export default function certificateUrlParse(url) { if (url.indexOf(WILDCARD_CHARACTER) === -1) { return urlParse(url); } else { @@ -18,7 +23,7 @@ export default function certificateUrlParse (url) { } } -function _reinstateWildcards (string) { +function _reinstateWildcards(string) { if (string) { return string.replace(WILDCARD_SUBSTITUTION_PATTERN, WILDCARD_CHARACTER); } else { diff --git a/packages/insomnia-app/app/network/multipart.js b/packages/insomnia-app/app/network/multipart.js index 7ebe8bdaf0..699a079e1b 100644 --- a/packages/insomnia-app/app/network/multipart.js +++ b/packages/insomnia-app/app/network/multipart.js @@ -3,18 +3,21 @@ import * as electron from 'electron'; import mimes from 'mime-types'; import fs from 'fs'; import path from 'path'; -import type {RequestBodyParameter} from '../models/request'; +import type { RequestBodyParameter } from '../models/request'; export const DEFAULT_BOUNDARY = 'X-INSOMNIA-BOUNDARY'; -export async function buildMultipart (params: Array) { +export async function buildMultipart(params: Array) { return new Promise(async (resolve: Function, reject: Function) => { - const filePath = path.join(electron.remote.app.getPath('temp'), Math.random() + '.body'); + const filePath = path.join( + electron.remote.app.getPath('temp'), + Math.random() + '.body' + ); const writeStream = fs.createWriteStream(filePath); const lineBreak = '\r\n'; let totalSize = 0; - function addFile (path: string): Promise { + function addFile(path: string): Promise { return new Promise((resolve, reject) => { let size; try { @@ -26,7 +29,10 @@ export async function buildMultipart (params: Array) { stream.once('end', () => { resolve(); }); - stream.pipe(writeStream, {end: false}); + stream.pipe( + writeStream, + { end: false } + ); totalSize += size; }); } @@ -51,11 +57,12 @@ export async function buildMultipart (params: Array) { if (param.type === 'file' && param.fileName) { const name = param.name || ''; const fileName = param.fileName; - const contentType = mimes.lookup(fileName) || 'application/octet-stream'; + const contentType = + mimes.lookup(fileName) || 'application/octet-stream'; addString( 'Content-Disposition: form-data; ' + - `name="${name.replace(/"/g, '\\"')}"; ` + - `filename="${path.basename(fileName).replace(/"/g, '\\"')}"` + `name="${name.replace(/"/g, '\\"')}"; ` + + `filename="${path.basename(fileName).replace(/"/g, '\\"')}"` ); addString(lineBreak); addString(`Content-Type: ${contentType}`); @@ -86,7 +93,11 @@ export async function buildMultipart (params: Array) { }); writeStream.on('close', () => { - resolve({boundary: DEFAULT_BOUNDARY, filePath, contentLength: totalSize}); + resolve({ + boundary: DEFAULT_BOUNDARY, + filePath, + contentLength: totalSize + }); }); // We're done here. End the stream and tell FS to save/close the file. diff --git a/packages/insomnia-app/app/network/network.js b/packages/insomnia-app/app/network/network.js index c1c7413350..98899d7c6c 100644 --- a/packages/insomnia-app/app/network/network.js +++ b/packages/insomnia-app/app/network/network.js @@ -1,15 +1,18 @@ // @flow -import type {ResponseHeader, ResponseTimelineEntry} from '../models/response'; -import type {Request, RequestHeader} from '../models/request'; -import type {Workspace} from '../models/workspace'; -import type {Settings} from '../models/settings'; -import type {RenderedRequest} from '../common/render'; -import {getRenderedRequestAndContext, RENDER_PURPOSE_SEND} from '../common/render'; +import type { ResponseHeader, ResponseTimelineEntry } from '../models/response'; +import type { Request, RequestHeader } from '../models/request'; +import type { Workspace } from '../models/workspace'; +import type { Settings } from '../models/settings'; +import type { RenderedRequest } from '../common/render'; +import { + getRenderedRequestAndContext, + RENDER_PURPOSE_SEND +} from '../common/render'; import mkdirp from 'mkdirp'; import clone from 'clone'; -import {parse as urlParse, resolve as urlResolve} from 'url'; -import {Curl} from 'insomnia-libcurl'; -import {join as pathJoin} from 'path'; +import { parse as urlParse, resolve as urlResolve } from 'url'; +import { Curl } from 'insomnia-libcurl'; +import { join as pathJoin } from 'path'; import uuid from 'uuid'; import * as electron from 'electron'; import * as models from '../models'; @@ -39,19 +42,24 @@ import { hasUserAgentHeader, waitForStreamToFinish } from '../common/misc'; -import {buildQueryStringFromParams, joinUrlAndQueryString, setDefaultProtocol, smartEncodeUrl} from 'insomnia-url'; +import { + buildQueryStringFromParams, + joinUrlAndQueryString, + setDefaultProtocol, + smartEncodeUrl +} from 'insomnia-url'; import fs from 'fs'; import * as db from '../common/database'; import * as CACerts from './cacert'; import * as plugins from '../plugins/index'; import * as pluginContexts from '../plugins/context/index'; -import {getAuthHeader} from './authentication'; -import {cookiesFromJar, jarFromCookies} from 'insomnia-cookies'; -import {urlMatchesCertHost} from './url-matches-cert-host'; +import { getAuthHeader } from './authentication'; +import { cookiesFromJar, jarFromCookies } from 'insomnia-cookies'; +import { urlMatchesCertHost } from './url-matches-cert-host'; import aws4 from 'aws4'; -import {buildMultipart} from './multipart'; +import { buildMultipart } from './multipart'; -const {app} = electron.remote || electron; +const { app } = electron.remote || electron; export type ResponsePatch = { statusMessage?: string, @@ -82,13 +90,13 @@ const DISABLE_HEADER_VALUE = '__Di$aB13d__'; let cancelRequestFunction = null; let lastUserInteraction = Date.now(); -export function cancelCurrentRequest () { +export function cancelCurrentRequest() { if (typeof cancelRequestFunction === 'function') { cancelRequestFunction(); } } -export async function _actuallySend ( +export async function _actuallySend( renderedRequest: RenderedRequest, renderContext: Object, workspace: Workspace, @@ -101,15 +109,22 @@ export async function _actuallySend ( const curl = new Curl(); /** Helper function to respond with a success */ - async function respond (patch: ResponsePatch, bodyPath: string | null, noPlugins: boolean = false): Promise { - const responsePatchBeforeHooks = Object.assign(({ - parentId: renderedRequest._id, - bodyCompression: null, // Will default to .zip otherwise - timeline: timeline, - bodyPath: bodyPath || '', - settingSendCookies: renderedRequest.settingSendCookies, - settingStoreCookies: renderedRequest.settingStoreCookies - }: ResponsePatch), patch); + async function respond( + patch: ResponsePatch, + bodyPath: string | null, + noPlugins: boolean = false + ): Promise { + const responsePatchBeforeHooks = Object.assign( + ({ + parentId: renderedRequest._id, + bodyCompression: null, // Will default to .zip otherwise + timeline: timeline, + bodyPath: bodyPath || '', + settingSendCookies: renderedRequest.settingSendCookies, + settingStoreCookies: renderedRequest.settingStoreCookies + }: ResponsePatch), + patch + ); if (noPlugins) { resolve(responsePatchBeforeHooks); @@ -118,9 +133,19 @@ export async function _actuallySend ( let responsePatch: ?ResponsePatch; try { - responsePatch = await _applyResponsePluginHooks(responsePatchBeforeHooks, renderedRequest, renderContext); + responsePatch = await _applyResponsePluginHooks( + responsePatchBeforeHooks, + renderedRequest, + renderContext + ); } catch (err) { - handleError(new Error(`[plugin] Response hook failed plugin=${err.plugin.name} err=${err.message}`)); + handleError( + new Error( + `[plugin] Response hook failed plugin=${err.plugin.name} err=${ + err.message + }` + ) + ); return; } @@ -128,46 +153,58 @@ export async function _actuallySend ( } /** Helper function to respond with an error */ - function handleError (err: Error): void { - respond({ - url: renderedRequest.url, - parentId: renderedRequest._id, - error: err.message, - elapsedTime: 0, - statusMessage: 'Error', - settingSendCookies: renderedRequest.settingSendCookies, - settingStoreCookies: renderedRequest.settingStoreCookies - }, null, true); + function handleError(err: Error): void { + respond( + { + url: renderedRequest.url, + parentId: renderedRequest._id, + error: err.message, + elapsedTime: 0, + statusMessage: 'Error', + settingSendCookies: renderedRequest.settingSendCookies, + settingStoreCookies: renderedRequest.settingStoreCookies + }, + null, + true + ); } /** Helper function to set Curl options */ - function setOpt (opt: number, val: any, optional: boolean = false) { - const name = Object.keys(Curl.option).find(name => Curl.option[name] === opt); + function setOpt(opt: number, val: any, optional: boolean = false) { + const name = Object.keys(Curl.option).find( + name => Curl.option[name] === opt + ); try { curl.setOpt(opt, val); } catch (err) { if (!optional) { throw new Error(`${err.message} (${opt} ${name || 'n/a'})`); } else { - console.warn(`Failed to set optional Curl opt (${opt} ${name || 'n/a'})`); + console.warn( + `Failed to set optional Curl opt (${opt} ${name || 'n/a'})` + ); } } } - function enable (feature: number) { + function enable(feature: number) { curl.enable(feature); } try { // Setup the cancellation logic cancelRequestFunction = () => { - respond({ - elapsedTime: curl.getInfo(Curl.info.TOTAL_TIME) * 1000, - bytesRead: curl.getInfo(Curl.info.SIZE_DOWNLOAD), - url: curl.getInfo(Curl.info.EFFECTIVE_URL), - statusMessage: 'Cancelled', - error: 'Request was cancelled' - }, null, true); + respond( + { + elapsedTime: curl.getInfo(Curl.info.TOTAL_TIME) * 1000, + bytesRead: curl.getInfo(Curl.info.SIZE_DOWNLOAD), + url: curl.getInfo(Curl.info.EFFECTIVE_URL), + statusMessage: 'Cancelled', + error: 'Request was cancelled' + }, + null, + true + ); // Kill it! curl.close(); @@ -212,7 +249,10 @@ export async function _actuallySend ( // Setup debug handler setOpt(Curl.option.DEBUGFUNCTION, (infoType: string, content: string) => { - const name = Object.keys(Curl.info.debug).find(k => Curl.info.debug[k] === infoType) || ''; + const name = + Object.keys(Curl.info.debug).find( + k => Curl.info.debug[k] === infoType + ) || ''; if ( infoType === Curl.info.debug.SSL_DATA_IN || @@ -225,10 +265,15 @@ export async function _actuallySend ( if (infoType === Curl.info.debug.DATA_OUT) { if (content.length === 0) { // Sometimes this happens, but I'm not sure why. Just ignore it. - } else if (content.length < renderedRequest.settingMaxTimelineDataSize) { - timeline.push({name, value: content}); + } else if ( + content.length < renderedRequest.settingMaxTimelineDataSize + ) { + timeline.push({ name, value: content }); } else { - timeline.push({name, value: `(${describeByteSize(content.length)} hidden)`}); + timeline.push({ + name, + value: `(${describeByteSize(content.length)} hidden)` + }); } return 0; } @@ -242,11 +287,14 @@ export async function _actuallySend ( } // Don't show cookie setting because this will display every domain in the jar - if (infoType === Curl.info.debug.TEXT && content.indexOf('Added cookie') === 0) { + if ( + infoType === Curl.info.debug.TEXT && + content.indexOf('Added cookie') === 0 + ) { return 0; } - timeline.push({name, value: content}); + timeline.push({ name, value: content }); return 0; // Must be here }); @@ -256,19 +304,23 @@ export async function _actuallySend ( let lastPercent = 0; // NOTE: This option was added in 7.32.0 so make it optional - setOpt(Curl.option.XFERINFOFUNCTION, (dltotal, dlnow, ultotal, ulnow) => { - if (dltotal === 0) { + setOpt( + Curl.option.XFERINFOFUNCTION, + (dltotal, dlnow, ultotal, ulnow) => { + if (dltotal === 0) { + return 0; + } + + const percent = Math.round((dlnow / dltotal) * 100); + if (percent !== lastPercent) { + // console.log(`[network] Request downloaded ${percent}%`); + lastPercent = percent; + } + return 0; - } - - const percent = Math.round(dlnow / dltotal * 100); - if (percent !== lastPercent) { - // console.log(`[network] Request downloaded ${percent}%`); - lastPercent = percent; - } - - return 0; - }, true); + }, + true + ); // Set the URL, including the query parameters const qs = buildQueryStringFromParams(renderedRequest.parameters); @@ -286,23 +338,29 @@ export async function _actuallySend ( } else { curl.setUrl(finalUrl); } - timeline.push({name: 'TEXT', value: 'Preparing request to ' + finalUrl}); - timeline.push({name: 'TEXT', value: `Using ${Curl.getVersion()}`}); + timeline.push({ + name: 'TEXT', + value: 'Preparing request to ' + finalUrl + }); + timeline.push({ name: 'TEXT', value: `Using ${Curl.getVersion()}` }); // log some things if (renderedRequest.settingEncodeUrl) { - timeline.push({name: 'TEXT', value: 'Enable automatic URL encoding'}); + timeline.push({ name: 'TEXT', value: 'Enable automatic URL encoding' }); } else { - timeline.push({name: 'TEXT', value: 'Disable automatic URL encoding'}); + timeline.push({ + name: 'TEXT', + value: 'Disable automatic URL encoding' + }); } // SSL Validation if (settings.validateSSL) { - timeline.push({name: 'TEXT', value: 'Enable SSL validation'}); + timeline.push({ name: 'TEXT', value: 'Enable SSL validation' }); } else { setOpt(Curl.option.SSL_VERIFYHOST, 0); setOpt(Curl.option.SSL_VERIFYPEER, 0); - timeline.push({name: 'TEXT', value: 'Disable SSL validation'}); + timeline.push({ name: 'TEXT', value: 'Disable SSL validation' }); } // Setup CA Root Certificates if not on Mac. Thanks to libcurl, Mac will use @@ -337,25 +395,29 @@ export async function _actuallySend ( expiresTimestamp = Math.round(expiresDate.getTime() / 1000); } - setOpt(Curl.option.COOKIELIST, [ - cookie.httpOnly ? `#HttpOnly_${cookie.domain}` : cookie.domain, - cookie.hostOnly ? 'FALSE' : 'TRUE', - cookie.path, - cookie.secure ? 'TRUE' : 'FALSE', - expiresTimestamp, - cookie.key, - cookie.value - ].join('\t')); + setOpt( + Curl.option.COOKIELIST, + [ + cookie.httpOnly ? `#HttpOnly_${cookie.domain}` : cookie.domain, + cookie.hostOnly ? 'FALSE' : 'TRUE', + cookie.path, + cookie.secure ? 'TRUE' : 'FALSE', + expiresTimestamp, + cookie.key, + cookie.value + ].join('\t') + ); } - for (const {name, value} of renderedRequest.cookies) { + for (const { name, value } of renderedRequest.cookies) { setOpt(Curl.option.COOKIE, `${name}=${value}`); } timeline.push({ name: 'TEXT', - value: 'Enable cookie sending with jar of ' + - `${cookies.length} cookie${cookies.length !== 1 ? 's' : ''}` + value: + 'Enable cookie sending with jar of ' + + `${cookies.length} cookie${cookies.length !== 1 ? 's' : ''}` }); } else { timeline.push({ @@ -366,11 +428,14 @@ export async function _actuallySend ( // Set proxy settings if we have them if (settings.proxyEnabled) { - const {protocol} = urlParse(renderedRequest.url); - const {httpProxy, httpsProxy, noProxy} = settings; + const { protocol } = urlParse(renderedRequest.url); + const { httpProxy, httpsProxy, noProxy } = settings; const proxyHost = protocol === 'https:' ? httpsProxy : httpProxy; const proxy = proxyHost ? setDefaultProtocol(proxyHost) : null; - timeline.push({name: 'TEXT', value: `Enable network proxy for ${protocol || ''}`}); + timeline.push({ + name: 'TEXT', + value: `Enable network proxy for ${protocol || ''}` + }); if (proxy) { setOpt(Curl.option.PROXY, proxy); setOpt(Curl.option.PROXYAUTH, Curl.auth.ANY); @@ -383,13 +448,18 @@ export async function _actuallySend ( } // Set client certs if needed - const clientCertificates = await models.clientCertificate.findByParentId(workspace._id); + const clientCertificates = await models.clientCertificate.findByParentId( + workspace._id + ); for (const certificate of clientCertificates) { if (certificate.disabled) { continue; } - const cHostWithProtocol = setDefaultProtocol(certificate.host, 'https:'); + const cHostWithProtocol = setDefaultProtocol( + certificate.host, + 'https:' + ); if (urlMatchesCertHost(cHostWithProtocol, renderedRequest.url)) { const ensureFile = blobOrFilename => { @@ -411,23 +481,32 @@ export async function _actuallySend ( return blobOrFilename; }; - const {passphrase, cert, key, pfx} = certificate; + const { passphrase, cert, key, pfx } = certificate; if (cert) { setOpt(Curl.option.SSLCERT, ensureFile(cert)); setOpt(Curl.option.SSLCERTTYPE, 'PEM'); - timeline.push({name: 'TEXT', value: 'Adding SSL PEM certificate'}); + timeline.push({ + name: 'TEXT', + value: 'Adding SSL PEM certificate' + }); } if (pfx) { setOpt(Curl.option.SSLCERT, ensureFile(pfx)); setOpt(Curl.option.SSLCERTTYPE, 'P12'); - timeline.push({name: 'TEXT', value: 'Adding SSL P12 certificate'}); + timeline.push({ + name: 'TEXT', + value: 'Adding SSL P12 certificate' + }); } if (key) { setOpt(Curl.option.SSLKEY, ensureFile(key)); - timeline.push({name: 'TEXT', value: 'Adding SSL KEY certificate'}); + timeline.push({ + name: 'TEXT', + value: 'Adding SSL KEY certificate' + }); } if (passphrase) { @@ -439,12 +518,21 @@ export async function _actuallySend ( // Build the body let noBody = false; let requestBody = null; - const expectsBody = ['POST', 'PUT', 'PATCH'].includes(renderedRequest.method.toUpperCase()); + const expectsBody = ['POST', 'PUT', 'PATCH'].includes( + renderedRequest.method.toUpperCase() + ); if (renderedRequest.body.mimeType === CONTENT_TYPE_FORM_URLENCODED) { - requestBody = buildQueryStringFromParams(renderedRequest.body.params || [], false); + requestBody = buildQueryStringFromParams( + renderedRequest.body.params || [], + false + ); } else if (renderedRequest.body.mimeType === CONTENT_TYPE_FORM_DATA) { const params = renderedRequest.body.params || []; - const {filePath: multipartBodyPath, boundary, contentLength} = await buildMultipart(params); + const { + filePath: multipartBodyPath, + boundary, + contentLength + } = await buildMultipart(params); // Extend the Content-Type header const contentTypeHeader = getContentTypeHeader(headers); @@ -468,14 +556,13 @@ export async function _actuallySend ( const fn = () => { fs.closeSync(fd); - fs.unlink(multipartBodyPath, () => { - }); + fs.unlink(multipartBodyPath, () => {}); }; curl.on('end', fn); curl.on('error', fn); } else if (renderedRequest.body.fileName) { - const {size} = fs.statSync(renderedRequest.body.fileName); + const { size } = fs.statSync(renderedRequest.body.fileName); const fileName = renderedRequest.body.fileName || ''; const fd = fs.openSync(fileName, 'r'); @@ -489,7 +576,10 @@ export async function _actuallySend ( const fn = () => fs.closeSync(fd); curl.on('end', fn); curl.on('error', fn); - } else if (typeof renderedRequest.body.mimeType === 'string' || expectsBody) { + } else if ( + typeof renderedRequest.body.mimeType === 'string' || + expectsBody + ) { requestBody = renderedRequest.body.text || ''; } else { // No body @@ -498,8 +588,11 @@ export async function _actuallySend ( if (!noBody) { // Don't chunk uploads - headers.push({name: 'Expect', value: DISABLE_HEADER_VALUE}); - headers.push({name: 'Transfer-Encoding', value: DISABLE_HEADER_VALUE}); + headers.push({ name: 'Expect', value: DISABLE_HEADER_VALUE }); + headers.push({ + name: 'Transfer-Encoding', + value: DISABLE_HEADER_VALUE + }); } // If we calculated the body within Insomnia (ie. not computed by Curl) @@ -510,26 +603,29 @@ export async function _actuallySend ( // Handle Authorization header if (!hasAuthHeader(headers) && !renderedRequest.authentication.disabled) { if (renderedRequest.authentication.type === AUTH_BASIC) { - const {username, password} = renderedRequest.authentication; + const { username, password } = renderedRequest.authentication; setOpt(Curl.option.HTTPAUTH, Curl.auth.BASIC); setOpt(Curl.option.USERNAME, username || ''); setOpt(Curl.option.PASSWORD, password || ''); } else if (renderedRequest.authentication.type === AUTH_DIGEST) { - const {username, password} = renderedRequest.authentication; + const { username, password } = renderedRequest.authentication; setOpt(Curl.option.HTTPAUTH, Curl.auth.DIGEST); setOpt(Curl.option.USERNAME, username || ''); setOpt(Curl.option.PASSWORD, password || ''); } else if (renderedRequest.authentication.type === AUTH_NTLM) { - const {username, password} = renderedRequest.authentication; + const { username, password } = renderedRequest.authentication; setOpt(Curl.option.HTTPAUTH, Curl.auth.NTLM); setOpt(Curl.option.USERNAME, username || ''); setOpt(Curl.option.PASSWORD, password || ''); } else if (renderedRequest.authentication.type === AUTH_AWS_IAM) { if (!noBody && !requestBody) { return handleError( - new Error('AWS authentication not supported for provided body type')); + new Error( + 'AWS authentication not supported for provided body type' + ) + ); } - const {authentication} = renderedRequest; + const { authentication } = renderedRequest; const credentials = { accessKeyId: authentication.accessKeyId || '', secretAccessKey: authentication.secretAccessKey || '', @@ -568,12 +664,12 @@ export async function _actuallySend ( // Send a default Accept headers of anything if (!hasAcceptHeader(headers)) { - headers.push({name: 'Accept', value: '*/*'}); // Default to anything + headers.push({ name: 'Accept', value: '*/*' }); // Default to anything } // Don't auto-send Accept-Encoding header if (!hasAcceptEncodingHeader(headers)) { - headers.push({name: 'Accept-Encoding', value: DISABLE_HEADER_VALUE}); + headers.push({ name: 'Accept-Encoding', value: DISABLE_HEADER_VALUE }); } // Set User-Agent if it't not already in headers @@ -583,25 +679,23 @@ export async function _actuallySend ( // Prevent curl from adding default content-type header if (!hasContentTypeHeader(headers)) { - headers.push({name: 'content-type', value: DISABLE_HEADER_VALUE}); + headers.push({ name: 'content-type', value: DISABLE_HEADER_VALUE }); } // NOTE: This is last because headers might be modified multiple times - const headerStrings = headers - .filter(h => h.name) - .map(h => { - const value = h.value || ''; - if (value === '') { - // Curl needs a semicolon suffix to send empty header values - return `${h.name};`; - } else if (value === DISABLE_HEADER_VALUE) { - // Tell Curl NOT to send the header if value is null - return `${h.name}:`; - } else { - // Send normal header value - return `${h.name}: ${value}`; - } - }); + const headerStrings = headers.filter(h => h.name).map(h => { + const value = h.value || ''; + if (value === '') { + // Curl needs a semicolon suffix to send empty header values + return `${h.name};`; + } else if (value === DISABLE_HEADER_VALUE) { + // Tell Curl NOT to send the header if value is null + return `${h.name}:`; + } else { + // Send normal header value + return `${h.name}: ${value}`; + } + }); setOpt(Curl.option.HTTPHEADER, headerStrings); let responseBodyBytes = 0; @@ -621,7 +715,8 @@ export async function _actuallySend ( curl.on('end', async (_1, _2, rawHeaders) => { const allCurlHeadersObjects = _parseHeaders(rawHeaders); // Headers are an array (one for each redirect) - const lastCurlHeadersObject = allCurlHeadersObjects[allCurlHeadersObjects.length - 1]; + const lastCurlHeadersObject = + allCurlHeadersObjects[allCurlHeadersObjects.length - 1]; // Collect various things const httpVersion = lastCurlHeadersObject.version || ''; @@ -640,10 +735,13 @@ export async function _actuallySend ( let setCookieStrings: Array = []; const jar = jarFromCookies(renderedRequest.cookieJar.cookies); - for (const {headers} of allCurlHeadersObjects) { + for (const { headers } of allCurlHeadersObjects) { // Collect Set-Cookie headers const setCookieHeaders = getSetCookieHeaders(headers); - setCookieStrings = [...setCookieStrings, ...setCookieHeaders.map(h => h.value)]; + setCookieStrings = [ + ...setCookieStrings, + ...setCookieHeaders.map(h => h.value) + ]; // Pull out new URL if there is a redirect const newLocation = getLocationHeader(headers); @@ -657,23 +755,32 @@ export async function _actuallySend ( try { jar.setCookieSync(setCookieStr, currentUrl); } catch (err) { - timeline.push({name: 'TEXT', value: `Rejected cookie: ${err.message}`}); + timeline.push({ + name: 'TEXT', + value: `Rejected cookie: ${err.message}` + }); } } // Update cookie jar if we need to and if we found any cookies if (renderedRequest.settingStoreCookies && setCookieStrings.length) { const cookies = await cookiesFromJar(jar); - models.cookieJar.update(renderedRequest.cookieJar, {cookies}); + models.cookieJar.update(renderedRequest.cookieJar, { cookies }); } // Print informational message if (setCookieStrings.length > 0) { const n = setCookieStrings.length; if (renderedRequest.settingStoreCookies) { - timeline.push({name: 'TEXT', value: `Saved ${n} cookie${n === 1 ? '' : 's'}`}); + timeline.push({ + name: 'TEXT', + value: `Saved ${n} cookie${n === 1 ? '' : 's'}` + }); } else { - timeline.push({name: 'TEXT', value: `Ignored ${n} cookie${n === 1 ? '' : 's'}`}); + timeline.push({ + name: 'TEXT', + value: `Ignored ${n} cookie${n === 1 ? '' : 's'}` + }); } } @@ -699,7 +806,7 @@ export async function _actuallySend ( respond(responsePatch, responseBodyPath); }); - curl.on('error', function (err, code) { + curl.on('error', function(err, code) { let error = err + ''; let statusMessage = 'Error'; @@ -708,7 +815,7 @@ export async function _actuallySend ( statusMessage = 'Abort'; } - respond({statusMessage, error}, null, true); + respond({ statusMessage, error }, null, true); }); curl.perform(); @@ -718,7 +825,7 @@ export async function _actuallySend ( }); } -export async function sendWithSettings ( +export async function sendWithSettings( requestId: string, requestPatch: Object ): Promise { @@ -734,32 +841,48 @@ export async function sendWithSettings ( models.workspace.type ]); - const workspaceDoc = ancestors.find(doc => doc.type === models.workspace.type); + const workspaceDoc = ancestors.find( + doc => doc.type === models.workspace.type + ); const workspaceId = workspaceDoc ? workspaceDoc._id : 'n/a'; const workspace = await models.workspace.getById(workspaceId); if (!workspace) { throw new Error(`Failed to find workspace for: ${requestId}`); } - const workspaceMeta = await models.workspaceMeta.getOrCreateByParentId(workspace._id); + const workspaceMeta = await models.workspaceMeta.getOrCreateByParentId( + workspace._id + ); const environmentId: string = workspaceMeta.activeEnvironmentId || 'n/a'; - const newRequest: Request = await models.initModel(models.request.type, requestPatch, { - _id: request._id + '.other', - parentId: request._id - }); + const newRequest: Request = await models.initModel( + models.request.type, + requestPatch, + { + _id: request._id + '.other', + parentId: request._id + } + ); let renderResult: { request: RenderedRequest, context: Object }; try { - renderResult = await getRenderedRequestAndContext(newRequest, environmentId); + renderResult = await getRenderedRequestAndContext( + newRequest, + environmentId + ); } catch (err) { throw new Error(`Failed to render request: ${requestId}`); } - return _actuallySend(renderResult.request, renderResult.context, workspace, settings); + return _actuallySend( + renderResult.request, + renderResult.context, + workspace, + settings + ); } -export async function send ( +export async function send( requestId: string, environmentId: string ): Promise { @@ -799,8 +922,12 @@ export async function send ( const renderedRequestBeforePlugins = renderResult.request; const renderedContextBeforePlugins = renderResult.context; - const workspaceDoc = ancestors.find(doc => doc.type === models.workspace.type); - const workspace = await models.workspace.getById(workspaceDoc ? workspaceDoc._id : 'n/a'); + const workspaceDoc = ancestors.find( + doc => doc.type === models.workspace.type + ); + const workspace = await models.workspace.getById( + workspaceDoc ? workspaceDoc._id : 'n/a' + ); if (!workspace) { throw new Error(`Failed to find workspace for request: ${requestId}`); } @@ -823,15 +950,20 @@ export async function send ( }; } - return _actuallySend(renderedRequest, renderedContextBeforePlugins, workspace, settings); + return _actuallySend( + renderedRequest, + renderedContextBeforePlugins, + workspace, + settings + ); } -async function _applyRequestPluginHooks ( +async function _applyRequestPluginHooks( renderedRequest: RenderedRequest, renderedContext: Object ): Promise { const newRenderedRequest = clone(renderedRequest); - for (const {plugin, hook} of await plugins.getRequestHooks()) { + for (const { plugin, hook } of await plugins.getRequestHooks()) { const context = { ...pluginContexts.app.init(), ...pluginContexts.store.init(plugin), @@ -849,7 +981,7 @@ async function _applyRequestPluginHooks ( return newRenderedRequest; } -async function _applyResponsePluginHooks ( +async function _applyResponsePluginHooks( response: ResponsePatch, request: RenderedRequest, renderContext: Object @@ -857,7 +989,7 @@ async function _applyResponsePluginHooks ( const newResponse = clone(response); const newRequest = clone(request); - for (const {plugin, hook} of await plugins.getResponseHooks()) { + for (const { plugin, hook } of await plugins.getResponseHooks()) { const context = { ...pluginContexts.app.init(), ...pluginContexts.store.init(plugin), @@ -876,9 +1008,14 @@ async function _applyResponsePluginHooks ( return newResponse; } -export function _parseHeaders ( +export function _parseHeaders( buffer: Buffer -): Array<{ headers: Array, version: string, code: number, reason: string }> { +): Array<{ + headers: Array, + version: string, + code: number, + reason: string +}> { const results = []; const lines = buffer.toString('utf8').split(/\r?\n|\r/g); @@ -904,7 +1041,7 @@ export function _parseHeaders ( }; } else { const [name, value] = line.split(/:\s(.+)/); - const header: ResponseHeader = {name, value: value || ''}; + const header: ResponseHeader = { name, value: value || '' }; currentResult.headers.push(header); } } @@ -913,11 +1050,11 @@ export function _parseHeaders ( } // exported for unit tests only -export function _getAwsAuthHeaders ( +export function _getAwsAuthHeaders( credentials: { accessKeyId: string, secretAccessKey: string, - sessionToken: string, + sessionToken: string }, headers: Array, body: string, @@ -949,7 +1086,7 @@ export function _getAwsAuthHeaders ( return Object.keys(signature.headers) .filter(name => name !== 'content-type') // Don't add this because we already have it - .map(name => ({name, value: signature.headers[name]})); + .map(name => ({ name, value: signature.headers[name] })); } document.addEventListener('keydown', (e: KeyboardEvent) => { diff --git a/packages/insomnia-app/app/network/o-auth-1/constants.js b/packages/insomnia-app/app/network/o-auth-1/constants.js index 7741afe1d1..05c8603278 100644 --- a/packages/insomnia-app/app/network/o-auth-1/constants.js +++ b/packages/insomnia-app/app/network/o-auth-1/constants.js @@ -1,6 +1,11 @@ // @flow -export type OAuth1SignatureMethod = 'HMAC-SHA1' | 'RSA-SHA1' | 'HMAC-SHA256' | 'PLAINTEXT'; +export type OAuth1SignatureMethod = + | 'HMAC-SHA1' + | 'RSA-SHA1' + | 'HMAC-SHA256' + | 'PLAINTEXT'; export const SIGNATURE_METHOD_HMAC_SHA1: OAuth1SignatureMethod = 'HMAC-SHA1'; -export const SIGNATURE_METHOD_HMAC_SHA256: OAuth1SignatureMethod = 'HMAC-SHA256'; +export const SIGNATURE_METHOD_HMAC_SHA256: OAuth1SignatureMethod = + 'HMAC-SHA256'; export const SIGNATURE_METHOD_RSA_SHA1: OAuth1SignatureMethod = 'RSA-SHA1'; export const SIGNATURE_METHOD_PLAINTEXT: OAuth1SignatureMethod = 'PLAINTEXT'; diff --git a/packages/insomnia-app/app/network/o-auth-1/get-token.js b/packages/insomnia-app/app/network/o-auth-1/get-token.js index 071293e51d..eda2d381db 100644 --- a/packages/insomnia-app/app/network/o-auth-1/get-token.js +++ b/packages/insomnia-app/app/network/o-auth-1/get-token.js @@ -11,30 +11,39 @@ import { SIGNATURE_METHOD_PLAINTEXT, SIGNATURE_METHOD_HMAC_SHA256 } from './constants'; -import type {OAuth1SignatureMethod} from './constants'; -import type {RequestAuthentication} from '../../models/request'; +import type { OAuth1SignatureMethod } from './constants'; +import type { RequestAuthentication } from '../../models/request'; -function hashFunction (signatureMethod: OAuth1SignatureMethod) { +function hashFunction(signatureMethod: OAuth1SignatureMethod) { if (signatureMethod === SIGNATURE_METHOD_HMAC_SHA1) { - return function (baseString: string, key: string): string { - return crypto.createHmac('sha1', key).update(baseString).digest('base64'); + return function(baseString: string, key: string): string { + return crypto + .createHmac('sha1', key) + .update(baseString) + .digest('base64'); }; } if (signatureMethod === SIGNATURE_METHOD_HMAC_SHA256) { - return function (baseString: string, key: string): string { - return crypto.createHmac('sha256', key).update(baseString).digest('base64'); + return function(baseString: string, key: string): string { + return crypto + .createHmac('sha256', key) + .update(baseString) + .digest('base64'); }; } if (signatureMethod === SIGNATURE_METHOD_RSA_SHA1) { - return function (baseString: string, privatekey: string): string { - return crypto.createSign('RSA-SHA1').update(baseString).sign(privatekey, 'base64'); + return function(baseString: string, privatekey: string): string { + return crypto + .createSign('RSA-SHA1') + .update(baseString) + .sign(privatekey, 'base64'); }; } if (signatureMethod === SIGNATURE_METHOD_PLAINTEXT) { - return function (baseString: string): string { + return function(baseString: string): string { return baseString; }; } @@ -42,11 +51,11 @@ function hashFunction (signatureMethod: OAuth1SignatureMethod) { throw new Error(`Invalid signature method ${signatureMethod}`); } -export default async function ( +export default async function( url: string, method: string, authentication: RequestAuthentication -): {[string]: string} { +): { [string]: string } { const oauth = new OAuth1({ consumer: { key: authentication.consumerKey, @@ -84,15 +93,18 @@ export default async function ( let token = null; if (authentication.tokenKey && authentication.tokenSecret) { - token = {key: authentication.tokenKey, secret: authentication.tokenSecret}; + token = { + key: authentication.tokenKey, + secret: authentication.tokenSecret + }; } else if (authentication.tokenKey) { - token = {key: authentication.tokenKey}; + token = { key: authentication.tokenKey }; } if (authentication.signatureMethod === SIGNATURE_METHOD_RSA_SHA1) { - token = {key: authentication.tokenKey, secret: authentication.privateKey}; + token = { key: authentication.tokenKey, secret: authentication.privateKey }; // We override getSigningKey for RSA-SHA1 because we don't want ddo/oauth-1.0a to percentEncode the token - oauth.getSigningKey = function (tokenSecret) { + oauth.getSigningKey = function(tokenSecret) { return tokenSecret || ''; }; } diff --git a/packages/insomnia-app/app/network/o-auth-2/__tests__/grant-authorization-code.test.js b/packages/insomnia-app/app/network/o-auth-2/__tests__/grant-authorization-code.test.js index 2c15d360d0..2596a6d8e0 100644 --- a/packages/insomnia-app/app/network/o-auth-2/__tests__/grant-authorization-code.test.js +++ b/packages/insomnia-app/app/network/o-auth-2/__tests__/grant-authorization-code.test.js @@ -1,10 +1,10 @@ import getToken from '../grant-authorization-code'; -import {createBWRedirectMock} from './helpers'; -import {globalBeforeEach} from '../../../__jest__/before-each'; +import { createBWRedirectMock } from './helpers'; +import { globalBeforeEach } from '../../../__jest__/before-each'; import * as network from '../../network'; import fs from 'fs'; import path from 'path'; -import {getTempDir} from '../../../common/constants'; +import { getTempDir } from '../../../common/constants'; // Mock some test things const AUTHORIZE_URL = 'https://foo.com/authorizeAuthCode'; @@ -21,16 +21,19 @@ describe('authorization_code', () => { createBWRedirectMock(`${REDIRECT_URI}?code=code_123&state=${STATE}`); const bodyPath = path.join(getTempDir(), 'foo.response'); - fs.writeFileSync(bodyPath, JSON.stringify({ - access_token: 'token_123', - token_type: 'token_type', - scope: SCOPE - })); + fs.writeFileSync( + bodyPath, + JSON.stringify({ + access_token: 'token_123', + token_type: 'token_type', + scope: SCOPE + }) + ); network.sendWithSettings = jest.fn(() => ({ bodyPath, statusCode: 200, - headers: [{name: 'Content-Type', value: 'application/json'}] + headers: [{ name: 'Content-Type', value: 'application/json' }] })); const result = await getToken( @@ -46,24 +49,38 @@ describe('authorization_code', () => { ); // Check the request to fetch the token - expect(network.sendWithSettings.mock.calls).toEqual([['req_1', { - url: ACCESS_TOKEN_URL, - method: 'POST', - body: { - mimeType: 'application/x-www-form-urlencoded', - params: [ - {name: 'grant_type', value: 'authorization_code'}, - {name: 'code', value: 'code_123'}, - {name: 'redirect_uri', value: REDIRECT_URI}, - {name: 'state', value: STATE} - ] - }, - headers: [ - {name: 'Content-Type', value: 'application/x-www-form-urlencoded'}, - {name: 'Accept', value: 'application/x-www-form-urlencoded, application/json'}, - {name: 'Authorization', value: 'Basic Y2xpZW50XzEyMzpzZWNyZXRfMTIzNDU0NTY2Nzc3NTYzNDM='} + expect(network.sendWithSettings.mock.calls).toEqual([ + [ + 'req_1', + { + url: ACCESS_TOKEN_URL, + method: 'POST', + body: { + mimeType: 'application/x-www-form-urlencoded', + params: [ + { name: 'grant_type', value: 'authorization_code' }, + { name: 'code', value: 'code_123' }, + { name: 'redirect_uri', value: REDIRECT_URI }, + { name: 'state', value: STATE } + ] + }, + headers: [ + { + name: 'Content-Type', + value: 'application/x-www-form-urlencoded' + }, + { + name: 'Accept', + value: 'application/x-www-form-urlencoded, application/json' + }, + { + name: 'Authorization', + value: 'Basic Y2xpZW50XzEyMzpzZWNyZXRfMTIzNDU0NTY2Nzc3NTYzNDM=' + } + ] + } ] - }]]); + ]); // Check the expected value expect(result).toEqual({ @@ -82,16 +99,21 @@ describe('authorization_code', () => { createBWRedirectMock(`${REDIRECT_URI}?code=code_123&state=${STATE}`); const bodyPath = path.join(getTempDir(), 'foo.response'); - fs.writeFileSync(bodyPath, JSON.stringify({ - access_token: 'token_123', - token_type: 'token_type', - scope: SCOPE - })); + fs.writeFileSync( + bodyPath, + JSON.stringify({ + access_token: 'token_123', + token_type: 'token_type', + scope: SCOPE + }) + ); network.sendWithSettings = jest.fn(() => ({ bodyPath, statusCode: 200, - headers: [{name: 'Content-Type', value: 'application/x-www-form-urlencoded'}] + headers: [ + { name: 'Content-Type', value: 'application/x-www-form-urlencoded' } + ] })); const result = await getToken( @@ -107,25 +129,36 @@ describe('authorization_code', () => { ); // Check the request to fetch the token - expect(network.sendWithSettings.mock.calls).toEqual([['req_1', { - url: ACCESS_TOKEN_URL, - method: 'POST', - body: { - mimeType: 'application/x-www-form-urlencoded', - params: [ - {name: 'grant_type', value: 'authorization_code'}, - {name: 'code', value: 'code_123'}, - {name: 'redirect_uri', value: REDIRECT_URI}, - {name: 'state', value: STATE}, - {name: 'client_id', value: CLIENT_ID}, - {name: 'client_secret', value: CLIENT_SECRET} - ] - }, - headers: [ - {name: 'Content-Type', value: 'application/x-www-form-urlencoded'}, - {name: 'Accept', value: 'application/x-www-form-urlencoded, application/json'} + expect(network.sendWithSettings.mock.calls).toEqual([ + [ + 'req_1', + { + url: ACCESS_TOKEN_URL, + method: 'POST', + body: { + mimeType: 'application/x-www-form-urlencoded', + params: [ + { name: 'grant_type', value: 'authorization_code' }, + { name: 'code', value: 'code_123' }, + { name: 'redirect_uri', value: REDIRECT_URI }, + { name: 'state', value: STATE }, + { name: 'client_id', value: CLIENT_ID }, + { name: 'client_secret', value: CLIENT_SECRET } + ] + }, + headers: [ + { + name: 'Content-Type', + value: 'application/x-www-form-urlencoded' + }, + { + name: 'Accept', + value: 'application/x-www-form-urlencoded, application/json' + } + ] + } ] - }]]); + ]); // Check the expected value expect(result).toEqual({ diff --git a/packages/insomnia-app/app/network/o-auth-2/__tests__/grant-client-credentials.test.js b/packages/insomnia-app/app/network/o-auth-2/__tests__/grant-client-credentials.test.js index eda8bcacaf..a25a6916b2 100644 --- a/packages/insomnia-app/app/network/o-auth-2/__tests__/grant-client-credentials.test.js +++ b/packages/insomnia-app/app/network/o-auth-2/__tests__/grant-client-credentials.test.js @@ -1,9 +1,9 @@ import getToken from '../grant-client-credentials'; -import {globalBeforeEach} from '../../../__jest__/before-each'; +import { globalBeforeEach } from '../../../__jest__/before-each'; import path from 'path'; import fs from 'fs'; import * as network from '../../network'; -import {getTempDir} from '../../../common/constants'; +import { getTempDir } from '../../../common/constants'; // Mock some test things const ACCESS_TOKEN_URL = 'https://foo.com/access_token'; @@ -16,16 +16,19 @@ describe('client_credentials', () => { it('gets token with JSON and basic auth', async () => { const bodyPath = path.join(getTempDir(), 'foo.response'); - fs.writeFileSync(bodyPath, JSON.stringify({ - access_token: 'token_123', - token_type: 'token_type', - scope: SCOPE - })); + fs.writeFileSync( + bodyPath, + JSON.stringify({ + access_token: 'token_123', + token_type: 'token_type', + scope: SCOPE + }) + ); network.sendWithSettings = jest.fn(() => ({ bodyPath, statusCode: 200, - headers: [{name: 'Content-Type', value: 'application/json'}] + headers: [{ name: 'Content-Type', value: 'application/json' }] })); const result = await getToken( @@ -38,22 +41,36 @@ describe('client_credentials', () => { ); // Check the request to fetch the token - expect(network.sendWithSettings.mock.calls).toEqual([['req_1', { - url: ACCESS_TOKEN_URL, - method: 'POST', - body: { - mimeType: 'application/x-www-form-urlencoded', - params: [ - {name: 'grant_type', value: 'client_credentials'}, - {name: 'scope', value: SCOPE} - ] - }, - headers: [ - {name: 'Content-Type', value: 'application/x-www-form-urlencoded'}, - {name: 'Accept', value: 'application/x-www-form-urlencoded, application/json'}, - {name: 'Authorization', value: 'Basic Y2xpZW50XzEyMzpzZWNyZXRfMTIzNDU0NTY2Nzc3NTYzNDM='} + expect(network.sendWithSettings.mock.calls).toEqual([ + [ + 'req_1', + { + url: ACCESS_TOKEN_URL, + method: 'POST', + body: { + mimeType: 'application/x-www-form-urlencoded', + params: [ + { name: 'grant_type', value: 'client_credentials' }, + { name: 'scope', value: SCOPE } + ] + }, + headers: [ + { + name: 'Content-Type', + value: 'application/x-www-form-urlencoded' + }, + { + name: 'Accept', + value: 'application/x-www-form-urlencoded, application/json' + }, + { + name: 'Authorization', + value: 'Basic Y2xpZW50XzEyMzpzZWNyZXRfMTIzNDU0NTY2Nzc3NTYzNDM=' + } + ] + } ] - }]]); + ]); // Check the expected value expect(result).toEqual({ @@ -70,16 +87,21 @@ describe('client_credentials', () => { it('gets token with urlencoded and body auth', async () => { const bodyPath = path.join(getTempDir(), 'foo.response'); - fs.writeFileSync(bodyPath, JSON.stringify({ - access_token: 'token_123', - token_type: 'token_type', - scope: SCOPE - })); + fs.writeFileSync( + bodyPath, + JSON.stringify({ + access_token: 'token_123', + token_type: 'token_type', + scope: SCOPE + }) + ); network.sendWithSettings = jest.fn(() => ({ bodyPath, statusCode: 200, - headers: [{name: 'Content-Type', value: 'application/x-www-form-urlencoded'}] + headers: [ + { name: 'Content-Type', value: 'application/x-www-form-urlencoded' } + ] })); const result = await getToken( @@ -92,23 +114,34 @@ describe('client_credentials', () => { ); // Check the request to fetch the token - expect(network.sendWithSettings.mock.calls).toEqual([['req_1', { - url: ACCESS_TOKEN_URL, - method: 'POST', - body: { - mimeType: 'application/x-www-form-urlencoded', - params: [ - {name: 'grant_type', value: 'client_credentials'}, - {name: 'scope', value: SCOPE}, - {name: 'client_id', value: CLIENT_ID}, - {name: 'client_secret', value: CLIENT_SECRET} - ] - }, - headers: [ - {name: 'Content-Type', value: 'application/x-www-form-urlencoded'}, - {name: 'Accept', value: 'application/x-www-form-urlencoded, application/json'} + expect(network.sendWithSettings.mock.calls).toEqual([ + [ + 'req_1', + { + url: ACCESS_TOKEN_URL, + method: 'POST', + body: { + mimeType: 'application/x-www-form-urlencoded', + params: [ + { name: 'grant_type', value: 'client_credentials' }, + { name: 'scope', value: SCOPE }, + { name: 'client_id', value: CLIENT_ID }, + { name: 'client_secret', value: CLIENT_SECRET } + ] + }, + headers: [ + { + name: 'Content-Type', + value: 'application/x-www-form-urlencoded' + }, + { + name: 'Accept', + value: 'application/x-www-form-urlencoded, application/json' + } + ] + } ] - }]]); + ]); // Check the expected value expect(result).toEqual({ diff --git a/packages/insomnia-app/app/network/o-auth-2/__tests__/grant-implicit.test.js b/packages/insomnia-app/app/network/o-auth-2/__tests__/grant-implicit.test.js index bc103bcc25..1a55742aed 100644 --- a/packages/insomnia-app/app/network/o-auth-2/__tests__/grant-implicit.test.js +++ b/packages/insomnia-app/app/network/o-auth-2/__tests__/grant-implicit.test.js @@ -1,6 +1,6 @@ import getToken from '../grant-implicit'; -import {createBWRedirectMock} from './helpers'; -import {globalBeforeEach} from '../../../__jest__/before-each'; +import { createBWRedirectMock } from './helpers'; +import { globalBeforeEach } from '../../../__jest__/before-each'; // Mock some test things const AUTHORIZE_URL = 'https://foo.com/authorizeAuthCode'; @@ -12,7 +12,9 @@ const STATE = 'state_123'; describe('implicit', () => { beforeEach(globalBeforeEach); it('works in default case', async () => { - createBWRedirectMock(`${REDIRECT_URI}#access_token=token_123&state=${STATE}&foo=bar`); + createBWRedirectMock( + `${REDIRECT_URI}#access_token=token_123&state=${STATE}&foo=bar` + ); const result = await getToken( AUTHORIZE_URL, diff --git a/packages/insomnia-app/app/network/o-auth-2/__tests__/grant-password.test.js b/packages/insomnia-app/app/network/o-auth-2/__tests__/grant-password.test.js index 3e2138a29a..4f3248699c 100644 --- a/packages/insomnia-app/app/network/o-auth-2/__tests__/grant-password.test.js +++ b/packages/insomnia-app/app/network/o-auth-2/__tests__/grant-password.test.js @@ -1,7 +1,7 @@ import getToken from '../grant-password'; -import {globalBeforeEach} from '../../../__jest__/before-each'; +import { globalBeforeEach } from '../../../__jest__/before-each'; import * as network from '../../network'; -import {getTempDir} from '../../../common/constants'; +import { getTempDir } from '../../../common/constants'; import path from 'path'; import fs from 'fs'; @@ -18,16 +18,19 @@ describe('password', () => { it('gets token with JSON and basic auth', async () => { const bodyPath = path.join(getTempDir(), 'foo.response'); - fs.writeFileSync(bodyPath, JSON.stringify({ - access_token: 'token_123', - token_type: 'token_type', - scope: SCOPE - })); + fs.writeFileSync( + bodyPath, + JSON.stringify({ + access_token: 'token_123', + token_type: 'token_type', + scope: SCOPE + }) + ); network.sendWithSettings = jest.fn(() => ({ bodyPath, statusCode: 200, - headers: [{name: 'Content-Type', value: 'application/json'}] + headers: [{ name: 'Content-Type', value: 'application/json' }] })); const result = await getToken( @@ -42,24 +45,38 @@ describe('password', () => { ); // Check the request to fetch the token - expect(network.sendWithSettings.mock.calls).toEqual([['req_1', { - url: ACCESS_TOKEN_URL, - method: 'POST', - body: { - mimeType: 'application/x-www-form-urlencoded', - params: [ - {name: 'grant_type', value: 'password'}, - {name: 'username', value: USERNAME}, - {name: 'password', value: PASSWORD}, - {name: 'scope', value: SCOPE} - ] - }, - headers: [ - {name: 'Content-Type', value: 'application/x-www-form-urlencoded'}, - {name: 'Accept', value: 'application/x-www-form-urlencoded, application/json'}, - {name: 'Authorization', value: 'Basic Y2xpZW50XzEyMzpzZWNyZXRfMTIzNDU0NTY2Nzc3NTYzNDM='} + expect(network.sendWithSettings.mock.calls).toEqual([ + [ + 'req_1', + { + url: ACCESS_TOKEN_URL, + method: 'POST', + body: { + mimeType: 'application/x-www-form-urlencoded', + params: [ + { name: 'grant_type', value: 'password' }, + { name: 'username', value: USERNAME }, + { name: 'password', value: PASSWORD }, + { name: 'scope', value: SCOPE } + ] + }, + headers: [ + { + name: 'Content-Type', + value: 'application/x-www-form-urlencoded' + }, + { + name: 'Accept', + value: 'application/x-www-form-urlencoded, application/json' + }, + { + name: 'Authorization', + value: 'Basic Y2xpZW50XzEyMzpzZWNyZXRfMTIzNDU0NTY2Nzc3NTYzNDM=' + } + ] + } ] - }]]); + ]); // Check the expected value expect(result).toEqual({ @@ -77,16 +94,21 @@ describe('password', () => { it('gets token with urlencoded and body auth', async () => { const bodyPath = path.join(getTempDir(), 'foo.response'); - fs.writeFileSync(bodyPath, JSON.stringify({ - access_token: 'token_123', - token_type: 'token_type', - scope: SCOPE - })); + fs.writeFileSync( + bodyPath, + JSON.stringify({ + access_token: 'token_123', + token_type: 'token_type', + scope: SCOPE + }) + ); network.sendWithSettings = jest.fn(() => ({ bodyPath, statusCode: 200, - headers: [{name: 'Content-Type', value: 'application/x-www-form-urlencoded'}] + headers: [ + { name: 'Content-Type', value: 'application/x-www-form-urlencoded' } + ] })); const result = await getToken( @@ -101,25 +123,36 @@ describe('password', () => { ); // Check the request to fetch the token - expect(network.sendWithSettings.mock.calls).toEqual([['req_1', { - url: ACCESS_TOKEN_URL, - method: 'POST', - body: { - mimeType: 'application/x-www-form-urlencoded', - params: [ - {name: 'grant_type', value: 'password'}, - {name: 'username', value: USERNAME}, - {name: 'password', value: PASSWORD}, - {name: 'scope', value: SCOPE}, - {name: 'client_id', value: CLIENT_ID}, - {name: 'client_secret', value: CLIENT_SECRET} - ] - }, - headers: [ - {name: 'Content-Type', value: 'application/x-www-form-urlencoded'}, - {name: 'Accept', value: 'application/x-www-form-urlencoded, application/json'} + expect(network.sendWithSettings.mock.calls).toEqual([ + [ + 'req_1', + { + url: ACCESS_TOKEN_URL, + method: 'POST', + body: { + mimeType: 'application/x-www-form-urlencoded', + params: [ + { name: 'grant_type', value: 'password' }, + { name: 'username', value: USERNAME }, + { name: 'password', value: PASSWORD }, + { name: 'scope', value: SCOPE }, + { name: 'client_id', value: CLIENT_ID }, + { name: 'client_secret', value: CLIENT_SECRET } + ] + }, + headers: [ + { + name: 'Content-Type', + value: 'application/x-www-form-urlencoded' + }, + { + name: 'Accept', + value: 'application/x-www-form-urlencoded, application/json' + } + ] + } ] - }]]); + ]); // Check the expected value expect(result).toEqual({ diff --git a/packages/insomnia-app/app/network/o-auth-2/__tests__/helpers.js b/packages/insomnia-app/app/network/o-auth-2/__tests__/helpers.js index 52ac92cac8..b09ab91a17 100644 --- a/packages/insomnia-app/app/network/o-auth-2/__tests__/helpers.js +++ b/packages/insomnia-app/app/network/o-auth-2/__tests__/helpers.js @@ -1,8 +1,8 @@ import electron from 'electron'; import EventEmitter from 'events'; -export function createBWRedirectMock (redirectTo) { - electron.remote.BrowserWindow = jest.fn(function () { +export function createBWRedirectMock(redirectTo) { + electron.remote.BrowserWindow = jest.fn(function() { this._emitter = new EventEmitter(); this.loadURL = () => this.webContents.emit('did-navigate'); this.on = (event, cb) => this._emitter.on(event, cb); diff --git a/packages/insomnia-app/app/network/o-auth-2/get-token.js b/packages/insomnia-app/app/network/o-auth-2/get-token.js index 5b072d75af..c483b62c26 100644 --- a/packages/insomnia-app/app/network/o-auth-2/get-token.js +++ b/packages/insomnia-app/app/network/o-auth-2/get-token.js @@ -4,22 +4,41 @@ import getAccessTokenClientCredentials from './grant-client-credentials'; import getAccessTokenPassword from './grant-password'; import getAccessTokenImplicit from './grant-implicit'; import refreshAccessToken from './refresh-token'; -import {GRANT_TYPE_AUTHORIZATION_CODE, GRANT_TYPE_CLIENT_CREDENTIALS, GRANT_TYPE_IMPLICIT, GRANT_TYPE_PASSWORD, P_ACCESS_TOKEN, P_ERROR, P_ERROR_DESCRIPTION, P_ERROR_URI, P_EXPIRES_IN, P_REFRESH_TOKEN} from './constants'; +import { + GRANT_TYPE_AUTHORIZATION_CODE, + GRANT_TYPE_CLIENT_CREDENTIALS, + GRANT_TYPE_IMPLICIT, + GRANT_TYPE_PASSWORD, + P_ACCESS_TOKEN, + P_ERROR, + P_ERROR_DESCRIPTION, + P_ERROR_URI, + P_EXPIRES_IN, + P_REFRESH_TOKEN +} from './constants'; import * as models from '../../models'; -import type {RequestAuthentication} from '../../models/request'; -import type {OAuth2Token} from '../../models/o-auth-2-token'; +import type { RequestAuthentication } from '../../models/request'; +import type { OAuth2Token } from '../../models/o-auth-2-token'; /** Get an OAuth2Token object and also handle storing/saving/refreshing */ -export default async function ( +export default async function( requestId: string, authentication: RequestAuthentication, forceRefresh: boolean = false ): Promise { switch (authentication.grantType) { case GRANT_TYPE_AUTHORIZATION_CODE: - return _getOAuth2AuthorizationCodeHeader(requestId, authentication, forceRefresh); + return _getOAuth2AuthorizationCodeHeader( + requestId, + authentication, + forceRefresh + ); case GRANT_TYPE_CLIENT_CREDENTIALS: - return _getOAuth2ClientCredentialsHeader(requestId, authentication, forceRefresh); + return _getOAuth2ClientCredentialsHeader( + requestId, + authentication, + forceRefresh + ); case GRANT_TYPE_IMPLICIT: return _getOAuth2ImplicitHeader(requestId, authentication, forceRefresh); case GRANT_TYPE_PASSWORD: @@ -29,12 +48,16 @@ export default async function ( return null; } -async function _getOAuth2AuthorizationCodeHeader ( +async function _getOAuth2AuthorizationCodeHeader( requestId: string, authentication: RequestAuthentication, forceRefresh: boolean ): Promise { - const oAuth2Token = await _getAccessToken(requestId, authentication, forceRefresh); + const oAuth2Token = await _getAccessToken( + requestId, + authentication, + forceRefresh + ); if (oAuth2Token) { return oAuth2Token; @@ -55,12 +78,16 @@ async function _getOAuth2AuthorizationCodeHeader ( return _updateOAuth2Token(requestId, results); } -async function _getOAuth2ClientCredentialsHeader ( +async function _getOAuth2ClientCredentialsHeader( requestId: string, authentication: RequestAuthentication, forceRefresh: boolean ): Promise { - const oAuth2Token = await _getAccessToken(requestId, authentication, forceRefresh); + const oAuth2Token = await _getAccessToken( + requestId, + authentication, + forceRefresh + ); if (oAuth2Token) { return oAuth2Token; @@ -79,12 +106,16 @@ async function _getOAuth2ClientCredentialsHeader ( return _updateOAuth2Token(requestId, results); } -async function _getOAuth2ImplicitHeader ( +async function _getOAuth2ImplicitHeader( requestId: string, authentication: RequestAuthentication, forceRefresh: boolean ): Promise { - const oAuth2Token = await _getAccessToken(requestId, authentication, forceRefresh); + const oAuth2Token = await _getAccessToken( + requestId, + authentication, + forceRefresh + ); if (oAuth2Token) { return oAuth2Token; @@ -103,12 +134,16 @@ async function _getOAuth2ImplicitHeader ( return _updateOAuth2Token(requestId, results); } -async function _getOAuth2PasswordHeader ( +async function _getOAuth2PasswordHeader( requestId: string, authentication: RequestAuthentication, forceRefresh: boolean ): Promise { - const oAuth2Token = await _getAccessToken(requestId, authentication, forceRefresh); + const oAuth2Token = await _getAccessToken( + requestId, + authentication, + forceRefresh + ); if (oAuth2Token) { return oAuth2Token; @@ -128,7 +163,7 @@ async function _getOAuth2PasswordHeader ( return _updateOAuth2Token(requestId, results); } -async function _getAccessToken ( +async function _getAccessToken( requestId: string, authentication: RequestAuthentication, forceRefresh: boolean @@ -137,7 +172,9 @@ async function _getAccessToken ( // See if we have a token already // // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // - let token: OAuth2Token | null = await models.oAuth2Token.getByParentId(requestId); + let token: OAuth2Token | null = await models.oAuth2Token.getByParentId( + requestId + ); if (!token) { return null; @@ -182,12 +219,15 @@ async function _getAccessToken ( return _updateOAuth2Token(requestId, refreshResults); } -async function _updateOAuth2Token (requestId: string, authResults: Object): Promise { +async function _updateOAuth2Token( + requestId: string, + authResults: Object +): Promise { const oAuth2Token = await models.oAuth2Token.getOrCreateByParentId(requestId); // Calculate expiry date const expiresIn = authResults[P_EXPIRES_IN]; - const expiresAt = expiresIn ? (Date.now() + (expiresIn * 1000)) : null; + const expiresAt = expiresIn ? Date.now() + expiresIn * 1000 : null; return models.oAuth2Token.update(oAuth2Token, { expiresAt, diff --git a/packages/insomnia-app/app/network/o-auth-2/grant-authorization-code.js b/packages/insomnia-app/app/network/o-auth-2/grant-authorization-code.js index e29c85f83a..64a1886beb 100644 --- a/packages/insomnia-app/app/network/o-auth-2/grant-authorization-code.js +++ b/packages/insomnia-app/app/network/o-auth-2/grant-authorization-code.js @@ -1,14 +1,17 @@ // @flow -import {parse as urlParse} from 'url'; +import { parse as urlParse } from 'url'; import * as c from './constants'; -import {buildQueryStringFromParams, joinUrlAndQueryString} from 'insomnia-url'; -import {authorizeUserInWindow, responseToObject} from './misc'; -import {escapeRegex} from '../../common/misc'; +import { + buildQueryStringFromParams, + joinUrlAndQueryString +} from 'insomnia-url'; +import { authorizeUserInWindow, responseToObject } from './misc'; +import { escapeRegex } from '../../common/misc'; import * as models from '../../models/index'; -import {sendWithSettings} from '../network'; -import {getBasicAuthHeader} from '../basic-auth/get-header'; +import { sendWithSettings } from '../network'; +import { getBasicAuthHeader } from '../basic-auth/get-header'; -export default async function ( +export default async function( requestId: string, authorizeUrl: string, accessTokenUrl: string, @@ -55,16 +58,22 @@ export default async function ( ); } -async function _authorize (url, clientId, redirectUri = '', scope = '', state = '') { +async function _authorize( + url, + clientId, + redirectUri = '', + scope = '', + state = '' +) { const params = [ - {name: c.P_RESPONSE_TYPE, value: c.RESPONSE_TYPE_CODE}, - {name: c.P_CLIENT_ID, value: clientId} + { name: c.P_RESPONSE_TYPE, value: c.RESPONSE_TYPE_CODE }, + { name: c.P_CLIENT_ID, value: clientId } ]; // Add optional params - redirectUri && params.push({name: c.P_REDIRECT_URI, value: redirectUri}); - scope && params.push({name: c.P_SCOPE, value: scope}); - state && params.push({name: c.P_STATE, value: state}); + redirectUri && params.push({ name: c.P_REDIRECT_URI, value: redirectUri }); + scope && params.push({ name: c.P_SCOPE, value: scope }); + state && params.push({ name: c.P_STATE, value: state }); // Add query params to URL const qs = buildQueryStringFromParams(params); @@ -72,11 +81,15 @@ async function _authorize (url, clientId, redirectUri = '', scope = '', state = const successRegex = new RegExp(`${escapeRegex(redirectUri)}.*(code=)`, 'i'); const failureRegex = new RegExp(`${escapeRegex(redirectUri)}.*(error=)`, 'i'); - const redirectedTo = await authorizeUserInWindow(finalUrl, successRegex, failureRegex); + const redirectedTo = await authorizeUserInWindow( + finalUrl, + successRegex, + failureRegex + ); console.log('[oauth2] Detected redirect ' + redirectedTo); - const {query} = urlParse(redirectedTo); + const { query } = urlParse(redirectedTo); return responseToObject(query, [ c.P_CODE, c.P_STATE, @@ -86,7 +99,7 @@ async function _authorize (url, clientId, redirectUri = '', scope = '', state = ]); } -async function _getToken ( +async function _getToken( requestId: string, url: string, credentialsInBody: boolean, @@ -97,22 +110,25 @@ async function _getToken ( state: string = '' ): Promise { const params = [ - {name: c.P_GRANT_TYPE, value: c.GRANT_TYPE_AUTHORIZATION_CODE}, - {name: c.P_CODE, value: code} + { name: c.P_GRANT_TYPE, value: c.GRANT_TYPE_AUTHORIZATION_CODE }, + { name: c.P_CODE, value: code } ]; // Add optional params - redirectUri && params.push({name: c.P_REDIRECT_URI, value: redirectUri}); - state && params.push({name: c.P_STATE, value: state}); + redirectUri && params.push({ name: c.P_REDIRECT_URI, value: redirectUri }); + state && params.push({ name: c.P_STATE, value: state }); const headers = [ - {name: 'Content-Type', value: 'application/x-www-form-urlencoded'}, - {name: 'Accept', value: 'application/x-www-form-urlencoded, application/json'} + { name: 'Content-Type', value: 'application/x-www-form-urlencoded' }, + { + name: 'Accept', + value: 'application/x-www-form-urlencoded, application/json' + } ]; if (credentialsInBody) { - params.push({name: c.P_CLIENT_ID, value: clientId}); - params.push({name: c.P_CLIENT_SECRET, value: clientSecret}); + params.push({ name: c.P_CLIENT_ID, value: clientId }); + params.push({ name: c.P_CLIENT_SECRET, value: clientSecret }); } else { headers.push(getBasicAuthHeader(clientId, clientSecret)); } @@ -133,7 +149,7 @@ async function _getToken ( if (statusCode < 200 || statusCode >= 300) { throw new Error( `[oauth2] Failed to fetch token url=${url} status=${statusCode}\n` + - bodyBuffer.toString('utf8') + bodyBuffer.toString('utf8') ); } diff --git a/packages/insomnia-app/app/network/o-auth-2/grant-client-credentials.js b/packages/insomnia-app/app/network/o-auth-2/grant-client-credentials.js index 5f17905cde..3403435c01 100644 --- a/packages/insomnia-app/app/network/o-auth-2/grant-client-credentials.js +++ b/packages/insomnia-app/app/network/o-auth-2/grant-client-credentials.js @@ -1,12 +1,12 @@ // @flow -import {setDefaultProtocol} from 'insomnia-url'; +import { setDefaultProtocol } from 'insomnia-url'; import * as c from './constants'; -import {responseToObject} from './misc'; -import {sendWithSettings} from '../network'; +import { responseToObject } from './misc'; +import { sendWithSettings } from '../network'; import * as models from '../../models/index'; -import {getBasicAuthHeader} from '../basic-auth/get-header'; +import { getBasicAuthHeader } from '../basic-auth/get-header'; -export default async function ( +export default async function( requestId: string, accessTokenUrl: string, credentialsInBody: boolean, @@ -16,21 +16,24 @@ export default async function ( audience: string = '' ): Promise { const params = [ - {name: c.P_GRANT_TYPE, value: c.GRANT_TYPE_CLIENT_CREDENTIALS} + { name: c.P_GRANT_TYPE, value: c.GRANT_TYPE_CLIENT_CREDENTIALS } ]; // Add optional params - scope && params.push({name: c.P_SCOPE, value: scope}); - audience && params.push({name: c.P_AUDIENCE, value: audience}); + scope && params.push({ name: c.P_SCOPE, value: scope }); + audience && params.push({ name: c.P_AUDIENCE, value: audience }); const headers = [ - {name: 'Content-Type', value: 'application/x-www-form-urlencoded'}, - {name: 'Accept', value: 'application/x-www-form-urlencoded, application/json'} + { name: 'Content-Type', value: 'application/x-www-form-urlencoded' }, + { + name: 'Accept', + value: 'application/x-www-form-urlencoded, application/json' + } ]; if (credentialsInBody) { - params.push({name: c.P_CLIENT_ID, value: clientId}); - params.push({name: c.P_CLIENT_SECRET, value: clientSecret}); + params.push({ name: c.P_CLIENT_ID, value: clientId }); + params.push({ name: c.P_CLIENT_SECRET, value: clientSecret }); } else { headers.push(getBasicAuthHeader(clientId, clientSecret)); } @@ -51,7 +54,9 @@ export default async function ( const statusCode = response.statusCode || 0; if (statusCode < 200 || statusCode >= 300) { - throw new Error(`[oauth2] Failed to fetch token url=${url} status=${statusCode}`); + throw new Error( + `[oauth2] Failed to fetch token url=${url} status=${statusCode}` + ); } const results = responseToObject(bodyBuffer.toString('utf8'), [ diff --git a/packages/insomnia-app/app/network/o-auth-2/grant-implicit.js b/packages/insomnia-app/app/network/o-auth-2/grant-implicit.js index d9fbadf42c..5f461074a3 100644 --- a/packages/insomnia-app/app/network/o-auth-2/grant-implicit.js +++ b/packages/insomnia-app/app/network/o-auth-2/grant-implicit.js @@ -1,9 +1,12 @@ // @flow import * as c from './constants'; -import {buildQueryStringFromParams, joinUrlAndQueryString} from 'insomnia-url'; -import {responseToObject, authorizeUserInWindow} from './misc'; +import { + buildQueryStringFromParams, + joinUrlAndQueryString +} from 'insomnia-url'; +import { responseToObject, authorizeUserInWindow } from './misc'; -export default async function ( +export default async function( requestId: string, authorizationUrl: string, clientId: string, @@ -13,25 +16,32 @@ export default async function ( state: string = '' ): Promise { const params = [ - {name: c.P_RESPONSE_TYPE, value: responseType}, - {name: c.P_CLIENT_ID, value: clientId} + { name: c.P_RESPONSE_TYPE, value: responseType }, + { name: c.P_CLIENT_ID, value: clientId } ]; // Add optional params - if (responseType === c.RESPONSE_TYPE_ID_TOKEN_TOKEN || responseType === c.RESPONSE_TYPE_ID_TOKEN) { + if ( + responseType === c.RESPONSE_TYPE_ID_TOKEN_TOKEN || + responseType === c.RESPONSE_TYPE_ID_TOKEN + ) { const nonce = Math.floor(Math.random() * 9999999999999) + 1; - params.push({name: c.P_NONCE, value: nonce}); + params.push({ name: c.P_NONCE, value: nonce }); } - redirectUri && params.push({name: c.P_REDIRECT_URI, value: redirectUri}); - scope && params.push({name: c.P_SCOPE, value: scope}); - state && params.push({name: c.P_STATE, value: state}); + redirectUri && params.push({ name: c.P_REDIRECT_URI, value: redirectUri }); + scope && params.push({ name: c.P_SCOPE, value: scope }); + state && params.push({ name: c.P_STATE, value: state }); // Add query params to URL const qs = buildQueryStringFromParams(params); const finalUrl = joinUrlAndQueryString(authorizationUrl, qs); - const redirectedTo = await authorizeUserInWindow(finalUrl, /(access_token=)/, /(error=)/); + const redirectedTo = await authorizeUserInWindow( + finalUrl, + /(access_token=)/, + /(error=)/ + ); const fragment = redirectedTo.split('#')[1]; if (fragment) { diff --git a/packages/insomnia-app/app/network/o-auth-2/grant-password.js b/packages/insomnia-app/app/network/o-auth-2/grant-password.js index ee25dde69b..1852964574 100644 --- a/packages/insomnia-app/app/network/o-auth-2/grant-password.js +++ b/packages/insomnia-app/app/network/o-auth-2/grant-password.js @@ -1,12 +1,12 @@ // @flow -import {setDefaultProtocol} from 'insomnia-url'; +import { setDefaultProtocol } from 'insomnia-url'; import * as c from './constants'; -import {responseToObject} from './misc'; +import { responseToObject } from './misc'; import * as network from '../network'; import * as models from '../../models/index'; -import {getBasicAuthHeader} from '../basic-auth/get-header'; +import { getBasicAuthHeader } from '../basic-auth/get-header'; -export default async function ( +export default async function( requestId: string, accessTokenUrl: string, credentialsInBody: boolean, @@ -17,22 +17,25 @@ export default async function ( scope: string = '' ): Promise { const params = [ - {name: c.P_GRANT_TYPE, value: c.GRANT_TYPE_PASSWORD}, - {name: c.P_USERNAME, value: username}, - {name: c.P_PASSWORD, value: password} + { name: c.P_GRANT_TYPE, value: c.GRANT_TYPE_PASSWORD }, + { name: c.P_USERNAME, value: username }, + { name: c.P_PASSWORD, value: password } ]; // Add optional params - scope && params.push({name: c.P_SCOPE, value: scope}); + scope && params.push({ name: c.P_SCOPE, value: scope }); const headers = [ - {name: 'Content-Type', value: 'application/x-www-form-urlencoded'}, - {name: 'Accept', value: 'application/x-www-form-urlencoded, application/json'} + { name: 'Content-Type', value: 'application/x-www-form-urlencoded' }, + { + name: 'Accept', + value: 'application/x-www-form-urlencoded, application/json' + } ]; if (credentialsInBody) { - params.push({name: c.P_CLIENT_ID, value: clientId}); - params.push({name: c.P_CLIENT_SECRET, value: clientSecret}); + params.push({ name: c.P_CLIENT_ID, value: clientId }); + params.push({ name: c.P_CLIENT_SECRET, value: clientSecret }); } else { headers.push(getBasicAuthHeader(clientId, clientSecret)); } @@ -53,7 +56,9 @@ export default async function ( const statusCode = response.statusCode || 0; if (statusCode < 200 || statusCode >= 300) { - throw new Error(`[oauth2] Failed to fetch access token url=${url} status=${statusCode}`); + throw new Error( + `[oauth2] Failed to fetch access token url=${url} status=${statusCode}` + ); } const results = responseToObject(bodyBuffer.toString(), [ diff --git a/packages/insomnia-app/app/network/o-auth-2/misc.js b/packages/insomnia-app/app/network/o-auth-2/misc.js index 51c28199e5..878481a6de 100644 --- a/packages/insomnia-app/app/network/o-auth-2/misc.js +++ b/packages/insomnia-app/app/network/o-auth-2/misc.js @@ -4,18 +4,16 @@ import querystring from 'querystring'; const AUTH_WINDOW_SESSION_ID = uuid.v4(); -export function responseToObject (body, keys) { +export function responseToObject(body, keys) { let data = null; try { data = JSON.parse(body); - } catch (err) { - } + } catch (err) {} if (!data) { try { data = querystring.parse(body); - } catch (err) { - } + } catch (err) {} } let results = {}; @@ -26,7 +24,7 @@ export function responseToObject (body, keys) { return results; } -export function authorizeUserInWindow ( +export function authorizeUserInWindow( url, urlSuccessRegex = /(code=).*/, urlFailureRegex = /(error=).*/ @@ -34,20 +32,26 @@ export function authorizeUserInWindow ( return new Promise((resolve, reject) => { let finalUrl = null; - function _parseUrl (currentUrl) { + function _parseUrl(currentUrl) { if (currentUrl.match(urlSuccessRegex)) { - console.log(`[oauth2] Matched success redirect to "${currentUrl}" with ${urlSuccessRegex.toString()}`); + console.log( + `[oauth2] Matched success redirect to "${currentUrl}" with ${urlSuccessRegex.toString()}` + ); finalUrl = currentUrl; child.close(); } else if (currentUrl.match(urlFailureRegex)) { - console.log(`[oauth2] Matched error redirect to "${currentUrl}" with ${urlFailureRegex.toString()}`); + console.log( + `[oauth2] Matched error redirect to "${currentUrl}" with ${urlFailureRegex.toString()}` + ); finalUrl = currentUrl; child.close(); } else if (currentUrl === url) { // It's the first one, so it's not a redirect console.log(`[oauth2] Loaded "${currentUrl}"`); } else { - console.log(`[oauth2] Ignoring URL "${currentUrl}". Didn't match ${urlSuccessRegex.toString()}`); + console.log( + `[oauth2] Ignoring URL "${currentUrl}". Didn't match ${urlSuccessRegex.toString()}` + ); } } @@ -77,10 +81,13 @@ export function authorizeUserInWindow ( _parseUrl(currentUrl); }); - child.webContents.on('did-fail-load', (e, errorCode, errorDescription, url) => { - // Listen for did-fail-load to be able to parse the URL even when the callback server is unreachable - _parseUrl(url); - }); + child.webContents.on( + 'did-fail-load', + (e, errorCode, errorDescription, url) => { + // Listen for did-fail-load to be able to parse the URL even when the callback server is unreachable + _parseUrl(url); + } + ); // Show the window to the user after it loads child.on('ready-to-show', child.show.bind(child)); diff --git a/packages/insomnia-app/app/network/o-auth-2/refresh-token.js b/packages/insomnia-app/app/network/o-auth-2/refresh-token.js index cfc6f6d9a9..da46580e4c 100644 --- a/packages/insomnia-app/app/network/o-auth-2/refresh-token.js +++ b/packages/insomnia-app/app/network/o-auth-2/refresh-token.js @@ -1,12 +1,12 @@ // @flow import * as c from './constants'; -import {responseToObject} from './misc'; -import {setDefaultProtocol} from 'insomnia-url'; +import { responseToObject } from './misc'; +import { setDefaultProtocol } from 'insomnia-url'; import * as models from '../../models/index'; -import {sendWithSettings} from '../network'; -import {getBasicAuthHeader} from '../basic-auth/get-header'; +import { sendWithSettings } from '../network'; +import { getBasicAuthHeader } from '../basic-auth/get-header'; -export default async function ( +export default async function( requestId: string, accessTokenUrl: string, credentialsInBody: boolean, @@ -16,21 +16,24 @@ export default async function ( scope: string ): Promise { const params = [ - {name: c.P_GRANT_TYPE, value: c.GRANT_TYPE_REFRESH}, - {name: c.P_REFRESH_TOKEN, value: refreshToken} + { name: c.P_GRANT_TYPE, value: c.GRANT_TYPE_REFRESH }, + { name: c.P_REFRESH_TOKEN, value: refreshToken } ]; // Add optional params - scope && params.push({name: c.P_SCOPE, value: scope}); + scope && params.push({ name: c.P_SCOPE, value: scope }); const headers = [ - {name: 'Content-Type', value: 'application/x-www-form-urlencoded'}, - {name: 'Accept', value: 'application/x-www-form-urlencoded, application/json'} + { name: 'Content-Type', value: 'application/x-www-form-urlencoded' }, + { + name: 'Accept', + value: 'application/x-www-form-urlencoded, application/json' + } ]; if (credentialsInBody) { - params.push({name: c.P_CLIENT_ID, value: clientId}); - params.push({name: c.P_CLIENT_SECRET, value: clientSecret}); + params.push({ name: c.P_CLIENT_ID, value: clientId }); + params.push({ name: c.P_CLIENT_SECRET, value: clientSecret }); } else { headers.push(getBasicAuthHeader(clientId, clientSecret)); } @@ -46,7 +49,9 @@ export default async function ( const statusCode = response.statusCode || 0; if (statusCode < 200 || statusCode >= 300) { - throw new Error(`[oauth2] Failed to refresh token url=${url} status=${statusCode}`); + throw new Error( + `[oauth2] Failed to refresh token url=${url} status=${statusCode}` + ); } const bodyBuffer = models.response.getBodyBuffer(response); diff --git a/packages/insomnia-app/app/network/url-matches-cert-host.js b/packages/insomnia-app/app/network/url-matches-cert-host.js index 24245b2555..ac0cd5931a 100644 --- a/packages/insomnia-app/app/network/url-matches-cert-host.js +++ b/packages/insomnia-app/app/network/url-matches-cert-host.js @@ -1,14 +1,16 @@ -import {parse as urlParse} from 'url'; +import { parse as urlParse } from 'url'; import certificateUrlParse from './certificate-url-parse'; -import {escapeRegex} from '../common/misc'; -import {setDefaultProtocol} from 'insomnia-url'; +import { escapeRegex } from '../common/misc'; +import { setDefaultProtocol } from 'insomnia-url'; const DEFAULT_PORT = 443; -export function urlMatchesCertHost (certificateHost, requestUrl) { +export function urlMatchesCertHost(certificateHost, requestUrl) { const cHostWithProtocol = setDefaultProtocol(certificateHost, 'https:'); - const {hostname, port} = urlParse(requestUrl); - const {hostname: cHostname, port: cPort} = certificateUrlParse(cHostWithProtocol); + const { hostname, port } = urlParse(requestUrl); + const { hostname: cHostname, port: cPort } = certificateUrlParse( + cHostWithProtocol + ); const assumedPort = parseInt(port) || DEFAULT_PORT; const assumedCPort = parseInt(cPort) || DEFAULT_PORT; diff --git a/packages/insomnia-app/app/plugins/context/__tests__/app.test.js b/packages/insomnia-app/app/plugins/context/__tests__/app.test.js index e9ba41b9d2..8641afd157 100644 --- a/packages/insomnia-app/app/plugins/context/__tests__/app.test.js +++ b/packages/insomnia-app/app/plugins/context/__tests__/app.test.js @@ -1,7 +1,7 @@ import * as plugin from '../app'; import * as modals from '../../../ui/components/modals'; -import {globalBeforeEach} from '../../../__jest__/before-each'; -import {RENDER_PURPOSE_SEND} from '../../../common/render'; +import { globalBeforeEach } from '../../../__jest__/before-each'; +import { RENDER_PURPOSE_SEND } from '../../../common/render'; describe('init()', () => { beforeEach(globalBeforeEach); @@ -39,8 +39,8 @@ describe('app.alert()', () => { // Make sure it passes correct arguments expect(modals.showAlert.mock.calls).toEqual([ - [{title: 'Title'}], - [{title: 'Title', message: 'Message'}] + [{ title: 'Title' }], + [{ title: 'Title', message: 'Message' }] ]); }); }); @@ -63,12 +63,25 @@ describe('app.prompt()', () => { // Make sure it returns result of showAlert() result.app.prompt('Title'); - result.app.prompt('Title', {label: 'Label'}); + result.app.prompt('Title', { label: 'Label' }); // Make sure it passes correct arguments expect(modals.showPrompt.mock.calls).toEqual([ - [{title: 'Title', onComplete: expect.any(Function), onCancel: expect.any(Function)}], - [{title: 'Title', label: 'Label', onComplete: expect.any(Function), onCancel: expect.any(Function)}] + [ + { + title: 'Title', + onComplete: expect.any(Function), + onCancel: expect.any(Function) + } + ], + [ + { + title: 'Title', + label: 'Label', + onComplete: expect.any(Function), + onCancel: expect.any(Function) + } + ] ]); }); }); diff --git a/packages/insomnia-app/app/plugins/context/__tests__/data.test.js b/packages/insomnia-app/app/plugins/context/__tests__/data.test.js index a485d2d6fb..a9188a0fb3 100644 --- a/packages/insomnia-app/app/plugins/context/__tests__/data.test.js +++ b/packages/insomnia-app/app/plugins/context/__tests__/data.test.js @@ -1,11 +1,11 @@ import * as plugin from '../data'; import * as modals from '../../../ui/components/modals'; import path from 'path'; -import {globalBeforeEach} from '../../../__jest__/before-each'; +import { globalBeforeEach } from '../../../__jest__/before-each'; import * as models from '../../../models/index'; import * as db from '../../../common/database'; import fs from 'fs'; -import {getAppVersion} from '../../../common/constants'; +import { getAppVersion } from '../../../common/constants'; const PLUGIN = { name: 'my-plugin', @@ -17,16 +17,10 @@ const PLUGIN = { describe('init()', () => { beforeEach(globalBeforeEach); it('initializes correctly', async () => { - const result = plugin.init({name: PLUGIN}); + const result = plugin.init({ name: PLUGIN }); expect(Object.keys(result)).toEqual(['import', 'export']); - expect(Object.keys(result.export).sort()).toEqual([ - 'har', - 'insomnia' - ]); - expect(Object.keys(result.import).sort()).toEqual([ - 'raw', - 'uri' - ]); + expect(Object.keys(result.export).sort()).toEqual(['har', 'insomnia']); + expect(Object.keys(result.import).sort()).toEqual(['raw', 'uri']); }); }); @@ -46,7 +40,10 @@ describe('app.import.*', () => { expect(await db.count(models.request.type)).toBe(0); const result = plugin.init(PLUGIN); - const filename = path.resolve(__dirname, '../__fixtures__/basic-import.json'); + const filename = path.resolve( + __dirname, + '../__fixtures__/basic-import.json' + ); await result.import.uri(`file://${filename}`); const allWorkspaces = await db.all(models.workspace.type); @@ -62,29 +59,31 @@ describe('app.import.*', () => { type: 'Workspace' } ]); - expect(await db.all(models.request.type)).toEqual([{ - _id: 'req_imported_1', - isPrivate: false, - authentication: {}, - body: {}, - created: 111, - description: '', - headers: [], - metaSortKey: 0, - method: 'GET', - modified: 222, - name: 'Test', - parameters: [], - parentId: 'wrk_imported_1', - settingDisableRenderRequestBody: false, - settingEncodeUrl: true, - settingSendCookies: true, - settingStoreCookies: true, - settingRebuildPath: true, - settingMaxTimelineDataSize: 1000, - type: 'Request', - url: 'https://insomnia.rest' - }]); + expect(await db.all(models.request.type)).toEqual([ + { + _id: 'req_imported_1', + isPrivate: false, + authentication: {}, + body: {}, + created: 111, + description: '', + headers: [], + metaSortKey: 0, + method: 'GET', + modified: 222, + name: 'Test', + parameters: [], + parentId: 'wrk_imported_1', + settingDisableRenderRequestBody: false, + settingEncodeUrl: true, + settingSendCookies: true, + settingStoreCookies: true, + settingRebuildPath: true, + settingMaxTimelineDataSize: 1000, + type: 'Request', + url: 'https://insomnia.rest' + } + ]); }); it('importRaw', async () => { @@ -94,7 +93,10 @@ describe('app.import.*', () => { expect(await db.count(models.request.type)).toBe(0); const result = plugin.init(PLUGIN); - const filename = path.resolve(__dirname, '../__fixtures__/basic-import.json'); + const filename = path.resolve( + __dirname, + '../__fixtures__/basic-import.json' + ); await result.import.raw(fs.readFileSync(filename, 'utf8')); const allWorkspaces = await db.all(models.workspace.type); @@ -110,29 +112,31 @@ describe('app.import.*', () => { type: 'Workspace' } ]); - expect(await db.all(models.request.type)).toEqual([{ - _id: 'req_imported_1', - isPrivate: false, - authentication: {}, - body: {}, - created: 111, - description: '', - headers: [], - metaSortKey: 0, - method: 'GET', - modified: 222, - name: 'Test', - parameters: [], - parentId: 'wrk_imported_1', - settingDisableRenderRequestBody: false, - settingEncodeUrl: true, - settingSendCookies: true, - settingStoreCookies: true, - settingRebuildPath: true, - settingMaxTimelineDataSize: 1000, - type: 'Request', - url: 'https://insomnia.rest' - }]); + expect(await db.all(models.request.type)).toEqual([ + { + _id: 'req_imported_1', + isPrivate: false, + authentication: {}, + body: {}, + created: 111, + description: '', + headers: [], + metaSortKey: 0, + method: 'GET', + modified: 222, + name: 'Test', + parameters: [], + parentId: 'wrk_imported_1', + settingDisableRenderRequestBody: false, + settingEncodeUrl: true, + settingSendCookies: true, + settingStoreCookies: true, + settingRebuildPath: true, + settingMaxTimelineDataSize: 1000, + type: 'Request', + url: 'https://insomnia.rest' + } + ]); }); }); @@ -173,37 +177,40 @@ describe('app.export.*', () => { __export_format: 3, __export_source: `insomnia.desktop.app:v${getAppVersion()}`, _type: 'export', - resources: [{ - _id: 'wrk_1', - _type: 'workspace', - created: 111, - description: '', - modified: 222, - name: 'New Workspace', - parentId: null - }, { - _id: 'req_1', - _type: 'request', - isPrivate: false, - authentication: {}, - body: {}, - created: 111, - description: '', - headers: [], - metaSortKey: 0, - method: 'GET', - modified: 222, - name: 'New Request', - parameters: [], - parentId: 'wrk_1', - settingDisableRenderRequestBody: false, - settingEncodeUrl: true, - settingSendCookies: true, - settingStoreCookies: true, - settingRebuildPath: true, - settingMaxTimelineDataSize: 1000, - url: 'https://insomnia.rest' - }] + resources: [ + { + _id: 'wrk_1', + _type: 'workspace', + created: 111, + description: '', + modified: 222, + name: 'New Workspace', + parentId: null + }, + { + _id: 'req_1', + _type: 'request', + isPrivate: false, + authentication: {}, + body: {}, + created: 111, + description: '', + headers: [], + metaSortKey: 0, + method: 'GET', + modified: 222, + name: 'New Request', + parameters: [], + parentId: 'wrk_1', + settingDisableRenderRequestBody: false, + settingEncodeUrl: true, + settingSendCookies: true, + settingStoreCookies: true, + settingRebuildPath: true, + settingMaxTimelineDataSize: 1000, + url: 'https://insomnia.rest' + } + ] }); }); @@ -214,64 +221,62 @@ describe('app.export.*', () => { const exported = await result.export.har(); const exportedData = JSON.parse(exported); exportedData.log.entries[0].startedDateTime = '2017-11-24T18:12:12.849Z'; - expect(exportedData).toEqual( - { - log: { - creator: { - name: 'Insomnia REST Client', - version: `insomnia.desktop.app:v${getAppVersion()}` - }, - entries: [ - { - cache: {}, - comment: 'New Request', - request: { - bodySize: -1, - cookies: [], - headers: [], - headersSize: -1, - httpVersion: 'HTTP/1.1', - method: 'GET', - postData: { - mimeType: '', - params: [], - text: '' - }, - queryString: [], - url: 'https://insomnia.rest/', - settingEncodeUrl: true + expect(exportedData).toEqual({ + log: { + creator: { + name: 'Insomnia REST Client', + version: `insomnia.desktop.app:v${getAppVersion()}` + }, + entries: [ + { + cache: {}, + comment: 'New Request', + request: { + bodySize: -1, + cookies: [], + headers: [], + headersSize: -1, + httpVersion: 'HTTP/1.1', + method: 'GET', + postData: { + mimeType: '', + params: [], + text: '' }, - response: { - bodySize: -1, - content: { - mimeType: '', - size: 3, - text: 'foo' - }, - cookies: [], - headers: [], - headersSize: -1, - httpVersion: 'HTTP/1.1', - redirectURL: '', - status: 200, - statusText: '' + queryString: [], + url: 'https://insomnia.rest/', + settingEncodeUrl: true + }, + response: { + bodySize: -1, + content: { + mimeType: '', + size: 3, + text: 'foo' }, - startedDateTime: '2017-11-24T18:12:12.849Z', - time: 0, - timings: { - blocked: -1, - connect: -1, - dns: -1, - receive: 0, - send: 0, - ssl: -1, - wait: 0 - } + cookies: [], + headers: [], + headersSize: -1, + httpVersion: 'HTTP/1.1', + redirectURL: '', + status: 200, + statusText: '' + }, + startedDateTime: '2017-11-24T18:12:12.849Z', + time: 0, + timings: { + blocked: -1, + connect: -1, + dns: -1, + receive: 0, + send: 0, + ssl: -1, + wait: 0 } - ], - version: '1.2' - } + } + ], + version: '1.2' } - ); + }); }); }); diff --git a/packages/insomnia-app/app/plugins/context/__tests__/request.test.js b/packages/insomnia-app/app/plugins/context/__tests__/request.test.js index 60262c3ffb..95d4370819 100644 --- a/packages/insomnia-app/app/plugins/context/__tests__/request.test.js +++ b/packages/insomnia-app/app/plugins/context/__tests__/request.test.js @@ -1,20 +1,24 @@ import * as plugin from '../request'; import * as models from '../../../models'; -import {globalBeforeEach} from '../../../__jest__/before-each'; +import { globalBeforeEach } from '../../../__jest__/before-each'; const CONTEXT = { user_key: 'my_user_key', hello: 'world', array_test: ['a', 'b'], - object_test: {a: 'A', b: 'B'}, + object_test: { a: 'A', b: 'B' }, null_test: null }; describe('init()', () => { beforeEach(async () => { await globalBeforeEach(); - await models.workspace.create({_id: 'wrk_1', name: 'My Workspace'}); - await models.request.create({_id: 'req_1', parentId: 'wrk_1', name: 'My Request'}); + await models.workspace.create({ _id: 'wrk_1', name: 'My Workspace' }); + await models.request.create({ + _id: 'req_1', + parentId: 'wrk_1', + name: 'My Request' + }); }); it('initializes correctly', async () => { @@ -50,7 +54,11 @@ describe('init()', () => { }); it('initializes correctly in read-only mode', async () => { - const result = plugin.init(await models.request.getById('req_1'), CONTEXT, true); + const result = plugin.init( + await models.request.getById('req_1'), + CONTEXT, + true + ); expect(Object.keys(result)).toEqual(['request']); expect(Object.keys(result.request).sort()).toEqual([ 'getBodyText', @@ -70,27 +78,28 @@ describe('init()', () => { }); it('fails to initialize without request', () => { - expect(() => plugin.init()) - .toThrowError('contexts.request initialized without request'); + expect(() => plugin.init()).toThrowError( + 'contexts.request initialized without request' + ); }); }); describe('request.*', () => { beforeEach(async () => { await globalBeforeEach(); - await models.workspace.create({_id: 'wrk_1', name: 'My Workspace'}); + await models.workspace.create({ _id: 'wrk_1', name: 'My Workspace' }); await models.request.create({ _id: 'req_1', parentId: 'wrk_1', name: 'My Request', - body: {text: 'body'}, + body: { text: 'body' }, headers: [ - {name: 'hello', value: 'world'}, - {name: 'Content-Type', value: 'application/json'} + { name: 'hello', value: 'world' }, + { name: 'Content-Type', value: 'application/json' } ], parameters: [ - {name: 'foo', value: 'bar'}, - {name: 'message', value: 'Hello World!'} + { name: 'foo', value: 'bar' }, + { name: 'message', value: 'Hello World!' } ] }); }); @@ -109,8 +118,8 @@ describe('request.*', () => { // getParameters() expect(result.request.getParameters()).toEqual([ - {name: 'foo', value: 'bar'}, - {name: 'message', value: 'Hello World!'} + { name: 'foo', value: 'bar' }, + { name: 'message', value: 'Hello World!' } ]); // getParameter() @@ -140,8 +149,8 @@ describe('request.*', () => { // getHeaders() expect(result.request.getHeaders()).toEqual([ - {name: 'hello', value: 'world'}, - {name: 'Content-Type', value: 'application/json'} + { name: 'hello', value: 'world' }, + { name: 'Content-Type', value: 'application/json' } ]); // getHeader() @@ -174,7 +183,7 @@ describe('request.*', () => { result.request.setCookie('foo', 'bar'); result.request.setCookie('foo', 'baz'); - expect(request.cookies).toEqual([{name: 'foo', value: 'baz'}]); + expect(request.cookies).toEqual([{ name: 'foo', value: 'baz' }]); }); it('works for environment', async () => { @@ -188,15 +197,23 @@ describe('request.*', () => { user_key: 'my_user_key', hello: 'world', array_test: ['a', 'b'], - object_test: {a: 'A', b: 'B'}, + object_test: { a: 'A', b: 'B' }, null_test: null }); // getEnvironmentVariable - expect(result.request.getEnvironmentVariable('user_key')).toBe('my_user_key'); + expect(result.request.getEnvironmentVariable('user_key')).toBe( + 'my_user_key' + ); expect(result.request.getEnvironmentVariable('hello')).toBe('world'); - expect(result.request.getEnvironmentVariable('array_test')).toEqual(['a', 'b']); - expect(result.request.getEnvironmentVariable('object_test')).toEqual({a: 'A', b: 'B'}); + expect(result.request.getEnvironmentVariable('array_test')).toEqual([ + 'a', + 'b' + ]); + expect(result.request.getEnvironmentVariable('object_test')).toEqual({ + a: 'A', + b: 'B' + }); expect(result.request.getEnvironmentVariable('null_test')).toBe(null); expect(result.request.getEnvironmentVariable('bad')).toBeUndefined(); }); diff --git a/packages/insomnia-app/app/plugins/context/__tests__/response.test.js b/packages/insomnia-app/app/plugins/context/__tests__/response.test.js index ec1c8b6204..59df52c802 100644 --- a/packages/insomnia-app/app/plugins/context/__tests__/response.test.js +++ b/packages/insomnia-app/app/plugins/context/__tests__/response.test.js @@ -1,6 +1,6 @@ import * as plugin from '../response'; -import {globalBeforeEach} from '../../../__jest__/before-each'; -import {getTempDir} from '../../../common/constants'; +import { globalBeforeEach } from '../../../__jest__/before-each'; +import { getTempDir } from '../../../common/constants'; import fs from 'fs'; import path from 'path'; import * as models from '../../../models/index'; @@ -25,8 +25,9 @@ describe('init()', () => { }); it('fails to initialize without response', () => { - expect(() => plugin.init()) - .toThrowError('contexts.response initialized without response'); + expect(() => plugin.init()).toThrowError( + 'contexts.response initialized without response' + ); }); }); @@ -65,15 +66,18 @@ describe('response.*', () => { it('works for getting headers', () => { const response = { headers: [ - {name: 'content-type', value: 'application/json'}, - {name: 'set-cookie', value: 'foo=bar'}, - {name: 'set-cookie', value: 'baz=qux'} + { name: 'content-type', value: 'application/json' }, + { name: 'set-cookie', value: 'foo=bar' }, + { name: 'set-cookie', value: 'baz=qux' } ] }; const result = plugin.init(response); expect(result.response.getHeader('Does-Not-Exist')).toBeNull(); expect(result.response.getHeader('CONTENT-TYPE')).toBe('application/json'); - expect(result.response.getHeader('set-cookie')).toEqual(['foo=bar', 'baz=qux']); + expect(result.response.getHeader('set-cookie')).toEqual([ + 'foo=bar', + 'baz=qux' + ]); expect(result.response.hasHeader('foo')).toBe(false); expect(result.response.hasHeader('ConTent-Type')).toBe(true); }); diff --git a/packages/insomnia-app/app/plugins/context/__tests__/store.test.js b/packages/insomnia-app/app/plugins/context/__tests__/store.test.js index dec0cb9fca..00dee256ba 100644 --- a/packages/insomnia-app/app/plugins/context/__tests__/store.test.js +++ b/packages/insomnia-app/app/plugins/context/__tests__/store.test.js @@ -1,5 +1,5 @@ import * as plugin from '../store'; -import {globalBeforeEach} from '../../../__jest__/before-each'; +import { globalBeforeEach } from '../../../__jest__/before-each'; const PLUGIN = { name: 'my-plugin', @@ -11,7 +11,7 @@ const PLUGIN = { describe('init()', () => { beforeEach(globalBeforeEach); it('initializes correctly', async () => { - const result = plugin.init({name: PLUGIN}); + const result = plugin.init({ name: PLUGIN }); expect(Object.keys(result.store).sort()).toEqual([ 'getItem', 'hasItem', diff --git a/packages/insomnia-app/app/plugins/context/app.js b/packages/insomnia-app/app/plugins/context/app.js index d84e1acdde..4df50f3799 100644 --- a/packages/insomnia-app/app/plugins/context/app.js +++ b/packages/insomnia-app/app/plugins/context/app.js @@ -1,20 +1,25 @@ // @flow import * as electron from 'electron'; -import {showAlert, showPrompt} from '../../ui/components/modals/index'; -import type {RenderPurpose} from '../../common/render'; -import {RENDER_PURPOSE_GENERAL, RENDER_PURPOSE_SEND} from '../../common/render'; +import { showAlert, showPrompt } from '../../ui/components/modals/index'; +import type { RenderPurpose } from '../../common/render'; +import { + RENDER_PURPOSE_GENERAL, + RENDER_PURPOSE_SEND +} from '../../common/render'; -export function init (renderPurpose: RenderPurpose = RENDER_PURPOSE_GENERAL): {app: Object} { +export function init( + renderPurpose: RenderPurpose = RENDER_PURPOSE_GENERAL +): { app: Object } { return { app: { - alert (title: string, message?: string): Promise { + alert(title: string, message?: string): Promise { if (renderPurpose !== RENDER_PURPOSE_SEND) { return Promise.resolve(); } - return showAlert({title, message}); + return showAlert({ title, message }); }, - prompt ( + prompt( title: string, options?: { label?: string, @@ -33,16 +38,16 @@ export function init (renderPurpose: RenderPurpose = RENDER_PURPOSE_GENERAL): {a showPrompt({ title, ...(options || {}), - onCancel () { + onCancel() { reject(new Error(`Prompt ${title} cancelled`)); }, - onComplete (value: string) { + onComplete(value: string) { resolve(value); } }); }); }, - getPath (name: string): string { + getPath(name: string): string { switch (name.toLowerCase()) { case 'desktop': return electron.remote.app.getPath('desktop'); @@ -50,7 +55,9 @@ export function init (renderPurpose: RenderPurpose = RENDER_PURPOSE_GENERAL): {a throw new Error(`Unknown path name ${name}`); } }, - async showSaveDialog (options: {defaultPath?: string} = {}): Promise { + async showSaveDialog( + options: { defaultPath?: string } = {} + ): Promise { if (renderPurpose !== RENDER_PURPOSE_SEND) { return Promise.resolve(null); } diff --git a/packages/insomnia-app/app/plugins/context/data.js b/packages/insomnia-app/app/plugins/context/data.js index 6a38d09065..92aeffe83a 100644 --- a/packages/insomnia-app/app/plugins/context/data.js +++ b/packages/insomnia-app/app/plugins/context/data.js @@ -1,22 +1,35 @@ // @flow -import {exportHAR, exportJSON, importRaw, importUri} from '../../common/import'; +import { + exportHAR, + exportJSON, + importRaw, + importUri +} from '../../common/import'; -export function init (): {'import': Object, 'export': Object} { +export function init(): { import: Object, export: Object } { return { - 'import': { - async uri (uri: string, options: {workspaceId?: string} = {}): Promise { + import: { + async uri( + uri: string, + options: { workspaceId?: string } = {} + ): Promise { await importUri(options.workspaceId || null, uri); }, - async raw (text: string, options: {workspaceId?: string} = {}): Promise { + async raw( + text: string, + options: { workspaceId?: string } = {} + ): Promise { await importRaw(options.workspaceId || null, text); } }, - 'export': { - async insomnia (options: {includePrivate?: boolean} = {}): Promise { + export: { + async insomnia( + options: { includePrivate?: boolean } = {} + ): Promise { options = options || {}; return exportJSON(null, options.includePrivate); }, - async har (options: {includePrivate?: boolean} = {}): Promise { + async har(options: { includePrivate?: boolean } = {}): Promise { return exportHAR(null, options.includePrivate); } } diff --git a/packages/insomnia-app/app/plugins/context/request.js b/packages/insomnia-app/app/plugins/context/request.js index c7c1dd35e6..c892c58e4e 100644 --- a/packages/insomnia-app/app/plugins/context/request.js +++ b/packages/insomnia-app/app/plugins/context/request.js @@ -1,8 +1,8 @@ // @flow -import type {RenderedRequest} from '../../common/render'; +import type { RenderedRequest } from '../../common/render'; import * as misc from '../../common/misc'; -export function init ( +export function init( renderedRequest: RenderedRequest, renderedContext: Object, readOnly: boolean = false @@ -12,51 +12,53 @@ export function init ( } const request = { - getId (): string { + getId(): string { return renderedRequest._id; }, - getBodyText (): string { + getBodyText(): string { return renderedRequest.body.text || ''; }, - getName (): string { + getName(): string { return renderedRequest.name; }, - getUrl (): string { + getUrl(): string { return renderedRequest.url; }, - getMethod (): string { + getMethod(): string { return renderedRequest.method; }, - setBodyText (text: string): void { + setBodyText(text: string): void { renderedRequest.body.text = text; }, - setCookie (name: string, value: string): void { + setCookie(name: string, value: string): void { const cookie = renderedRequest.cookies.find(c => c.name === name); if (cookie) { cookie.value = value; } else { - renderedRequest.cookies.push({name, value}); + renderedRequest.cookies.push({ name, value }); } }, - getEnvironmentVariable (name: string): string | number | boolean | Object | Array | null { + getEnvironmentVariable( + name: string + ): string | number | boolean | Object | Array | null { return renderedContext[name]; }, - getEnvironment (): Object { + getEnvironment(): Object { return renderedContext; }, - settingSendCookies (enabled: boolean) { + settingSendCookies(enabled: boolean) { renderedRequest.settingSendCookies = enabled; }, - settingStoreCookies (enabled: boolean) { + settingStoreCookies(enabled: boolean) { renderedRequest.settingStoreCookies = enabled; }, - settingEncodeUrl (enabled: boolean) { + settingEncodeUrl(enabled: boolean) { renderedRequest.settingEncodeUrl = enabled; }, - settingDisableRenderRequestBody (enabled: boolean) { + settingDisableRenderRequestBody(enabled: boolean) { renderedRequest.settingDisableRenderRequestBody = enabled; }, - getHeader (name: string): string | null { + getHeader(name: string): string | null { const headers = misc.filterHeaders(renderedRequest.headers, name); if (headers.length) { // Use the last header if there are multiple of the same @@ -66,19 +68,22 @@ export function init ( return null; } }, - getHeaders (): Array<{ name: string, value: string }> { - return renderedRequest.headers.map(h => ({name: h.name, value: h.value})); + getHeaders(): Array<{ name: string, value: string }> { + return renderedRequest.headers.map(h => ({ + name: h.name, + value: h.value + })); }, - hasHeader (name: string): boolean { + hasHeader(name: string): boolean { return this.getHeader(name) !== null; }, - removeHeader (name: string): void { + removeHeader(name: string): void { const headers = misc.filterHeaders(renderedRequest.headers, name); renderedRequest.headers = renderedRequest.headers.filter( h => !headers.includes(h) ); }, - setHeader (name: string, value: string): void { + setHeader(name: string, value: string): void { const header = misc.filterHeaders(renderedRequest.headers, name)[0]; if (header) { header.value = value; @@ -86,14 +91,17 @@ export function init ( this.addHeader(name, value); } }, - addHeader (name: string, value: string): void { + addHeader(name: string, value: string): void { const header = misc.filterHeaders(renderedRequest.headers, name)[0]; if (!header) { - renderedRequest.headers.push({name, value}); + renderedRequest.headers.push({ name, value }); } }, - getParameter (name: string): string | null { - const parameters = misc.filterParameters(renderedRequest.parameters, name); + getParameter(name: string): string | null { + const parameters = misc.filterParameters( + renderedRequest.parameters, + name + ); if (parameters.length) { // Use the last parameter if there are multiple of the same const parameter = parameters[parameters.length - 1]; @@ -102,30 +110,42 @@ export function init ( return null; } }, - getParameters (): Array<{ name: string, value: string }> { - return renderedRequest.parameters.map(p => ({name: p.name, value: p.value})); + getParameters(): Array<{ name: string, value: string }> { + return renderedRequest.parameters.map(p => ({ + name: p.name, + value: p.value + })); }, - hasParameter (name: string): boolean { + hasParameter(name: string): boolean { return this.getParameter(name) !== null; }, - removeParameter (name: string): void { - const parameters = misc.filterParameters(renderedRequest.parameters, name); + removeParameter(name: string): void { + const parameters = misc.filterParameters( + renderedRequest.parameters, + name + ); renderedRequest.parameters = renderedRequest.parameters.filter( p => !parameters.includes(p) ); }, - setParameter (name: string, value: string): void { - const parameter = misc.filterParameters(renderedRequest.parameters, name)[0]; + setParameter(name: string, value: string): void { + const parameter = misc.filterParameters( + renderedRequest.parameters, + name + )[0]; if (parameter) { parameter.value = value; } else { this.addParameter(name, value); } }, - addParameter (name: string, value: string): void { - const parameter = misc.filterParameters(renderedRequest.parameters, name)[0]; + addParameter(name: string, value: string): void { + const parameter = misc.filterParameters( + renderedRequest.parameters, + name + )[0]; if (!parameter) { - renderedRequest.parameters.push({name, value}); + renderedRequest.parameters.push({ name, value }); } } @@ -152,5 +172,5 @@ export function init ( delete request.addParameter; } - return {request}; + return { request }; } diff --git a/packages/insomnia-app/app/plugins/context/response.js b/packages/insomnia-app/app/plugins/context/response.js index d5f5eb33b7..90b7836456 100644 --- a/packages/insomnia-app/app/plugins/context/response.js +++ b/packages/insomnia-app/app/plugins/context/response.js @@ -1,8 +1,8 @@ // @flow -import type {ResponseHeader} from '../../models/response'; +import type { ResponseHeader } from '../../models/response'; import * as models from '../../models/index'; import fs from 'fs'; -import {Readable} from 'stream'; +import { Readable } from 'stream'; type MaybeResponse = { parentId?: string, @@ -13,9 +13,9 @@ type MaybeResponse = { bodyPath?: string, elapsedTime?: number, headers?: Array -} +}; -export function init (response: MaybeResponse): { response: Object } { +export function init(response: MaybeResponse): { response: Object } { if (!response) { throw new Error('contexts.response initialized without response'); } @@ -27,28 +27,28 @@ export function init (response: MaybeResponse): { response: Object } { // getId () { // return response.parentId; // }, - getRequestId (): string { + getRequestId(): string { return response.parentId || ''; }, - getStatusCode (): number { + getStatusCode(): number { return response.statusCode || 0; }, - getStatusMessage (): string { + getStatusMessage(): string { return response.statusMessage || ''; }, - getBytesRead (): number { + getBytesRead(): number { return response.bytesRead || 0; }, - getTime (): number { + getTime(): number { return response.elapsedTime || 0; }, - getBody (): Buffer | null { + getBody(): Buffer | null { return models.response.getBodyBuffer(response); }, - getBodyStream (): Readable | null { + getBodyStream(): Readable | null { return models.response.getBodyStream(response); }, - setBody (body: Buffer) { + setBody(body: Buffer) { // Should never happen but just in case it does... if (!response.bodyPath) { throw new Error('Could not set body without existing body path'); @@ -57,9 +57,11 @@ export function init (response: MaybeResponse): { response: Object } { fs.writeFileSync(response.bodyPath, body); response.bytesContent = body.length; }, - getHeader (name: string): string | Array | null { + getHeader(name: string): string | Array | null { const headers = response.headers || []; - const matchedHeaders = headers.filter(h => h.name.toLowerCase() === name.toLowerCase()); + const matchedHeaders = headers.filter( + h => h.name.toLowerCase() === name.toLowerCase() + ); if (matchedHeaders.length > 1) { return matchedHeaders.map(h => h.value); } else if (matchedHeaders.length === 1) { @@ -68,7 +70,7 @@ export function init (response: MaybeResponse): { response: Object } { return null; } }, - hasHeader (name: string): boolean { + hasHeader(name: string): boolean { return this.getHeader(name) !== null; } } diff --git a/packages/insomnia-app/app/plugins/context/store.js b/packages/insomnia-app/app/plugins/context/store.js index bf58eec52b..6661975fa7 100644 --- a/packages/insomnia-app/app/plugins/context/store.js +++ b/packages/insomnia-app/app/plugins/context/store.js @@ -1,22 +1,22 @@ // @flow -import type {Plugin} from '../index'; +import type { Plugin } from '../index'; import * as models from '../../models'; -export function init (plugin: Plugin) { +export function init(plugin: Plugin) { return { store: { - async hasItem (key: string): Promise { + async hasItem(key: string): Promise { const doc = await models.pluginData.getByKey(plugin.name, key); return doc !== null; }, - async setItem (key: string, value: string): Promise { + async setItem(key: string, value: string): Promise { await models.pluginData.upsertByKey(plugin.name, key, String(value)); }, - async getItem (key: string): Promise { + async getItem(key: string): Promise { const doc = await models.pluginData.getByKey(plugin.name, key); return doc ? doc.value : null; }, - async removeItem (key: string): Promise { + async removeItem(key: string): Promise { await models.pluginData.removeByKey(plugin.name, key); } } diff --git a/packages/insomnia-app/app/plugins/index.js b/packages/insomnia-app/app/plugins/index.js index d4adfd5fd1..9d3ff6e4b7 100644 --- a/packages/insomnia-app/app/plugins/index.js +++ b/packages/insomnia-app/app/plugins/index.js @@ -3,10 +3,10 @@ import mkdirp from 'mkdirp'; import * as models from '../models'; import fs from 'fs'; import path from 'path'; -import {PLUGIN_PATH} from '../common/constants'; -import {resolveHomePath} from '../common/misc'; -import {showError} from '../ui/components/modals/index'; -import type {PluginTemplateTag} from '../templating/extensions/index'; +import { PLUGIN_PATH } from '../common/constants'; +import { resolveHomePath } from '../common/misc'; +import { showError } from '../ui/components/modals/index'; +import type { PluginTemplateTag } from '../templating/extensions/index'; export type Plugin = { name: string, @@ -19,17 +19,17 @@ export type Plugin = { export type TemplateTag = { plugin: Plugin, templateTag: PluginTemplateTag -} +}; export type RequestHook = { plugin: Plugin, hook: Function -} +}; export type ResponseHook = { plugin: Plugin, hook: Function -} +}; const CORE_PLUGINS = [ 'insomnia-plugin-base64', @@ -45,12 +45,12 @@ const CORE_PLUGINS = [ let plugins: ?Array = null; -export async function init (): Promise { +export async function init(): Promise { // Force plugins to load. await getPlugins(true); } -async function _traversePluginPath (pluginMap: Object, allPaths: Array) { +async function _traversePluginPath(pluginMap: Object, allPaths: Array) { for (const p of allPaths) { if (!fs.existsSync(p)) { continue; @@ -94,7 +94,11 @@ async function _traversePluginPath (pluginMap: Object, allPaths: Array) // Delete require cache entry and re-require const module = global.require(modulePath); - pluginMap[pluginJson.name] = _initPlugin(pluginJson || {}, module, modulePath); + pluginMap[pluginJson.name] = _initPlugin( + pluginJson || {}, + module, + modulePath + ); console.log(`[plugin] Loaded ${modulePath}`); } catch (err) { showError({ @@ -107,14 +111,19 @@ async function _traversePluginPath (pluginMap: Object, allPaths: Array) } } -export async function getPlugins (force: boolean = false): Promise> { +export async function getPlugins( + force: boolean = false +): Promise> { if (force) { plugins = null; } if (!plugins) { const settings = await models.settings.getOrCreate(); - const extraPaths = settings.pluginPath.split(':').filter(p => p).map(resolveHomePath); + const extraPaths = settings.pluginPath + .split(':') + .filter(p => p) + .map(resolveHomePath); // Make sure the default directories exist mkdirp.sync(PLUGIN_PATH); @@ -145,46 +154,46 @@ export async function getPlugins (force: boolean = false): Promise return plugins; } -export async function getTemplateTags (): Promise> { +export async function getTemplateTags(): Promise> { let extensions = []; for (const plugin of await getPlugins()) { const templateTags = plugin.module.templateTags || []; extensions = [ ...extensions, - ...templateTags.map(tt => ({plugin, templateTag: tt})) + ...templateTags.map(tt => ({ plugin, templateTag: tt })) ]; } return extensions; } -export async function getRequestHooks (): Promise> { +export async function getRequestHooks(): Promise> { let functions = []; for (const plugin of await getPlugins()) { const moreFunctions = plugin.module.requestHooks || []; functions = [ ...functions, - ...moreFunctions.map(hook => ({plugin, hook})) + ...moreFunctions.map(hook => ({ plugin, hook })) ]; } return functions; } -export async function getResponseHooks (): Promise> { +export async function getResponseHooks(): Promise> { let functions = []; for (const plugin of await getPlugins()) { const moreFunctions = plugin.module.responseHooks || []; functions = [ ...functions, - ...moreFunctions.map(hook => ({plugin, hook})) + ...moreFunctions.map(hook => ({ plugin, hook })) ]; } return functions; } -function _initPlugin (packageJSON: Object, module: any, path: ?string): Plugin { +function _initPlugin(packageJSON: Object, module: any, path: ?string): Plugin { const meta = packageJSON.insomnia || {}; return { name: packageJSON.name || meta.name, diff --git a/packages/insomnia-app/app/plugins/install.js b/packages/insomnia-app/app/plugins/install.js index e2a161856f..b0c19ba54a 100644 --- a/packages/insomnia-app/app/plugins/install.js +++ b/packages/insomnia-app/app/plugins/install.js @@ -3,11 +3,11 @@ import * as electron from 'electron'; import fs from 'fs'; import fsx from 'fs-extra'; import childProcess from 'child_process'; -import {getTempDir, isDevelopment, PLUGIN_PATH} from '../common/constants'; +import { getTempDir, isDevelopment, PLUGIN_PATH } from '../common/constants'; import mkdirp from 'mkdirp'; import path from 'path'; -export default async function (moduleName: string): Promise { +export default async function(moduleName: string): Promise { return new Promise(async (resolve, reject) => { let info: Object = {}; try { @@ -21,18 +21,20 @@ export default async function (moduleName: string): Promise { // Download the module const request = electron.remote.net.request(info.dist.tarball); request.on('error', err => { - reject(new Error(`Failed to make plugin request ${info.dist.tarball}: ${err.message}`)); + reject( + new Error( + `Failed to make plugin request ${info.dist.tarball}: ${err.message}` + ) + ); }); - const {tmpDir} = await _installPluginToTmpDir(moduleName); + const { tmpDir } = await _installPluginToTmpDir(moduleName); console.log(`[plugins] Moving plugin from ${tmpDir} to ${pluginDir}`); // Move entire module to plugins folder - fsx.moveSync( - path.join(tmpDir, moduleName), - pluginDir, - {overwrite: true} - ); + fsx.moveSync(path.join(tmpDir, moduleName), pluginDir, { + overwrite: true + }); // Move each dependency into node_modules folder const pluginModulesDir = path.join(pluginDir, 'node_modules'); @@ -44,7 +46,7 @@ export default async function (moduleName: string): Promise { } const dest = path.join(pluginModulesDir, name); - fsx.moveSync(src, dest, {overwrite: true}); + fsx.moveSync(src, dest, { overwrite: true }); } } catch (err) { reject(err); @@ -55,7 +57,7 @@ export default async function (moduleName: string): Promise { }); } -async function _isInsomniaPlugin (moduleName: string): Promise { +async function _isInsomniaPlugin(moduleName: string): Promise { return new Promise((resolve, reject) => { console.log(`[plugins] Fetching module info from npm`); childProcess.execFile( @@ -65,10 +67,11 @@ async function _isInsomniaPlugin (moduleName: string): Promise { timeout: 5 * 60 * 1000, maxBuffer: 1024 * 1024, env: { - 'NODE_ENV': 'production', - 'ELECTRON_RUN_AS_NODE': 'true' + NODE_ENV: 'production', + ELECTRON_RUN_AS_NODE: 'true' } - }, (err, stdout, stderr) => { + }, + (err, stdout, stderr) => { if (err) { reject(new Error(`${moduleName} npm error: ${err.message}`)); return; @@ -89,7 +92,11 @@ async function _isInsomniaPlugin (moduleName: string): Promise { const data = yarnOutput.data; if (!data.hasOwnProperty('insomnia')) { - reject(new Error(`"${moduleName}" not a plugin! Package missing "insomnia" attribute`)); + reject( + new Error( + `"${moduleName}" not a plugin! Package missing "insomnia" attribute` + ) + ); return; } @@ -109,7 +116,9 @@ async function _isInsomniaPlugin (moduleName: string): Promise { }); } -async function _installPluginToTmpDir (moduleName: string): Promise<{tmpDir: string}> { +async function _installPluginToTmpDir( + moduleName: string +): Promise<{ tmpDir: string }> { return new Promise((resolve, reject) => { const tmpDir = path.join(getTempDir(), `${moduleName}-${Date.now()}`); mkdirp.sync(tmpDir); @@ -117,9 +126,13 @@ async function _installPluginToTmpDir (moduleName: string): Promise<{tmpDir: str childProcess.execFile( process.execPath, [ - _getYarnPath(), 'add', moduleName, - '--modules-folder', tmpDir, - '--cwd', tmpDir, + _getYarnPath(), + 'add', + moduleName, + '--modules-folder', + tmpDir, + '--cwd', + tmpDir, '--no-lockfile', '--production', '--no-progress' @@ -129,10 +142,11 @@ async function _installPluginToTmpDir (moduleName: string): Promise<{tmpDir: str maxBuffer: 1024 * 1024, cwd: tmpDir, env: { - 'NODE_ENV': 'production', - 'ELECTRON_RUN_AS_NODE': 'true' + NODE_ENV: 'production', + ELECTRON_RUN_AS_NODE: 'true' } - }, (err, stdout, stderr) => { + }, + (err, stdout, stderr) => { if (err) { reject(new Error(`${moduleName} install error: ${err.message}`)); return; @@ -143,14 +157,14 @@ async function _installPluginToTmpDir (moduleName: string): Promise<{tmpDir: str return; } - resolve({tmpDir}); + resolve({ tmpDir }); } ); }); } -function _getYarnPath () { - const {app} = electron.remote || electron; +function _getYarnPath() { + const { app } = electron.remote || electron; // TODO: This is brittle. Make finding this more robust. if (isDevelopment()) { diff --git a/packages/insomnia-app/app/sync/__tests__/crypt.test.js b/packages/insomnia-app/app/sync/__tests__/crypt.test.js index 0451139ce3..ff199ab754 100644 --- a/packages/insomnia-app/app/sync/__tests__/crypt.test.js +++ b/packages/insomnia-app/app/sync/__tests__/crypt.test.js @@ -1,5 +1,5 @@ import * as crypt from '../crypt'; -import {globalBeforeEach} from '../../__jest__/before-each'; +import { globalBeforeEach } from '../../__jest__/before-each'; describe('deriveKey()', () => { beforeEach(globalBeforeEach); @@ -15,7 +15,11 @@ describe('deriveKey()', () => { describe('encryptRSA', () => { beforeEach(globalBeforeEach); it('encrypts and decrypts', () => { - const resultEncrypted = crypt.encryptAES('rawkey', 'Hello World!', 'additional data'); + const resultEncrypted = crypt.encryptAES( + 'rawkey', + 'Hello World!', + 'additional data' + ); const resultDecrypted = crypt.decryptAES('rawkey', resultEncrypted); const expectedEncrypted = { diff --git a/packages/insomnia-app/app/sync/__tests__/sync.test.js b/packages/insomnia-app/app/sync/__tests__/sync.test.js index c17ffa005e..469c8067b0 100644 --- a/packages/insomnia-app/app/sync/__tests__/sync.test.js +++ b/packages/insomnia-app/app/sync/__tests__/sync.test.js @@ -4,7 +4,7 @@ import * as models from '../../models'; import * as db from '../../common/database'; import * as syncStorage from '../storage'; import * as crypt from '../crypt'; -import {globalBeforeEach} from '../../__jest__/before-each'; +import { globalBeforeEach } from '../../__jest__/before-each'; describe('Test push/pull behaviour', () => { beforeEach(async () => { @@ -16,14 +16,22 @@ describe('Test push/pull behaviour', () => { await _setupSessionMocks(); // Init sync and storage - const config = {inMemoryOnly: true, autoload: false, filename: null}; + const config = { inMemoryOnly: true, autoload: false, filename: null }; await syncStorage.initDB(config, true); // Add some data - await models.workspace.create({_id: 'wrk_1', name: 'Workspace 1'}); - await models.workspace.create({_id: 'wrk_2', name: 'Workspace 2'}); - await models.request.create({_id: 'req_1', name: 'Request 1', parentId: 'wrk_1'}); - await models.request.create({_id: 'req_2', name: 'Request 2', parentId: 'wrk_2'}); + await models.workspace.create({ _id: 'wrk_1', name: 'Workspace 1' }); + await models.workspace.create({ _id: 'wrk_2', name: 'Workspace 2' }); + await models.request.create({ + _id: 'req_1', + name: 'Request 1', + parentId: 'wrk_1' + }); + await models.request.create({ + _id: 'req_2', + name: 'Request 2', + parentId: 'wrk_2' + }); // Create resources, resource groups, and configs const workspaces = await models.workspace.all(); @@ -40,8 +48,14 @@ describe('Test push/pull behaviour', () => { const resourceRequest2 = await syncStorage.getResourceByDocId(request2._id); // Set up sync modes - await sync.createOrUpdateConfig(resourceRequest.resourceGroupId, syncStorage.SYNC_MODE_ON); - await sync.createOrUpdateConfig(resourceRequest2.resourceGroupId, syncStorage.SYNC_MODE_UNSET); + await sync.createOrUpdateConfig( + resourceRequest.resourceGroupId, + syncStorage.SYNC_MODE_ON + ); + await sync.createOrUpdateConfig( + resourceRequest2.resourceGroupId, + syncStorage.SYNC_MODE_UNSET + ); await sync.push(); // Push only active configs await sync.push(resourceRequest.resourceGroupId); // Force push rg_1 @@ -62,11 +76,14 @@ describe('Test push/pull behaviour', () => { it('Updates dirty flag for push response', async () => { const request = await models.request.getById('req_1'); const resourceRequest = await syncStorage.getResourceByDocId(request._id); - await sync.createOrUpdateConfig(resourceRequest.resourceGroupId, syncStorage.SYNC_MODE_ON); + await sync.createOrUpdateConfig( + resourceRequest.resourceGroupId, + syncStorage.SYNC_MODE_ON + ); session.syncPush.mockReturnValueOnce({ updated: [], - created: [{id: request._id, version: 'new-version'}], + created: [{ id: request._id, version: 'new-version' }], removed: [], conflicts: [] }); @@ -86,19 +103,35 @@ describe('Test push/pull behaviour', () => { it('Updates resources for pull response', async () => { const request = await models.request.getById('req_1'); const request2 = await models.request.getById('req_2'); - const requestNew = Object.assign({}, request, {_id: 'req_new', name: 'New Request'}); + const requestNew = Object.assign({}, request, { + _id: 'req_new', + name: 'New Request' + }); const resourceBefore = await syncStorage.getResourceByDocId(request._id); - const resource2Before = await syncStorage.getResourceByDocId(requestNew._id); - await sync.createOrUpdateConfig(resourceBefore.resourceGroupId, syncStorage.SYNC_MODE_ON); - const updatedRequest = Object.assign({}, request, {name: 'Request Updated'}); + const resource2Before = await syncStorage.getResourceByDocId( + requestNew._id + ); + await sync.createOrUpdateConfig( + resourceBefore.resourceGroupId, + syncStorage.SYNC_MODE_ON + ); + const updatedRequest = Object.assign({}, request, { + name: 'Request Updated' + }); const updatedResource = Object.assign({}, resourceBefore, { version: 'ver1', - encContent: await sync.encryptDoc(resourceBefore.resourceGroupId, updatedRequest) + encContent: await sync.encryptDoc( + resourceBefore.resourceGroupId, + updatedRequest + ) }); const createdResourceNew = Object.assign({}, resourceBefore, { id: requestNew._id, resourceGroupId: 'rg_1', - encContent: await sync.encryptDoc(resourceBefore.resourceGroupId, requestNew) + encContent: await sync.encryptDoc( + resourceBefore.resourceGroupId, + requestNew + ) }); session.syncPull.mockReturnValueOnce({ @@ -113,9 +146,14 @@ describe('Test push/pull behaviour', () => { const requestAfter = await models.request.getById(request._id); const request2After = await models.request.getById(request2._id); const requestNewAfter = await models.request.getById('req_new'); - const resourceAfter = await syncStorage.getResourceByDocId(request._id, resourceBefore.resourceGroupId); + const resourceAfter = await syncStorage.getResourceByDocId( + request._id, + resourceBefore.resourceGroupId + ); const resource2After = await syncStorage.getResourceByDocId(request2._id); - const resourceNewAfter = await syncStorage.getResourceByDocId(requestNewAfter._id); + const resourceNewAfter = await syncStorage.getResourceByDocId( + requestNewAfter._id + ); // Assert expect(resourceBefore.version).toBe('__NO_VERSION__'); @@ -131,11 +169,18 @@ describe('Test push/pull behaviour', () => { it('Conflict: local version wins on modified before', async () => { const requestClient = await models.request.getById('req_1'); - const requestServer = Object.assign({}, requestClient, {name: 'Server Request'}); - const resourceRequest = await syncStorage.getResourceByDocId(requestClient._id); + const requestServer = Object.assign({}, requestClient, { + name: 'Server Request' + }); + const resourceRequest = await syncStorage.getResourceByDocId( + requestClient._id + ); const resourceConflict = Object.assign({}, resourceRequest, { version: 'ver-2', - encContent: await sync.encryptDoc(resourceRequest.resourceGroupId, requestServer), + encContent: await sync.encryptDoc( + resourceRequest.resourceGroupId, + requestServer + ), lastEdited: resourceRequest.lastEdited - 1000 // Same edited time }); @@ -147,7 +192,10 @@ describe('Test push/pull behaviour', () => { }); await sync.push(resourceRequest.resourceGroupId); - const resourceAfter = await syncStorage.getResourceByDocId(requestClient._id, resourceRequest.resourceGroupId); + const resourceAfter = await syncStorage.getResourceByDocId( + requestClient._id, + resourceRequest.resourceGroupId + ); const requestAfter = await models.request.getById(requestClient._id); // Assert @@ -163,11 +211,18 @@ describe('Test push/pull behaviour', () => { it('Conflict: local version wins on modified tie', async () => { const requestClient = await models.request.getById('req_1'); - const requestServer = Object.assign({}, requestClient, {name: 'Server Request'}); - const resourceRequest = await syncStorage.getResourceByDocId(requestClient._id); + const requestServer = Object.assign({}, requestClient, { + name: 'Server Request' + }); + const resourceRequest = await syncStorage.getResourceByDocId( + requestClient._id + ); const resourceConflict = Object.assign({}, resourceRequest, { version: 'ver-2', - encContent: await sync.encryptDoc(resourceRequest.resourceGroupId, requestServer), + encContent: await sync.encryptDoc( + resourceRequest.resourceGroupId, + requestServer + ), lastEdited: resourceRequest.lastEdited // Same edited time }); @@ -179,7 +234,10 @@ describe('Test push/pull behaviour', () => { }); await sync.push(resourceRequest.resourceGroupId); - const resourceAfter = await syncStorage.getResourceByDocId(requestClient._id, resourceRequest.resourceGroupId); + const resourceAfter = await syncStorage.getResourceByDocId( + requestClient._id, + resourceRequest.resourceGroupId + ); const requestAfter = await models.request.getById(requestClient._id); // Assert @@ -195,11 +253,18 @@ describe('Test push/pull behaviour', () => { it('Conflict: server version wins if modified after', async () => { const requestClient = await models.request.getById('req_1'); - const requestServer = Object.assign({}, requestClient, {name: 'Server Request'}); - const resourceRequest = await syncStorage.getResourceByDocId(requestClient._id); + const requestServer = Object.assign({}, requestClient, { + name: 'Server Request' + }); + const resourceRequest = await syncStorage.getResourceByDocId( + requestClient._id + ); const resourceConflict = Object.assign({}, resourceRequest, { version: 'ver-2', - encContent: await sync.encryptDoc(resourceRequest.resourceGroupId, requestServer), + encContent: await sync.encryptDoc( + resourceRequest.resourceGroupId, + requestServer + ), lastEdited: resourceRequest.lastEdited + 1000 }); @@ -211,13 +276,18 @@ describe('Test push/pull behaviour', () => { }); await sync.push(resourceRequest.resourceGroupId); - const resourceAfter = await syncStorage.getResourceByDocId(requestClient._id, resourceRequest.resourceGroupId); + const resourceAfter = await syncStorage.getResourceByDocId( + requestClient._id, + resourceRequest.resourceGroupId + ); const requestAfter = await models.request.getById(requestClient._id); // Assert expect(session.syncPush.mock.calls.length).toBe(1); expect(session.syncPush.mock.calls[0][0].length).toBe(2); - expect(resourceAfter.lastEdited).toBeGreaterThan(resourceRequest.lastEdited); + expect(resourceAfter.lastEdited).toBeGreaterThan( + resourceRequest.lastEdited + ); expect(resourceAfter.version).toBe(resourceConflict.version); // Local resource gets marked as dirty so it's pushed right away expect(resourceAfter.dirty).toBe(false); @@ -239,16 +309,36 @@ describe('Integration tests for creating Resources and pushing', () => { jest.useFakeTimers(); // Init storage - const config = {inMemoryOnly: true, autoload: false, filename: null}; + const config = { inMemoryOnly: true, autoload: false, filename: null }; await syncStorage.initDB(config, true); // Add some data - await models.workspace.create({_id: 'wrk_empty', name: 'Workspace Empty'}); - await models.workspace.create({_id: 'wrk_1', name: 'Workspace 1'}); - await models.request.create({_id: 'req_1', name: 'Request 1', parentId: 'wrk_1'}); - await models.request.create({_id: 'req_2', name: 'Request 2', parentId: 'wrk_1'}); - await models.request.create({_id: 'req_3', name: 'Request 3', parentId: 'wrk_1'}); - await models.environment.create({_id: 'env_2', name: 'Env Prv', parentId: 'wrk_1', isPrivate: true}); + await models.workspace.create({ + _id: 'wrk_empty', + name: 'Workspace Empty' + }); + await models.workspace.create({ _id: 'wrk_1', name: 'Workspace 1' }); + await models.request.create({ + _id: 'req_1', + name: 'Request 1', + parentId: 'wrk_1' + }); + await models.request.create({ + _id: 'req_2', + name: 'Request 2', + parentId: 'wrk_1' + }); + await models.request.create({ + _id: 'req_3', + name: 'Request 3', + parentId: 'wrk_1' + }); + await models.environment.create({ + _id: 'env_2', + name: 'Env Prv', + parentId: 'wrk_1', + isPrivate: true + }); // Flush changes just to be sure they won't affect our tests await db.flushChanges(); @@ -326,14 +416,13 @@ describe('Integration tests for creating Resources and pushing', () => { // Mark resource as removed const originalResource = await syncStorage.getResourceByDocId('req_t'); - const updatedResource = await syncStorage.updateResource( - originalResource, - {removed: true} - ); + const updatedResource = await syncStorage.updateResource(originalResource, { + removed: true + }); // Update it and push it again await db.bufferChanges(); - await models.request.update(request, {name: 'New Name'}); + await models.request.update(request, { name: 'New Name' }); await db.flushChanges(); await sync.writePendingChanges(); await sync.push(); @@ -350,7 +439,9 @@ describe('Integration tests for creating Resources and pushing', () => { const request = await models.request.getById('req_1'); const resource = await syncStorage.getResourceByDocId(request._id); await db.bufferChanges(); - const updatedRequest = await models.request.update(request, {name: 'New Name'}); + const updatedRequest = await models.request.update(request, { + name: 'New Name' + }); // Drain and fetch new resource await db.flushChanges(); @@ -399,14 +490,14 @@ describe('Integration tests for creating Resources and pushing', () => { // Helpers // // ~~~~~~~ // -function _decryptResource (resource) { +function _decryptResource(resource) { const message = JSON.parse(resource.encContent); const fakeKey = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'; const docJSON = crypt.decryptAES(fakeKey, message); return JSON.parse(docJSON); } -async function _setSessionData () { +async function _setSessionData() { const symmetricKey = { alg: 'A256GCM', ext: true, @@ -424,7 +515,7 @@ async function _setSessionData () { n: 'aaaa' }; - const {privateKey} = await crypt.generateKeyPairJWK(); + const { privateKey } = await crypt.generateKeyPairJWK(); const encPrivateKey = { ad: '', d: Buffer.from(JSON.stringify(privateKey)).toString('hex'), @@ -445,7 +536,7 @@ async function _setSessionData () { ); } -async function _setupSessionMocks () { +async function _setupSessionMocks() { const resourceGroups = {}; session.syncCreateResourceGroup = jest.fn((parentId, name, _) => { @@ -454,15 +545,19 @@ async function _setupSessionMocks () { // Generate a public key and use a symmetric equal to it's Id for // convenience const publicKey = session.getPublicKey(); - const symmetricKeyStr = JSON.stringify({k: id}); + const symmetricKeyStr = JSON.stringify({ k: id }); const encSymmetricKey = crypt.encryptRSAWithJWK(publicKey, symmetricKeyStr); // Store the resource group and return it - resourceGroups[id] = Object.assign({}, {id, encSymmetricKey}, { - parentResourceId: parentId, - name: name, - encSymmetricKey: encSymmetricKey - }); + resourceGroups[id] = Object.assign( + {}, + { id, encSymmetricKey }, + { + parentResourceId: parentId, + name: name, + encSymmetricKey: encSymmetricKey + } + ); return resourceGroups[id]; }); diff --git a/packages/insomnia-app/app/sync/crypt.js b/packages/insomnia-app/app/sync/crypt.js index 40efa0fe52..68437d39f9 100644 --- a/packages/insomnia-app/app/sync/crypt.js +++ b/packages/insomnia-app/app/sync/crypt.js @@ -3,7 +3,7 @@ import srp from 'srp-js'; import * as forge from 'node-forge'; const DEFAULT_BYTE_LENGTH = 32; -const DEFAULT_PBKDF2_ITERATIONS = 1E5; // 100,000 +const DEFAULT_PBKDF2_ITERATIONS = 1e5; // 100,000 /** * Generate hex signing key used for AES encryption @@ -12,7 +12,7 @@ const DEFAULT_PBKDF2_ITERATIONS = 1E5; // 100,000 * @param email * @param salt */ -export async function deriveKey (pass, email, salt) { +export async function deriveKey(pass, email, salt) { const combinedSalt = await _hkdfSalt(salt, email); return _pbkdf2Passphrase(pass, combinedSalt); } @@ -24,7 +24,7 @@ export async function deriveKey (pass, email, salt) { * @param plaintext * @return String */ -export function encryptRSAWithJWK (publicKeyJWK, plaintext) { +export function encryptRSAWithJWK(publicKeyJWK, plaintext) { if (publicKeyJWK.alg !== 'RSA-OAEP-256') { throw new Error('Public key algorithm was not RSA-OAEP-256'); } else if (publicKeyJWK.kty !== 'RSA') { @@ -45,7 +45,7 @@ export function encryptRSAWithJWK (publicKeyJWK, plaintext) { return forge.util.bytesToHex(encrypted); } -export function decryptRSAWithJWK (privateJWK, encryptedBlob) { +export function decryptRSAWithJWK(privateJWK, encryptedBlob) { const n = _b64UrlToBigInt(privateJWK.n); const e = _b64UrlToBigInt(privateJWK.e); const d = _b64UrlToBigInt(privateJWK.d); @@ -64,7 +64,7 @@ export function decryptRSAWithJWK (privateJWK, encryptedBlob) { return decodeURIComponent(decrypted); } -export function recryptRSAWithJWK (privateJWK, publicJWK, encryptedBlob) { +export function recryptRSAWithJWK(privateJWK, publicJWK, encryptedBlob) { const decrypted = decryptRSAWithJWK(privateJWK, encryptedBlob); return encryptRSAWithJWK(publicJWK, decrypted); } @@ -77,9 +77,10 @@ export function recryptRSAWithJWK (privateJWK, publicJWK, encryptedBlob) { * @param additionalData any additional public data to attach * @returns {{iv, t, d, ad}} */ -export function encryptAES (jwkOrKey, plaintext, additionalData = '') { +export function encryptAES(jwkOrKey, plaintext, additionalData = '') { // TODO: Add assertion checks for JWK - const rawKey = typeof jwkOrKey === 'string' ? jwkOrKey : _b64UrlToHex(jwkOrKey.k); + const rawKey = + typeof jwkOrKey === 'string' ? jwkOrKey : _b64UrlToHex(jwkOrKey.k); const key = forge.util.hexToBytes(rawKey); const iv = forge.random.getBytesSync(12); @@ -88,7 +89,7 @@ export function encryptAES (jwkOrKey, plaintext, additionalData = '') { // Plaintext could contain weird unicode, so we have to encode that const encodedPlaintext = encodeURIComponent(plaintext); - cipher.start({additionalData, iv, tagLength: 128}); + cipher.start({ additionalData, iv, tagLength: 128 }); cipher.update(forge.util.createBuffer(encodedPlaintext)); cipher.finish(); @@ -107,9 +108,10 @@ export function encryptAES (jwkOrKey, plaintext, additionalData = '') { * @param message * @returns String */ -export function decryptAES (jwkOrKey, message) { +export function decryptAES(jwkOrKey, message) { // TODO: Add assertion checks for JWK - const rawKey = typeof jwkOrKey === 'string' ? jwkOrKey : _b64UrlToHex(jwkOrKey.k); + const rawKey = + typeof jwkOrKey === 'string' ? jwkOrKey : _b64UrlToHex(jwkOrKey.k); const key = forge.util.hexToBytes(rawKey); // ~~~~~~~~~~~~~~~~~~~~ // @@ -138,7 +140,7 @@ export function decryptAES (jwkOrKey, message) { * * @returns {string} */ -export function getRandomHex (bytes = DEFAULT_BYTE_LENGTH) { +export function getRandomHex(bytes = DEFAULT_BYTE_LENGTH) { return forge.util.bytesToHex(forge.random.getBytesSync(bytes)); } @@ -147,7 +149,7 @@ export function getRandomHex (bytes = DEFAULT_BYTE_LENGTH) { * * @returns {string} */ -export function generateAccountId () { +export function generateAccountId() { return `act_${getRandomHex(DEFAULT_BYTE_LENGTH)}`; } @@ -156,7 +158,7 @@ export function generateAccountId () { * * @returns {Promise} */ -export function srpGenKey () { +export function srpGenKey() { return new Promise((resolve, reject) => { srp.genKey((err, secret1Buffer) => { if (err) { @@ -171,14 +173,14 @@ export function srpGenKey () { /** * Generate a random AES256 key for use with symmetric encryption */ -export async function generateAES256Key () { +export async function generateAES256Key() { const c = window.crypto; const subtle = c ? c.subtle || c.webkitSubtle : null; if (subtle) { console.log('[crypt] Using Native AES Key Generation'); const key = await subtle.generateKey( - {name: 'AES-GCM', length: 256}, + { name: 'AES-GCM', length: 256 }, true, ['encrypt', 'decrypt'] ); @@ -201,7 +203,7 @@ export async function generateAES256Key () { * * @returns Object */ -export async function generateKeyPairJWK () { +export async function generateKeyPairJWK() { // NOTE: Safari has crypto.webkitSubtle, but it does not support RSA-OAEP-SHA256 const subtle = window.crypto && window.crypto.subtle; @@ -226,7 +228,7 @@ export async function generateKeyPairJWK () { } else { console.log('[crypt] Using Forge RSA Generation'); - const pair = forge.pki.rsa.generateKeyPair({bits: 2048, e: 0x10001}); + const pair = forge.pki.rsa.generateKeyPair({ bits: 2048, e: 0x10001 }); const privateKey = { alg: 'RSA-OAEP-256', kty: 'RSA', @@ -250,7 +252,7 @@ export async function generateKeyPairJWK () { n: _bigIntToB64Url(pair.publicKey.n) }; - return {privateKey, publicKey}; + return { privateKey, publicKey }; } } @@ -265,10 +267,12 @@ export async function generateKeyPairJWK () { * @param rawEmail * @returns {Promise} */ -function _hkdfSalt (rawSalt, rawEmail) { +function _hkdfSalt(rawSalt, rawEmail) { return new Promise(resolve => { const hkdf = new HKDF('sha256', rawSalt, rawEmail); - hkdf.derive('', DEFAULT_BYTE_LENGTH, buffer => resolve(buffer.toString('hex'))); + hkdf.derive('', DEFAULT_BYTE_LENGTH, buffer => + resolve(buffer.toString('hex')) + ); }); } @@ -279,23 +283,24 @@ function _hkdfSalt (rawSalt, rawEmail) { * @param n BigInteger * @returns {string} */ -function _bigIntToB64Url (n) { +function _bigIntToB64Url(n) { return _hexToB64Url(n.toString(16)); } -function _hexToB64Url (h) { +function _hexToB64Url(h) { const bytes = forge.util.hexToBytes(h); - return window.btoa(bytes) + return window + .btoa(bytes) .replace(/=/g, '') .replace(/\+/g, '-') .replace(/\//g, '_'); } -function _b64UrlToBigInt (s) { +function _b64UrlToBigInt(s) { return new forge.jsbn.BigInteger(_b64UrlToHex(s), 16); } -function _b64UrlToHex (s) { +function _b64UrlToHex(s) { const b64 = s.replace(/-/g, '+').replace(/_/g, '/'); return forge.util.bytesToHex(window.atob(b64)); } @@ -306,14 +311,14 @@ function _b64UrlToHex (s) { * @param passphrase * @param salt hex representation of salt */ -async function _pbkdf2Passphrase (passphrase, salt) { +async function _pbkdf2Passphrase(passphrase, salt) { if (window.crypto && window.crypto.subtle) { console.log('[crypt] Using native PBKDF2'); const k = await window.crypto.subtle.importKey( 'raw', Buffer.from(passphrase, 'utf8'), - {name: 'PBKDF2'}, + { name: 'PBKDF2' }, false, ['deriveBits'] ); @@ -325,7 +330,11 @@ async function _pbkdf2Passphrase (passphrase, salt) { hash: 'SHA-256' }; - const derivedKeyRaw = await window.crypto.subtle.deriveBits(algo, k, DEFAULT_BYTE_LENGTH * 8); + const derivedKeyRaw = await window.crypto.subtle.deriveBits( + algo, + k, + DEFAULT_BYTE_LENGTH * 8 + ); return Buffer.from(derivedKeyRaw).toString('hex'); } else { console.log('[crypt] Using Forge PBKDF2'); diff --git a/packages/insomnia-app/app/sync/index.js b/packages/insomnia-app/app/sync/index.js index c77796061e..c21fec5d29 100644 --- a/packages/insomnia-app/app/sync/index.js +++ b/packages/insomnia-app/app/sync/index.js @@ -7,9 +7,9 @@ import * as misc from '../common/misc'; import Logger from './logger'; import * as zlib from 'zlib'; -export const START_DELAY = 1E3; -export const PULL_PERIOD = 15E3; -export const WRITE_PERIOD = 1E3; +export const START_DELAY = 1e3; +export const PULL_PERIOD = 15e3; +export const WRITE_PERIOD = 1e3; const WHITE_LIST = { [models.workspace.type]: true, @@ -30,7 +30,7 @@ let _writeChangesInterval = null; let _pendingDBChanges = {}; let _isInitialized = false; -export async function init () { +export async function init() { if (_isInitialized) { logger.debug('Already enabled'); return; @@ -41,7 +41,7 @@ export async function init () { db.onChange(async changes => { // To help prevent bugs, put Workspaces first const sortedChanges = changes.sort( - ([event, doc, fromSync]) => doc.type === models.workspace.type ? 1 : -1 + ([event, doc, fromSync]) => (doc.type === models.workspace.type ? 1 : -1) ); for (const [event, doc, fromSync] of sortedChanges) { @@ -108,7 +108,7 @@ export async function init () { } // Used only during tests! -export function _testReset () { +export function _testReset() { _isInitialized = false; clearInterval(_pullChangesInterval); clearInterval(_writeChangesInterval); @@ -118,7 +118,7 @@ export function _testReset () { * Non-blocking function to perform initial sync for an account. This will pull * all remote resources (if they exist) before initializing sync. */ -export function doInitialSync () { +export function doInitialSync() { process.nextTick(async () => { // First, pull down all remote resources, without first creating new ones. // This makes sure that the first sync won't create resources locally, when @@ -135,7 +135,7 @@ export function doInitialSync () { * ResourceGroup created for them. This function should be called on init (or maybe * even periodically) and can be removed once the bug stops persisting. */ -export async function fixDuplicateResourceGroups () { +export async function fixDuplicateResourceGroups() { if (!session.isLoggedIn()) { return; } @@ -152,7 +152,7 @@ export async function fixDuplicateResourceGroups () { // Fix duplicates const ids = resources.map(r => r.resourceGroupId); - const {deleteResourceGroupIds} = await session.syncFixDupes(ids); + const { deleteResourceGroupIds } = await session.syncFixDupes(ids); for (const idToDelete of deleteResourceGroupIds) { await store.removeResourceGroup(idToDelete); @@ -162,13 +162,15 @@ export async function fixDuplicateResourceGroups () { } if (duplicateCount) { - logger.debug(`Fixed ${duplicateCount}/${workspaces.length} duplicate synced Workspaces`); + logger.debug( + `Fixed ${duplicateCount}/${workspaces.length} duplicate synced Workspaces` + ); } else { logger.debug('No dupes found to fix'); } } -export async function writePendingChanges () { +export async function writePendingChanges() { // First make a copy and clear pending changes const changes = Object.assign({}, _pendingDBChanges); _pendingDBChanges = {}; @@ -186,14 +188,16 @@ export async function writePendingChanges () { } } -export async function push (resourceGroupId = null) { +export async function push(resourceGroupId = null) { if (!session.isLoggedIn()) { return; } let dirtyResources = []; if (resourceGroupId) { - dirtyResources = await store.findActiveDirtyResourcesForResourceGroup(resourceGroupId); + dirtyResources = await store.findActiveDirtyResourcesForResourceGroup( + resourceGroupId + ); } else { dirtyResources = await store.findActiveDirtyResources(); } @@ -211,35 +215,30 @@ export async function push (resourceGroupId = null) { return; } - const { - updated, - created, - removed, - conflicts - } = responseBody; + const { updated, created, removed, conflicts } = responseBody; // Update all resource versions with the ones that were returned - for (const {id, version} of updated) { + for (const { id, version } of updated) { const resource = await store.getResourceByDocId(id); - await store.updateResource(resource, {version, dirty: false}); + await store.updateResource(resource, { version, dirty: false }); } if (updated.length) { logger.debug(`Push updated ${updated.length} resources`); } // Update all resource versions with the ones that were returned - for (const {id, version} of created) { + for (const { id, version } of created) { const resource = await store.getResourceByDocId(id); - await store.updateResource(resource, {version, dirty: false}); + await store.updateResource(resource, { version, dirty: false }); } if (created.length) { logger.debug(`Push created ${created.length} resources`); } // Update all resource versions with the ones that were returned - for (const {id, version} of removed) { + for (const { id, version } of removed) { const resource = await store.getResourceByDocId(id); - await store.updateResource(resource, {version, dirty: false}); + await store.updateResource(resource, { version, dirty: false }); } if (removed.length) { logger.debug(`Push removed ${removed.length} resources`); @@ -284,7 +283,10 @@ export async function push (resourceGroupId = null) { db.flushChangesAsync(); } -export async function pull (resourceGroupId = null, createMissingResources = true) { +export async function pull( + resourceGroupId = null, + createMissingResources = true +) { if (!session.isLoggedIn()) { return; } @@ -304,7 +306,9 @@ export async function pull (resourceGroupId = null, createMissingResources = tru if (resourceGroupId) { // When doing specific sync, blacklist all configs except the one we're trying to sync. const allConfigs = await store.allConfigs(); - blacklistedConfigs = allConfigs.filter(c => c.resourceGroupId !== resourceGroupId); + blacklistedConfigs = allConfigs.filter( + c => c.resourceGroupId !== resourceGroupId + ); } else { // When doing a full sync, blacklist the inactive configs blacklistedConfigs = await store.findInactiveConfigs(resourceGroupId); @@ -317,7 +321,9 @@ export async function pull (resourceGroupId = null, createMissingResources = tru removed: r.removed })); - const blacklistedResourceGroupIds = blacklistedConfigs.map(c => c.resourceGroupId); + const blacklistedResourceGroupIds = blacklistedConfigs.map( + c => c.resourceGroupId + ); const body = { resources, @@ -350,7 +356,7 @@ export async function pull (resourceGroupId = null, createMissingResources = tru let doc; try { - const {resourceGroupId, encContent} = serverResource; + const { resourceGroupId, encContent } = serverResource; doc = await decryptDoc(resourceGroupId, encContent); } catch (e) { logger.warn('Failed to decode created resource', e, serverResource); @@ -359,7 +365,7 @@ export async function pull (resourceGroupId = null, createMissingResources = tru // Update local Resource try { - await store.insertResource(serverResource, {dirty: false}); + await store.insertResource(serverResource, { dirty: false }); } catch (e) { // This probably means we already have it. This should never happen, but // might due to a rare race condition. @@ -377,8 +383,10 @@ export async function pull (resourceGroupId = null, createMissingResources = tru } else { // Mark as not seen if we created a new workspace from sync if (doc.type === models.workspace.type) { - const workspaceMeta = await models.workspaceMeta.getOrCreateByParentId(doc._id); - await models.workspaceMeta.update(workspaceMeta, {hasSeen: false}); + const workspaceMeta = await models.workspaceMeta.getOrCreateByParentId( + doc._id + ); + await models.workspaceMeta.update(workspaceMeta, { hasSeen: false }); } await db.insert(doc, true); } @@ -397,7 +405,7 @@ export async function pull (resourceGroupId = null, createMissingResources = tru await db.bufferChanges(); for (const serverResource of updatedResources) { try { - const {resourceGroupId, encContent} = serverResource; + const { resourceGroupId, encContent } = serverResource; const doc = await decryptDoc(resourceGroupId, encContent); // Update app database @@ -409,7 +417,7 @@ export async function pull (resourceGroupId = null, createMissingResources = tru serverResource.id, serverResource.resourceGroupId ); - await store.updateResource(resource, serverResource, {dirty: false}); + await store.updateResource(resource, serverResource, { dirty: false }); } catch (e) { logger.warn('Failed to decode updated resource', e, serverResource); } @@ -437,7 +445,7 @@ export async function pull (resourceGroupId = null, createMissingResources = tru } // Mark resource as deleted - await store.updateResource(resource, {dirty: false, removed: true}); + await store.updateResource(resource, { dirty: false, removed: true }); // Remove from DB await db.remove(doc, true); @@ -455,32 +463,32 @@ export async function pull (resourceGroupId = null, createMissingResources = tru } // Mark all resources to push as dirty for the next push - await store.updateResource(resource, {dirty: true}); + await store.updateResource(resource, { dirty: true }); } return updatedResources.length + createdResources.length; } -export async function getOrCreateConfig (resourceGroupId) { +export async function getOrCreateConfig(resourceGroupId) { const config = await store.getConfig(resourceGroupId); if (!config) { - return store.insertConfig({resourceGroupId}); + return store.insertConfig({ resourceGroupId }); } else { return config; } } -export async function ensureConfigExists (resourceGroupId, syncMode) { +export async function ensureConfigExists(resourceGroupId, syncMode) { const config = await store.getConfig(resourceGroupId); if (!config) { - await store.insertConfig({resourceGroupId, syncMode}); + await store.insertConfig({ resourceGroupId, syncMode }); } } -export async function createOrUpdateConfig (resourceGroupId, syncMode) { +export async function createOrUpdateConfig(resourceGroupId, syncMode) { const config = await store.getConfig(resourceGroupId); - const patch = {resourceGroupId, syncMode}; + const patch = { resourceGroupId, syncMode }; if (config) { return store.updateConfig(config, patch); @@ -489,18 +497,18 @@ export async function createOrUpdateConfig (resourceGroupId, syncMode) { } } -export async function logout () { +export async function logout() { await session.logout(); await resetLocalData(); } -export async function cancelTrial () { +export async function cancelTrial() { await session.endTrial(); await session.logout(); await resetLocalData(); } -export async function resetLocalData () { +export async function resetLocalData() { for (const c of await store.allConfigs()) { await store.removeConfig(c); } @@ -510,7 +518,7 @@ export async function resetLocalData () { } } -export async function resetRemoteData () { +export async function resetRemoteData() { await session.syncResetData(); } @@ -518,7 +526,7 @@ export async function resetRemoteData () { // HELPERS // // ~~~~~~~ // -async function _handleChangeAndPush (event, doc, timestamp) { +async function _handleChangeAndPush(event, doc, timestamp) { // Update the resource content and set dirty // TODO: Remove one of these steps since it does encryption twice // in the case where the resource does not exist yet @@ -546,7 +554,10 @@ async function _handleChangeAndPush (event, doc, timestamp) { const _fetchResourceGroupPromises = {}; const _resourceGroupCache = {}; -export async function fetchResourceGroup (resourceGroupId, invalidateCache = false) { +export async function fetchResourceGroup( + resourceGroupId, + invalidateCache = false +) { if (invalidateCache) { delete _resourceGroupCache[resourceGroupId]; delete _fetchResourceGroupPromises[resourceGroupId]; @@ -610,7 +621,7 @@ export async function fetchResourceGroup (resourceGroupId, invalidateCache = fal * @param resourceGroupId * @private */ -async function _getResourceGroupSymmetricKey (resourceGroupId) { +async function _getResourceGroupSymmetricKey(resourceGroupId) { let key = resourceGroupSymmetricKeysCache[resourceGroupId]; if (!key) { @@ -631,7 +642,7 @@ async function _getResourceGroupSymmetricKey (resourceGroupId) { return key; } -export async function encryptDoc (resourceGroupId, doc) { +export async function encryptDoc(resourceGroupId, doc) { try { const symmetricKey = await _getResourceGroupSymmetricKey(resourceGroupId); @@ -650,14 +661,17 @@ export async function encryptDoc (resourceGroupId, doc) { } } -export async function decryptDoc (resourceGroupId, messageJSON) { +export async function decryptDoc(resourceGroupId, messageJSON) { let decrypted; try { const symmetricKey = await _getResourceGroupSymmetricKey(resourceGroupId); const message = JSON.parse(messageJSON); decrypted = crypt.decryptAES(symmetricKey, message); } catch (e) { - logger.error(`Failed to decrypt from ${resourceGroupId}: ${e}`, messageJSON); + logger.error( + `Failed to decrypt from ${resourceGroupId}: ${e}`, + messageJSON + ); throw e; } @@ -670,29 +684,39 @@ export async function decryptDoc (resourceGroupId, messageJSON) { try { return JSON.parse(decrypted); } catch (e) { - logger.error(`Failed to parse after decrypt from ${resourceGroupId}: ${e}`, decrypted); + logger.error( + `Failed to parse after decrypt from ${resourceGroupId}: ${e}`, + decrypted + ); throw e; } } -async function _getWorkspaceForDoc (doc) { +async function _getWorkspaceForDoc(doc) { const ancestors = await db.withAncestors(doc); return ancestors.find(d => d.type === models.workspace.type); } -export async function createResourceGroup (parentId, name) { +export async function createResourceGroup(parentId, name) { // Generate symmetric key for ResourceGroup const rgSymmetricJWK = await crypt.generateAES256Key(); const rgSymmetricJWKStr = JSON.stringify(rgSymmetricJWK); // Encrypt the symmetric key with Account public key const publicJWK = session.getPublicKey(); - const encRGSymmetricJWK = crypt.encryptRSAWithJWK(publicJWK, rgSymmetricJWKStr); + const encRGSymmetricJWK = crypt.encryptRSAWithJWK( + publicJWK, + rgSymmetricJWKStr + ); // Create the new ResourceGroup let resourceGroup; try { - resourceGroup = await session.syncCreateResourceGroup(parentId, name, encRGSymmetricJWK); + resourceGroup = await session.syncCreateResourceGroup( + parentId, + name, + encRGSymmetricJWK + ); } catch (e) { logger.error(`Failed to create ResourceGroup: ${e}`); throw e; @@ -705,7 +729,7 @@ export async function createResourceGroup (parentId, name) { return resourceGroup; } -export async function createResource (doc, resourceGroupId) { +export async function createResource(doc, resourceGroupId) { return store.insertResource({ id: doc._id, name: doc.name || 'n/a', // Set name to the doc name if it has one @@ -721,7 +745,7 @@ export async function createResource (doc, resourceGroupId) { }); } -export async function createResourceForDoc (doc) { +export async function createResourceForDoc(doc) { // No resource yet, so create one const workspace = await _getWorkspaceForDoc(doc); @@ -734,8 +758,14 @@ export async function createResourceForDoc (doc) { let workspaceResource = await store.getResourceByDocId(workspace._id); if (!workspaceResource) { - const workspaceResourceGroup = await createResourceGroup(workspace._id, workspace.name); - workspaceResource = await createResource(workspace, workspaceResourceGroup.id); + const workspaceResourceGroup = await createResourceGroup( + workspace._id, + workspace.name + ); + workspaceResource = await createResource( + workspace, + workspaceResourceGroup.id + ); } if (workspace === doc) { @@ -746,7 +776,7 @@ export async function createResourceForDoc (doc) { } } -export async function getOrCreateResourceForDoc (doc) { +export async function getOrCreateResourceForDoc(doc) { let [resource, ...extras] = await store.findResourcesByDocId(doc._id); // Sometimes there may be multiple resources created by accident for @@ -762,13 +792,15 @@ export async function getOrCreateResourceForDoc (doc) { } } -export async function getOrCreateAllActiveResources (resourceGroupId = null) { +export async function getOrCreateAllActiveResources(resourceGroupId = null) { const startTime = Date.now(); const activeResourceMap = {}; let activeResources; if (resourceGroupId) { - activeResources = await store.activeResourcesForResourceGroup(resourceGroupId); + activeResources = await store.activeResourcesForResourceGroup( + resourceGroupId + ); } else { activeResources = await store.allActiveResources(); } @@ -779,7 +811,7 @@ export async function getOrCreateAllActiveResources (resourceGroupId = null) { // Make sure Workspace is first, because the loop below depends on it const modelTypes = Object.keys(WHITE_LIST).sort( - (a, b) => a.type === models.workspace.type ? 1 : -1 + (a, b) => (a.type === models.workspace.type ? 1 : -1) ); let created = 0; @@ -802,11 +834,15 @@ export async function getOrCreateAllActiveResources (resourceGroupId = null) { } } - const resources = Object.keys(activeResourceMap).map(k => activeResourceMap[k]); + const resources = Object.keys(activeResourceMap).map( + k => activeResourceMap[k] + ); const time = (Date.now() - startTime) / 1000; if (created > 0) { - logger.debug(`Created ${created}/${resources.length} Resources (${time.toFixed(2)}s)`); + logger.debug( + `Created ${created}/${resources.length} Resources (${time.toFixed(2)}s)` + ); } return resources; } diff --git a/packages/insomnia-app/app/sync/logger.js b/packages/insomnia-app/app/sync/logger.js index 8812ae309c..5c7bf391eb 100644 --- a/packages/insomnia-app/app/sync/logger.js +++ b/packages/insomnia-app/app/sync/logger.js @@ -1,26 +1,26 @@ export default class Logger { - constructor () { + constructor() { this._logs = []; } - debug (message, ...args) { + debug(message, ...args) { this._log('debug', message, ...args); } - warn (message, ...args) { + warn(message, ...args) { this._log('warn', message, ...args); } - error (message, ...args) { + error(message, ...args) { this._log('error', message, ...args); } - tail () { + tail() { return this._logs; } /** @private */ - _log (type, message, ...args) { + _log(type, message, ...args) { let fn; if (type === 'debug') { fn = 'log'; @@ -32,6 +32,6 @@ export default class Logger { console[fn](`[sync] ${message}`, ...args); const date = new Date(); - this._logs.push({type, date, message}); + this._logs.push({ type, date, message }); } } diff --git a/packages/insomnia-app/app/sync/session.js b/packages/insomnia-app/app/sync/session.js index 0944a57945..90ce5f089f 100644 --- a/packages/insomnia-app/app/sync/session.js +++ b/packages/insomnia-app/app/sync/session.js @@ -3,7 +3,7 @@ import * as crypt from './crypt'; import * as util from '../common/fetch'; /** Create a new session for the user */ -export async function login (rawEmail, rawPassphrase) { +export async function login(rawEmail, rawPassphrase) { // ~~~~~~~~~~~~~~~ // // Sanitize Inputs // // ~~~~~~~~~~~~~~~ // @@ -15,7 +15,7 @@ export async function login (rawEmail, rawPassphrase) { // Fetch Salt and Submit A To Server // // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // - const {saltKey, saltAuth} = await util.post('/auth/login-s', {email}); + const { saltKey, saltAuth } = await util.post('/auth/login-s', { email }); const authSecret = await crypt.deriveKey(passphrase, email, saltKey); const secret1 = await crypt.srpGenKey(); const c = new srp.Client( @@ -26,7 +26,10 @@ export async function login (rawEmail, rawPassphrase) { Buffer.from(secret1, 'hex') ); const srpA = c.computeA().toString('hex'); - const {sessionStarterId, srpB} = await util.post('/auth/login-a', {srpA, email}); + const { sessionStarterId, srpB } = await util.post('/auth/login-a', { + srpA, + email + }); // ~~~~~~~~~~~~~~~~~~~~~ // // Compute and Submit M1 // @@ -34,7 +37,10 @@ export async function login (rawEmail, rawPassphrase) { c.setB(Buffer.from(srpB, 'hex')); const srpM1 = c.computeM1().toString('hex'); - const {srpM2} = await util.post('/auth/login-m1', {srpM1, sessionStarterId}); + const { srpM2 } = await util.post('/auth/login-m1', { + srpM1, + sessionStarterId + }); // ~~~~~~~~~~~~~~~~~~~~~~~~~ // // Verify Server Identity M2 // @@ -61,7 +67,10 @@ export async function login (rawEmail, rawPassphrase) { } = await whoami(sessionId); const derivedSymmetricKey = await crypt.deriveKey(passphrase, email, saltEnc); - const symmetricKeyStr = await crypt.decryptAES(derivedSymmetricKey, JSON.parse(encSymmetricKey)); + const symmetricKeyStr = await crypt.decryptAES( + derivedSymmetricKey, + JSON.parse(encSymmetricKey) + ); // Store the information for later setSessionData( @@ -76,41 +85,52 @@ export async function login (rawEmail, rawPassphrase) { ); } -export function syncCreateResourceGroup (parentResourceId, name, encSymmetricKey) { - return util.post('/api/resource_groups', {parentResourceId, name, encSymmetricKey}); +export function syncCreateResourceGroup( + parentResourceId, + name, + encSymmetricKey +) { + return util.post('/api/resource_groups', { + parentResourceId, + name, + encSymmetricKey + }); } -export function syncGetResourceGroup (id) { +export function syncGetResourceGroup(id) { return util.get(`/api/resource_groups/${id}`); } -export function syncPull (body) { +export function syncPull(body) { return util.post('/sync/pull', body); } -export function syncPush (body) { +export function syncPush(body) { return util.post('/sync/push', body); } -export function syncResetData () { +export function syncResetData() { return util.post('/auth/reset'); } -export function syncFixDupes (resourceGroupIds) { - return util.post('/sync/fix-dupes', {ids: resourceGroupIds}); +export function syncFixDupes(resourceGroupIds) { + return util.post('/sync/fix-dupes', { ids: resourceGroupIds }); } -export function unshareWithAllTeams (resourceGroupId) { +export function unshareWithAllTeams(resourceGroupId) { return util.put(`/api/resource_groups/${resourceGroupId}/unshare`); } -export async function shareWithTeam (resourceGroupId, teamId, rawPassphrase) { +export async function shareWithTeam(resourceGroupId, teamId, rawPassphrase) { // Ask the server what we need to do to invite the member - const instructions = await util.post(`/api/resource_groups/${resourceGroupId}/share-a`, {teamId}); + const instructions = await util.post( + `/api/resource_groups/${resourceGroupId}/share-a`, + { teamId } + ); // Compute keys necessary to invite the member const passPhrase = _sanitizePassphrase(rawPassphrase); - const {email, saltEnc, encPrivateKey, encSymmetricKey} = await whoami(); + const { email, saltEnc, encPrivateKey, encSymmetricKey } = await whoami(); const secret = await crypt.deriveKey(passPhrase, email, saltEnc); let symmetricKey; try { @@ -118,7 +138,10 @@ export async function shareWithTeam (resourceGroupId, teamId, rawPassphrase) { } catch (err) { throw new Error('Invalid password'); } - const privateKey = crypt.decryptAES(JSON.parse(symmetricKey), JSON.parse(encPrivateKey)); + const privateKey = crypt.decryptAES( + JSON.parse(symmetricKey), + JSON.parse(encPrivateKey) + ); const privateKeyJWK = JSON.parse(privateKey); const resourceGroupSymmetricKey = crypt.decryptRSAWithJWK( privateKeyJWK, @@ -136,20 +159,23 @@ export async function shareWithTeam (resourceGroupId, teamId, rawPassphrase) { } // Actually share it with the team - await util.post(`/api/resource_groups/${resourceGroupId}/share-b`, {teamId, keys: newKeys}); + await util.post(`/api/resource_groups/${resourceGroupId}/share-b`, { + teamId, + keys: newKeys + }); } -export function getPublicKey () { +export function getPublicKey() { return getSessionData().publicKey; } -export function getPrivateKey () { - const {symmetricKey, encPrivateKey} = getSessionData(); +export function getPrivateKey() { + const { symmetricKey, encPrivateKey } = getSessionData(); const privateKeyStr = crypt.decryptAES(symmetricKey, encPrivateKey); return JSON.parse(privateKeyStr); } -export function getCurrentSessionId () { +export function getCurrentSessionId() { if (window) { return window.localStorage.getItem('currentSessionId'); } else { @@ -157,20 +183,20 @@ export function getCurrentSessionId () { } } -export function getAccountId () { +export function getAccountId() { return getSessionData().accountId; } -export function getEmail () { +export function getEmail() { return getSessionData().email; } -export function getFirstName () { +export function getFirstName() { return getSessionData().firstName; } -export function getFullName () { - const {firstName, lastName} = getSessionData(); +export function getFullName() { + const { firstName, lastName } = getSessionData(); return `${firstName || ''} ${lastName || ''}`.trim(); } @@ -178,7 +204,7 @@ export function getFullName () { * get Data about the current session * @returns Object */ -export function getSessionData () { +export function getSessionData() { const sessionId = getCurrentSessionId(); if (!sessionId || !window) { return {}; @@ -189,14 +215,16 @@ export function getSessionData () { } /** Set data for the new session and store it encrypted with the sessionId */ -export function setSessionData (sessionId, - accountId, - firstName, - lastName, - email, - symmetricKey, - publicKey, - encPrivateKey) { +export function setSessionData( + sessionId, + accountId, + firstName, + lastName, + email, + symmetricKey, + publicKey, + encPrivateKey +) { const dataStr = JSON.stringify({ id: sessionId, accountId: accountId, @@ -215,19 +243,19 @@ export function setSessionData (sessionId, } /** Unset the session data (log out) */ -export function unsetSessionData () { +export function unsetSessionData() { const sessionId = getCurrentSessionId(); window.localStorage.removeItem(getSessionKey(sessionId)); window.localStorage.removeItem(`currentSessionId`); } /** Check if we (think) we have a session */ -export function isLoggedIn () { +export function isLoggedIn() { return getCurrentSessionId(); } /** Log out and delete session data */ -export async function logout () { +export async function logout() { try { await util.post('/auth/logout'); } catch (e) { @@ -239,19 +267,19 @@ export async function logout () { unsetSessionData(); } -export async function listTeams () { +export async function listTeams() { return util.get('/api/teams'); } -export async function endTrial () { +export async function endTrial() { await util.put('/api/billing/end-trial'); } -export function whoami (sessionId = null) { +export function whoami(sessionId = null) { return util.get('/auth/whoami', sessionId); } -export function getSessionKey (sessionId) { +export function getSessionKey(sessionId) { return `session__${(sessionId || '').slice(0, 10)}`; } @@ -259,14 +287,14 @@ export function getSessionKey (sessionId) { // Helper Functions // // ~~~~~~~~~~~~~~~~ // -function _getSrpParams () { +function _getSrpParams() { return srp.params[2048]; } -function _sanitizeEmail (email) { +function _sanitizeEmail(email) { return email.trim().toLowerCase(); } -function _sanitizePassphrase (passphrase) { +function _sanitizePassphrase(passphrase) { return passphrase.trim().normalize('NFKD'); } diff --git a/packages/insomnia-app/app/sync/storage.js b/packages/insomnia-app/app/sync/storage.js index 4db4f288e4..d1cc55b348 100644 --- a/packages/insomnia-app/app/sync/storage.js +++ b/packages/insomnia-app/app/sync/storage.js @@ -3,7 +3,7 @@ import NeDB from 'nedb'; import fsPath from 'path'; import crypto from 'crypto'; import * as util from '../common/misc'; -import {DB_PERSIST_INTERVAL} from '../common/constants'; +import { DB_PERSIST_INTERVAL } from '../common/constants'; const TYPE_RESOURCE = 'Resource'; const TYPE_CONFIG = 'Config'; @@ -14,16 +14,16 @@ export const SYNC_MODE_NEVER = 'never'; export const SYNC_MODE_UNSET = 'unset'; let changeListeners = []; -export function onChange (callback) { +export function onChange(callback) { changeListeners.push(callback); } -export function offChange (callback) { +export function offChange(callback) { changeListeners = changeListeners.filter(l => l !== callback); } let _changeTimeout = null; -function _notifyChange () { +function _notifyChange() { clearTimeout(_changeTimeout); _changeTimeout = setTimeout(() => { for (const fn of changeListeners) { @@ -32,54 +32,58 @@ function _notifyChange () { }, 200); } -export function allActiveResources (resourceGroupId = null) { +export function allActiveResources(resourceGroupId = null) { if (resourceGroupId) { - return findActiveResources({resourceGroupId}); + return findActiveResources({ resourceGroupId }); } else { return findActiveResources({}); } } -export function activeResourcesForResourceGroup (resourceGroupId) { - return findActiveResources({resourceGroupId}); +export function activeResourcesForResourceGroup(resourceGroupId) { + return findActiveResources({ resourceGroupId }); } -export function allResources () { +export function allResources() { return findResources({}); } -export async function findResources (query = {}) { +export async function findResources(query = {}) { return _execDB(TYPE_RESOURCE, 'find', query); } -export async function findActiveResources (query) { +export async function findActiveResources(query) { const configs = await findActiveConfigs(); const resourceGroupIds = configs.map(c => c.resourceGroupId); - return findResources(Object.assign({resourceGroupId: {$in: resourceGroupIds}}, query)); + return findResources( + Object.assign({ resourceGroupId: { $in: resourceGroupIds } }, query) + ); } -export async function findActiveDirtyResources () { - return findActiveResources({dirty: true}); +export async function findActiveDirtyResources() { + return findActiveResources({ dirty: true }); } -export async function findActiveDirtyResourcesForResourceGroup (resourceGroupId) { - return findActiveResources({dirty: true, resourceGroupId}); +export async function findActiveDirtyResourcesForResourceGroup( + resourceGroupId +) { + return findActiveResources({ dirty: true, resourceGroupId }); } -export async function findDirtyResourcesForResourceGroup (resourceGroupId) { - return findResources({dirty: true, resourceGroupId}); +export async function findDirtyResourcesForResourceGroup(resourceGroupId) { + return findResources({ dirty: true, resourceGroupId }); } -export async function findResourcesForResourceGroup (resourceGroupId) { - return findResources({resourceGroupId}); +export async function findResourcesForResourceGroup(resourceGroupId) { + return findResources({ resourceGroupId }); } -export async function getResourceByDocId (id, resourceGroupId = null) { +export async function getResourceByDocId(id, resourceGroupId = null) { let query; if (resourceGroupId) { - query = {id, resourceGroupId}; + query = { id, resourceGroupId }; } else { - query = {id}; + query = { id }; } const rawDocs = await _execDB(TYPE_RESOURCE, 'find', query); @@ -92,8 +96,8 @@ export async function getResourceByDocId (id, resourceGroupId = null) { * @param id * @returns {*} */ -export function findResourcesByDocId (id) { - return _execDB(TYPE_RESOURCE, 'find', {id}); +export function findResourcesByDocId(id) { + return _execDB(TYPE_RESOURCE, 'find', { id }); } /** @@ -102,31 +106,40 @@ export function findResourcesByDocId (id) { * @param resourceGroupId * @returns {*} */ -export async function removeResourceGroup (resourceGroupId) { - await _execDB(TYPE_RESOURCE, 'remove', {resourceGroupId}, {multi: true}); - await _execDB(TYPE_CONFIG, 'remove', {resourceGroupId}, {multi: true}); +export async function removeResourceGroup(resourceGroupId) { + await _execDB(TYPE_RESOURCE, 'remove', { resourceGroupId }, { multi: true }); + await _execDB(TYPE_CONFIG, 'remove', { resourceGroupId }, { multi: true }); _notifyChange(); } -export async function insertResource (resource) { +export async function insertResource(resource) { const h = crypto.createHash('md5'); h.update(resource.resourceGroupId); h.update(resource.id); - const newResource = Object.assign({}, resource, {_id: `rs_${h.digest('hex')}`}); + const newResource = Object.assign({}, resource, { + _id: `rs_${h.digest('hex')}` + }); await _execDB(TYPE_RESOURCE, 'insert', newResource); _notifyChange(); return newResource; } -export async function updateResource (resource, ...patches) { +export async function updateResource(resource, ...patches) { const newDoc = Object.assign({}, resource, ...patches); - await _execDB(TYPE_RESOURCE, 'update', {_id: resource._id}, newDoc, {multi: true}); + await _execDB(TYPE_RESOURCE, 'update', { _id: resource._id }, newDoc, { + multi: true + }); _notifyChange(); return newDoc; } -export async function removeResource (resource) { - await _execDB(TYPE_RESOURCE, 'remove', {_id: resource._id}, {multi: true}); +export async function removeResource(resource) { + await _execDB( + TYPE_RESOURCE, + 'remove', + { _id: resource._id }, + { multi: true } + ); _notifyChange(); } @@ -134,60 +147,65 @@ export async function removeResource (resource) { // Config // // ~~~~~~ // -export function findConfigs (query) { +export function findConfigs(query) { return _execDB(TYPE_CONFIG, 'find', query); } -export function allConfigs () { +export function allConfigs() { return findConfigs({}); } -export function findInactiveConfigs (excludedResourceGroupId = null) { +export function findInactiveConfigs(excludedResourceGroupId = null) { if (excludedResourceGroupId) { - return findConfigs({$not: {syncMode: SYNC_MODE_ON, excludedResourceGroupId}}); + return findConfigs({ + $not: { syncMode: SYNC_MODE_ON, excludedResourceGroupId } + }); } else { - return findConfigs({$not: {syncMode: SYNC_MODE_ON}}); + return findConfigs({ $not: { syncMode: SYNC_MODE_ON } }); } } -export function findActiveConfigs (resourceGroupId = null) { +export function findActiveConfigs(resourceGroupId = null) { if (resourceGroupId) { - return findConfigs({syncMode: SYNC_MODE_ON, resourceGroupId}); + return findConfigs({ syncMode: SYNC_MODE_ON, resourceGroupId }); } else { - return findConfigs({syncMode: SYNC_MODE_ON}); + return findConfigs({ syncMode: SYNC_MODE_ON }); } } -export async function getConfig (resourceGroupId) { - const rawDocs = await _execDB(TYPE_CONFIG, 'find', {resourceGroupId}); +export async function getConfig(resourceGroupId) { + const rawDocs = await _execDB(TYPE_CONFIG, 'find', { resourceGroupId }); return rawDocs.length >= 1 ? _initConfig(rawDocs[0]) : null; } -export async function updateConfig (config, ...patches) { +export async function updateConfig(config, ...patches) { const doc = _initConfig(Object.assign(config, ...patches)); - await _execDB(TYPE_CONFIG, 'update', {_id: doc._id}, doc); + await _execDB(TYPE_CONFIG, 'update', { _id: doc._id }, doc); return doc; } -export function removeConfig (config) { - return _execDB(TYPE_CONFIG, 'remove', {_id: config._id}); +export function removeConfig(config) { + return _execDB(TYPE_CONFIG, 'remove', { _id: config._id }); } -export async function insertConfig (config) { +export async function insertConfig(config) { const doc = _initConfig(config); await _execDB(TYPE_CONFIG, 'insert', doc); return doc; } -function _initConfig (data) { - return Object.assign({ - _id: util.generateId('scf'), - syncMode: SYNC_MODE_UNSET, - resourceGroupId: null - }, data); +function _initConfig(data) { + return Object.assign( + { + _id: util.generateId('scf'), + syncMode: SYNC_MODE_UNSET, + resourceGroupId: null + }, + data + ); } -export function initDB (config, forceReset) { +export function initDB(config, forceReset) { if (!_database || forceReset) { const basePath = electron.remote.app.getPath('userData'); _database = {}; @@ -198,11 +216,11 @@ export function initDB (config, forceReset) { // Fill in the defaults _database['Resource'] = new NeDB( - Object.assign({filename: resourcePath, autoload: true}, config) + Object.assign({ filename: resourcePath, autoload: true }, config) ); _database['Config'] = new NeDB( - Object.assign({filename: configPath, autoload: true}, config) + Object.assign({ filename: configPath, autoload: true }, config) ); for (const key of Object.keys(_database)) { @@ -220,12 +238,12 @@ export function initDB (config, forceReset) { let _database = null; -function _getDB (type, config = {}) { +function _getDB(type, config = {}) { initDB(config); return _database[type]; } -function _execDB (type, fnName, ...args) { +function _execDB(type, fnName, ...args) { return new Promise((resolve, reject) => { _getDB(type)[fnName](...args, (err, data) => { err ? reject(err) : resolve(data); diff --git a/packages/insomnia-app/app/templating/__tests__/utils.test.js b/packages/insomnia-app/app/templating/__tests__/utils.test.js index fbb4e35e92..64e28b6680 100644 --- a/packages/insomnia-app/app/templating/__tests__/utils.test.js +++ b/packages/insomnia-app/app/templating/__tests__/utils.test.js @@ -1,51 +1,44 @@ import * as utils from '../utils'; -import {globalBeforeEach} from '../../__jest__/before-each'; +import { globalBeforeEach } from '../../__jest__/before-each'; describe('getKeys()', () => { beforeEach(globalBeforeEach); it('flattens complex object', () => { const obj = { foo: 'bar', - nested: {a: {b: {}}}, + nested: { a: { b: {} } }, null: null, undefined: undefined, false: false, - array: [ - 'hello', - {hi: 'there'}, - true, - ['x', 'y', 'z'] - ] + array: ['hello', { hi: 'there' }, true, ['x', 'y', 'z']] }; - const keys = utils - .getKeys(obj) - .sort((a, b) => a.name > b.name ? 1 : -1); + const keys = utils.getKeys(obj).sort((a, b) => (a.name > b.name ? 1 : -1)); expect(keys).toEqual([ - {name: 'array[0]', value: obj.array[0]}, - {name: 'array[1].hi', value: obj.array[1].hi}, - {name: 'array[2]', value: obj.array[2]}, - {name: 'array[3][0]', value: obj.array[3][0]}, - {name: 'array[3][1]', value: obj.array[3][1]}, - {name: 'array[3][2]', value: obj.array[3][2]}, - {name: 'false', value: obj.false}, - {name: 'foo', value: obj.foo}, - {name: 'null', value: obj.null}, - {name: 'undefined', value: obj.undefined} + { name: 'array[0]', value: obj.array[0] }, + { name: 'array[1].hi', value: obj.array[1].hi }, + { name: 'array[2]', value: obj.array[2] }, + { name: 'array[3][0]', value: obj.array[3][0] }, + { name: 'array[3][1]', value: obj.array[3][1] }, + { name: 'array[3][2]', value: obj.array[3][2] }, + { name: 'false', value: obj.false }, + { name: 'foo', value: obj.foo }, + { name: 'null', value: obj.null }, + { name: 'undefined', value: obj.undefined } ]); }); it('ignores functions', () => { const obj = { foo: 'bar', - toString: function () { + toString: function() { // Nothing } }; const keys = utils.getKeys(obj); - expect(keys).toEqual([{name: 'foo', value: 'bar'}]); + expect(keys).toEqual([{ name: 'foo', value: 'bar' }]); }); }); @@ -59,9 +52,9 @@ describe('tokenizeTag()', () => { const expected = { name: 'name', args: [ - {type: 'variable', value: 'bar'}, - {type: 'string', value: 'baz "qux"', quotedBy: '"'}, - {type: 'expression', value: '1 + 5 | default("foo")'} + { type: 'variable', value: 'bar' }, + { type: 'string', value: 'baz "qux"', quotedBy: '"' }, + { type: 'expression', value: '1 + 5 | default("foo")' } ] }; @@ -75,8 +68,8 @@ describe('tokenizeTag()', () => { const expected = { name: 'name', args: [ - {type: 'string', value: 'foo', quotedBy: "'"}, - {type: 'variable', value: 'bar'} + { type: 'string', value: 'foo', quotedBy: "'" }, + { type: 'variable', value: 'bar' } ] }; @@ -89,7 +82,7 @@ describe('tokenizeTag()', () => { const expected = { name: 'name', - args: [{type: 'string', value: 'foo', quotedBy: "'"}] + args: [{ type: 'string', value: 'foo', quotedBy: "'" }] }; expect(actual).toEqual(expected); @@ -101,9 +94,9 @@ describe('tokenizeTag()', () => { const expected = { name: 'name', args: [ - {type: 'number', value: '9.324'}, - {type: 'number', value: '8'}, - {type: 'number', value: '7'} + { type: 'number', value: '9.324' }, + { type: 'number', value: '8' }, + { type: 'number', value: '7' } ] }; @@ -116,8 +109,8 @@ describe('tokenizeTag()', () => { const expected = { name: 'name', args: [ - {type: 'boolean', value: true}, - {type: 'boolean', value: false} + { type: 'boolean', value: true }, + { type: 'boolean', value: false } ] }; @@ -125,11 +118,13 @@ describe('tokenizeTag()', () => { }); it('handles type expression', () => { - const actual = utils.tokenizeTag(`{% name 5 * 10 + 'hello' | default(2 - 3) %}`); + const actual = utils.tokenizeTag( + `{% name 5 * 10 + 'hello' | default(2 - 3) %}` + ); const expected = { name: 'name', - args: [{type: 'expression', value: `5 * 10 + 'hello' | default(2 - 3)`}] + args: [{ type: 'expression', value: `5 * 10 + 'hello' | default(2 - 3)` }] }; expect(actual).toEqual(expected); @@ -144,7 +139,7 @@ describe('tokenizeTag()', () => { const expected = { name: 'name', - args: [{type: 'expression', value: 'foo bar baz'}] + args: [{ type: 'expression', value: 'foo bar baz' }] }; expect(actual).toEqual(expected); @@ -166,8 +161,8 @@ describe('unTokenizeTag()', () => { const tagData = { name: 'name', args: [ - {type: 'file', value: 'foo/bar/baz'}, - {type: 'model', value: 'foo'} + { type: 'file', value: 'foo/bar/baz' }, + { type: 'model', value: 'foo' } ] }; diff --git a/packages/insomnia-app/app/templating/base-extension.js b/packages/insomnia-app/app/templating/base-extension.js index a7045a5c61..f579c89a11 100644 --- a/packages/insomnia-app/app/templating/base-extension.js +++ b/packages/insomnia-app/app/templating/base-extension.js @@ -5,41 +5,41 @@ import * as pluginContexts from '../plugins/context'; const EMPTY_ARG = '__EMPTY_NUNJUCKS_ARG__'; export default class BaseExtension { - constructor (ext, plugin) { + constructor(ext, plugin) { this._ext = ext; this._plugin = plugin; this.tags = [this.getTag()]; } - getTag () { + getTag() { return this._ext.name; } - getPriority () { + getPriority() { return this._ext.priority || -1; } - getName () { + getName() { return this._ext.displayName || this.getTag(); } - getDescription () { + getDescription() { return this._ext.description || 'no description'; } - getArgs () { + getArgs() { return this._ext.args || []; } - isDeprecated () { + isDeprecated() { return this._ext.deprecated || false; } - run (...args) { + run(...args) { return this._ext.run(...args); } - parse (parser, nodes, lexer) { + parse(parser, nodes, lexer) { const tok = parser.nextToken(); let args; @@ -55,7 +55,7 @@ export default class BaseExtension { return new nodes.CallExtensionAsync(this, 'asyncRun', args); } - asyncRun ({ctx: renderContext}, ...runArgs) { + asyncRun({ ctx: renderContext }, ...runArgs) { // Pull the callback off the end const callback = runArgs[runArgs.length - 1]; @@ -63,7 +63,9 @@ export default class BaseExtension { const renderMeta = renderContext.getMeta ? renderContext.getMeta() : {}; // Pull out the purpose - const renderPurpose = renderContext.getPurpose ? renderContext.getPurpose() : null; + const renderPurpose = renderContext.getPurpose + ? renderContext.getPurpose() + : null; // Extract the rest of the args const args = runArgs @@ -77,12 +79,12 @@ export default class BaseExtension { context: renderContext, meta: renderMeta, util: { - render: str => templating.render(str, {context: renderContext}), + render: str => templating.render(str, { context: renderContext }), models: { - request: {getById: models.request.getById}, - requestGroup: {getById: models.requestGroup.getById}, - workspace: {getById: models.workspace.getById}, - oAuth2Token: {getByRequestId: models.oAuth2Token.getByParentId}, + request: { getById: models.request.getById }, + requestGroup: { getById: models.requestGroup.getById }, + workspace: { getById: models.workspace.getById }, + oAuth2Token: { getByRequestId: models.oAuth2Token.getByParentId }, cookieJar: { getOrCreateForWorkspace: workspace => { return models.cookieJar.getOrCreateForParentId(workspace._id); diff --git a/packages/insomnia-app/app/templating/extensions/index.js b/packages/insomnia-app/app/templating/extensions/index.js index eeb46612f8..9131e959ff 100644 --- a/packages/insomnia-app/app/templating/extensions/index.js +++ b/packages/insomnia-app/app/templating/extensions/index.js @@ -1,16 +1,16 @@ // @flow -import type {NunjucksParsedTagArg} from '../utils'; -import type {Request} from '../../models/request'; -import type {Response} from '../../models/response'; +import type { NunjucksParsedTagArg } from '../utils'; +import type { Request } from '../../models/request'; +import type { Response } from '../../models/response'; export type PluginArgumentValue = string | number | boolean; -type DisplayName = string | (args: Array) => string; +type DisplayName = string | ((args: Array) => string); type PluginArgumentBase = { displayName: DisplayName, description?: string, help?: string, - hide?: (args: Array) => boolean, + hide?: (args: Array) => boolean }; export type PluginArgumentEnumOption = { @@ -18,7 +18,7 @@ export type PluginArgumentEnumOption = { value: PluginArgumentValue, description?: string, placeholder?: string -} +}; export type PluginArgumentEnum = PluginArgumentBase & { type: 'enum', @@ -48,13 +48,13 @@ export type PluginArgumentFile = PluginArgumentBase & { }; export type PluginArgumentNumber = PluginArgumentBase & { - type: 'number'; + type: 'number', placeholder?: string, defaultValue?: number }; export type PluginArgument = - PluginArgumentEnum + | PluginArgumentEnum | PluginArgumentModel | PluginArgumentString | PluginArgumentBoolean @@ -69,7 +69,10 @@ export type PluginTemplateTagContext = { }, response: { getLatestForRequestId: (id: string) => Promise, - getBodyBuffer: (response: Response, fallback?: any) => Promise, + getBodyBuffer: ( + response: Response, + fallback?: any + ) => Promise } } } @@ -80,7 +83,10 @@ export type PluginTemplateTag = { name: string, displayName: DisplayName, description: string, - run: (context: PluginTemplateTagContext, ...arg: Array) => Promise | any, + run: ( + context: PluginTemplateTagContext, + ...arg: Array + ) => Promise | any, deprecated?: boolean, validate?: (value: any) => ?string, priority?: number diff --git a/packages/insomnia-app/app/templating/index.js b/packages/insomnia-app/app/templating/index.js index b1b94dadaa..8b8bf01156 100644 --- a/packages/insomnia-app/app/templating/index.js +++ b/packages/insomnia-app/app/templating/index.js @@ -1,13 +1,13 @@ // @flow import nunjucks from 'nunjucks'; import BaseExtension from './base-extension'; -import type {NunjucksParsedTag} from './utils'; +import type { NunjucksParsedTag } from './utils'; import * as plugins from '../plugins/index'; export class RenderError extends Error { message: string; path: string | null; - location: {line: number, column: number}; + location: { line: number, column: number }; type: string; reason: string; } @@ -30,7 +30,7 @@ let nunjucksAll = null; * @param {Object} [config.path] - Path to include in the error message * @param {Object} [config.renderMode] - Only render variables (not tags) */ -export function render (text: string, config: Object = {}): Promise { +export function render(text: string, config: Object = {}): Promise { const context = config.context || {}; const path = config.path || null; const renderMode = config.renderMode || RENDER_ALL; @@ -49,14 +49,16 @@ export function render (text: string, config: Object = {}): Promise { const location = err.message.match(/\[Line (\d)+, Column (\d)*]/); const line = location ? parseInt(location[1]) : 1; const column = location ? parseInt(location[2]) : 1; - const reason = err.message.includes('attempted to output null or undefined value') + const reason = err.message.includes( + 'attempted to output null or undefined value' + ) ? 'undefined' : 'error'; const newError = new RenderError(sanitizedMsg); newError.path = path || ''; newError.message = sanitizedMsg; - newError.location = {line, column}; + newError.location = { line, column }; newError.type = 'render'; newError.reason = reason; reject(newError); @@ -70,7 +72,7 @@ export function render (text: string, config: Object = {}): Promise { /** * Reload Nunjucks environments. Useful for if plugins change. */ -export function reload (): void { +export function reload(): void { nunjucksAll = null; nunjucksVariablesOnly = null; nunjucksTagsOnly = null; @@ -79,13 +81,13 @@ export function reload (): void { /** * Get definitions of template tags */ -export async function getTagDefinitions (): Promise> { +export async function getTagDefinitions(): Promise> { const env = await getNunjucks(RENDER_ALL); return Object.keys(env.extensions) .map(k => env.extensions[k]) .filter(ext => !ext.isDeprecated()) - .sort((a, b) => a.getPriority() > b.getPriority() ? 1 : -1) + .sort((a, b) => (a.getPriority() > b.getPriority() ? 1 : -1)) .map(ext => ({ name: ext.getTag(), displayName: ext.getName(), @@ -94,7 +96,7 @@ export async function getTagDefinitions (): Promise> { })); } -async function getNunjucks (renderMode: string) { +async function getNunjucks(renderMode: string) { if (renderMode === RENDER_VARS && nunjucksVariablesOnly) { return nunjucksVariablesOnly; } @@ -145,7 +147,7 @@ async function getNunjucks (renderMode: string) { const allTemplateTagPlugins = await plugins.getTemplateTags(); const allExtensions = allTemplateTagPlugins; for (let i = 0; i < allExtensions.length; i++) { - const {templateTag, plugin} = allExtensions[i]; + const { templateTag, plugin } = allExtensions[i]; templateTag.priority = templateTag.priority || i * 100; const instance = new BaseExtension(templateTag, plugin); nj.addExtension(instance.getTag(), instance); diff --git a/packages/insomnia-app/app/templating/utils.js b/packages/insomnia-app/app/templating/utils.js index cacff5ee86..2a2a473cd5 100644 --- a/packages/insomnia-app/app/templating/utils.js +++ b/packages/insomnia-app/app/templating/utils.js @@ -25,7 +25,10 @@ export type NunjucksParsedTag = { * @param {String} [prefix] - base path to prefix to all paths * @returns {Array} - list of paths */ -export function getKeys (obj: any, prefix: string = ''): Array<{name: string, value: any}> { +export function getKeys( + obj: any, + prefix: string = '' +): Array<{ name: string, value: any }> { let allKeys = []; const typeOfObj = Object.prototype.toString.call(obj); @@ -43,7 +46,7 @@ export function getKeys (obj: any, prefix: string = ''): Array<{name: string, va } else if (typeOfObj === '[object Function]') { // Ignore functions } else if (prefix) { - allKeys.push({name: prefix, value: obj}); + allKeys.push({ name: prefix, value: obj }); } return allKeys; @@ -54,7 +57,7 @@ export function getKeys (obj: any, prefix: string = ''): Array<{name: string, va * @param {string} tagStr - the template string for the tag * @return {object} parsed tag data */ -export function tokenizeTag (tagStr: string): NunjucksParsedTag { +export function tokenizeTag(tagStr: string): NunjucksParsedTag { // ~~~~~~~~ // // Sanitize // // ~~~~~~~~ // @@ -125,15 +128,15 @@ export function tokenizeTag (tagStr: string): NunjucksParsedTag { if (currentArg !== null && argCompleted) { let arg; if (quotedBy) { - arg = {type: 'string', value: currentArg, quotedBy}; + arg = { type: 'string', value: currentArg, quotedBy }; } else if (['true', 'false'].includes(currentArg)) { - arg = {type: 'boolean', value: currentArg.toLowerCase() === 'true'}; + arg = { type: 'boolean', value: currentArg.toLowerCase() === 'true' }; } else if (currentArg.match(/^\d*\.?\d*$/)) { - arg = {type: 'number', value: currentArg}; + arg = { type: 'number', value: currentArg }; } else if (currentArg.match(/^[a-zA-Z_$][0-9a-zA-Z_$]*$/)) { - arg = {type: 'variable', value: currentArg}; + arg = { type: 'variable', value: currentArg }; } else { - arg = {type: 'expression', value: currentArg}; + arg = { type: 'expression', value: currentArg }; } args.push(arg); @@ -143,11 +146,11 @@ export function tokenizeTag (tagStr: string): NunjucksParsedTag { } } - return {name, args}; + return { name, args }; } /** Convert a tokenized tag back into a Nunjucks string */ -export function unTokenizeTag (tagData: NunjucksParsedTag): string { +export function unTokenizeTag(tagData: NunjucksParsedTag): string { const args = []; for (const arg of tagData.args) { if (['string', 'model', 'file'].includes(arg.type)) { @@ -167,12 +170,16 @@ export function unTokenizeTag (tagData: NunjucksParsedTag): string { } /** Get the default Nunjucks string for an extension */ -export function getDefaultFill (name: string, args: Array): string { +export function getDefaultFill( + name: string, + args: Array +): string { const stringArgs: Array = (args || []).map(argDefinition => { switch (argDefinition.type) { case 'enum': - const {defaultValue, options} = argDefinition; - const value = defaultValue !== undefined ? defaultValue : options[0].value; + const { defaultValue, options } = argDefinition; + const value = + defaultValue !== undefined ? defaultValue : options[0].value; return `'${value}'`; case 'number': return `${parseFloat(argDefinition.defaultValue) || 0}`; diff --git a/packages/insomnia-app/app/ui/components/base/button.js b/packages/insomnia-app/app/ui/components/base/button.js index edd517c21d..c9fec7f10c 100644 --- a/packages/insomnia-app/app/ui/components/base/button.js +++ b/packages/insomnia-app/app/ui/components/base/button.js @@ -1,11 +1,11 @@ -import React, {PureComponent} from 'react'; +import React, { PureComponent } from 'react'; import PropTypes from 'prop-types'; import autobind from 'autobind-decorator'; @autobind class Button extends PureComponent { - _handleClick (e) { - const {onClick, onDisabledClick, disabled} = this.props; + _handleClick(e) { + const { onClick, onDisabledClick, disabled } = this.props; const fn = disabled ? onDisabledClick : onClick; if (this.props.hasOwnProperty('value')) { @@ -15,25 +15,19 @@ class Button extends PureComponent { } } - render () { - const { - children, - disabled, - tabIndex, - className, - type, - id - } = this.props; + render() { + const { children, disabled, tabIndex, className, type, id } = this.props; return ( - + ); } } diff --git a/packages/insomnia-app/app/ui/components/base/copy-button.js b/packages/insomnia-app/app/ui/components/base/copy-button.js index 13f63ace7b..93eb9c2b58 100644 --- a/packages/insomnia-app/app/ui/components/base/copy-button.js +++ b/packages/insomnia-app/app/ui/components/base/copy-button.js @@ -1,41 +1,42 @@ -import React, {PureComponent} from 'react'; +import React, { PureComponent } from 'react'; import PropTypes from 'prop-types'; import autobind from 'autobind-decorator'; -const {clipboard} = require('electron'); +const { clipboard } = require('electron'); @autobind class CopyButton extends PureComponent { - constructor (props) { + constructor(props) { super(props); this.state = { showConfirmation: false }; } - async _handleClick (e) { + async _handleClick(e) { e.preventDefault(); e.stopPropagation(); - const content = typeof this.props.content === 'string' - ? this.props.content - : await this.props.content(); + const content = + typeof this.props.content === 'string' + ? this.props.content + : await this.props.content(); if (content) { clipboard.writeText(content); } - this.setState({showConfirmation: true}); + this.setState({ showConfirmation: true }); this._triggerTimeout = setTimeout(() => { - this.setState({showConfirmation: false}); + this.setState({ showConfirmation: false }); }, 2000); } - componentWillUnmount () { + componentWillUnmount() { clearTimeout(this._triggerTimeout); } - render () { + render() { const { content, // eslint-disable-line no-unused-vars children, @@ -43,16 +44,20 @@ class CopyButton extends PureComponent { confirmMessage, ...other } = this.props; - const {showConfirmation} = this.state; + const { showConfirmation } = this.state; - const confirm = typeof confirmMessage === 'string' ? confirmMessage : 'Copied'; + const confirm = + typeof confirmMessage === 'string' ? confirmMessage : 'Copied'; return ( ); } diff --git a/packages/insomnia-app/app/ui/components/base/debounced-input.js b/packages/insomnia-app/app/ui/components/base/debounced-input.js index 53a9c1634b..6b68e4a7a3 100644 --- a/packages/insomnia-app/app/ui/components/base/debounced-input.js +++ b/packages/insomnia-app/app/ui/components/base/debounced-input.js @@ -1,11 +1,11 @@ -import React, {PureComponent} from 'react'; +import React, { PureComponent } from 'react'; import PropTypes from 'prop-types'; import autobind from 'autobind-decorator'; -import {debounce} from '../../../common/misc'; +import { debounce } from '../../../common/misc'; @autobind class DebouncedInput extends PureComponent { - constructor (props) { + constructor(props) { super(props); if (!props.delay) { @@ -17,41 +17,41 @@ class DebouncedInput extends PureComponent { this._hasFocus = false; } - _handleChange (e) { + _handleChange(e) { this._handleValueChange(e.target.value); } - _handleFocus (e) { + _handleFocus(e) { this._hasFocus = true; this.props.onFocus && this.props.onFocus(e); } - _handleBlur (e) { + _handleBlur(e) { this._hasFocus = false; this.props.onBlur && this.props.onBlur(e); } - _setRef (n) { + _setRef(n) { this._input = n; } - setAttribute (name, value) { + setAttribute(name, value) { this._input.setAttribute(name, value); } - removeAttribute (name) { + removeAttribute(name) { this._input.removeAttribute(name); } - getAttribute (name) { + getAttribute(name) { this._input.getAttribute(name); } - hasFocus () { + hasFocus() { return this._hasFocus; } - getSelectionStart () { + getSelectionStart() { if (this._input) { return this._input.selectionStart; } else { @@ -59,7 +59,7 @@ class DebouncedInput extends PureComponent { } } - getSelectionEnd () { + getSelectionEnd() { if (this._input) { return this._input.selectionEnd; } else { @@ -67,13 +67,13 @@ class DebouncedInput extends PureComponent { } } - focus () { + focus() { if (this._input) { this._input.focus(); } } - focusEnd () { + focusEnd() { if (this._input) { // Hack to focus the end (set value to current value); this._input.value = this.getValue(); @@ -81,19 +81,19 @@ class DebouncedInput extends PureComponent { } } - blur () { + blur() { if (this._input) { this._input.blur(); } } - select () { + select() { if (this._input) { this._input.select(); } } - getValue () { + getValue() { if (this._input) { return this._input.value; } else { @@ -101,7 +101,7 @@ class DebouncedInput extends PureComponent { } } - render () { + render() { const { onChange, // eslint-disable-line no-unused-vars onFocus, // eslint-disable-line no-unused-vars diff --git a/packages/insomnia-app/app/ui/components/base/dropdown/dropdown-button.js b/packages/insomnia-app/app/ui/components/base/dropdown/dropdown-button.js index 2c036cd554..ec8bad1992 100644 --- a/packages/insomnia-app/app/ui/components/base/dropdown/dropdown-button.js +++ b/packages/insomnia-app/app/ui/components/base/dropdown/dropdown-button.js @@ -1,9 +1,9 @@ -import React, {PureComponent} from 'react'; +import React, { PureComponent } from 'react'; import PropTypes from 'prop-types'; class DropdownButton extends PureComponent { - render () { - const {children, ...props} = this.props; + render() { + const { children, ...props } = this.props; return ( ); diff --git a/packages/insomnia-app/app/ui/components/base/highlight.js b/packages/insomnia-app/app/ui/components/base/highlight.js index da685ef184..95682355aa 100644 --- a/packages/insomnia-app/app/ui/components/base/highlight.js +++ b/packages/insomnia-app/app/ui/components/base/highlight.js @@ -2,28 +2,22 @@ import * as React from 'react'; import autobind from 'autobind-decorator'; import fuzzySort from 'fuzzysort'; -import {fuzzyMatch} from '../../../common/misc'; +import { fuzzyMatch } from '../../../common/misc'; type Props = {| search: string, - text: string, + text: string |}; @autobind class Highlight extends React.PureComponent { - render () { - const { - search, - text, - ...otherProps - } = this.props; + render() { + const { search, text, ...otherProps } = this.props; const results = fuzzyMatch(search, text); if (results.searchTermsMatched === 0) { - return ( - {text} - ); + return {text}; } return ( diff --git a/packages/insomnia-app/app/ui/components/base/lazy.js b/packages/insomnia-app/app/ui/components/base/lazy.js index 34883bfda5..ae7ecfa74e 100644 --- a/packages/insomnia-app/app/ui/components/base/lazy.js +++ b/packages/insomnia-app/app/ui/components/base/lazy.js @@ -1,19 +1,19 @@ -import {PureComponent} from 'react'; +import { PureComponent } from 'react'; import PropTypes from 'prop-types'; import autobind from 'autobind-decorator'; @autobind class Lazy extends PureComponent { - constructor (props) { + constructor(props) { super(props); - this.state = {show: false}; + this.state = { show: false }; } - show () { - this.setState({show: true}); + show() { + this.setState({ show: true }); } - componentWillMount () { + componentWillMount() { if (this.props.delay < 0) { // Show right away if negative delay passed this.show(); @@ -22,7 +22,7 @@ class Lazy extends PureComponent { } } - render () { + render() { return this.state.show ? this.props.children : null; } } diff --git a/packages/insomnia-app/app/ui/components/base/link.js b/packages/insomnia-app/app/ui/components/base/link.js index cb30249750..ce7fea8d2d 100644 --- a/packages/insomnia-app/app/ui/components/base/link.js +++ b/packages/insomnia-app/app/ui/components/base/link.js @@ -14,9 +14,9 @@ type Props = {| @autobind class Link extends React.PureComponent { - _handleClick (e: SyntheticEvent) { + _handleClick(e: SyntheticEvent) { e && e.preventDefault(); - const {href, onClick} = this.props; + const { href, onClick } = this.props; // Also call onClick that was passed to us if there was one onClick && onClick(e); @@ -24,7 +24,7 @@ class Link extends React.PureComponent { misc.clickLink(href); } - render () { + render() { const { onClick, // eslint-disable-line no-unused-vars button, @@ -38,7 +38,11 @@ class Link extends React.PureComponent { {children} ) : ( - + {children} ); diff --git a/packages/insomnia-app/app/ui/components/base/mailto.js b/packages/insomnia-app/app/ui/components/base/mailto.js index 79f474fab9..e4c9b3d567 100644 --- a/packages/insomnia-app/app/ui/components/base/mailto.js +++ b/packages/insomnia-app/app/ui/components/base/mailto.js @@ -1,35 +1,36 @@ // @flow import * as React from 'react'; import autobind from 'autobind-decorator'; -import {buildQueryStringFromParams, joinUrlAndQueryString} from 'insomnia-url'; +import { + buildQueryStringFromParams, + joinUrlAndQueryString +} from 'insomnia-url'; import Link from './link'; type Props = {| email: string, children?: React.Node, subject?: string, - body?: string, + body?: string |}; @autobind class Mailto extends React.PureComponent { - render () { - const {email, body, subject, children} = this.props; + render() { + const { email, body, subject, children } = this.props; const params = []; if (subject) { - params.push({name: 'subject', value: subject}); + params.push({ name: 'subject', value: subject }); } if (body) { - params.push({name: 'body', value: body}); + params.push({ name: 'body', value: body }); } const qs = buildQueryStringFromParams(params); const href = joinUrlAndQueryString(`mailto:${email}`, qs); - return ( - {children || email} - ); + return {children || email}; } } diff --git a/packages/insomnia-app/app/ui/components/base/modal-body.js b/packages/insomnia-app/app/ui/components/base/modal-body.js index 3e31e9b532..55b94284b2 100644 --- a/packages/insomnia-app/app/ui/components/base/modal-body.js +++ b/packages/insomnia-app/app/ui/components/base/modal-body.js @@ -1,15 +1,13 @@ -import React, {PureComponent} from 'react'; +import React, { PureComponent } from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; class ModalBody extends PureComponent { - render () { - const {className, children, noScroll, ...props} = this.props; - const classes = classnames( - className, - 'modal__body', - {'modal__body--no-scroll': noScroll} - ); + render() { + const { className, children, noScroll, ...props } = this.props; + const classes = classnames(className, 'modal__body', { + 'modal__body--no-scroll': noScroll + }); return (
diff --git a/packages/insomnia-app/app/ui/components/base/modal-footer.js b/packages/insomnia-app/app/ui/components/base/modal-footer.js index 0160002ee5..7728dc895f 100644 --- a/packages/insomnia-app/app/ui/components/base/modal-footer.js +++ b/packages/insomnia-app/app/ui/components/base/modal-footer.js @@ -1,14 +1,12 @@ -import React, {PureComponent} from 'react'; +import React, { PureComponent } from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; class ModalFooter extends PureComponent { - render () { - const {children, className} = this.props; + render() { + const { children, className } = this.props; return ( -
- {children} -
+
{children}
); } } diff --git a/packages/insomnia-app/app/ui/components/base/modal-header.js b/packages/insomnia-app/app/ui/components/base/modal-header.js index b82c9894f3..4b99ba5d79 100644 --- a/packages/insomnia-app/app/ui/components/base/modal-header.js +++ b/packages/insomnia-app/app/ui/components/base/modal-header.js @@ -1,25 +1,26 @@ -import React, {PureComponent} from 'react'; +import React, { PureComponent } from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; class ModalHeader extends PureComponent { - render () { - const {hideCloseButton, className, children} = this.props; + render() { + const { hideCloseButton, className, children } = this.props; let closeButton = null; if (!hideCloseButton) { closeButton = ( - ); } return (
-
- {children} -
+
{children}
{closeButton}
); diff --git a/packages/insomnia-app/app/ui/components/base/modal.js b/packages/insomnia-app/app/ui/components/base/modal.js index bc5fb81dbc..42c203418b 100644 --- a/packages/insomnia-app/app/ui/components/base/modal.js +++ b/packages/insomnia-app/app/ui/components/base/modal.js @@ -1,4 +1,4 @@ -import React, {PureComponent} from 'react'; +import React, { PureComponent } from 'react'; import PropTypes from 'prop-types'; import autobind from 'autobind-decorator'; import classnames from 'classnames'; @@ -11,7 +11,7 @@ let globalZIndex = 1000; @autobind class Modal extends PureComponent { - constructor (props) { + constructor(props) { super(props); this.state = { @@ -21,7 +21,7 @@ class Modal extends PureComponent { }; } - _handleKeyDown (e) { + _handleKeyDown(e) { if (!this.state.open) { return; } @@ -43,7 +43,7 @@ class Modal extends PureComponent { } } - _handleClick (e) { + _handleClick(e) { // Don't check for close keys if we don't want them if (this.props.noEscape) { return; @@ -56,7 +56,10 @@ class Modal extends PureComponent { let shouldHide = false; for (let i = 0; i < 5; i++) { - if (target instanceof HTMLElement && target.hasAttribute('data-close-modal')) { + if ( + target instanceof HTMLElement && + target.hasAttribute('data-close-modal') + ) { shouldHide = true; break; } @@ -70,13 +73,13 @@ class Modal extends PureComponent { } } - _setModalRef (n) { + _setModalRef(n) { this._node = n; } - show () { - const {freshState} = this.props; - const {forceRefreshCounter} = this.state; + show() { + const { freshState } = this.props; + const { forceRefreshCounter } = this.state; this.setState({ open: true, @@ -91,7 +94,7 @@ class Modal extends PureComponent { setTimeout(() => this._node && this._node.focus()); } - toggle () { + toggle() { if (this.state.open) { this.hide(); } else { @@ -99,18 +102,18 @@ class Modal extends PureComponent { } } - isOpen () { + isOpen() { return this.state.open; } - hide () { - this.setState({open: false}); + hide() { + this.setState({ open: false }); this.props.onHide && this.props.onHide(); } - render () { - const {tall, wide, noEscape, className, children} = this.props; - const {open, zIndex, forceRefreshCounter} = this.state; + render() { + const { tall, wide, noEscape, className, children } = this.props; + const { open, zIndex, forceRefreshCounter } = this.state; if (!open) { return null; @@ -119,9 +122,9 @@ class Modal extends PureComponent { const classes = classnames( 'modal', className, - {'modal--fixed-height': tall}, - {'modal--noescape': noEscape}, - {'modal--wide': wide} + { 'modal--fixed-height': tall }, + { 'modal--noescape': noEscape }, + { 'modal--wide': wide } ); const styles = {}; @@ -131,12 +134,16 @@ class Modal extends PureComponent { return ( -
-
+
+
{children} diff --git a/packages/insomnia-app/app/ui/components/base/prompt-button.js b/packages/insomnia-app/app/ui/components/base/prompt-button.js index a681726440..50289ef814 100644 --- a/packages/insomnia-app/app/ui/components/base/prompt-button.js +++ b/packages/insomnia-app/app/ui/components/base/prompt-button.js @@ -1,4 +1,4 @@ -import React, {PureComponent} from 'react'; +import React, { PureComponent } from 'react'; import PropTypes from 'prop-types'; import autobind from 'autobind-decorator'; import Button from './button'; @@ -9,7 +9,7 @@ const STATE_DONE = 'done'; @autobind class PromptButton extends PureComponent { - constructor (props) { + constructor(props) { super(props); this.state = { @@ -17,7 +17,7 @@ class PromptButton extends PureComponent { }; } - _confirm (...args) { + _confirm(...args) { // Clear existing timeouts clearTimeout(this._triggerTimeout); @@ -26,16 +26,16 @@ class PromptButton extends PureComponent { // Set the state to done (but delay a bit to not alarm user) this._doneTimeout = setTimeout(() => { - this.setState({state: STATE_DONE}); + this.setState({ state: STATE_DONE }); }, 100); // Set a timeout to hide the confirmation this._triggerTimeout = setTimeout(() => { - this.setState({state: STATE_DEFAULT}); + this.setState({ state: STATE_DEFAULT }); }, 2000); } - _ask (...args) { + _ask(...args) { const e = args[args.length - 1]; // Prevent events (ex. won't close dropdown if it's in one) @@ -43,16 +43,16 @@ class PromptButton extends PureComponent { e.stopPropagation(); // Toggle the confirmation notice - this.setState({state: STATE_ASK}); + this.setState({ state: STATE_ASK }); // Set a timeout to hide the confirmation this._triggerTimeout = setTimeout(() => { - this.setState({state: STATE_DEFAULT}); + this.setState({ state: STATE_DEFAULT }); }, 2000); } - _handleClick (...args) { - const {state} = this.state; + _handleClick(...args) { + const { state } = this.state; if (state === STATE_ASK) { this._confirm(...args); } else if (state === STATE_DEFAULT) { @@ -62,12 +62,12 @@ class PromptButton extends PureComponent { } } - componentWillUnmount () { + componentWillUnmount() { clearTimeout(this._triggerTimeout); clearTimeout(this._doneTimeout); } - render () { + render() { const { onClick, // eslint-disable-line no-unused-vars children, @@ -79,7 +79,7 @@ class PromptButton extends PureComponent { ...other } = this.props; - const {state} = this.state; + const { state } = this.state; const finalConfirmMessage = (confirmMessage || 'Click to confirm').trim(); const finalDoneMessage = doneMessage || 'Done'; @@ -88,11 +88,12 @@ class PromptButton extends PureComponent { if (state === STATE_ASK && addIcon) { innerMsg = ( - - {finalConfirmMessage - ? {finalConfirmMessage} - : '' - } + + {finalConfirmMessage ? ( + {finalConfirmMessage} + ) : ( + '' + )} ); } else if (state === STATE_ASK) { @@ -108,10 +109,11 @@ class PromptButton extends PureComponent { } return ( - ); diff --git a/packages/insomnia-app/app/ui/components/check-for-updates-button.js b/packages/insomnia-app/app/ui/components/check-for-updates-button.js index 9aaafe045b..fe2caf7fe9 100644 --- a/packages/insomnia-app/app/ui/components/check-for-updates-button.js +++ b/packages/insomnia-app/app/ui/components/check-for-updates-button.js @@ -16,7 +16,7 @@ type State = { @autobind class CheckForUpdatesButton extends React.PureComponent { - constructor (props: Props) { + constructor(props: Props) { super(props); this.state = { status: '', @@ -25,37 +25,49 @@ class CheckForUpdatesButton extends React.PureComponent { }; } - _listenerCheckComplete (e: any, updateAvailable: true, status: string) { - this.setState({status, updateAvailable}); + _listenerCheckComplete(e: any, updateAvailable: true, status: string) { + this.setState({ status, updateAvailable }); } - _listenerCheckStatus (e: any, status: string) { + _listenerCheckStatus(e: any, status: string) { if (this.state.checking) { - this.setState({status}); + this.setState({ status }); } } - _handleCheckForUpdates () { + _handleCheckForUpdates() { electron.ipcRenderer.send('updater.check'); - this.setState({checking: true}); + this.setState({ checking: true }); } - componentDidMount () { + componentDidMount() { electron.ipcRenderer.on('updater.check.status', this._listenerCheckStatus); - electron.ipcRenderer.on('updater.check.complete', this._listenerCheckComplete); + electron.ipcRenderer.on( + 'updater.check.complete', + this._listenerCheckComplete + ); } - componentWillUnmount () { - electron.ipcRenderer.removeListener('updater.check.complete', this._listenerCheckComplete); - electron.ipcRenderer.removeListener('updater.check.status', this._listenerCheckStatus); + componentWillUnmount() { + electron.ipcRenderer.removeListener( + 'updater.check.complete', + this._listenerCheckComplete + ); + electron.ipcRenderer.removeListener( + 'updater.check.status', + this._listenerCheckStatus + ); } - render () { - const {children, className} = this.props; - const {status, checking} = this.state; + render() { + const { children, className } = this.props; + const { status, checking } = this.state; return ( - ); diff --git a/packages/insomnia-app/app/ui/components/codemirror/base-imports.js b/packages/insomnia-app/app/ui/components/codemirror/base-imports.js index 10f596b572..58644af493 100644 --- a/packages/insomnia-app/app/ui/components/codemirror/base-imports.js +++ b/packages/insomnia-app/app/ui/components/codemirror/base-imports.js @@ -55,5 +55,5 @@ import 'codemirror/lib/codemirror.css'; import '../../css/editor/index.less'; // Make jsonlint available to the jsonlint plugin -import {parser as jsonlint} from 'jsonlint'; +import { parser as jsonlint } from 'jsonlint'; global.jsonlint = jsonlint; diff --git a/packages/insomnia-app/app/ui/components/codemirror/code-editor.js b/packages/insomnia-app/app/ui/components/codemirror/code-editor.js index 1ad4e67675..4f27f72299 100644 --- a/packages/insomnia-app/app/ui/components/codemirror/code-editor.js +++ b/packages/insomnia-app/app/ui/components/codemirror/code-editor.js @@ -6,17 +6,17 @@ import classnames from 'classnames'; import clone from 'clone'; import jq from 'jsonpath'; import vkBeautify from 'vkbeautify'; -import {showModal} from '../modals/index'; +import { showModal } from '../modals/index'; import FilterHelpModal from '../modals/filter-help-modal'; import * as misc from '../../../common/misc'; import prettify from 'insomnia-prettify'; -import {DEBOUNCE_MILLIS, isMac} from '../../../common/constants'; +import { DEBOUNCE_MILLIS, isMac } from '../../../common/constants'; import './base-imports'; -import {getTagDefinitions} from '../../../templating/index'; +import { getTagDefinitions } from '../../../templating/index'; import Dropdown from '../base/dropdown/dropdown'; import DropdownButton from '../base/dropdown/dropdown-button'; import DropdownItem from '../base/dropdown/dropdown-item'; -import {query as queryXPath} from 'insomnia-xpath'; +import { query as queryXPath } from 'insomnia-xpath'; import deepEqual from 'deep-equal'; const TAB_KEY = 9; @@ -49,10 +49,10 @@ const BASE_CODEMIRROR_OPTIONS = { cursorScrollMargin: 12, // NOTE: This is px keyMap: 'default', extraKeys: CodeMirror.normalizeKeyMap({ - 'Ctrl-Q': function (cm) { + 'Ctrl-Q': function(cm) { cm.foldCode(cm.getCursor()); }, - [isMac() ? 'Cmd-Enter' : 'Ctrl-Enter']: function (cm) { + [isMac() ? 'Cmd-Enter' : 'Ctrl-Enter']: function(cm) { // HACK: So nothing conflicts withe the "Send Request" shortcut }, 'Ctrl-Space': 'autocomplete', @@ -65,7 +65,7 @@ const BASE_CODEMIRROR_OPTIONS = { @autobind class CodeEditor extends React.Component { - constructor (props) { + constructor(props) { super(props); this.state = { @@ -77,34 +77,37 @@ class CodeEditor extends React.Component { this._previousUniquenessKey = 'n/a'; } - componentWillUnmount () { + componentWillUnmount() { if (this.codeMirror) { this.codeMirror.toTextArea(); } } - componentDidMount () { + componentDidMount() { this._restoreState(); } - componentWillReceiveProps (nextProps) { + componentWillReceiveProps(nextProps) { this._uniquenessKey = nextProps.uniquenessKey; this._previousUniquenessKey = this.props.uniquenessKey; // Sync the filter too - this.setState({filter: nextProps.filter || ''}); + this.setState({ filter: nextProps.filter || '' }); } - componentDidUpdate () { + componentDidUpdate() { this._codemirrorSetOptions(); - const {defaultValue} = this.props; - if (this._uniquenessKey && this._uniquenessKey !== this._previousUniquenessKey) { + const { defaultValue } = this.props; + if ( + this._uniquenessKey && + this._uniquenessKey !== this._previousUniquenessKey + ) { this._codemirrorSetValue(defaultValue); this._restoreState(); } } - shouldComponentUpdate (nextProps) { + shouldComponentUpdate(nextProps) { // Update if any properties changed, except value. We ignore value. for (const key of Object.keys(nextProps)) { if (key === 'defaultValue') { @@ -119,40 +122,37 @@ class CodeEditor extends React.Component { return false; } - selectAll () { + selectAll() { if (this.codeMirror) { this.codeMirror.setSelection( - {line: 0, ch: 0}, - {line: this.codeMirror.lineCount(), ch: 0} + { line: 0, ch: 0 }, + { line: this.codeMirror.lineCount(), ch: 0 } ); } } - focus () { + focus() { if (this.codeMirror) { this.codeMirror.focus(); } } - setCursor (ch, line = 0) { + setCursor(ch, line = 0) { if (this.codeMirror) { if (!this.hasFocus()) { this.focus(); } - this.codeMirror.setCursor({line, ch}); + this.codeMirror.setCursor({ line, ch }); } } - setSelection (chStart, chEnd, line = 0) { + setSelection(chStart, chEnd, line = 0) { if (this.codeMirror) { - this.codeMirror.setSelection( - {line, ch: chStart}, - {line, ch: chEnd} - ); + this.codeMirror.setSelection({ line, ch: chStart }, { line, ch: chEnd }); } } - getSelectionStart () { + getSelectionStart() { const selections = this.codeMirror.listSelections(); if (selections.length) { return selections[0].anchor.ch; @@ -161,7 +161,7 @@ class CodeEditor extends React.Component { } } - getSelectionEnd () { + getSelectionEnd() { const selections = this.codeMirror.listSelections(); if (selections.length) { return selections[0].head.ch; @@ -170,7 +170,7 @@ class CodeEditor extends React.Component { } } - focusEnd () { + focusEnd() { if (this.codeMirror) { if (!this.hasFocus()) { this.focus(); @@ -180,7 +180,7 @@ class CodeEditor extends React.Component { } } - hasFocus () { + hasFocus() { if (this.codeMirror) { return this.codeMirror.hasFocus(); } else { @@ -188,19 +188,19 @@ class CodeEditor extends React.Component { } } - setAttribute (name, value) { + setAttribute(name, value) { this.codeMirror.getTextArea().parentNode.setAttribute(name, value); } - removeAttribute (name) { + removeAttribute(name) { this.codeMirror.getTextArea().parentNode.removeAttribute(name); } - getAttribute (name) { + getAttribute(name) { this.codeMirror.getTextArea().parentNode.getAttribute(name); } - clearSelection () { + clearSelection() { // Never do this if dropdown is open if (this.codeMirror.isHintDropdownActive()) { return; @@ -208,14 +208,14 @@ class CodeEditor extends React.Component { if (this.codeMirror) { this.codeMirror.setSelection( - {line: -1, ch: -1}, - {line: -1, ch: -1}, - {scroll: false} + { line: -1, ch: -1 }, + { line: -1, ch: -1 }, + { scroll: false } ); } } - getValue () { + getValue() { if (this.codeMirror) { return this.codeMirror.getValue(); } else { @@ -223,8 +223,8 @@ class CodeEditor extends React.Component { } } - _persistState () { - const {uniquenessKey} = this.props; + _persistState() { + const { uniquenessKey } = this.props; if (!uniquenessKey || !this.codeMirror) { return; @@ -238,26 +238,26 @@ class CodeEditor extends React.Component { }; } - _restoreState () { - const {uniquenessKey} = this.props; + _restoreState() { + const { uniquenessKey } = this.props; if (!editorStates.hasOwnProperty(uniquenessKey)) { return; } - const {scroll, selections, cursor, history} = editorStates[uniquenessKey]; + const { scroll, selections, cursor, history } = editorStates[uniquenessKey]; this.codeMirror.scrollTo(scroll.left, scroll.top); this.codeMirror.setHistory(history); // NOTE: These won't be visible unless the editor is focused - this.codeMirror.setCursor(cursor.line, cursor.ch, {scroll: false}); - this.codeMirror.setSelections(selections, null, {scroll: false}); + this.codeMirror.setCursor(cursor.line, cursor.ch, { scroll: false }); + this.codeMirror.setSelections(selections, null, { scroll: false }); } - _setFilterInputRef (n) { + _setFilterInputRef(n) { this._filterInput = n; } - _handleInitTextarea (textarea) { + _handleInitTextarea(textarea) { if (!textarea) { // Not mounted return; @@ -268,12 +268,18 @@ class CodeEditor extends React.Component { return; } - const {defaultValue, debounceMillis: ms} = this.props; - this.codeMirror = CodeMirror.fromTextArea(textarea, BASE_CODEMIRROR_OPTIONS); + const { defaultValue, debounceMillis: ms } = this.props; + this.codeMirror = CodeMirror.fromTextArea( + textarea, + BASE_CODEMIRROR_OPTIONS + ); // Set default listeners const debounceMillis = typeof ms === 'number' ? ms : DEBOUNCE_MILLIS; - this.codeMirror.on('changes', misc.debounce(this._codemirrorValueChanged, debounceMillis)); + this.codeMirror.on( + 'changes', + misc.debounce(this._codemirrorValueChanged, debounceMillis) + ); this.codeMirror.on('beforeChange', this._codemirrorValueBeforeChange); this.codeMirror.on('keydown', this._codemirrorKeyDown); this.codeMirror.on('keyup', this._codemirrorTriggerCompletionKeyUp); @@ -288,12 +294,14 @@ class CodeEditor extends React.Component { this.codeMirror.on('cut', this._codemirrorPreventWhenTypePassword); this.codeMirror.on('dragstart', this._codemirrorPreventWhenTypePassword); - this.codeMirror.setCursor({line: -1, ch: -1}); + this.codeMirror.setCursor({ line: -1, ch: -1 }); if (!this.codeMirror.getOption('indentWithTabs')) { this.codeMirror.setOption('extraKeys', { Tab: cm => { - const spaces = (new Array(this.codeMirror.getOption('indentUnit') + 1)).join(' '); + const spaces = new Array( + this.codeMirror.getOption('indentUnit') + 1 + ).join(' '); cm.replaceSelection(spaces); } }); @@ -334,7 +342,7 @@ class CodeEditor extends React.Component { } } - _isJSON (mode) { + _isJSON(mode) { if (!mode) { return false; } @@ -342,7 +350,7 @@ class CodeEditor extends React.Component { return mode.indexOf('json') !== -1; } - _isXML (mode) { + _isXML(mode) { if (!mode) { return false; } @@ -350,15 +358,15 @@ class CodeEditor extends React.Component { return mode.indexOf('xml') !== -1; } - _handleBeautify () { + _handleBeautify() { this._prettify(this.codeMirror.getValue()); } - _prettify (code) { + _prettify(code) { this._codemirrorSetValue(code, true); } - _prettifyJSON (code) { + _prettifyJSON(code) { try { let jsonString = code; @@ -379,7 +387,7 @@ class CodeEditor extends React.Component { } } - _prettifyXML (code) { + _prettifyXML(code) { if (this.props.updateFilter && this.state.filter) { try { const results = queryXPath(code, this.state.filter); @@ -401,7 +409,7 @@ class CodeEditor extends React.Component { /** * Sets options on the CodeMirror editor while also sanitizing them */ - async _codemirrorSetOptions () { + async _codemirrorSetOptions() { const { mode: rawMode, readOnly, @@ -427,7 +435,7 @@ class CodeEditor extends React.Component { let mode; if (this.props.render) { - mode = {name: 'nunjucks', baseMode: this._normalizeMode(rawMode)}; + mode = { name: 'nunjucks', baseMode: this._normalizeMode(rawMode) }; } else { // foo bar baz mode = this._normalizeMode(rawMode); @@ -507,7 +515,8 @@ class CodeEditor extends React.Component { } for (const option of tagDef.args[0].options) { - const optionName = misc.fnOrString(option.displayName, tagDef.args) || option.name; + const optionName = + misc.fnOrString(option.displayName, tagDef.args) || option.name; const newDef = clone(tagDef); newDef.displayName = `${tagDef.displayName} ⇒ ${optionName}`; newDef.args[0].defaultValue = option.value; @@ -541,7 +550,7 @@ class CodeEditor extends React.Component { }); } - _normalizeMode (mode) { + _normalizeMode(mode) { const mimeType = mode ? mode.split(';')[0] : 'text/plain'; if (mimeType.includes('graphql-variables')) { @@ -558,7 +567,7 @@ class CodeEditor extends React.Component { } } - async _codemirrorKeyDown (doc, e) { + async _codemirrorKeyDown(doc, e) { // Use default tab behaviour if we're told if (this.props.defaultTabBehavior && e.keyCode === TAB_KEY) { e.codemirrorIgnore = true; @@ -569,11 +578,11 @@ class CodeEditor extends React.Component { } } - _codemirrorEndCompletion (doc, e) { + _codemirrorEndCompletion(doc, e) { clearInterval(this._autocompleteDebounce); } - _codemirrorTriggerCompletionKeyUp (doc, e) { + _codemirrorTriggerCompletionKeyUp(doc, e) { // Enable graphql completion if we're in that mode if (doc.options.mode === 'graphql') { // Only operate on one-letter keys. This will filter out @@ -589,24 +598,24 @@ class CodeEditor extends React.Component { } } - _codemirrorFocus (doc, e) { + _codemirrorFocus(doc, e) { if (this.props.onFocus) { this.props.onFocus(e); } } - _codemirrorBlur (doc, e) { + _codemirrorBlur(doc, e) { this._persistState(); if (this.props.onBlur) { this.props.onBlur(e); } } - _codemirrorScroll () { + _codemirrorScroll() { this._persistState(); } - _codemirrorValueBeforeChange (doc, change) { + _codemirrorValueBeforeChange(doc, change) { // If we're in single-line mode, merge all changed lines into one if (this.props.singleLine && change.text && change.text.length > 1) { const text = change.text @@ -616,14 +625,14 @@ class CodeEditor extends React.Component { } } - _codemirrorPaste (cm, e) { + _codemirrorPaste(cm, e) { if (this.props.onPaste) { this.props.onPaste(e); } } - _codemirrorPreventWhenTypePassword (cm, e) { - const {type} = this.props; + _codemirrorPreventWhenTypePassword(cm, e) { + const { type } = this.props; if (type && type.toLowerCase() === 'password') { e.preventDefault(); } @@ -632,7 +641,7 @@ class CodeEditor extends React.Component { /** * Wrapper function to add extra behaviour to our onChange event */ - _codemirrorValueChanged () { + _codemirrorValueChanged() { // Don't trigger change event if we're ignoring changes if (this._ignoreNextChange || !this.props.onChange) { this._ignoreNextChange = false; @@ -641,7 +650,8 @@ class CodeEditor extends React.Component { const value = this.codeMirror.getDoc().getValue(); - const lint = value.length > MAX_SIZE_FOR_LINTING ? false : !this.props.noLint; + const lint = + value.length > MAX_SIZE_FOR_LINTING ? false : !this.props.noLint; const existingLint = this.codeMirror.options.lint || false; if (lint !== existingLint) { this.codeMirror.setOption('lint', lint); @@ -655,7 +665,7 @@ class CodeEditor extends React.Component { * @param code the code to set in the editor * @param forcePrettify */ - _codemirrorSetValue (code, forcePrettify = false) { + _codemirrorSetValue(code, forcePrettify = false) { if (typeof code !== 'string') { console.warn('Code editor was passed non-string value', code); return; @@ -681,19 +691,19 @@ class CodeEditor extends React.Component { this.codeMirror.setValue(code || ''); } - _handleFilterHistorySelect (filter) { + _handleFilterHistorySelect(filter) { this._filterInput.value = filter; this._setFilter(filter); } - _handleFilterChange (e) { + _handleFilterChange(e) { this._setFilter(e.target.value); } - _setFilter (filter) { + _setFilter(filter) { clearTimeout(this._filterTimeout); this._filterTimeout = setTimeout(() => { - this.setState({filter}); + this.setState({ filter }); this._codemirrorSetValue(this._originalCode); if (this.props.updateFilter) { this.props.updateFilter(filter); @@ -701,17 +711,17 @@ class CodeEditor extends React.Component { }, 200); } - _canPrettify () { - const {mode} = this.props; + _canPrettify() { + const { mode } = this.props; return this._isJSON(mode) || this._isXML(mode); } - _showFilterHelp () { + _showFilterHelp() { const isJson = this._isJSON(this.props.mode); showModal(FilterHelpModal, isJson); } - render () { + render() { const { id, readOnly, @@ -728,7 +738,7 @@ class CodeEditor extends React.Component { } = this.props; const classes = classnames(className, { - 'editor': true, + editor: true, 'editor--dynamic-height': dynamicHeight, 'editor--readonly': readOnly }); @@ -742,7 +752,11 @@ class CodeEditor extends React.Component { type="text" title="Filter response body" defaultValue={filter || ''} - placeholder={this._isJSON(mode) ? '$.store.books[*].author' : '/store/books/author'} + placeholder={ + this._isJSON(mode) + ? '$.store.books[*].author' + : '/store/books/author' + } onChange={this._handleFilterChange} /> ); @@ -751,10 +765,13 @@ class CodeEditor extends React.Component { toolbarChildren.push( - + {filterHistory.reverse().map(filter => ( - + {filter} ))} @@ -763,8 +780,11 @@ class CodeEditor extends React.Component { } toolbarChildren.push( - ); } @@ -778,10 +798,11 @@ class CodeEditor extends React.Component { } toolbarChildren.push( - ); @@ -803,14 +824,15 @@ class CodeEditor extends React.Component { return (
-
+
+ style={{ fontSize }} + /> ); } } diff --git a/packages/insomnia-app/app/ui/components/viewers/response-timeline-viewer.js b/packages/insomnia-app/app/ui/components/viewers/response-timeline-viewer.js index dff44335bd..f34812fde6 100644 --- a/packages/insomnia-app/app/ui/components/viewers/response-timeline-viewer.js +++ b/packages/insomnia-app/app/ui/components/viewers/response-timeline-viewer.js @@ -1,15 +1,15 @@ -import React, {PureComponent} from 'react'; +import React, { PureComponent } from 'react'; import PropTypes from 'prop-types'; -import {shell} from 'electron'; +import { shell } from 'electron'; import CodeEditor from '../codemirror/code-editor'; class ResponseTimelineViewer extends PureComponent { - _handleClickLink (link) { + _handleClickLink(link) { shell.openExternal(link); } - renderRow (row) { - const {name, value} = row; + renderRow(row) { + const { name, value } = row; let prefix = null; switch (name) { @@ -47,9 +47,17 @@ class ResponseTimelineViewer extends PureComponent { } } - render () { - const {timeline, editorFontSize, editorIndentSize, editorLineWrapping} = this.props; - const rows = timeline.map(this.renderRow).filter(r => r !== null).join('\n'); + render() { + const { + timeline, + editorFontSize, + editorIndentSize, + editorLineWrapping + } = this.props; + const rows = timeline + .map(this.renderRow) + .filter(r => r !== null) + .join('\n'); return ( { - constructor (props: Props) { + constructor(props: Props) { super(props); this.state = { blockingBecauseTooLarge: false, @@ -52,7 +57,7 @@ class ResponseViewer extends React.Component { }; } - _decodeIconv (bodyBuffer: Buffer, charset: string): string { + _decodeIconv(bodyBuffer: Buffer, charset: string): string { try { return iconv.decode(bodyBuffer, charset); } catch (err) { @@ -61,25 +66,25 @@ class ResponseViewer extends React.Component { } } - _handleOpenLink (link: string) { + _handleOpenLink(link: string) { shell.openExternal(link); } - _handleDismissBlocker () { - this.setState({blockingBecauseTooLarge: false}); + _handleDismissBlocker() { + this.setState({ blockingBecauseTooLarge: false }); this._maybeLoadResponseBody(this.props, true); } - _handleDisableBlocker () { + _handleDisableBlocker() { alwaysShowLargeResponses = true; this._handleDismissBlocker(); } - _maybeLoadResponseBody (props: Props, forceShow?: boolean) { + _maybeLoadResponseBody(props: Props, forceShow?: boolean) { // Block the response if it's too large const responseIsTooLarge = props.bytes > LARGE_RESPONSE_MB * 1024 * 1024; if (!forceShow && !alwaysShowLargeResponses && responseIsTooLarge) { - this.setState({blockingBecauseTooLarge: true}); + this.setState({ blockingBecauseTooLarge: true }); } else { try { const bodyBuffer = props.getBody(); @@ -88,20 +93,22 @@ class ResponseViewer extends React.Component { blockingBecauseTooLarge: false }); } catch (err) { - this.setState({error: `Failed reading response from filesystem: ${err.stack}`}); + this.setState({ + error: `Failed reading response from filesystem: ${err.stack}` + }); } } } - componentWillMount () { + componentWillMount() { this._maybeLoadResponseBody(this.props); } - componentWillReceiveProps (nextProps: Props) { + componentWillReceiveProps(nextProps: Props) { this._maybeLoadResponseBody(nextProps); } - shouldComponentUpdate (nextProps: Props, nextState: State) { + shouldComponentUpdate(nextProps: Props, nextState: State) { for (let k of Object.keys(nextProps)) { const next = nextProps[k]; const current = this.props[k]; @@ -147,7 +154,7 @@ class ResponseViewer extends React.Component { return false; } - render () { + render() { const { bytes, download, @@ -166,24 +173,20 @@ class ResponseViewer extends React.Component { let contentType = this.props.contentType; - const {bodyBuffer, error: parseError} = this.state; + const { bodyBuffer, error: parseError } = this.state; const error = responseError || parseError; if (error) { return (
- +
); } const wayTooLarge = bytes > HUGE_RESPONSE_MB * 1024 * 1024; - const {blockingBecauseTooLarge} = this.state; + const { blockingBecauseTooLarge } = this.state; if (blockingBecauseTooLarge) { return (
@@ -192,28 +195,35 @@ class ResponseViewer extends React.Component {

Responses over {HUGE_RESPONSE_MB}MB cannot be shown

- ) : (

- Response over {LARGE_RESPONSE_MB}MB hidden for performance reasons + Response over {LARGE_RESPONSE_MB}MB hidden for performance + reasons

- -
-
@@ -232,11 +242,7 @@ class ResponseViewer extends React.Component { } if (bodyBuffer.length === 0) { - return ( -
- No body returned for response -
- ); + return
No body returned for response
; } // Try to detect JSON in all cases (even if header is set). Apparently users @@ -252,7 +258,11 @@ class ResponseViewer extends React.Component { // common for webservers to send errors in HTML by default. // NOTE: This will probably never throw but I'm not 100% so wrap anyway try { - const isProbablyHTML = bodyBuffer.slice(0, 100).toString().trim().match(/^/i); + const isProbablyHTML = bodyBuffer + .slice(0, 100) + .toString() + .trim() + .match(/^/i); if (contentType.indexOf('text/html') !== 0 && isProbablyHTML) { contentType = 'text/html'; } @@ -267,16 +277,18 @@ class ResponseViewer extends React.Component { return (
- +
); } else if (previewMode === PREVIEW_MODE_FRIENDLY && ct.includes('html')) { const justContentType = contentType.split(';')[0]; const match = contentType.match(/charset=([\w-]+)/); - const charset = (match && match.length >= 2) ? match[1] : 'utf-8'; + const charset = match && match.length >= 2 ? match[1] : 'utf-8'; return ( { url={url} /> ); - } else if (previewMode === PREVIEW_MODE_FRIENDLY && ct.indexOf('application/pdf') === 0) { + } else if ( + previewMode === PREVIEW_MODE_FRIENDLY && + ct.indexOf('application/pdf') === 0 + ) { return (
- +
); - } else if (previewMode === PREVIEW_MODE_FRIENDLY && ct.indexOf('text/csv') === 0) { + } else if ( + previewMode === PREVIEW_MODE_FRIENDLY && + ct.indexOf('text/csv') === 0 + ) { return (
- +
); - } else if (previewMode === PREVIEW_MODE_FRIENDLY && ct.indexOf('multipart/') === 0) { + } else if ( + previewMode === PREVIEW_MODE_FRIENDLY && + ct.indexOf('multipart/') === 0 + ) { return ( { url={url} /> ); - } else if (previewMode === PREVIEW_MODE_FRIENDLY && ct.indexOf('audio/') === 0) { + } else if ( + previewMode === PREVIEW_MODE_FRIENDLY && + ct.indexOf('audio/') === 0 + ) { const justContentType = contentType.split(';')[0]; const base64Body = bodyBuffer.toString('base64'); return (
); } else if (previewMode === PREVIEW_MODE_RAW) { const match = contentType.match(/charset=([\w-]+)/); - const charset = (match && match.length >= 2) ? match[1] : 'utf-8'; + const charset = match && match.length >= 2 ? match[1] : 'utf-8'; return ( { fontSize={editorFontSize} /> ); - } else { // Show everything else as "source" + } else { + // Show everything else as "source" const match = contentType.match(/charset=([\w-]+)/); - const charset = (match && match.length >= 2) ? match[1] : 'utf-8'; + const charset = match && match.length >= 2 ? match[1] : 'utf-8'; // Sometimes iconv conversion fails so fallback to regular buffer const body = this._decodeIconv(bodyBuffer, charset); diff --git a/packages/insomnia-app/app/ui/components/viewers/response-web-view.js b/packages/insomnia-app/app/ui/components/viewers/response-web-view.js index bf8988b332..f3614327d1 100644 --- a/packages/insomnia-app/app/ui/components/viewers/response-web-view.js +++ b/packages/insomnia-app/app/ui/components/viewers/response-web-view.js @@ -1,25 +1,25 @@ -import React, {PureComponent} from 'react'; -import {EventEmitter} from 'events'; +import React, { PureComponent } from 'react'; +import { EventEmitter } from 'events'; import PropTypes from 'prop-types'; import autobind from 'autobind-decorator'; import contextMenu from 'electron-context-menu'; @autobind class ResponseWebView extends PureComponent { - _handleSetWebViewRef (n) { + _handleSetWebViewRef(n) { this._webview = n; if (n) { - contextMenu({window: this._webview}); + contextMenu({ window: this._webview }); } } - _handleDOMReady () { + _handleDOMReady() { this._webview.removeEventListener('dom-ready', this._handleDOMReady); this._setBody(); } - _setBody () { - const {body, contentType, url} = this.props; + _setBody() { + const { body, contentType, url } = this.props; const newBody = body.replace('', ``); this._webview.loadURL(`data:${contentType},${encodeURIComponent(newBody)}`); @@ -29,18 +29,16 @@ class ResponseWebView extends PureComponent { this._webview.webContents.session = new EventEmitter(); } - componentDidUpdate () { + componentDidUpdate() { this._setBody(); } - componentDidMount () { + componentDidMount() { this._webview.addEventListener('dom-ready', this._handleDOMReady); } - render () { - return ( - - ); + render() { + return ; } } diff --git a/packages/insomnia-app/app/ui/components/wrap.js b/packages/insomnia-app/app/ui/components/wrap.js index a371af0874..867c411c4d 100644 --- a/packages/insomnia-app/app/ui/components/wrap.js +++ b/packages/insomnia-app/app/ui/components/wrap.js @@ -6,7 +6,7 @@ type Props = { }; class Wrap extends React.PureComponent { - render () { + render() { return this.props.children; } } diff --git a/packages/insomnia-app/app/ui/components/wrapper.js b/packages/insomnia-app/app/ui/components/wrapper.js index 984e4e6d91..2f47cbc609 100644 --- a/packages/insomnia-app/app/ui/components/wrapper.js +++ b/packages/insomnia-app/app/ui/components/wrapper.js @@ -1,14 +1,20 @@ // @flow -import type {Settings} from '../../models/settings'; -import type {Response} from '../../models/response'; -import type {OAuth2Token} from '../../models/o-auth-2-token'; -import type {Workspace} from '../../models/workspace'; -import type {Request, RequestAuthentication, RequestBody, RequestHeader, RequestParameter} from '../../models/request'; +import type { Settings } from '../../models/settings'; +import type { Response } from '../../models/response'; +import type { OAuth2Token } from '../../models/o-auth-2-token'; +import type { Workspace } from '../../models/workspace'; +import type { + Request, + RequestAuthentication, + RequestBody, + RequestHeader, + RequestParameter +} from '../../models/request'; import * as React from 'react'; import autobind from 'autobind-decorator'; import classnames from 'classnames'; -import {registerModal, showModal} from './modals/index'; +import { registerModal, showModal } from './modals/index'; import AlertModal from './modals/alert-modal'; import WrapperModal from './modals/wrapper-modal'; import ErrorModal from './modals/error-modal'; @@ -38,10 +44,10 @@ import WorkspaceShareSettingsModal from './modals/workspace-share-settings-modal import CodePromptModal from './modals/code-prompt-modal'; import * as models from '../../models/index'; import * as importers from 'insomnia-importers'; -import type {CookieJar} from '../../models/cookie-jar'; -import type {Environment} from '../../models/environment'; +import type { CookieJar } from '../../models/cookie-jar'; +import type { Environment } from '../../models/environment'; import ErrorBoundary from './error-boundary'; -import type {ClientCertificate} from '../../models/client-certificate'; +import type { ClientCertificate } from '../../models/client-certificate'; import MoveRequestGroupModal from './modals/move-request-group-modal'; type Props = { @@ -110,7 +116,7 @@ type Props = { // Optional oAuth2Token: ?OAuth2Token, activeRequest: ?Request, - activeResponse: ?Response, + activeResponse: ?Response }; type State = { @@ -129,7 +135,7 @@ const sUpdate = models.settings.update; @autobind class Wrapper extends React.PureComponent { - constructor (props: any) { + constructor(props: any) { super(props); this.state = { forceRefreshKey: Date.now() @@ -137,7 +143,7 @@ class Wrapper extends React.PureComponent { } // Request updaters - async _handleForceUpdateRequest (patch: Object): Promise { + async _handleForceUpdateRequest(patch: Object): Promise { const newRequest = await rUpdate(this.props.activeRequest, patch); // Give it a second for the app to render first. If we don't wait, it will refresh @@ -147,46 +153,52 @@ class Wrapper extends React.PureComponent { return newRequest; } - _handleUpdateRequestBody (body: RequestBody): Promise { - return rUpdate(this.props.activeRequest, {body}); + _handleUpdateRequestBody(body: RequestBody): Promise { + return rUpdate(this.props.activeRequest, { body }); } - _handleUpdateRequestMethod (method: string): Promise { - return rUpdate(this.props.activeRequest, {method}); + _handleUpdateRequestMethod(method: string): Promise { + return rUpdate(this.props.activeRequest, { method }); } - _handleUpdateRequestParameters (parameters: Array): Promise { - return rUpdate(this.props.activeRequest, {parameters}); + _handleUpdateRequestParameters( + parameters: Array + ): Promise { + return rUpdate(this.props.activeRequest, { parameters }); } - _handleUpdateRequestAuthentication (authentication: RequestAuthentication): Promise { - return rUpdate(this.props.activeRequest, {authentication}); + _handleUpdateRequestAuthentication( + authentication: RequestAuthentication + ): Promise { + return rUpdate(this.props.activeRequest, { authentication }); } - _handleUpdateRequestHeaders (headers: Array): Promise { - return rUpdate(this.props.activeRequest, {headers}); + _handleUpdateRequestHeaders(headers: Array): Promise { + return rUpdate(this.props.activeRequest, { headers }); } - _handleForceUpdateRequestHeaders (headers: Array): Promise { - return this._handleForceUpdateRequest({headers}); + _handleForceUpdateRequestHeaders( + headers: Array + ): Promise { + return this._handleForceUpdateRequest({ headers }); } - _handleUpdateRequestUrl (url: string): Promise { - return rUpdate(this.props.activeRequest, {url}); + _handleUpdateRequestUrl(url: string): Promise { + return rUpdate(this.props.activeRequest, { url }); } // Special request updaters - _handleStartDragSidebar (e: Event): void { + _handleStartDragSidebar(e: Event): void { e.preventDefault(); this.props.handleStartDragSidebar(); } - async _handleImport (text: string): Promise { + async _handleImport(text: string): Promise { // Allow user to paste any import file into the url. If it results in // only one item, it will overwrite the current request. try { - const {data} = await importers.convert(text); - const {resources} = data; + const { data } = await importers.convert(text); + const { resources } = data; const r = resources[0]; if (r && r._type === 'request') { @@ -208,53 +220,60 @@ class Wrapper extends React.PureComponent { } // Settings updaters - _handleUpdateSettingsShowPasswords (showPasswords: boolean): Promise { - return sUpdate(this.props.settings, {showPasswords}); + _handleUpdateSettingsShowPasswords( + showPasswords: boolean + ): Promise { + return sUpdate(this.props.settings, { showPasswords }); } - _handleUpdateSettingsUseBulkHeaderEditor (useBulkHeaderEditor: boolean): Promise { - return sUpdate(this.props.settings, {useBulkHeaderEditor}); + _handleUpdateSettingsUseBulkHeaderEditor( + useBulkHeaderEditor: boolean + ): Promise { + return sUpdate(this.props.settings, { useBulkHeaderEditor }); } // Other Helpers - _handleImportFile (): void { + _handleImportFile(): void { this.props.handleImportFileToWorkspace(this.props.activeWorkspace._id); } - _handleImportUri (uri: string): void { + _handleImportUri(uri: string): void { this.props.handleImportUriToWorkspace(this.props.activeWorkspace._id, uri); } - _handleExportWorkspaceToFile (): void { + _handleExportWorkspaceToFile(): void { this.props.handleExportFile(this.props.activeWorkspace._id); } - _handleSetActiveResponse (responseId: string | null): void { + _handleSetActiveResponse(responseId: string | null): void { if (!this.props.activeRequest) { console.warn('Tried to set active response when request not active'); return; } - this.props.handleSetActiveResponse(this.props.activeRequest._id, responseId); + this.props.handleSetActiveResponse( + this.props.activeRequest._id, + responseId + ); } - _handleShowEnvironmentsModal (): void { + _handleShowEnvironmentsModal(): void { showModal(WorkspaceEnvironmentsEditModal, this.props.activeWorkspace); } - _handleShowCookiesModal (): void { + _handleShowCookiesModal(): void { showModal(CookiesModal, this.props.activeWorkspace); } - _handleShowModifyCookieModal (cookie: Object): void { + _handleShowModifyCookieModal(cookie: Object): void { showModal(CookieModifyModal, cookie); } - _handleShowRequestSettingsModal (): void { - showModal(RequestSettingsModal, {request: this.props.activeRequest}); + _handleShowRequestSettingsModal(): void { + showModal(RequestSettingsModal, { request: this.props.activeRequest }); } - _handleDeleteResponses (): void { + _handleDeleteResponses(): void { if (!this.props.activeRequest) { console.warn('Tried to delete responses when request not active'); return; @@ -264,62 +283,82 @@ class Wrapper extends React.PureComponent { this._handleSetActiveResponse(null); } - async _handleDeleteResponse (response: Response): Promise { + async _handleDeleteResponse(response: Response): Promise { if (response) { await models.response.remove(response); } // Also unset active response it's the one we're deleting - if (this.props.activeResponse && this.props.activeResponse._id === response._id) { + if ( + this.props.activeResponse && + this.props.activeResponse._id === response._id + ) { this._handleSetActiveResponse(null); } } - async _handleRemoveActiveWorkspace (): Promise { - const {workspaces, activeWorkspace} = this.props; + async _handleRemoveActiveWorkspace(): Promise { + const { workspaces, activeWorkspace } = this.props; if (workspaces.length <= 1) { showModal(AlertModal, { title: 'Deleting Last Workspace', - message: 'Since you deleted your only workspace, a new one has been created for you.' + message: + 'Since you deleted your only workspace, a new one has been created for you.' }); - models.workspace.create({name: 'Insomnia'}); + models.workspace.create({ name: 'Insomnia' }); } await models.workspace.remove(activeWorkspace); } - _handleSendRequestWithActiveEnvironment (): void { - const {activeRequest, activeEnvironment, handleSendRequestWithEnvironment} = this.props; + _handleSendRequestWithActiveEnvironment(): void { + const { + activeRequest, + activeEnvironment, + handleSendRequestWithEnvironment + } = this.props; const activeRequestId = activeRequest ? activeRequest._id : 'n/a'; - const activeEnvironmentId = activeEnvironment ? activeEnvironment._id : 'n/a'; + const activeEnvironmentId = activeEnvironment + ? activeEnvironment._id + : 'n/a'; handleSendRequestWithEnvironment(activeRequestId, activeEnvironmentId); } - _handleSendAndDownloadRequestWithActiveEnvironment (filename: string): void { - const {activeRequest, activeEnvironment, handleSendAndDownloadRequestWithEnvironment} = this.props; + _handleSendAndDownloadRequestWithActiveEnvironment(filename: string): void { + const { + activeRequest, + activeEnvironment, + handleSendAndDownloadRequestWithEnvironment + } = this.props; const activeRequestId = activeRequest ? activeRequest._id : 'n/a'; - const activeEnvironmentId = activeEnvironment ? activeEnvironment._id : 'n/a'; - handleSendAndDownloadRequestWithEnvironment(activeRequestId, activeEnvironmentId, filename); + const activeEnvironmentId = activeEnvironment + ? activeEnvironment._id + : 'n/a'; + handleSendAndDownloadRequestWithEnvironment( + activeRequestId, + activeEnvironmentId, + filename + ); } - _handleSetPreviewMode (previewMode: string): void { + _handleSetPreviewMode(previewMode: string): void { const activeRequest = this.props.activeRequest; const activeRequestId = activeRequest ? activeRequest._id : 'n/a'; this.props.handleSetResponsePreviewMode(activeRequestId, previewMode); } - _handleSetResponseFilter (filter: string): void { + _handleSetResponseFilter(filter: string): void { const activeRequest = this.props.activeRequest; const activeRequestId = activeRequest ? activeRequest._id : 'n/a'; this.props.handleSetResponseFilter(activeRequestId, filter); } - _forceRequestPaneRefresh (): void { - this.setState({forceRefreshKey: Date.now()}); + _forceRequestPaneRefresh(): void { + this.setState({ forceRefreshKey: Date.now() }); } - render () { + render() { const { activeEnvironment, activeRequest, @@ -378,24 +417,25 @@ class Wrapper extends React.PureComponent { const realSidebarWidth = sidebarHidden ? 0 : sidebarWidth; - const columns = `${realSidebarWidth}rem 0 minmax(0, ${paneWidth}fr) 0 minmax(0, ${1 - paneWidth}fr)`; + const columns = `${realSidebarWidth}rem 0 minmax(0, ${paneWidth}fr) 0 minmax(0, ${1 - + paneWidth}fr)`; const rows = `minmax(0, ${paneHeight}fr) 0 minmax(0, ${1 - paneHeight}fr)`; return [
- - - + + + - - - - - - - - + + + + + + + + { workspace={activeWorkspace} /> - + { workspaces={workspaces} workspaceChildren={workspaceChildren} workspaceId={activeWorkspace._id} - activeRequestParentId={activeRequest ? activeRequest.parentId : activeWorkspace._id} + activeRequestParentId={ + activeRequest ? activeRequest.parentId : activeWorkspace._id + } activateRequest={handleActivateRequest} handleSetActiveWorkspace={handleSetActiveWorkspace} /> @@ -511,10 +550,7 @@ class Wrapper extends React.PureComponent { nunjucksPowerUserMode={settings.nunjucksPowerUserMode} /> - + { editorFontSize={settings.editorFontSize} editorIndentSize={settings.editorIndentSize} editorKeyMap={settings.editorKeyMap} - activeEnvironmentId={activeEnvironment ? activeEnvironment._id : null} + activeEnvironmentId={ + activeEnvironment ? activeEnvironment._id : null + } render={handleRender} getRenderContext={handleGetRenderContext} nunjucksPowerUserMode={settings.nunjucksPowerUserMode} />
, -
- +
{
-
-
+
@@ -594,29 +636,37 @@ class Wrapper extends React.PureComponent { updateRequestUrl={this._handleUpdateRequestUrl} updateRequestMethod={this._handleUpdateRequestMethod} updateRequestParameters={this._handleUpdateRequestParameters} - updateRequestAuthentication={this._handleUpdateRequestAuthentication} + updateRequestAuthentication={ + this._handleUpdateRequestAuthentication + } updateRequestHeaders={this._handleUpdateRequestHeaders} updateRequestMimeType={handleUpdateRequestMimeType} - updateSettingsShowPasswords={this._handleUpdateSettingsShowPasswords} - updateSettingsUseBulkHeaderEditor={this._handleUpdateSettingsUseBulkHeaderEditor} + updateSettingsShowPasswords={ + this._handleUpdateSettingsShowPasswords + } + updateSettingsUseBulkHeaderEditor={ + this._handleUpdateSettingsUseBulkHeaderEditor + } forceRefreshCounter={this.state.forceRefreshKey} handleSend={this._handleSendRequestWithActiveEnvironment} - handleSendAndDownload={this._handleSendAndDownloadRequestWithActiveEnvironment} + handleSendAndDownload={ + this._handleSendAndDownloadRequestWithActiveEnvironment + } />
-
+ onDoubleClick={handleResetDragPaneHorizontal} + />
-
+ onDoubleClick={handleResetDragPaneVertical} + />
diff --git a/packages/insomnia-app/app/ui/containers/app.js b/packages/insomnia-app/app/ui/containers/app.js index d367a536a9..6b905d6fda 100644 --- a/packages/insomnia-app/app/ui/containers/app.js +++ b/packages/insomnia-app/app/ui/containers/app.js @@ -1,49 +1,77 @@ -import React, {PureComponent} from 'react'; +import React, { PureComponent } from 'react'; import PropTypes from 'prop-types'; import autobind from 'autobind-decorator'; import fs from 'fs'; -import {clipboard, ipcRenderer, remote} from 'electron'; -import {parse as urlParse} from 'url'; +import { clipboard, ipcRenderer, remote } from 'electron'; +import { parse as urlParse } from 'url'; import HTTPSnippet from 'insomnia-httpsnippet'; import ReactDOM from 'react-dom'; -import {connect} from 'react-redux'; -import {bindActionCreators} from 'redux'; +import { connect } from 'react-redux'; +import { bindActionCreators } from 'redux'; import Wrapper from '../components/wrapper'; import WorkspaceEnvironmentsEditModal from '../components/modals/workspace-environments-edit-modal'; import Toast from '../components/toast'; import CookiesModal from '../components/modals/cookies-modal'; import RequestSwitcherModal from '../components/modals/request-switcher-modal'; -import SettingsModal, {TAB_INDEX_SHORTCUTS} from '../components/modals/settings-modal'; -import {COLLAPSE_SIDEBAR_REMS, DEFAULT_PANE_HEIGHT, DEFAULT_PANE_WIDTH, DEFAULT_SIDEBAR_WIDTH, MAX_PANE_HEIGHT, MAX_PANE_WIDTH, MAX_SIDEBAR_REMS, MIN_PANE_HEIGHT, MIN_PANE_WIDTH, MIN_SIDEBAR_REMS, PREVIEW_MODE_SOURCE} from '../../common/constants'; +import SettingsModal, { + TAB_INDEX_SHORTCUTS +} from '../components/modals/settings-modal'; +import { + COLLAPSE_SIDEBAR_REMS, + DEFAULT_PANE_HEIGHT, + DEFAULT_PANE_WIDTH, + DEFAULT_SIDEBAR_WIDTH, + MAX_PANE_HEIGHT, + MAX_PANE_WIDTH, + MAX_SIDEBAR_REMS, + MIN_PANE_HEIGHT, + MIN_PANE_WIDTH, + MIN_SIDEBAR_REMS, + PREVIEW_MODE_SOURCE +} from '../../common/constants'; import * as globalActions from '../redux/modules/global'; import * as db from '../../common/database'; import * as models from '../../models'; -import {selectActiveCookieJar, selectActiveOAuth2Token, selectActiveRequest, selectActiveRequestMeta, selectActiveRequestResponses, selectActiveResponse, selectActiveWorkspace, selectActiveWorkspaceClientCertificates, selectActiveWorkspaceMeta, selectEntitiesLists, selectSidebarChildren, selectUnseenWorkspaces, selectWorkspaceRequestsAndRequestGroups} from '../redux/selectors'; +import { + selectActiveCookieJar, + selectActiveOAuth2Token, + selectActiveRequest, + selectActiveRequestMeta, + selectActiveRequestResponses, + selectActiveResponse, + selectActiveWorkspace, + selectActiveWorkspaceClientCertificates, + selectActiveWorkspaceMeta, + selectEntitiesLists, + selectSidebarChildren, + selectUnseenWorkspaces, + selectWorkspaceRequestsAndRequestGroups +} from '../redux/selectors'; import RequestCreateModal from '../components/modals/request-create-modal'; import GenerateCodeModal from '../components/modals/generate-code-modal'; import WorkspaceSettingsModal from '../components/modals/workspace-settings-modal'; import RequestSettingsModal from '../components/modals/request-settings-modal'; import RequestRenderErrorModal from '../components/modals/request-render-error-modal'; import * as network from '../../network/network'; -import {debounce, getContentDispositionHeader} from '../../common/misc'; +import { debounce, getContentDispositionHeader } from '../../common/misc'; import * as mime from 'mime-types'; import * as path from 'path'; import * as render from '../../common/render'; -import {getKeys} from '../../templating/utils'; -import {showAlert, showModal, showPrompt} from '../components/modals/index'; -import {exportHarRequest} from '../../common/har'; +import { getKeys } from '../../templating/utils'; +import { showAlert, showModal, showPrompt } from '../components/modals/index'; +import { exportHarRequest } from '../../common/har'; import * as hotkeys from '../../common/hotkeys'; import KeydownBinder from '../components/keydown-binder'; import ErrorBoundary from '../components/error-boundary'; import * as plugins from '../../plugins'; import * as templating from '../../templating/index'; import AskModal from '../components/modals/ask-modal'; -import {updateMimeType} from '../../models/request'; +import { updateMimeType } from '../../models/request'; import MoveRequestGroupModal from '../components/modals/move-request-group-modal'; @autobind class App extends PureComponent { - constructor (props) { + constructor(props) { super(props); this.state = { @@ -60,96 +88,137 @@ class App extends PureComponent { this._getRenderContextPromiseCache = {}; - this._savePaneWidth = debounce(paneWidth => this._updateActiveWorkspaceMeta({paneWidth})); - this._savePaneHeight = debounce(paneHeight => this._updateActiveWorkspaceMeta({paneHeight})); - this._saveSidebarWidth = debounce( - sidebarWidth => this._updateActiveWorkspaceMeta({sidebarWidth})); + this._savePaneWidth = debounce(paneWidth => + this._updateActiveWorkspaceMeta({ paneWidth }) + ); + this._savePaneHeight = debounce(paneHeight => + this._updateActiveWorkspaceMeta({ paneHeight }) + ); + this._saveSidebarWidth = debounce(sidebarWidth => + this._updateActiveWorkspaceMeta({ sidebarWidth }) + ); this._globalKeyMap = null; } - _setGlobalKeyMap () { + _setGlobalKeyMap() { this._globalKeyMap = [ - [hotkeys.SHOW_WORKSPACE_SETTINGS, () => { - const {activeWorkspace} = this.props; - showModal(WorkspaceSettingsModal, activeWorkspace); - }], - [hotkeys.SHOW_REQUEST_SETTINGS, () => { - if (this.props.activeRequest) { - showModal(RequestSettingsModal, {request: this.props.activeRequest}); + [ + hotkeys.SHOW_WORKSPACE_SETTINGS, + () => { + const { activeWorkspace } = this.props; + showModal(WorkspaceSettingsModal, activeWorkspace); } - }], - [hotkeys.SHOW_QUICK_SWITCHER, () => { - showModal(RequestSwitcherModal); - }], + ], + [ + hotkeys.SHOW_REQUEST_SETTINGS, + () => { + if (this.props.activeRequest) { + showModal(RequestSettingsModal, { + request: this.props.activeRequest + }); + } + } + ], + [ + hotkeys.SHOW_QUICK_SWITCHER, + () => { + showModal(RequestSwitcherModal); + } + ], [hotkeys.SEND_REQUEST, this._handleSendShortcut], [hotkeys.SEND_REQUEST_F5, this._handleSendShortcut], - [hotkeys.SHOW_ENVIRONMENTS, () => { - const {activeWorkspace} = this.props; - showModal(WorkspaceEnvironmentsEditModal, activeWorkspace); - }], - [hotkeys.SHOW_COOKIES, () => { - const {activeWorkspace} = this.props; - showModal(CookiesModal, activeWorkspace); - }], - [hotkeys.CREATE_REQUEST, () => { - const {activeRequest, activeWorkspace} = this.props; - const parentId = activeRequest ? activeRequest.parentId : activeWorkspace._id; - this._requestCreate(parentId); - }], - [hotkeys.DELETE_REQUEST, () => { - const {activeRequest} = this.props; - - if (!activeRequest) { - return; + [ + hotkeys.SHOW_ENVIRONMENTS, + () => { + const { activeWorkspace } = this.props; + showModal(WorkspaceEnvironmentsEditModal, activeWorkspace); } + ], + [ + hotkeys.SHOW_COOKIES, + () => { + const { activeWorkspace } = this.props; + showModal(CookiesModal, activeWorkspace); + } + ], + [ + hotkeys.CREATE_REQUEST, + () => { + const { activeRequest, activeWorkspace } = this.props; + const parentId = activeRequest + ? activeRequest.parentId + : activeWorkspace._id; + this._requestCreate(parentId); + } + ], + [ + hotkeys.DELETE_REQUEST, + () => { + const { activeRequest } = this.props; - showModal(AskModal, { - title: 'Delete Request?', - message: `Really delete ${activeRequest.name}?`, - onDone: confirmed => { - if (!confirmed) { - return; - } - models.request.remove(activeRequest); + if (!activeRequest) { + return; } - }); - }], - [hotkeys.CREATE_FOLDER, () => { - const {activeRequest, activeWorkspace} = this.props; - const parentId = activeRequest ? activeRequest.parentId : activeWorkspace._id; - this._requestGroupCreate(parentId); - }], - [hotkeys.GENERATE_CODE, async () => { - showModal(GenerateCodeModal, this.props.activeRequest); - }], - [hotkeys.DUPLICATE_REQUEST, async () => { - await this._requestDuplicate(this.props.activeRequest); - }] + + showModal(AskModal, { + title: 'Delete Request?', + message: `Really delete ${activeRequest.name}?`, + onDone: confirmed => { + if (!confirmed) { + return; + } + models.request.remove(activeRequest); + } + }); + } + ], + [ + hotkeys.CREATE_FOLDER, + () => { + const { activeRequest, activeWorkspace } = this.props; + const parentId = activeRequest + ? activeRequest.parentId + : activeWorkspace._id; + this._requestGroupCreate(parentId); + } + ], + [ + hotkeys.GENERATE_CODE, + async () => { + showModal(GenerateCodeModal, this.props.activeRequest); + } + ], + [ + hotkeys.DUPLICATE_REQUEST, + async () => { + await this._requestDuplicate(this.props.activeRequest); + } + ] ]; } - async _handleSendShortcut () { - const {activeRequest, activeEnvironment} = this.props; + async _handleSendShortcut() { + const { activeRequest, activeEnvironment } = this.props; await this._handleSendRequestWithEnvironment( activeRequest ? activeRequest._id : 'n/a', activeEnvironment ? activeEnvironment._id : 'n/a' ); } - _setRequestPaneRef (n) { + _setRequestPaneRef(n) { this._requestPane = n; } - _setResponsePaneRef (n) { + _setResponsePaneRef(n) { this._responsePane = n; } - _setSidebarRef (n) { + _setSidebarRef(n) { this._sidebar = n; } - _requestGroupCreate (parentId) { + _requestGroupCreate(parentId) { showPrompt({ title: 'New Folder', defaultValue: 'My Folder', @@ -157,13 +226,19 @@ class App extends PureComponent { label: 'Name', selectText: true, onComplete: async name => { - const requestGroup = await models.requestGroup.create({parentId, name}); - await models.requestGroupMeta.create({parentId: requestGroup._id, collapsed: false}); + const requestGroup = await models.requestGroup.create({ + parentId, + name + }); + await models.requestGroupMeta.create({ + parentId: requestGroup._id, + collapsed: false + }); } }); } - _requestCreate (parentId) { + _requestCreate(parentId) { showModal(RequestCreateModal, { parentId, onComplete: request => { @@ -172,15 +247,15 @@ class App extends PureComponent { }); } - async _requestGroupDuplicate (requestGroup) { + async _requestGroupDuplicate(requestGroup) { models.requestGroup.duplicate(requestGroup); } - async _requestGroupMove (requestGroup) { - showModal(MoveRequestGroupModal, {requestGroup}); + async _requestGroupMove(requestGroup) { + showModal(MoveRequestGroupModal, { requestGroup }); } - async _requestDuplicate (request) { + async _requestDuplicate(request) { if (!request) { return; } @@ -189,7 +264,7 @@ class App extends PureComponent { await this._handleSetActiveRequest(newRequest._id); } - async _workspaceDuplicate (callback) { + async _workspaceDuplicate(callback) { const workspace = this.props.activeWorkspace; showPrompt({ title: 'Duplicate Workspace', @@ -197,23 +272,23 @@ class App extends PureComponent { submitName: 'Duplicate', selectText: true, onComplete: async name => { - const newWorkspace = await db.duplicate(workspace, {name}); + const newWorkspace = await db.duplicate(workspace, { name }); await this.props.handleSetActiveWorkspace(newWorkspace._id); callback(); } }); } - async _fetchRenderContext () { - const {activeEnvironment, activeRequest} = this.props; + async _fetchRenderContext() { + const { activeEnvironment, activeRequest } = this.props; const environmentId = activeEnvironment ? activeEnvironment._id : null; return render.getRenderContext(activeRequest, environmentId, null); } - async _handleGetRenderContext () { + async _handleGetRenderContext() { const context = await this._fetchRenderContext(); const keys = getKeys(context); - return {context, keys}; + return { context, keys }; } /** @@ -224,8 +299,11 @@ class App extends PureComponent { * @returns {Promise} * @private */ - async _handleRenderText (text, contextCacheKey = null) { - if (!contextCacheKey || !this._getRenderContextPromiseCache[contextCacheKey]) { + async _handleRenderText(text, contextCacheKey = null) { + if ( + !contextCacheKey || + !this._getRenderContextPromiseCache[contextCacheKey] + ) { const context = this._fetchRenderContext(); // NOTE: We're caching promises here to avoid race conditions @@ -233,22 +311,25 @@ class App extends PureComponent { } // Set timeout to delete the key eventually - setTimeout(() => delete this._getRenderContextPromiseCache[contextCacheKey], 5000); + setTimeout( + () => delete this._getRenderContextPromiseCache[contextCacheKey], + 5000 + ); const context = await this._getRenderContextPromiseCache[contextCacheKey]; return render.render(text, context); } - _handleGenerateCodeForActiveRequest () { + _handleGenerateCodeForActiveRequest() { this._handleGenerateCode(this.props.activeRequest); } - _handleGenerateCode (request) { + _handleGenerateCode(request) { showModal(GenerateCodeModal, request); } - async _handleCopyAsCurl (request) { - const {activeEnvironment} = this.props; + async _handleCopyAsCurl(request) { + const { activeEnvironment } = this.props; const environmentId = activeEnvironment ? activeEnvironment._id : 'n/a'; const har = await exportHarRequest(request._id, environmentId); const snippet = new HTTPSnippet(har); @@ -256,53 +337,57 @@ class App extends PureComponent { clipboard.writeText(cmd); } - async _updateRequestGroupMetaByParentId (requestGroupId, patch) { - const requestGroupMeta = await models.requestGroupMeta.getByParentId(requestGroupId); + async _updateRequestGroupMetaByParentId(requestGroupId, patch) { + const requestGroupMeta = await models.requestGroupMeta.getByParentId( + requestGroupId + ); if (requestGroupMeta) { await models.requestGroupMeta.update(requestGroupMeta, patch); } else { - const newPatch = Object.assign({parentId: requestGroupId}, patch); + const newPatch = Object.assign({ parentId: requestGroupId }, patch); await models.requestGroupMeta.create(newPatch); } } - async _updateActiveWorkspaceMeta (patch) { + async _updateActiveWorkspaceMeta(patch) { const workspaceId = this.props.activeWorkspace._id; - const workspaceMeta = await models.workspaceMeta.getOrCreateByParentId(workspaceId); + const workspaceMeta = await models.workspaceMeta.getOrCreateByParentId( + workspaceId + ); if (workspaceMeta) { return models.workspaceMeta.update(workspaceMeta, patch); } else { - const newPatch = Object.assign({parentId: workspaceId}, patch); + const newPatch = Object.assign({ parentId: workspaceId }, patch); return models.workspaceMeta.create(newPatch); } } - async _updateRequestMetaByParentId (requestId, patch) { + async _updateRequestMetaByParentId(requestId, patch) { const requestMeta = await models.requestMeta.getByParentId(requestId); if (requestMeta) { return models.requestMeta.update(requestMeta, patch); } else { - const newPatch = Object.assign({parentId: requestId}, patch); + const newPatch = Object.assign({ parentId: requestId }, patch); return models.requestMeta.create(newPatch); } } - _handleSetPaneWidth (paneWidth) { - this.setState({paneWidth}); + _handleSetPaneWidth(paneWidth) { + this.setState({ paneWidth }); this._savePaneWidth(paneWidth); } - _handleSetPaneHeight (paneHeight) { - this.setState({paneHeight}); + _handleSetPaneHeight(paneHeight) { + this.setState({ paneHeight }); this._savePaneHeight(paneHeight); } - async _handleSetActiveRequest (activeRequestId) { - await this._updateActiveWorkspaceMeta({activeRequestId}); + async _handleSetActiveRequest(activeRequestId) { + await this._updateActiveWorkspaceMeta({ activeRequestId }); } - async _handleSetActiveEnvironment (activeEnvironmentId) { - await this._updateActiveWorkspaceMeta({activeEnvironmentId}); + async _handleSetActiveEnvironment(activeEnvironmentId) { + await this._updateActiveWorkspaceMeta({ activeEnvironmentId }); // Give it time to update and re-render setTimeout(() => { @@ -310,29 +395,29 @@ class App extends PureComponent { }, 100); } - _handleSetSidebarWidth (sidebarWidth) { - this.setState({sidebarWidth}); + _handleSetSidebarWidth(sidebarWidth) { + this.setState({ sidebarWidth }); this._saveSidebarWidth(sidebarWidth); } - async _handleSetSidebarHidden (sidebarHidden) { - await this._updateActiveWorkspaceMeta({sidebarHidden}); + async _handleSetSidebarHidden(sidebarHidden) { + await this._updateActiveWorkspaceMeta({ sidebarHidden }); } - async _handleSetSidebarFilter (sidebarFilter) { - await this._updateActiveWorkspaceMeta({sidebarFilter}); + async _handleSetSidebarFilter(sidebarFilter) { + await this._updateActiveWorkspaceMeta({ sidebarFilter }); } - _handleSetRequestGroupCollapsed (requestGroupId, collapsed) { - this._updateRequestGroupMetaByParentId(requestGroupId, {collapsed}); + _handleSetRequestGroupCollapsed(requestGroupId, collapsed) { + this._updateRequestGroupMetaByParentId(requestGroupId, { collapsed }); } - _handleSetResponsePreviewMode (requestId, previewMode) { - this._updateRequestMetaByParentId(requestId, {previewMode}); + _handleSetResponsePreviewMode(requestId, previewMode) { + this._updateRequestMetaByParentId(requestId, { previewMode }); } - async _handleSetResponseFilter (requestId, responseFilter) { - await this._updateRequestMetaByParentId(requestId, {responseFilter}); + async _handleSetResponseFilter(requestId, responseFilter) { + await this._updateRequestMetaByParentId(requestId, { responseFilter }); clearTimeout(this._responseFilterHistorySaveTimeout); this._responseFilterHistorySaveTimeout = setTimeout(async () => { @@ -350,11 +435,13 @@ class App extends PureComponent { } responseFilterHistory.unshift(responseFilter); - await this._updateRequestMetaByParentId(requestId, {responseFilterHistory}); + await this._updateRequestMetaByParentId(requestId, { + responseFilterHistory + }); }, 2000); } - async _handleUpdateRequestMimeType (mimeType) { + async _handleUpdateRequestMimeType(mimeType) { if (!this.props.activeRequest) { console.warn('Tried to update request mime-type when no active request'); return null; @@ -365,13 +452,21 @@ class App extends PureComponent { ); const savedBody = requestMeta.savedRequestBody; - const saveValue = (typeof mimeType !== 'string') // Switched to No body - ? this.props.activeRequest.body - : {}; // Clear saved value in requestMeta + const saveValue = + typeof mimeType !== 'string' // Switched to No body + ? this.props.activeRequest.body + : {}; // Clear saved value in requestMeta - await models.requestMeta.update(requestMeta, {savedRequestBody: saveValue}); + await models.requestMeta.update(requestMeta, { + savedRequestBody: saveValue + }); - const newRequest = await updateMimeType(this.props.activeRequest, mimeType, false, savedBody); + const newRequest = await updateMimeType( + this.props.activeRequest, + mimeType, + false, + savedBody + ); // Force it to update, because other editor components (header editor) // needs to change. Need to wait a delay so the next render can finish @@ -380,7 +475,11 @@ class App extends PureComponent { return newRequest; } - async _handleSendAndDownloadRequestWithEnvironment (requestId, environmentId, dir) { + async _handleSendAndDownloadRequestWithEnvironment( + requestId, + environmentId, + dir + ) { const request = await models.request.getById(requestId); if (!request) { return; @@ -407,8 +506,11 @@ class App extends PureComponent { } if (responsePatch.statusCode >= 200 && responsePatch.statusCode < 300) { - const extension = mime.extension(responsePatch.contentType) || 'unknown'; - const name = nameFromHeader || `${request.name.replace(/\s/g, '-').toLowerCase()}.${extension}`; + const extension = + mime.extension(responsePatch.contentType) || 'unknown'; + const name = + nameFromHeader || + `${request.name.replace(/\s/g, '-').toLowerCase()}.${extension}`; const filename = path.join(dir, name); const to = fs.createWriteStream(filename); @@ -426,7 +528,11 @@ class App extends PureComponent { }); readStream.on('error', async err => { - console.warn('Failed to download request after sending', responsePatch.bodyPath, err); + console.warn( + 'Failed to download request after sending', + responsePatch.bodyPath, + err + ); await models.response.create(responsePatch); }); } @@ -445,13 +551,15 @@ class App extends PureComponent { } // Unset active response because we just made a new one - await this._updateRequestMetaByParentId(requestId, {activeResponseId: null}); + await this._updateRequestMetaByParentId(requestId, { + activeResponseId: null + }); // Stop loading this.props.handleStopLoading(requestId); } - async _handleSendRequestWithEnvironment (requestId, environmentId) { + async _handleSendRequestWithEnvironment(requestId, environmentId) { const request = await models.request.getById(requestId); if (!request) { return; @@ -471,7 +579,7 @@ class App extends PureComponent { await models.response.create(responsePatch); } catch (err) { if (err.type === 'render') { - showModal(RequestRenderErrorModal, {request, error: err}); + showModal(RequestRenderErrorModal, { request, error: err }); } else { showAlert({ title: 'Unexpected Request Failure', @@ -488,15 +596,17 @@ class App extends PureComponent { } // Unset active response because we just made a new one - await this._updateRequestMetaByParentId(requestId, {activeResponseId: null}); + await this._updateRequestMetaByParentId(requestId, { + activeResponseId: null + }); // Stop loading this.props.handleStopLoading(requestId); } - async _handleSetActiveResponse (requestId, activeResponse = null) { + async _handleSetActiveResponse(requestId, activeResponse = null) { const activeResponseId = activeResponse ? activeResponse._id : null; - await this._updateRequestMetaByParentId(requestId, {activeResponseId}); + await this._updateRequestMetaByParentId(requestId, { activeResponseId }); let response; if (activeResponseId) { @@ -517,43 +627,43 @@ class App extends PureComponent { } } - _requestCreateForWorkspace () { + _requestCreateForWorkspace() { this._requestCreate(this.props.activeWorkspace._id); } - _startDragSidebar () { - this.setState({draggingSidebar: true}); + _startDragSidebar() { + this.setState({ draggingSidebar: true }); } - _resetDragSidebar () { + _resetDragSidebar() { // TODO: Remove setTimeout need be not triggering drag on double click setTimeout(() => this._handleSetSidebarWidth(DEFAULT_SIDEBAR_WIDTH), 50); } - _startDragPaneHorizontal () { - this.setState({draggingPaneHorizontal: true}); + _startDragPaneHorizontal() { + this.setState({ draggingPaneHorizontal: true }); } - _startDragPaneVertical () { - this.setState({draggingPaneVertical: true}); + _startDragPaneVertical() { + this.setState({ draggingPaneVertical: true }); } - _resetDragPaneHorizontal () { + _resetDragPaneHorizontal() { // TODO: Remove setTimeout need be not triggering drag on double click setTimeout(() => this._handleSetPaneWidth(DEFAULT_PANE_WIDTH), 50); } - _resetDragPaneVertical () { + _resetDragPaneVertical() { // TODO: Remove setTimeout need be not triggering drag on double click setTimeout(() => this._handleSetPaneHeight(DEFAULT_PANE_HEIGHT), 50); } - _handleMouseMove (e) { + _handleMouseMove(e) { if (this.state.draggingPaneHorizontal) { // Only pop the overlay after we've moved it a bit (so we don't block doubleclick); const distance = this.props.paneWidth - this.state.paneWidth; if (!this.state.showDragOverlay && Math.abs(distance) > 0.02 /* % */) { - this.setState({showDragOverlay: true}); + this.setState({ showDragOverlay: true }); } const requestPane = ReactDOM.findDOMNode(this._requestPane); @@ -571,7 +681,7 @@ class App extends PureComponent { // Only pop the overlay after we've moved it a bit (so we don't block doubleclick); const distance = this.props.paneHeight - this.state.paneHeight; if (!this.state.showDragOverlay && Math.abs(distance) > 0.02 /* % */) { - this.setState({showDragOverlay: true}); + this.setState({ showDragOverlay: true }); } const requestPane = ReactDOM.findDOMNode(this._requestPane); @@ -582,14 +692,17 @@ class App extends PureComponent { const pixelOffset = e.clientY - requestPane.offsetTop; let paneHeight = pixelOffset / (requestPaneHeight + responsePaneHeight); - paneHeight = Math.min(Math.max(paneHeight, MIN_PANE_HEIGHT), MAX_PANE_HEIGHT); + paneHeight = Math.min( + Math.max(paneHeight, MIN_PANE_HEIGHT), + MAX_PANE_HEIGHT + ); this._handleSetPaneHeight(paneHeight); } else if (this.state.draggingSidebar) { // Only pop the overlay after we've moved it a bit (so we don't block doubleclick); const distance = this.props.sidebarWidth - this.state.sidebarWidth; if (!this.state.showDragOverlay && Math.abs(distance) > 2 /* ems */) { - this.setState({showDragOverlay: true}); + this.setState({ showDragOverlay: true }); } const currentPixelWidth = ReactDOM.findDOMNode(this._sidebar).offsetWidth; @@ -606,27 +719,27 @@ class App extends PureComponent { } } - _handleMouseUp () { + _handleMouseUp() { if (this.state.draggingSidebar) { - this.setState({draggingSidebar: false, showDragOverlay: false}); + this.setState({ draggingSidebar: false, showDragOverlay: false }); } if (this.state.draggingPaneHorizontal) { - this.setState({draggingPaneHorizontal: false, showDragOverlay: false}); + this.setState({ draggingPaneHorizontal: false, showDragOverlay: false }); } if (this.state.draggingPaneVertical) { - this.setState({draggingPaneVertical: false, showDragOverlay: false}); + this.setState({ draggingPaneVertical: false, showDragOverlay: false }); } } - _handleKeyDown (e) { + _handleKeyDown(e) { for (const [definition, callback] of this._globalKeyMap) { hotkeys.executeHotKey(e, definition, callback); } } - _handleToggleMenuBar (hide) { + _handleToggleMenuBar(hide) { for (const win of remote.BrowserWindow.getAllWindows()) { if (win.isMenuBarAutoHide() !== hide) { win.setAutoHideMenuBar(hide); @@ -635,12 +748,12 @@ class App extends PureComponent { } } - async _handleToggleSidebar () { + async _handleToggleSidebar() { const sidebarHidden = !this.props.sidebarHidden; await this._handleSetSidebarHidden(sidebarHidden); } - _setWrapperRef (n) { + _setWrapperRef(n) { this._wrapper = n; } @@ -648,12 +761,8 @@ class App extends PureComponent { * Update document.title to be "Workspace (Environment) – Request" * @private */ - _updateDocumentTitle () { - const { - activeWorkspace, - activeEnvironment, - activeRequest - } = this.props; + _updateDocumentTitle() { + const { activeWorkspace, activeEnvironment, activeRequest } = this.props; let title = activeWorkspace.name; @@ -668,11 +777,11 @@ class App extends PureComponent { document.title = title; } - componentDidUpdate () { + componentDidUpdate() { this._updateDocumentTitle(); } - async componentDidMount () { + async componentDidMount() { // Bind mouse and key handlers document.addEventListener('mouseup', this._handleMouseUp); document.addEventListener('mousemove', this._handleMouseMove); @@ -691,7 +800,7 @@ class App extends PureComponent { fromSync ] = change; - const {activeRequest} = this.props; + const { activeRequest } = this.props; // No active request, so we don't need to force refresh anything if (!activeRequest) { @@ -742,34 +851,46 @@ class App extends PureComponent { }); // NOTE: This is required for "drop" event to trigger. - document.addEventListener('dragover', e => { - e.preventDefault(); - }, false); + document.addEventListener( + 'dragover', + e => { + e.preventDefault(); + }, + false + ); - document.addEventListener('drop', async e => { - e.preventDefault(); - const {activeWorkspace, handleImportUriToWorkspace} = this.props; - if (!activeWorkspace) { - return; - } + document.addEventListener( + 'drop', + async e => { + e.preventDefault(); + const { activeWorkspace, handleImportUriToWorkspace } = this.props; + if (!activeWorkspace) { + return; + } - if (e.dataTransfer.files.length === 0) { - console.log('[drag] Ignored drop event because no files present'); - return; - } + if (e.dataTransfer.files.length === 0) { + console.log('[drag] Ignored drop event because no files present'); + return; + } - const file = e.dataTransfer.files[0]; - const {path} = file; - const uri = `file://${path}`; + const file = e.dataTransfer.files[0]; + const { path } = file; + const uri = `file://${path}`; - await showAlert({ - title: 'Confirm Data Import', - message: Import {path}?, - addCancel: true - }); + await showAlert({ + title: 'Confirm Data Import', + message: ( + + Import {path}? + + ), + addCancel: true + }); - handleImportUriToWorkspace(activeWorkspace._id, uri); - }, false); + handleImportUriToWorkspace(activeWorkspace._id, uri); + }, + false + ); ipcRenderer.on('toggle-sidebar', this._handleToggleSidebar); @@ -780,15 +901,17 @@ class App extends PureComponent { setTimeout(() => ipcRenderer.send('window-ready'), 500); } - componentWillUnmount () { + componentWillUnmount() { // Remove mouse and key handlers document.removeEventListener('mouseup', this._handleMouseUp); document.removeEventListener('mousemove', this._handleMouseMove); } - async _ensureWorkspaceChildren (props) { - const {activeWorkspace, activeCookieJar, environments} = props; - const baseEnvironments = environments.filter(e => e.parentId === activeWorkspace._id); + async _ensureWorkspaceChildren(props) { + const { activeWorkspace, activeCookieJar, environments } = props; + const baseEnvironments = environments.filter( + e => e.parentId === activeWorkspace._id + ); // Nothing to do if (baseEnvironments.length && activeCookieJar) { @@ -805,13 +928,19 @@ class App extends PureComponent { await db.bufferChanges(); if (baseEnvironments.length === 0) { - await models.environment.create({parentId: activeWorkspace._id}); - console.log(`[app] Created missing base environment for ${activeWorkspace.name}`); + await models.environment.create({ parentId: activeWorkspace._id }); + console.log( + `[app] Created missing base environment for ${activeWorkspace.name}` + ); } if (!activeCookieJar) { - await models.cookieJar.create({parentId: this.props.activeWorkspace._id}); - console.log(`[app] Created missing cookie jar for ${activeWorkspace.name}`); + await models.cookieJar.create({ + parentId: this.props.activeWorkspace._id + }); + console.log( + `[app] Created missing cookie jar for ${activeWorkspace.name}` + ); } await db.flushChanges(); @@ -820,23 +949,26 @@ class App extends PureComponent { this._isMigratingChildren = false; } - componentWillReceiveProps (nextProps) { + componentWillReceiveProps(nextProps) { this._ensureWorkspaceChildren(nextProps); } - componentWillMount () { + componentWillMount() { this._ensureWorkspaceChildren(this.props); } - render () { + render() { if (this._isMigratingChildren) { console.log('[app] Waiting for migration to complete'); return null; } return ( - +
- + {/* Block all mouse activity by showing an overlay while dragging */} - {this.state.showDragOverlay ?
: null} + {this.state.showDragOverlay ? ( +
+ ) : null}
); @@ -912,32 +1054,24 @@ App.propTypes = { }) }; -function mapStateToProps (state, props) { - const { - entities, - global - } = state; +function mapStateToProps(state, props) { + const { entities, global } = state; - const { - isLoading, - loadingRequestIds - } = global; + const { isLoading, loadingRequestIds } = global; // Entities const entitiesLists = selectEntitiesLists(state, props); - const { - workspaces, - environments, - requests, - requestGroups - } = entitiesLists; + const { workspaces, environments, requests, requestGroups } = entitiesLists; const settings = entitiesLists.settings[0]; // Workspace stuff const workspaceMeta = selectActiveWorkspaceMeta(state, props) || {}; const activeWorkspace = selectActiveWorkspace(state, props); - const activeWorkspaceClientCertificates = selectActiveWorkspaceClientCertificates(state, props); + const activeWorkspaceClientCertificates = selectActiveWorkspaceClientCertificates( + state, + props + ); const sidebarHidden = workspaceMeta.sidebarHidden || false; const sidebarFilter = workspaceMeta.sidebarFilter || ''; const sidebarWidth = workspaceMeta.sidebarWidth || DEFAULT_SIDEBAR_WIDTH; @@ -955,7 +1089,8 @@ function mapStateToProps (state, props) { const activeCookieJar = selectActiveCookieJar(state, props); // Response stuff - const activeRequestResponses = selectActiveRequestResponses(state, props) || []; + const activeRequestResponses = + selectActiveRequestResponses(state, props) || []; const activeResponse = selectActiveResponse(state, props) || null; // Environment stuff @@ -966,9 +1101,13 @@ function mapStateToProps (state, props) { const oAuth2Token = selectActiveOAuth2Token(state, props); // Find other meta things - const loadStartTime = loadingRequestIds[activeRequest ? activeRequest._id : 'n/a'] || -1; + const loadStartTime = + loadingRequestIds[activeRequest ? activeRequest._id : 'n/a'] || -1; const sidebarChildren = selectSidebarChildren(state, props); - const workspaceChildren = selectWorkspaceRequestsAndRequestGroups(state, props); + const workspaceChildren = selectWorkspaceRequestsAndRequestGroups( + state, + props + ); const unseenWorkspaces = selectUnseenWorkspaces(state, props); return Object.assign({}, state, { @@ -1001,7 +1140,7 @@ function mapStateToProps (state, props) { }); } -function mapDispatchToProps (dispatch) { +function mapDispatchToProps(dispatch) { const global = bindActionCreators(globalActions, dispatch); return { @@ -1017,7 +1156,7 @@ function mapDispatchToProps (dispatch) { }; } -async function _moveDoc (docToMove, parentId, targetId, targetOffset) { +async function _moveDoc(docToMove, parentId, targetId, targetOffset) { // Nothing to do. We are in the same spot as we started if (docToMove._id === targetId) { return; @@ -1032,21 +1171,21 @@ async function _moveDoc (docToMove, parentId, targetId, targetOffset) { } } - function __updateDoc (doc, patch) { + function __updateDoc(doc, patch) { models.getModel(docToMove.type).update(doc, patch); } if (targetId === null) { // We are moving to an empty area. No sorting required - await __updateDoc(docToMove, {parentId}); + await __updateDoc(docToMove, { parentId }); return; } // NOTE: using requestToTarget's parentId so we can switch parents! let docs = [ - ...await models.request.findByParentId(parentId), - ...await models.requestGroup.findByParentId(parentId) - ].sort((a, b) => a.metaSortKey < b.metaSortKey ? -1 : 1); + ...(await models.request.findByParentId(parentId)), + ...(await models.requestGroup.findByParentId(parentId)) + ].sort((a, b) => (a.metaSortKey < b.metaSortKey ? -1 : 1)); // Find the index of doc B so we can re-order and save everything for (let i = 0; i < docs.length; i++) { @@ -1065,7 +1204,9 @@ async function _moveDoc (docToMove, parentId, targetId, targetOffset) { } const beforeKey = before ? before.metaSortKey : docs[0].metaSortKey - 100; - const afterKey = after ? after.metaSortKey : docs[docs.length - 1].metaSortKey + 100; + const afterKey = after + ? after.metaSortKey + : docs[docs.length - 1].metaSortKey + 100; if (Math.abs(afterKey - beforeKey) < 0.000001) { // If sort keys get too close together, we need to redistribute the list. This is @@ -1074,10 +1215,10 @@ async function _moveDoc (docToMove, parentId, targetId, targetOffset) { console.log(`[app] Recreating Sort Keys ${beforeKey} ${afterKey}`); await db.bufferChanges(300); - docs.map((r, i) => __updateDoc(r, {metaSortKey: i * 100, parentId})); + docs.map((r, i) => __updateDoc(r, { metaSortKey: i * 100, parentId })); } else { - const metaSortKey = afterKey - ((afterKey - beforeKey) / 2); - __updateDoc(docToMove, {metaSortKey, parentId}); + const metaSortKey = afterKey - (afterKey - beforeKey) / 2; + __updateDoc(docToMove, { metaSortKey, parentId }); } break; @@ -1085,4 +1226,7 @@ async function _moveDoc (docToMove, parentId, targetId, targetOffset) { } } -export default connect(mapStateToProps, mapDispatchToProps)(App); +export default connect( + mapStateToProps, + mapDispatchToProps +)(App); diff --git a/packages/insomnia-app/app/ui/dnd-backend.js b/packages/insomnia-app/app/ui/dnd-backend.js index f06f11a356..4816751304 100644 --- a/packages/insomnia-app/app/ui/dnd-backend.js +++ b/packages/insomnia-app/app/ui/dnd-backend.js @@ -1,7 +1,7 @@ import HTML5Backend from 'react-dnd-html5-backend/lib/HTML5Backend'; class DNDBackend extends HTML5Backend { - handleTopDragEndCapture (e) { + handleTopDragEndCapture(e) { if (this.isDraggingNativeItem()) { setTimeout(() => { this.actions.endDrag(); @@ -12,27 +12,27 @@ class DNDBackend extends HTML5Backend { super.handleTopDragEndCapture(e); } - handleTopDragOver (e) { + handleTopDragOver(e) { if (this.isDraggingNativeItem()) return; super.handleTopDragOver(e); } - handleTopDragLeaveCapture (e) { + handleTopDragLeaveCapture(e) { if (this.isDraggingNativeItem()) return; super.handleTopDragLeaveCapture(e); } - handleTopDropCapture (e) { + handleTopDropCapture(e) { if (this.isDraggingNativeItem()) return; super.handleTopDropCapture(e); } - handleTopDrop (e) { + handleTopDrop(e) { if (!this.monitor.isDragging() || this.isDraggingNativeItem()) return; super.handleTopDrop(e); } } -export default function (manager) { +export default function(manager) { return new DNDBackend(manager); } diff --git a/packages/insomnia-app/app/ui/index.js b/packages/insomnia-app/app/ui/index.js index 23e5aa1a61..8e0d84ad72 100644 --- a/packages/insomnia-app/app/ui/index.js +++ b/packages/insomnia-app/app/ui/index.js @@ -1,22 +1,22 @@ import * as React from 'react'; import ReactDOM from 'react-dom'; -import {AppContainer} from 'react-hot-loader'; -import {Provider} from 'react-redux'; -import {DragDropContext} from 'react-dnd'; +import { AppContainer } from 'react-hot-loader'; +import { Provider } from 'react-redux'; +import { DragDropContext } from 'react-dnd'; import App from './containers/app'; import * as models from '../models'; import * as db from '../common/database'; -import {init as initStore} from './redux/modules'; -import {init as initSync} from '../sync'; -import {init as initPlugins} from '../plugins'; +import { init as initStore } from './redux/modules'; +import { init as initSync } from '../sync'; +import { init as initPlugins } from '../plugins'; import DNDBackend from './dnd-backend'; import './css/index.less'; -import {isDevelopment} from '../common/constants'; +import { isDevelopment } from '../common/constants'; // Handy little helper document.body.setAttribute('data-platform', process.platform); -(async function () { +(async function() { await db.initClient(); // Create Redux store @@ -28,7 +28,7 @@ document.body.setAttribute('data-platform', process.platform); ReactDOM.render( - + , document.getElementById('root') @@ -66,7 +66,7 @@ if (window && !isDevelopment()) { }); } -function showUpdateNotification () { +function showUpdateNotification() { console.log('[app] Update Available'); // eslint-disable-next-line no-new @@ -77,7 +77,7 @@ function showUpdateNotification () { }); } -const {ipcRenderer} = require('electron'); +const { ipcRenderer } = require('electron'); ipcRenderer.on('update-available', () => { // Give it a few seconds before showing this. Sometimes, when // you relaunch too soon it doesn't work the first time. diff --git a/packages/insomnia-app/app/ui/redux/create.js b/packages/insomnia-app/app/ui/redux/create.js index 86156fc231..4d60197257 100644 --- a/packages/insomnia-app/app/ui/redux/create.js +++ b/packages/insomnia-app/app/ui/redux/create.js @@ -1,14 +1,14 @@ -import {createStore, applyMiddleware, compose} from 'redux'; +import { createStore, applyMiddleware, compose } from 'redux'; import thunkMiddleware from 'redux-thunk'; -import {reducer} from './modules'; +import { reducer } from './modules'; -export default function () { +export default function() { const composeEnhancers = - typeof window === 'object' && - window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ + typeof window === 'object' && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({ - // Specify extension’s options like name, actionsBlacklist, actionsCreators, serialize... - }) : compose; + // Specify extension’s options like name, actionsBlacklist, actionsCreators, serialize... + }) + : compose; const middleware = [thunkMiddleware]; const enhancer = composeEnhancers( applyMiddleware(...middleware) diff --git a/packages/insomnia-app/app/ui/redux/modules/entities.js b/packages/insomnia-app/app/ui/redux/modules/entities.js index 15578dd1d3..4717600798 100644 --- a/packages/insomnia-app/app/ui/redux/modules/entities.js +++ b/packages/insomnia-app/app/ui/redux/modules/entities.js @@ -7,7 +7,7 @@ const ENTITY_CHANGES = 'entities/changes'; // Reducers // // ~~~~~~~~ // -function getReducerName (type) { +function getReducerName(type) { const trailer = type.match(/s$/) ? '' : 's'; return `${type.slice(0, 1).toLowerCase()}${type.slice(1)}${trailer}`; } @@ -18,11 +18,11 @@ for (const type of models.types()) { initialState[getReducerName(type)] = {}; } -export function reducer (state = initialState, action) { +export function reducer(state = initialState, action) { switch (action.type) { case ENTITY_CHANGES: const newState = Object.assign({}, state); - const {changes} = action; + const { changes } = action; for (const [event, doc] of changes) { const referenceName = getReducerName(doc.type); @@ -52,7 +52,7 @@ export function reducer (state = initialState, action) { // Actions // // ~~~~~~~ // -export function addChanges (changes) { +export function addChanges(changes) { return dispatch => { setTimeout(() => { dispatch(addChangesSync(changes)); @@ -60,6 +60,6 @@ export function addChanges (changes) { }; } -export function addChangesSync (changes) { - return {type: ENTITY_CHANGES, changes}; +export function addChangesSync(changes) { + return { type: ENTITY_CHANGES, changes }; } diff --git a/packages/insomnia-app/app/ui/redux/modules/global.js b/packages/insomnia-app/app/ui/redux/modules/global.js index 4ec7af2a98..1fc8b21add 100644 --- a/packages/insomnia-app/app/ui/redux/modules/global.js +++ b/packages/insomnia-app/app/ui/redux/modules/global.js @@ -1,6 +1,6 @@ import electron from 'electron'; import * as React from 'react'; -import {combineReducers} from 'redux'; +import { combineReducers } from 'redux'; import fs from 'fs'; import path from 'path'; import AskModal from '../../../ui/components/modals/ask-modal'; @@ -12,7 +12,7 @@ import PaymentNotificationModal from '../../components/modals/payment-notificati import LoginModal from '../../components/modals/login-modal'; import * as models from '../../../models'; import SelectModal from '../../components/modals/select-modal'; -import {showError, showModal} from '../../components/modals/index'; +import { showError, showModal } from '../../components/modals/index'; const LOCALSTORAGE_PREFIX = `insomnia::meta`; @@ -31,7 +31,7 @@ const COMMAND_IMPORT_URI = 'app/import'; // REDUCERS // // ~~~~~~~~ // -function activeWorkspaceReducer (state = null, action) { +function activeWorkspaceReducer(state = null, action) { switch (action.type) { case SET_ACTIVE_WORKSPACE: return action.workspaceId; @@ -40,7 +40,7 @@ function activeWorkspaceReducer (state = null, action) { } } -function loadingReducer (state = false, action) { +function loadingReducer(state = false, action) { switch (action.type) { case LOAD_START: return true; @@ -51,12 +51,12 @@ function loadingReducer (state = false, action) { } } -function loadingRequestsReducer (state = {}, action) { +function loadingRequestsReducer(state = {}, action) { switch (action.type) { case LOAD_REQUEST_START: - return Object.assign({}, state, {[action.requestId]: action.time}); + return Object.assign({}, state, { [action.requestId]: action.time }); case LOAD_REQUEST_STOP: - return Object.assign({}, state, {[action.requestId]: -1}); + return Object.assign({}, state, { [action.requestId]: -1 }); default: return state; } @@ -72,14 +72,14 @@ export const reducer = combineReducers({ // ACTIONS // // ~~~~~~~ // -export function newCommand (command, args) { +export function newCommand(command, args) { return async dispatch => { switch (command) { case COMMAND_ALERT: - showModal(AlertModal, {title: args.title, message: args.message}); + showModal(AlertModal, { title: args.title, message: args.message }); break; case COMMAND_LOGIN: - showModal(LoginModal, {title: args.title, message: args.message}); + showModal(LoginModal, { title: args.title, message: args.message }); break; case COMMAND_TRIAL_END: showModal(PaymentNotificationModal); @@ -87,7 +87,11 @@ export function newCommand (command, args) { case COMMAND_IMPORT_URI: await showModal(AlertModal, { title: 'Confirm Data Import', - message: Do you really want to import {args.uri}?, + message: ( + + Do you really want to import {args.uri}? + + ), addCancel: true }); dispatch(importUri(args.workspaceId, args.uri)); @@ -96,35 +100,38 @@ export function newCommand (command, args) { }; } -export function loadStart () { - return {type: LOAD_START}; +export function loadStart() { + return { type: LOAD_START }; } -export function loadStop () { - return {type: LOAD_STOP}; +export function loadStop() { + return { type: LOAD_STOP }; } -export function loadRequestStart (requestId) { - return {type: LOAD_REQUEST_START, requestId, time: Date.now()}; +export function loadRequestStart(requestId) { + return { type: LOAD_REQUEST_START, requestId, time: Date.now() }; } -export function loadRequestStop (requestId) { - return {type: LOAD_REQUEST_STOP, requestId}; +export function loadRequestStop(requestId) { + return { type: LOAD_REQUEST_STOP, requestId }; } -export function setActiveWorkspace (workspaceId) { - window.localStorage.setItem(`${LOCALSTORAGE_PREFIX}::activeWorkspaceId`, JSON.stringify(workspaceId)); - return {type: SET_ACTIVE_WORKSPACE, workspaceId}; +export function setActiveWorkspace(workspaceId) { + window.localStorage.setItem( + `${LOCALSTORAGE_PREFIX}::activeWorkspaceId`, + JSON.stringify(workspaceId) + ); + return { type: SET_ACTIVE_WORKSPACE, workspaceId }; } -export function toggleRequestGroup (requestGroup) { +export function toggleRequestGroup(requestGroup) { return { type: REQUEST_GROUP_TOGGLE_COLLAPSE, requestGroupId: requestGroup._id }; } -export function importFile (workspaceId) { +export function importFile(workspaceId) { return async dispatch => { dispatch(loadStart()); @@ -132,12 +139,23 @@ export function importFile (workspaceId) { title: 'Import Insomnia Data', buttonLabel: 'Import', properties: ['openFile'], - filters: [{ - name: 'Insomnia Import', - extensions: [ - '', 'sh', 'txt', 'json', 'har', 'curl', 'bash', 'shell', 'yaml', 'yml' - ] - }] + filters: [ + { + name: 'Insomnia Import', + extensions: [ + '', + 'sh', + 'txt', + 'json', + 'har', + 'curl', + 'bash', + 'shell', + 'yaml', + 'yml' + ] + } + ] }; electron.remote.dialog.showOpenDialog(options, async paths => { @@ -153,7 +171,7 @@ export function importFile (workspaceId) { const uri = `file://${p}`; await importUtils.importUri(workspaceId, uri); } catch (err) { - showModal(AlertModal, {title: 'Import Failed', message: err + ''}); + showModal(AlertModal, { title: 'Import Failed', message: err + '' }); } finally { dispatch(loadStop()); } @@ -162,20 +180,20 @@ export function importFile (workspaceId) { }; } -export function importUri (workspaceId, uri) { +export function importUri(workspaceId, uri) { return async dispatch => { dispatch(loadStart()); try { await importUtils.importUri(workspaceId, uri); } catch (err) { - showModal(AlertModal, {title: 'Import Failed', message: err + ''}); + showModal(AlertModal, { title: 'Import Failed', message: err + '' }); } finally { dispatch(loadStop()); } }; } -export function exportFile (workspaceId = null) { +export function exportFile(workspaceId = null) { return dispatch => { dispatch(loadStart()); @@ -185,24 +203,28 @@ export function exportFile (workspaceId = null) { showModal(SelectModal, { title: 'Select Export Type', options: [ - {name: 'Insomnia – Sharable with other Insomnia users', value: VALUE_JSON}, - {name: 'HAR – HTTP Archive Format', value: VALUE_HAR} + { + name: 'Insomnia – Sharable with other Insomnia users', + value: VALUE_JSON + }, + { name: 'HAR – HTTP Archive Format', value: VALUE_HAR } ], message: 'Which format would you like to export as?', onCancel: () => { dispatch(loadStop()); }, onDone: async selectedFormat => { - const workspace = await - models.workspace.getById(workspaceId); + const workspace = await models.workspace.getById(workspaceId); // Check if we want to export private environments let environments; if (workspace) { - const parentEnv = await models.environment.getOrCreateForWorkspace(workspace); + const parentEnv = await models.environment.getOrCreateForWorkspace( + workspace + ); environments = [ parentEnv, - ...await models.environment.findByParentId(parentEnv._id) + ...(await models.environment.findByParentId(parentEnv._id)) ]; } else { environments = await models.environment.all(); @@ -219,7 +241,10 @@ export function exportFile (workspaceId = null) { } const date = moment().format('YYYY-MM-DD'); - const name = (workspace ? workspace.name : 'Insomnia All').replace(/ /g, '-'); + const name = (workspace ? workspace.name : 'Insomnia All').replace( + / /g, + '-' + ); const lastDir = window.localStorage.getItem('insomnia.lastExportPath'); const dir = lastDir || electron.remote.app.getPath('desktop'); @@ -231,9 +256,14 @@ export function exportFile (workspaceId = null) { }; if (selectedFormat === VALUE_HAR) { - options.filters = [{name: 'HTTP Archive 1.2', extensions: ['har', 'har.json', 'json']}]; + options.filters = [ + { + name: 'HTTP Archive 1.2', + extensions: ['har', 'har.json', 'json'] + } + ]; } else { - options.filters = [{name: 'Insomnia Export', extensions: ['json']}]; + options.filters = [{ name: 'Insomnia Export', extensions: ['json'] }]; } electron.remote.dialog.showSaveDialog(options, async filename => { @@ -246,9 +276,15 @@ export function exportFile (workspaceId = null) { let json; try { if (selectedFormat === VALUE_HAR) { - json = await importUtils.exportHAR(workspace, exportPrivateEnvironments); + json = await importUtils.exportHAR( + workspace, + exportPrivateEnvironments + ); } else { - json = await importUtils.exportJSON(workspace, exportPrivateEnvironments); + json = await importUtils.exportJSON( + workspace, + exportPrivateEnvironments + ); } } catch (err) { showError({ @@ -279,7 +315,7 @@ export function exportFile (workspaceId = null) { }; } -export function init () { +export function init() { let workspaceId = null; try { diff --git a/packages/insomnia-app/app/ui/redux/modules/index.js b/packages/insomnia-app/app/ui/redux/modules/index.js index 0f8d23060b..898b1baed1 100644 --- a/packages/insomnia-app/app/ui/redux/modules/index.js +++ b/packages/insomnia-app/app/ui/redux/modules/index.js @@ -1,4 +1,4 @@ -import {bindActionCreators, combineReducers} from 'redux'; +import { bindActionCreators, combineReducers } from 'redux'; import * as entities from './entities'; import configureStore from '../create'; import * as global from './global'; @@ -6,12 +6,15 @@ import * as db from '../../../common/database'; import * as models from '../../../models'; import * as fetch from '../../../common/fetch'; -export async function init () { +export async function init() { const store = configureStore(); // Do things that must happen before initial render - const {addChanges, addChangesSync} = bindActionCreators(entities, store.dispatch); - const {newCommand} = bindActionCreators(global, store.dispatch); + const { addChanges, addChangesSync } = bindActionCreators( + entities, + store.dispatch + ); + const { newCommand } = bindActionCreators(global, store.dispatch); const allDocs = await getAllDocs(); @@ -36,21 +39,21 @@ export const reducer = combineReducers({ /** * Async function to get all docs concurrently */ -async function getAllDocs () { +async function getAllDocs() { // Restore docs in parent->child->grandchild order const allDocs = [ - ...await models.settings.all(), - ...await models.workspace.all(), - ...await models.workspaceMeta.all(), - ...await models.environment.all(), - ...await models.cookieJar.all(), - ...await models.requestGroup.all(), - ...await models.requestGroupMeta.all(), - ...await models.request.all(), - ...await models.requestMeta.all(), - ...await models.response.all(), - ...await models.oAuth2Token.all(), - ...await models.clientCertificate.all() + ...(await models.settings.all()), + ...(await models.workspace.all()), + ...(await models.workspaceMeta.all()), + ...(await models.environment.all()), + ...(await models.cookieJar.all()), + ...(await models.requestGroup.all()), + ...(await models.requestGroupMeta.all()), + ...(await models.request.all()), + ...(await models.requestMeta.all()), + ...(await models.response.all()), + ...(await models.oAuth2Token.all()), + ...(await models.clientCertificate.all()) ]; return allDocs; diff --git a/packages/insomnia-app/app/ui/redux/selectors.js b/packages/insomnia-app/app/ui/redux/selectors.js index 00371a81cf..1aa5bb6120 100644 --- a/packages/insomnia-app/app/ui/redux/selectors.js +++ b/packages/insomnia-app/app/ui/redux/selectors.js @@ -1,5 +1,5 @@ -import {createSelector} from 'reselect'; -import {fuzzyMatchAll} from '../../common/misc'; +import { createSelector } from 'reselect'; +import { fuzzyMatchAll } from '../../common/misc'; // ~~~~~~~~~ // // Selectors // @@ -32,7 +32,9 @@ export const selectActiveWorkspaceClientCertificates = createSelector( selectEntitiesLists, selectActiveWorkspace, (entities, activeWorkspace) => { - return entities.clientCertificates.filter(c => c.parentId === activeWorkspace._id); + return entities.clientCertificates.filter( + c => c.parentId === activeWorkspace._id + ); } ); @@ -74,10 +76,17 @@ export const selectSidebarChildren = createSelector( selectRequestsAndRequestGroups, selectActiveWorkspace, selectActiveWorkspaceMeta, - (collapsed, requestsAndRequestGroups, activeWorkspace, activeWorkspaceMeta) => { - const sidebarFilter = activeWorkspaceMeta ? activeWorkspaceMeta.sidebarFilter : ''; + ( + collapsed, + requestsAndRequestGroups, + activeWorkspace, + activeWorkspaceMeta + ) => { + const sidebarFilter = activeWorkspaceMeta + ? activeWorkspaceMeta.sidebarFilter + : ''; - function next (parentId) { + function next(parentId) { const children = requestsAndRequestGroups .filter(e => e.parentId === parentId) .sort((a, b) => { @@ -100,7 +109,7 @@ export const selectSidebarChildren = createSelector( } } - function matchChildren (children, parentNames = []) { + function matchChildren(children, parentNames = []) { // Bail early if no filter defined if (!sidebarFilter) { return children; @@ -113,7 +122,7 @@ export const selectSidebarChildren = createSelector( const hasMatchedChildren = child.children.find(c => c.hidden === false); // Try to match request attributes - const {name, method} = child.doc; + const { name, method } = child.doc; const hasMatchedAttributes = fuzzyMatchAll(sidebarFilter, [ name, @@ -138,9 +147,11 @@ export const selectWorkspaceRequestsAndRequestGroups = createSelector( selectActiveWorkspace, selectEntitiesLists, (activeWorkspace, entities) => { - function getChildren (doc) { + function getChildren(doc) { const requests = entities.requests.filter(r => r.parentId === doc._id); - const requestGroups = entities.requestGroups.filter(rg => rg.parentId === doc._id); + const requestGroups = entities.requestGroups.filter( + rg => rg.parentId === doc._id + ); const requestGroupChildren = []; for (const requestGroup of requestGroups) { @@ -169,7 +180,9 @@ export const selectActiveCookieJar = createSelector( selectEntitiesLists, selectActiveWorkspace, (entities, workspace) => { - const cookieJar = entities.cookieJars.find(cj => cj.parentId === workspace._id); + const cookieJar = entities.cookieJars.find( + cj => cj.parentId === workspace._id + ); return cookieJar || null; } ); @@ -186,7 +199,7 @@ export const selectActiveOAuth2Token = createSelector( export const selectUnseenWorkspaces = createSelector( selectEntitiesLists, entities => { - const {workspaces, workspaceMetas} = entities; + const { workspaces, workspaceMetas } = entities; return workspaces.filter(workspace => { const meta = workspaceMetas.find(m => m.parentId === workspace._id); return !!(meta && !meta.hasSeen); @@ -210,7 +223,7 @@ export const selectActiveRequestResponses = createSelector( const requestId = activeRequest ? activeRequest._id : 'n/a'; return entities.responses .filter(response => requestId === response.parentId) - .sort((a, b) => a.created > b.created ? -1 : 1); + .sort((a, b) => (a.created > b.created ? -1 : 1)); } ); @@ -218,8 +231,12 @@ export const selectActiveResponse = createSelector( selectActiveRequestMeta, selectActiveRequestResponses, (activeRequestMeta, responses) => { - const activeResponseId = activeRequestMeta ? activeRequestMeta.activeResponseId : 'n/a'; - const activeResponse = responses.find(response => response._id === activeResponseId); + const activeResponseId = activeRequestMeta + ? activeRequestMeta.activeResponseId + : 'n/a'; + const activeResponse = responses.find( + response => response._id === activeResponseId + ); if (activeResponse) { return activeResponse; diff --git a/packages/insomnia-app/flow-typed/autobind-decorator.js b/packages/insomnia-app/flow-typed/autobind-decorator.js index 467cfc1b4b..88ace1e128 100644 --- a/packages/insomnia-app/flow-typed/autobind-decorator.js +++ b/packages/insomnia-app/flow-typed/autobind-decorator.js @@ -1,3 +1,3 @@ declare module 'autobind-decorator' { - declare module.exports: * + declare module.exports: *; } diff --git a/packages/insomnia-app/flow-typed/aws4.js b/packages/insomnia-app/flow-typed/aws4.js index ce2c899dcf..b2b4394fe1 100644 --- a/packages/insomnia-app/flow-typed/aws4.js +++ b/packages/insomnia-app/flow-typed/aws4.js @@ -1,5 +1,8 @@ declare module 'aws4' { declare module.exports: { - sign: (options: Object, credentials: Object) => {headers: {[string]: string}} - } + sign: ( + options: Object, + credentials: Object + ) => { headers: { [string]: string } } + }; } diff --git a/packages/insomnia-app/flow-typed/classnames.js b/packages/insomnia-app/flow-typed/classnames.js index 15526ddba8..c7c86d2c35 100644 --- a/packages/insomnia-app/flow-typed/classnames.js +++ b/packages/insomnia-app/flow-typed/classnames.js @@ -1,3 +1,3 @@ declare module 'classnames' { - declare module.exports: (...args: Array) => Object + declare module.exports: (...args: Array) => Object; } diff --git a/packages/insomnia-app/flow-typed/clone.js b/packages/insomnia-app/flow-typed/clone.js index d3e3797521..783a5fbac3 100644 --- a/packages/insomnia-app/flow-typed/clone.js +++ b/packages/insomnia-app/flow-typed/clone.js @@ -1,3 +1,3 @@ declare module 'clone' { - declare module.exports: (value: T) => T + declare module.exports: (value: T) => T; } diff --git a/packages/insomnia-app/flow-typed/deep-equal.js b/packages/insomnia-app/flow-typed/deep-equal.js index 49d23e29cc..756941bb47 100644 --- a/packages/insomnia-app/flow-typed/deep-equal.js +++ b/packages/insomnia-app/flow-typed/deep-equal.js @@ -1,3 +1,3 @@ declare module 'deep-equal' { - declare module.exports: Function + declare module.exports: Function; } diff --git a/packages/insomnia-app/flow-typed/electron-squirrel-startup.js b/packages/insomnia-app/flow-typed/electron-squirrel-startup.js index ac1fdcf9bf..7dd88d5e00 100644 --- a/packages/insomnia-app/flow-typed/electron-squirrel-startup.js +++ b/packages/insomnia-app/flow-typed/electron-squirrel-startup.js @@ -1,3 +1,3 @@ declare module 'electron-squirrel-startup' { - declare module.exports: * + declare module.exports: *; } diff --git a/packages/insomnia-app/flow-typed/electron.js b/packages/insomnia-app/flow-typed/electron.js index dc14c07c96..6f3c8550bc 100644 --- a/packages/insomnia-app/flow-typed/electron.js +++ b/packages/insomnia-app/flow-typed/electron.js @@ -21,5 +21,5 @@ declare module 'electron' { clipboard: Object, screen: Object, autoUpdater: Object - } + }; } diff --git a/packages/insomnia-app/flow-typed/fs-extra.js b/packages/insomnia-app/flow-typed/fs-extra.js index 10449e9617..db24ee086f 100644 --- a/packages/insomnia-app/flow-typed/fs-extra.js +++ b/packages/insomnia-app/flow-typed/fs-extra.js @@ -1,5 +1,9 @@ declare module 'fs-extra' { declare module.exports: { - moveSync: (src: string, dest: string, options?: {overwrite?: boolean}) => void - } + moveSync: ( + src: string, + dest: string, + options?: { overwrite?: boolean } + ) => void + }; } diff --git a/packages/insomnia-app/flow-typed/fuzzysort.js b/packages/insomnia-app/flow-typed/fuzzysort.js index 7b6429b837..ea5f1e34a0 100644 --- a/packages/insomnia-app/flow-typed/fuzzysort.js +++ b/packages/insomnia-app/flow-typed/fuzzysort.js @@ -2,5 +2,5 @@ declare module 'fuzzysort' { declare module.exports: { highlight: Function, single: Function - } -} \ No newline at end of file + }; +} diff --git a/packages/insomnia-app/flow-typed/graphql.js b/packages/insomnia-app/flow-typed/graphql.js index 7ca26c86bf..7a05c4224f 100644 --- a/packages/insomnia-app/flow-typed/graphql.js +++ b/packages/insomnia-app/flow-typed/graphql.js @@ -1,15 +1,15 @@ declare module 'graphql' { - declare module.exports: * + declare module.exports: *; } declare module 'graphql/utilities/introspectionQuery' { declare module.exports: { introspectionQuery: string - } + }; } declare module 'graphql/utilities/buildClientSchema' { declare module.exports: { buildClientSchema: Function - } + }; } diff --git a/packages/insomnia-app/flow-typed/hawk.js b/packages/insomnia-app/flow-typed/hawk.js index 86a8cc2fcf..71e373f410 100644 --- a/packages/insomnia-app/flow-typed/hawk.js +++ b/packages/insomnia-app/flow-typed/hawk.js @@ -1,3 +1,3 @@ declare module 'hawk' { - declare module.exports: * + declare module.exports: *; } diff --git a/packages/insomnia-app/flow-typed/iconv-lite.js b/packages/insomnia-app/flow-typed/iconv-lite.js index 4b7403df03..571dd549ce 100644 --- a/packages/insomnia-app/flow-typed/iconv-lite.js +++ b/packages/insomnia-app/flow-typed/iconv-lite.js @@ -1,3 +1,3 @@ declare module 'iconv-lite' { - declare module.exports: * + declare module.exports: *; } diff --git a/packages/insomnia-app/flow-typed/insomnia-cookies.js b/packages/insomnia-app/flow-typed/insomnia-cookies.js index 9425bd2c4a..e5ca0fd1ee 100644 --- a/packages/insomnia-app/flow-typed/insomnia-cookies.js +++ b/packages/insomnia-app/flow-typed/insomnia-cookies.js @@ -3,5 +3,5 @@ declare module 'insomnia-cookies' { cookieToString: Function, jarFromCookies: Function, cookiesFromJar: Function - } + }; } diff --git a/packages/insomnia-app/flow-typed/insomnia-importers.js b/packages/insomnia-app/flow-typed/insomnia-importers.js index 4929a0e5e6..f33d22dfe6 100644 --- a/packages/insomnia-app/flow-typed/insomnia-importers.js +++ b/packages/insomnia-app/flow-typed/insomnia-importers.js @@ -1,6 +1,8 @@ declare module 'insomnia-importers' { declare module.exports: { - convert: (data: string) => Promise<{ + convert: ( + data: string + ) => Promise<{ type: { id: string, name: string, @@ -10,5 +12,5 @@ declare module 'insomnia-importers' { resources: Array } }> - } + }; } diff --git a/packages/insomnia-app/flow-typed/insomnia-libcurl.js b/packages/insomnia-app/flow-typed/insomnia-libcurl.js index cfc7692575..aa6196a9da 100644 --- a/packages/insomnia-app/flow-typed/insomnia-libcurl.js +++ b/packages/insomnia-app/flow-typed/insomnia-libcurl.js @@ -45,7 +45,7 @@ declare class Curl { USERNAME: number, VERBOSE: number, WRITEFUNCTION: number, - XFERINFOFUNCTION: number, + XFERINFOFUNCTION: number }; static auth: { @@ -62,7 +62,7 @@ declare class Curl { static netrc: { IGNORED: number, OPTIONAL: number, - REQUIRED: number, + REQUIRED: number }; static info: { @@ -95,5 +95,5 @@ declare class Curl { declare module 'insomnia-libcurl' { declare module.exports: { Curl: typeof Curl - } + }; } diff --git a/packages/insomnia-app/flow-typed/insomnia-plugin-hash.js b/packages/insomnia-app/flow-typed/insomnia-plugin-hash.js index cde869e67a..0937d64c66 100644 --- a/packages/insomnia-app/flow-typed/insomnia-plugin-hash.js +++ b/packages/insomnia-app/flow-typed/insomnia-plugin-hash.js @@ -1,7 +1,7 @@ -import type {PluginTemplateTag} from '../app/templating/extensions/index'; +import type { PluginTemplateTag } from '../app/templating/extensions/index'; declare module 'insomnia-plugin-hash' { declare module.exports: { templateTags: Array - } + }; } diff --git a/packages/insomnia-app/flow-typed/insomnia-prettify.js b/packages/insomnia-app/flow-typed/insomnia-prettify.js index a9cb2cd617..2977296999 100644 --- a/packages/insomnia-app/flow-typed/insomnia-prettify.js +++ b/packages/insomnia-app/flow-typed/insomnia-prettify.js @@ -1,5 +1,5 @@ declare module 'insomnia-prettify' { declare module.exports: { json: Function - } + }; } diff --git a/packages/insomnia-app/flow-typed/insomnia-url.js b/packages/insomnia-app/flow-typed/insomnia-url.js index 6761464499..6705145f97 100644 --- a/packages/insomnia-app/flow-typed/insomnia-url.js +++ b/packages/insomnia-app/flow-typed/insomnia-url.js @@ -7,5 +7,5 @@ declare module 'insomnia-url' { extractQueryStringFromUrl: Function, buildQueryParameter: Function, buildQueryStringFromParams: Function - } + }; } diff --git a/packages/insomnia-app/flow-typed/jsonpath.js b/packages/insomnia-app/flow-typed/jsonpath.js index 4f8921fe63..1dfe3d2c8a 100644 --- a/packages/insomnia-app/flow-typed/jsonpath.js +++ b/packages/insomnia-app/flow-typed/jsonpath.js @@ -1,5 +1,5 @@ declare module 'jsonpath' { declare module.exports: { query: Function - } + }; } diff --git a/packages/insomnia-app/flow-typed/jwt-authentication.js b/packages/insomnia-app/flow-typed/jwt-authentication.js index 2c3d0e6b13..e676cb100c 100644 --- a/packages/insomnia-app/flow-typed/jwt-authentication.js +++ b/packages/insomnia-app/flow-typed/jwt-authentication.js @@ -1,3 +1,3 @@ declare module 'jwt-authentication' { - declare module.exports: * + declare module.exports: *; } diff --git a/packages/insomnia-app/flow-typed/mime-types.js b/packages/insomnia-app/flow-typed/mime-types.js index 45c56670c0..448060ec57 100644 --- a/packages/insomnia-app/flow-typed/mime-types.js +++ b/packages/insomnia-app/flow-typed/mime-types.js @@ -2,5 +2,5 @@ declare module 'mime-types' { declare module.exports: { lookup: (fileName: string) => string, extension: (mimeType: string) => string - } + }; } diff --git a/packages/insomnia-app/flow-typed/mkdirp.js b/packages/insomnia-app/flow-typed/mkdirp.js index 5a9cc168f9..d80bf7d300 100644 --- a/packages/insomnia-app/flow-typed/mkdirp.js +++ b/packages/insomnia-app/flow-typed/mkdirp.js @@ -1,5 +1,5 @@ declare module 'mkdirp' { declare module.exports: { sync: (path: string) => void - } + }; } diff --git a/packages/insomnia-app/flow-typed/moment.js b/packages/insomnia-app/flow-typed/moment.js index 88db67e31d..b15df649b6 100644 --- a/packages/insomnia-app/flow-typed/moment.js +++ b/packages/insomnia-app/flow-typed/moment.js @@ -1,8 +1,8 @@ declare type moment = { - fromNow: () => string; - format: (fmt: string) => string; + fromNow: () => string, + format: (fmt: string) => string }; declare module 'moment' { - declare module.exports: (date?: any) => moment + declare module.exports: (date?: any) => moment; } diff --git a/packages/insomnia-app/flow-typed/multiparty.js b/packages/insomnia-app/flow-typed/multiparty.js index f656efae75..8e6667c5d3 100644 --- a/packages/insomnia-app/flow-typed/multiparty.js +++ b/packages/insomnia-app/flow-typed/multiparty.js @@ -1,3 +1,3 @@ declare module 'multiparty' { - declare module.exports: * + declare module.exports: *; } diff --git a/packages/insomnia-app/flow-typed/nedb.js b/packages/insomnia-app/flow-typed/nedb.js index aec83ef0da..91a0dde2b9 100644 --- a/packages/insomnia-app/flow-typed/nedb.js +++ b/packages/insomnia-app/flow-typed/nedb.js @@ -1,10 +1,10 @@ declare class NeDB { constructor(config: Object): NeDB; persistence: { - setAutocompactionInterval: (millis: number) => void; - } + setAutocompactionInterval: (millis: number) => void + }; } declare module 'nedb' { - declare module.exports: typeof NeDB + declare module.exports: typeof NeDB; } diff --git a/packages/insomnia-app/flow-typed/nunjucks.js b/packages/insomnia-app/flow-typed/nunjucks.js index 94441d2b14..b30bb1c143 100644 --- a/packages/insomnia-app/flow-typed/nunjucks.js +++ b/packages/insomnia-app/flow-typed/nunjucks.js @@ -12,14 +12,14 @@ type NunjucksConfig = { }; declare class Nunjucks { - extensions: {[string]: T}, - addExtension: (name: string, ext: T) => void, - addFilter: (name: string, ext: Function) => void, - renderString: (text: string, context: Object, callback: Function) => void + extensions: { [string]: T }; + addExtension: (name: string, ext: T) => void; + addFilter: (name: string, ext: Function) => void; + renderString: (text: string, context: Object, callback: Function) => void; } declare module 'nunjucks' { declare module.exports: { configure: (config: NunjucksConfig) => Nunjucks - } + }; } diff --git a/packages/insomnia-app/flow-typed/oauth-1.0a.js b/packages/insomnia-app/flow-typed/oauth-1.0a.js index 008b6f716c..fbb4bd2254 100644 --- a/packages/insomnia-app/flow-typed/oauth-1.0a.js +++ b/packages/insomnia-app/flow-typed/oauth-1.0a.js @@ -1,9 +1,9 @@ type SignatureMethod = 'HMAC-SHA1' | 'RSA-SHA1' | 'PLAINTEXT'; -type Token = {key: string, secret?: string}; +type Token = { key: string, secret?: string }; type RequestData = { url: string, method: string, - data?: {[string]: string} + data?: { [string]: string } }; type OAuth1Config = { @@ -11,18 +11,18 @@ type OAuth1Config = { key: string, secret: string }, - signature_method: 'HMAC-SHA1' | 'RSA-SHA1' | 'PLAINTEXT'; + signature_method: 'HMAC-SHA1' | 'RSA-SHA1' | 'PLAINTEXT', version: '1.0', hash_function: (signatureMethod: SignatureMethod, key: string) => string }; declare class OAuth1 { - constructor (config: OAuth1Config): OAuth1; + constructor(config: OAuth1Config): OAuth1; authorize: (data: RequestData, token: Token | null) => RequestData; - toHeader: (data: RequestData) => {'Authorization': string}; + toHeader: (data: RequestData) => { Authorization: string }; getSigningKey: (tokenSecret: string) => string; } declare module 'oauth-1.0a' { - declare module .exports: typeof OAuth1 + declare module.exports: typeof OAuth1; } diff --git a/packages/insomnia-app/flow-typed/papaparse.js b/packages/insomnia-app/flow-typed/papaparse.js index 391545ce11..26bea29a5c 100644 --- a/packages/insomnia-app/flow-typed/papaparse.js +++ b/packages/insomnia-app/flow-typed/papaparse.js @@ -1,5 +1,5 @@ declare module 'papaparse' { declare module.exports: { parse: Function - } + }; } diff --git a/packages/insomnia-app/flow-typed/pdfjs-dist.js b/packages/insomnia-app/flow-typed/pdfjs-dist.js index d21da756d2..d24ba4f82f 100644 --- a/packages/insomnia-app/flow-typed/pdfjs-dist.js +++ b/packages/insomnia-app/flow-typed/pdfjs-dist.js @@ -1,3 +1,3 @@ declare module 'pdfjs-dist/webpack' { - declare module.exports: * + declare module.exports: *; } diff --git a/packages/insomnia-app/flow-typed/react-sortable-hoc.js b/packages/insomnia-app/flow-typed/react-sortable-hoc.js index 60f24404ca..da0d6d0d70 100644 --- a/packages/insomnia-app/flow-typed/react-sortable-hoc.js +++ b/packages/insomnia-app/flow-typed/react-sortable-hoc.js @@ -2,8 +2,8 @@ import * as React from 'react'; declare module 'react-sortable-hoc' { declare module.exports: { - SortableContainer: (Object => React.Node) => React.Component, - SortableElement: (Object => React.Node) => React.Component, - arrayMove: (Array, oldIndex: number, newIndex: number) => Array, - } + SortableContainer: ((Object) => React.Node) => React.Component, + SortableElement: ((Object) => React.Node) => React.Component, + arrayMove: (Array, oldIndex: number, newIndex: number) => Array + }; } diff --git a/packages/insomnia-app/flow-typed/react-tabs.js b/packages/insomnia-app/flow-typed/react-tabs.js index 0ff97b8237..57a857ff2a 100644 --- a/packages/insomnia-app/flow-typed/react-tabs.js +++ b/packages/insomnia-app/flow-typed/react-tabs.js @@ -6,5 +6,5 @@ declare module 'react-tabs' { TabList: React.Element<*>, TabPanel: React.Element<*>, Tabs: React.Element<*> - } + }; } diff --git a/packages/insomnia-app/flow-typed/reselect.js b/packages/insomnia-app/flow-typed/reselect.js index 489fb7e833..530688d393 100644 --- a/packages/insomnia-app/flow-typed/reselect.js +++ b/packages/insomnia-app/flow-typed/reselect.js @@ -1,5 +1,5 @@ declare module 'reselect' { declare module.exports: { createSelector: Function - } + }; } diff --git a/packages/insomnia-app/flow-typed/tough-cookie.js b/packages/insomnia-app/flow-typed/tough-cookie.js index cb6c670339..698e475264 100644 --- a/packages/insomnia-app/flow-typed/tough-cookie.js +++ b/packages/insomnia-app/flow-typed/tough-cookie.js @@ -1,3 +1,3 @@ declare module 'tough-cookie' { - declare module.exports: * + declare module.exports: *; } diff --git a/packages/insomnia-app/flow-typed/uuid.js b/packages/insomnia-app/flow-typed/uuid.js index 63d6d00ec9..db38e98c3d 100644 --- a/packages/insomnia-app/flow-typed/uuid.js +++ b/packages/insomnia-app/flow-typed/uuid.js @@ -2,5 +2,5 @@ declare module 'uuid' { declare module.exports: { v4: () => string, v1: () => string - } + }; } diff --git a/packages/insomnia-app/flow-typed/xmldom.js b/packages/insomnia-app/flow-typed/xmldom.js index 2a8b435ea7..d452f70322 100644 --- a/packages/insomnia-app/flow-typed/xmldom.js +++ b/packages/insomnia-app/flow-typed/xmldom.js @@ -1,5 +1,5 @@ declare module 'xmldom' { declare module.exports: { DOMParser: Function - } + }; } diff --git a/packages/insomnia-app/scripts/build.js b/packages/insomnia-app/scripts/build.js index 441bfcd7b7..5415e76392 100644 --- a/packages/insomnia-app/scripts/build.js +++ b/packages/insomnia-app/scripts/build.js @@ -15,7 +15,7 @@ if (require.main === module) { }); } -module.exports.start = async function () { +module.exports.start = async function() { // Remove folders first console.log('[build] Removing existing directories'); await emptyDir('../build'); @@ -41,7 +41,7 @@ module.exports.start = async function () { console.log('[build] Complete!'); }; -async function buildWebpack (config) { +async function buildWebpack(config) { return new Promise((resolve, reject) => { webpack(config, (err, stats) => { if (err || stats.hasErrors()) { @@ -53,7 +53,7 @@ async function buildWebpack (config) { }); } -async function emptyDir (relPath) { +async function emptyDir(relPath) { return new Promise((resolve, reject) => { const dir = path.resolve(__dirname, relPath); rimraf(dir, err => { @@ -67,7 +67,7 @@ async function emptyDir (relPath) { }); } -async function copyFiles (relSource, relDest) { +async function copyFiles(relSource, relDest) { return new Promise((resolve, reject) => { const source = path.resolve(__dirname, relSource); const dest = path.resolve(__dirname, relDest); @@ -81,26 +81,29 @@ async function copyFiles (relSource, relDest) { }); } -async function install (relDir) { +async function install(relDir) { return new Promise((resolve, reject) => { const prefix = path.resolve(__dirname, relDir); - npm.load({prefix, production: true, optional: false, 'package-lock': false}, err => { - if (err) { - return reject(err); - } - - npm.commands.install([prefix], err => { + npm.load( + { prefix, production: true, optional: false, 'package-lock': false }, + err => { if (err) { - reject(err); - } else { - resolve(); + return reject(err); } - }); - }); + + npm.commands.install([prefix], err => { + if (err) { + reject(err); + } else { + resolve(); + } + }); + } + ); }); } -function generatePackageJson (relBasePkg, relOutPkg) { +function generatePackageJson(relBasePkg, relOutPkg) { // Read package.json's const basePath = path.resolve(__dirname, relBasePkg); const outPath = path.resolve(__dirname, relOutPkg); diff --git a/packages/insomnia-app/scripts/package.js b/packages/insomnia-app/scripts/package.js index bcff7db49a..01efd511b8 100644 --- a/packages/insomnia-app/scripts/package.js +++ b/packages/insomnia-app/scripts/package.js @@ -22,7 +22,7 @@ if (require.main === module) { }); } -module.exports.start = async function () { +module.exports.start = async function() { console.log('[package] Removing existing directories'); await emptyDir('../dist/*'); @@ -32,7 +32,7 @@ module.exports.start = async function () { console.log('[package] Complete!'); }; -async function pkg (relConfigPath) { +async function pkg(relConfigPath) { try { const configPath = path.resolve(__dirname, relConfigPath); const config = JSON.parse(fs.readFileSync(configPath, 'utf8')); @@ -50,7 +50,7 @@ async function pkg (relConfigPath) { } } -async function emptyDir (relPath) { +async function emptyDir(relPath) { return new Promise((resolve, reject) => { const dir = path.resolve(__dirname, relPath); rimraf(dir, err => { diff --git a/packages/insomnia-app/webpack/webpack.config.base.babel.js b/packages/insomnia-app/webpack/webpack.config.base.babel.js index 424ba0034c..dd071a1157 100644 --- a/packages/insomnia-app/webpack/webpack.config.base.babel.js +++ b/packages/insomnia-app/webpack/webpack.config.base.babel.js @@ -5,10 +5,7 @@ const pkg = require('../package.json'); module.exports = { devtool: 'source-map', context: path.join(__dirname, '../app'), - entry: [ - './renderer.js', - './renderer.html' - ], + entry: ['./renderer.js', './renderer.html'], output: { path: path.join(__dirname, '../build'), filename: 'bundle.js', @@ -31,8 +28,8 @@ module.exports = { test: /\.(less|css)$/, use: [ 'style-loader', - {loader: 'css-loader', options: {importLoaders: 1}}, - {loader: 'less-loader', options: {noIeCompat: true}} + { loader: 'css-loader', options: { importLoaders: 1 } }, + { loader: 'less-loader', options: { noIeCompat: true } } ] }, { @@ -50,20 +47,28 @@ module.exports = { }, resolve: { extensions: ['.js', '.json'], - mainFields: ['webpack', 'browser', 'web', 'browserify', ['jam', 'main'], 'main'] + mainFields: [ + 'webpack', + 'browser', + 'web', + 'browserify', + ['jam', 'main'], + 'main' + ] }, node: { __dirname: false // Use Node __dirname }, externals: [ // Omit all dependencies in app/package.json (we want them loaded at runtime via NodeJS) - ...Object.keys(pkg.dependencies).filter(name => !pkg.packedDependencies.includes(name)), + ...Object.keys(pkg.dependencies).filter( + name => !pkg.packedDependencies.includes(name) + ), // To get jsonlint working... - 'file', 'system' - ], - plugins: [ - new webpack.optimize.LimitChunkCountPlugin({maxChunks: 1}) + 'file', + 'system' ], + plugins: [new webpack.optimize.LimitChunkCountPlugin({ maxChunks: 1 })], target: 'electron-renderer' }; diff --git a/packages/insomnia-app/webpack/webpack.config.development.babel.js b/packages/insomnia-app/webpack/webpack.config.development.babel.js index 8079e0453f..47095b08f0 100644 --- a/packages/insomnia-app/webpack/webpack.config.development.babel.js +++ b/packages/insomnia-app/webpack/webpack.config.development.babel.js @@ -26,7 +26,7 @@ module.exports = { }, plugins: [ ...baseConfig.plugins, - new webpack.LoaderOptionsPlugin({debug: true}), // Legacy global loader option + new webpack.LoaderOptionsPlugin({ debug: true }), // Legacy global loader option new webpack.HotModuleReplacementPlugin(), new webpack.NoEmitOnErrorsPlugin(), new webpack.NamedModulesPlugin(), diff --git a/packages/insomnia-app/webpack/webpack.config.electron.babel.js b/packages/insomnia-app/webpack/webpack.config.electron.babel.js index 05eaecf0ea..70e5b0e901 100644 --- a/packages/insomnia-app/webpack/webpack.config.electron.babel.js +++ b/packages/insomnia-app/webpack/webpack.config.electron.babel.js @@ -17,7 +17,9 @@ if (process.env.NODE_ENV === 'development') { devtool = 'eval-source-map'; plugins = [ new webpack.DefinePlugin({ - 'process.env.APP_RENDER_URL': JSON.stringify(`http://localhost:${PORT}/renderer.html`), + 'process.env.APP_RENDER_URL': JSON.stringify( + `http://localhost:${PORT}/renderer.html` + ), 'process.env.NODE_ENV': JSON.stringify('development'), 'process.env.INSOMNIA_ENV': JSON.stringify('development') }) @@ -31,9 +33,7 @@ if (process.env.NODE_ENV === 'development') { module.exports = { ...productionConfig, devtool: devtool, - entry: [ - './main.development.js' - ], + entry: ['./main.development.js'], output: output, node: { __dirname: false // Use node.js __dirname diff --git a/packages/insomnia-cookies/__tests__/index.test.js b/packages/insomnia-cookies/__tests__/index.test.js index b67ffdaee9..9dd3bb4877 100644 --- a/packages/insomnia-cookies/__tests__/index.test.js +++ b/packages/insomnia-cookies/__tests__/index.test.js @@ -1,13 +1,15 @@ -const {CookieJar} = require('tough-cookie'); -const {cookieToString, jarFromCookies, cookiesFromJar} = require('..'); +const { CookieJar } = require('tough-cookie'); +const { cookieToString, jarFromCookies, cookiesFromJar } = require('..'); describe('jarFromCookies()', () => { it('returns valid cookies', done => { - const jar = jarFromCookies([{ - key: 'foo', - value: 'bar', - domain: 'google.com' - }]); + const jar = jarFromCookies([ + { + key: 'foo', + value: 'bar', + domain: 'google.com' + } + ]); jar.store.getAllCookies((err, cookies) => { expect(err).toBeNull(); @@ -29,29 +31,34 @@ describe('jarFromCookies()', () => { describe('cookiesFromJar()', () => { it('returns valid jar', async () => { const d = new Date(); - const initialCookies = [{ - key: 'bar', - value: 'baz', - domain: 'insomnia.rest', - expires: d - }, { - // This one will fail to parse, and be skipped - bad: 'cookie' - }]; + const initialCookies = [ + { + key: 'bar', + value: 'baz', + domain: 'insomnia.rest', + expires: d + }, + { + // This one will fail to parse, and be skipped + bad: 'cookie' + } + ]; - const jar = CookieJar.fromJSON({cookies: initialCookies}); + const jar = CookieJar.fromJSON({ cookies: initialCookies }); const cookies = await cookiesFromJar(jar); expect(cookies[0].domain).toBe('insomnia.rest'); expect(cookies[0].key).toBe('bar'); expect(cookies[0].value).toBe('baz'); - expect(cookies[0].creation).toMatch(/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{3}Z/); + expect(cookies[0].creation).toMatch( + /\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{3}Z/ + ); expect(cookies[0].expires).toEqual(d.toISOString()); }); it('handles bad jar', async () => { - const jar = CookieJar.fromJSON({cookies: []}); + const jar = CookieJar.fromJSON({ cookies: [] }); // MemoryStore never actually throws errors, so lets mock the // function to force it to this time. @@ -62,4 +69,3 @@ describe('cookiesFromJar()', () => { expect(cookies.length).toBe(0); }); }); - diff --git a/packages/insomnia-cookies/index.js b/packages/insomnia-cookies/index.js index 59ca172313..77426a1b96 100644 --- a/packages/insomnia-cookies/index.js +++ b/packages/insomnia-cookies/index.js @@ -1,11 +1,11 @@ -const {CookieJar, Cookie} = require('tough-cookie'); +const { CookieJar, Cookie } = require('tough-cookie'); /** * Get a list of cookie objects from a request.jar() * * @param jar */ -module.exports.cookiesFromJar = function (jar) { +module.exports.cookiesFromJar = function(jar) { return new Promise(resolve => { jar.store.getAllCookies((err, cookies) => { if (err) { @@ -24,13 +24,13 @@ module.exports.cookiesFromJar = function (jar) { * * @param cookies */ -module.exports.jarFromCookies = function (cookies) { +module.exports.jarFromCookies = function(cookies) { let jar; try { // For some reason, fromJSON modifies `cookies`. Create a copy first // just to be sure - const copy = JSON.stringify({cookies}); + const copy = JSON.stringify({ cookies }); jar = CookieJar.fromJSON(copy); } catch (e) { console.log('[cookies] Failed to initialize cookie jar', e); @@ -43,7 +43,7 @@ module.exports.jarFromCookies = function (cookies) { return jar; }; -module.exports.cookieToString = function (cookie) { +module.exports.cookieToString = function(cookie) { // Cookie can either be a plain JS object or Cookie instance if (!(cookie instanceof Cookie)) { cookie = Cookie.fromJSON(cookie); @@ -59,4 +59,3 @@ module.exports.cookieToString = function (cookie) { return str; }; - diff --git a/packages/insomnia-httpsnippet/src/helpers/code-builder.js b/packages/insomnia-httpsnippet/src/helpers/code-builder.js index 335ea34c04..f0063c340a 100755 --- a/packages/insomnia-httpsnippet/src/helpers/code-builder.js +++ b/packages/insomnia-httpsnippet/src/helpers/code-builder.js @@ -1,6 +1,6 @@ -'use strict' +'use strict'; -var util = require('util') +var util = require('util'); /** * Helper object to format and aggragate lines of code. @@ -11,11 +11,11 @@ var util = require('util') * @param {string} indentation Desired indentation character for aggregated lines of code * @param {string} join Desired character to join each line of code */ -var CodeBuilder = function (indentation, join) { - this.code = [] - this.indentation = indentation - this.lineJoin = join || '\n' -} +var CodeBuilder = function(indentation, join) { + this.code = []; + this.indentation = indentation; + this.lineJoin = join || '\n'; +}; /** * Add given indentation level to given string and format the string (variadic) @@ -36,27 +36,27 @@ var CodeBuilder = function (indentation, join) { * builder.buildLine(2, 'console.log("%s %s")', 'hello', 'world') * // returns: 'console.log("\t\thello world")' */ -CodeBuilder.prototype.buildLine = function (indentationLevel, line) { - var lineIndentation = '' - var slice = 2 +CodeBuilder.prototype.buildLine = function(indentationLevel, line) { + var lineIndentation = ''; + var slice = 2; if (Object.prototype.toString.call(indentationLevel) === '[object String]') { - slice = 1 - line = indentationLevel - indentationLevel = 0 + slice = 1; + line = indentationLevel; + indentationLevel = 0; } else if (indentationLevel === null) { - return null + return null; } while (indentationLevel) { - lineIndentation += this.indentation - indentationLevel-- + lineIndentation += this.indentation; + indentationLevel--; } - var format = Array.prototype.slice.call(arguments, slice, arguments.length) - format.unshift(lineIndentation + line) + var format = Array.prototype.slice.call(arguments, slice, arguments.length); + format.unshift(lineIndentation + line); - return util.format.apply(this, format) -} + return util.format.apply(this, format); +}; /** * Invoke buildLine() and add the line at the top of current lines @@ -64,11 +64,11 @@ CodeBuilder.prototype.buildLine = function (indentationLevel, line) { * @param {string} line Line of code * @return {this} */ -CodeBuilder.prototype.unshift = function () { - this.code.unshift(this.buildLine.apply(this, arguments)) +CodeBuilder.prototype.unshift = function() { + this.code.unshift(this.buildLine.apply(this, arguments)); - return this -} + return this; +}; /** * Invoke buildLine() and add the line at the bottom of current lines @@ -76,28 +76,28 @@ CodeBuilder.prototype.unshift = function () { * @param {string} line Line of code * @return {this} */ -CodeBuilder.prototype.push = function () { - this.code.push(this.buildLine.apply(this, arguments)) +CodeBuilder.prototype.push = function() { + this.code.push(this.buildLine.apply(this, arguments)); - return this -} + return this; +}; /** * Add an empty line at the end of current lines * @return {this} */ -CodeBuilder.prototype.blank = function () { - this.code.push(null) +CodeBuilder.prototype.blank = function() { + this.code.push(null); - return this -} + return this; +}; /** * Concatenate all current lines using the given lineJoin * @return {string} */ -CodeBuilder.prototype.join = function () { - return this.code.join(this.lineJoin) -} +CodeBuilder.prototype.join = function() { + return this.code.join(this.lineJoin); +}; -module.exports = CodeBuilder +module.exports = CodeBuilder; diff --git a/packages/insomnia-httpsnippet/src/helpers/reducer.js b/packages/insomnia-httpsnippet/src/helpers/reducer.js index 2b961059cf..20d14d7191 100755 --- a/packages/insomnia-httpsnippet/src/helpers/reducer.js +++ b/packages/insomnia-httpsnippet/src/helpers/reducer.js @@ -1,23 +1,20 @@ -'use strict' +'use strict'; -module.exports = function (obj, pair) { +module.exports = function(obj, pair) { if (obj[pair.name] === undefined) { - obj[pair.name] = pair.value - return obj + obj[pair.name] = pair.value; + return obj; } if (Array.isArray(obj[pair.name])) { - obj[pair.name].push(pair.value) - return obj + obj[pair.name].push(pair.value); + return obj; } // convert to array - var arr = [ - obj[pair.name], - pair.value - ] + var arr = [obj[pair.name], pair.value]; - obj[pair.name] = arr + obj[pair.name] = arr; - return obj -} + return obj; +}; diff --git a/packages/insomnia-httpsnippet/src/helpers/shell.js b/packages/insomnia-httpsnippet/src/helpers/shell.js index 12b155b1a4..6cc18f22e2 100755 --- a/packages/insomnia-httpsnippet/src/helpers/shell.js +++ b/packages/insomnia-httpsnippet/src/helpers/shell.js @@ -1,6 +1,6 @@ -'use strict' +'use strict'; -var util = require('util') +var util = require('util'); module.exports = { /** @@ -8,18 +8,18 @@ module.exports = { * to deal with nested single quote characters. * http://wiki.bash-hackers.org/syntax/quoting#strong_quoting */ - quote: function (value) { - var safe = /^[a-z0-9-_/.@%^=:]+$/i + quote: function(value) { + var safe = /^[a-z0-9-_/.@%^=:]+$/i; // Unless `value` is a simple shell-safe string, quote it. if (!safe.test(value)) { - return util.format('\'%s\'', value.replace(/'/g, "\'\\'\'")) + return util.format("'%s'", value.replace(/'/g, "'\\''")); } - return value + return value; }, - escape: function (value) { - return value.replace(/\r/g, '\\r').replace(/\n/g, '\\n') + escape: function(value) { + return value.replace(/\r/g, '\\r').replace(/\n/g, '\\n'); } -} +}; diff --git a/packages/insomnia-httpsnippet/src/index.js b/packages/insomnia-httpsnippet/src/index.js index fd75874a44..51d6bb0731 100755 --- a/packages/insomnia-httpsnippet/src/index.js +++ b/packages/insomnia-httpsnippet/src/index.js @@ -1,96 +1,101 @@ -'use strict' +'use strict'; -var debug = require('debug')('httpsnippet') -var es = require('event-stream') -var MultiPartForm = require('form-data') -var qs = require('querystring') -var reducer = require('./helpers/reducer') -var targets = require('./targets') -var url = require('url') -var util = require('util') -var validate = require('har-validator/lib/async') +var debug = require('debug')('httpsnippet'); +var es = require('event-stream'); +var MultiPartForm = require('form-data'); +var qs = require('querystring'); +var reducer = require('./helpers/reducer'); +var targets = require('./targets'); +var url = require('url'); +var util = require('util'); +var validate = require('har-validator/lib/async'); // constructor -var HTTPSnippet = function (data) { - var entries - var self = this - var input = util._extend({}, data) +var HTTPSnippet = function(data) { + var entries; + var self = this; + var input = util._extend({}, data); // prep the main container - self.requests = [] + self.requests = []; // is it har? if (input.log && input.log.entries) { - entries = input.log.entries + entries = input.log.entries; } else { - entries = [{ - request: input - }] + entries = [ + { + request: input + } + ]; } - entries.forEach(function (entry) { + entries.forEach(function(entry) { // add optional properties to make validation successful - entry.request.httpVersion = entry.request.httpVersion || 'HTTP/1.1' - entry.request.queryString = entry.request.queryString || [] - entry.request.headers = entry.request.headers || [] - entry.request.cookies = entry.request.cookies || [] - entry.request.postData = entry.request.postData || {} - entry.request.postData.mimeType = entry.request.postData.mimeType || 'application/octet-stream' + entry.request.httpVersion = entry.request.httpVersion || 'HTTP/1.1'; + entry.request.queryString = entry.request.queryString || []; + entry.request.headers = entry.request.headers || []; + entry.request.cookies = entry.request.cookies || []; + entry.request.postData = entry.request.postData || {}; + entry.request.postData.mimeType = + entry.request.postData.mimeType || 'application/octet-stream'; - entry.request.bodySize = 0 - entry.request.headersSize = 0 - entry.request.postData.size = 0 + entry.request.bodySize = 0; + entry.request.headersSize = 0; + entry.request.postData.size = 0; - validate.request(entry.request, function (err, valid) { + validate.request(entry.request, function(err, valid) { if (!valid) { - throw err + throw err; } - self.requests.push(self.prepare(entry.request)) - }) - }) -} + self.requests.push(self.prepare(entry.request)); + }); + }); +}; -HTTPSnippet.prototype.prepare = function (request) { +HTTPSnippet.prototype.prepare = function(request) { // construct utility properties - request.queryObj = {} - request.headersObj = {} - request.cookiesObj = {} - request.allHeaders = {} - request.postData.jsonObj = false - request.postData.paramsObj = false + request.queryObj = {}; + request.headersObj = {}; + request.cookiesObj = {}; + request.allHeaders = {}; + request.postData.jsonObj = false; + request.postData.paramsObj = false; // construct query objects if (request.queryString && request.queryString.length) { - debug('queryString found, constructing queryString pair map') + debug('queryString found, constructing queryString pair map'); - request.queryObj = request.queryString.reduce(reducer, {}) + request.queryObj = request.queryString.reduce(reducer, {}); } // construct headers objects if (request.headers && request.headers.length) { // loweCase header keys - request.headersObj = request.headers.reduceRight(function (headers, header) { - headers[header.name.toLowerCase()] = header.value - return headers - }, {}) + request.headersObj = request.headers.reduceRight(function(headers, header) { + headers[header.name.toLowerCase()] = header.value; + return headers; + }, {}); } // construct headers objects if (request.cookies && request.cookies.length) { - request.cookiesObj = request.cookies.reduceRight(function (cookies, cookie) { - cookies[cookie.name] = cookie.value - return cookies - }, {}) + request.cookiesObj = request.cookies.reduceRight(function(cookies, cookie) { + cookies[cookie.name] = cookie.value; + return cookies; + }, {}); } // construct Cookie header - var cookies = request.cookies.map(function (cookie) { - return encodeURIComponent(cookie.name) + '=' + encodeURIComponent(cookie.value) - }) + var cookies = request.cookies.map(function(cookie) { + return ( + encodeURIComponent(cookie.name) + '=' + encodeURIComponent(cookie.value) + ); + }); if (cookies.length) { - request.allHeaders.cookie = cookies.join('; ') + request.allHeaders.cookie = cookies.join('; '); } switch (request.postData.mimeType) { @@ -99,152 +104,161 @@ HTTPSnippet.prototype.prepare = function (request) { case 'multipart/form-data': case 'multipart/alternative': // reset values - request.postData.text = '' - request.postData.mimeType = 'multipart/form-data' + request.postData.text = ''; + request.postData.mimeType = 'multipart/form-data'; if (request.postData.params) { - var form = new MultiPartForm() + var form = new MultiPartForm(); // easter egg - form._boundary = '---011000010111000001101001' + form._boundary = '---011000010111000001101001'; - request.postData.params.forEach(function (param) { + request.postData.params.forEach(function(param) { form.append(param.name, param.value || '', { filename: param.fileName || null, contentType: param.contentType || null + }); + }); + + form.pipe( + es.map(function(data, cb) { + request.postData.text += data; }) - }) + ); - form.pipe(es.map(function (data, cb) { - request.postData.text += data - })) - - request.postData.boundary = form.getBoundary() - request.headersObj['content-type'] = 'multipart/form-data; boundary=' + form.getBoundary() + request.postData.boundary = form.getBoundary(); + request.headersObj['content-type'] = + 'multipart/form-data; boundary=' + form.getBoundary(); } - break + break; case 'application/x-www-form-urlencoded': if (!request.postData.params) { - request.postData.text = '' + request.postData.text = ''; } else { - request.postData.paramsObj = request.postData.params.reduce(reducer, {}) + request.postData.paramsObj = request.postData.params.reduce( + reducer, + {} + ); // always overwrite - request.postData.text = qs.stringify(request.postData.paramsObj) + request.postData.text = qs.stringify(request.postData.paramsObj); } - break + break; case 'text/json': case 'text/x-json': case 'application/json': case 'application/x-json': - request.postData.mimeType = 'application/json' + request.postData.mimeType = 'application/json'; if (request.postData.text) { try { - request.postData.jsonObj = JSON.parse(request.postData.text) + request.postData.jsonObj = JSON.parse(request.postData.text); } catch (e) { - debug(e) + debug(e); // force back to text/plain // if headers have proper content-type value, then this should also work - request.postData.mimeType = 'text/plain' + request.postData.mimeType = 'text/plain'; } } - break + break; } // create allHeaders object - request.allHeaders = util._extend(request.allHeaders, request.headersObj) + request.allHeaders = util._extend(request.allHeaders, request.headersObj); // deconstruct the uri - request.uriObj = url.parse(request.url, true, true) + request.uriObj = url.parse(request.url, true, true); // merge all possible queryString values - request.queryObj = util._extend(request.queryObj, request.uriObj.query) + request.queryObj = util._extend(request.queryObj, request.uriObj.query); // reset uriObj values for a clean url - request.uriObj.query = null - request.uriObj.search = null - request.uriObj.path = request.uriObj.pathname + request.uriObj.query = null; + request.uriObj.search = null; + request.uriObj.path = request.uriObj.pathname; // keep the base url clean of queryString - request.url = url.format(request.uriObj) + request.url = url.format(request.uriObj); // update the uri object - request.uriObj.query = request.queryObj + request.uriObj.query = request.queryObj; request.uriObj.search = qs.stringify(request.queryObj, '&', '=', { encodeURIComponent: request.settingEncodeUrl ? null : str => str - }) + }); if (request.uriObj.search) { - request.uriObj.path = request.uriObj.pathname + '?' + request.uriObj.search + request.uriObj.path = request.uriObj.pathname + '?' + request.uriObj.search; } // construct a full url - request.fullUrl = url.format(request.uriObj) + request.fullUrl = url.format(request.uriObj); - return request -} + return request; +}; -HTTPSnippet.prototype.convert = function (target, client, opts) { +HTTPSnippet.prototype.convert = function(target, client, opts) { if (!opts && client) { - opts = client + opts = client; } - var func = this._matchTarget(target, client) + var func = this._matchTarget(target, client); if (func) { - var results = this.requests.map(function (request) { - return func(request, opts) - }) + var results = this.requests.map(function(request) { + return func(request, opts); + }); - return results.length === 1 ? results[0] : results + return results.length === 1 ? results[0] : results; } - return false -} + return false; +}; -HTTPSnippet.prototype._matchTarget = function (target, client) { +HTTPSnippet.prototype._matchTarget = function(target, client) { // does it exist? if (!targets.hasOwnProperty(target)) { - return false + return false; } // shorthand - if (typeof client === 'string' && typeof targets[target][client] === 'function') { - return targets[target][client] + if ( + typeof client === 'string' && + typeof targets[target][client] === 'function' + ) { + return targets[target][client]; } // default target - return targets[target][targets[target].info.default] -} + return targets[target][targets[target].info.default]; +}; // exports -module.exports = HTTPSnippet +module.exports = HTTPSnippet; -module.exports.availableTargets = function () { - return Object.keys(targets).map(function (key) { - var target = util._extend({}, targets[key].info) +module.exports.availableTargets = function() { + return Object.keys(targets).map(function(key) { + var target = util._extend({}, targets[key].info); var clients = Object.keys(targets[key]) - .filter(function (prop) { - return !~['info', 'index'].indexOf(prop) + .filter(function(prop) { + return !~['info', 'index'].indexOf(prop); }) - .map(function (client) { - return targets[key][client].info - }) + .map(function(client) { + return targets[key][client].info; + }); if (clients.length) { - target.clients = clients + target.clients = clients; } - return target - }) -} + return target; + }); +}; -module.exports.extname = function (target) { - return targets[target] ? targets[target].info.extname : '' -} +module.exports.extname = function(target) { + return targets[target] ? targets[target].info.extname : ''; +}; diff --git a/packages/insomnia-httpsnippet/src/targets/c/index.js b/packages/insomnia-httpsnippet/src/targets/c/index.js index 0a62726518..8d69e31fb6 100755 --- a/packages/insomnia-httpsnippet/src/targets/c/index.js +++ b/packages/insomnia-httpsnippet/src/targets/c/index.js @@ -1,4 +1,4 @@ -'use strict' +'use strict'; module.exports = { info: { @@ -9,4 +9,4 @@ module.exports = { }, libcurl: require('./libcurl') -} +}; diff --git a/packages/insomnia-httpsnippet/src/targets/c/libcurl.js b/packages/insomnia-httpsnippet/src/targets/c/libcurl.js index aad328e28f..f29fd8d7e4 100755 --- a/packages/insomnia-httpsnippet/src/targets/c/libcurl.js +++ b/packages/insomnia-httpsnippet/src/targets/c/libcurl.js @@ -1,50 +1,64 @@ -'use strict' +'use strict'; -var CodeBuilder = require('../../helpers/code-builder') +var CodeBuilder = require('../../helpers/code-builder'); -module.exports = function (source, options) { - var code = new CodeBuilder() +module.exports = function(source, options) { + var code = new CodeBuilder(); - code.push('CURL *hnd = curl_easy_init();') - .blank() - .push('curl_easy_setopt(hnd, CURLOPT_CUSTOMREQUEST, "%s");', source.method.toUpperCase()) - .push('curl_easy_setopt(hnd, CURLOPT_URL, "%s");', source.fullUrl) + code + .push('CURL *hnd = curl_easy_init();') + .blank() + .push( + 'curl_easy_setopt(hnd, CURLOPT_CUSTOMREQUEST, "%s");', + source.method.toUpperCase() + ) + .push('curl_easy_setopt(hnd, CURLOPT_URL, "%s");', source.fullUrl); // Add headers, including the cookies - var headers = Object.keys(source.headersObj) + var headers = Object.keys(source.headersObj); // construct headers if (headers.length) { - code.blank() - .push('struct curl_slist *headers = NULL;') + code.blank().push('struct curl_slist *headers = NULL;'); - headers.forEach(function (key) { - code.push('headers = curl_slist_append(headers, "%s: %s");', key, source.headersObj[key]) - }) + headers.forEach(function(key) { + code.push( + 'headers = curl_slist_append(headers, "%s: %s");', + key, + source.headersObj[key] + ); + }); - code.push('curl_easy_setopt(hnd, CURLOPT_HTTPHEADER, headers);') + code.push('curl_easy_setopt(hnd, CURLOPT_HTTPHEADER, headers);'); } // construct cookies if (source.allHeaders.cookie) { - code.blank() - .push('curl_easy_setopt(hnd, CURLOPT_COOKIE, "%s");', source.allHeaders.cookie) + code + .blank() + .push( + 'curl_easy_setopt(hnd, CURLOPT_COOKIE, "%s");', + source.allHeaders.cookie + ); } if (source.postData.text) { - code.blank() - .push('curl_easy_setopt(hnd, CURLOPT_POSTFIELDS, %s);', JSON.stringify(source.postData.text)) + code + .blank() + .push( + 'curl_easy_setopt(hnd, CURLOPT_POSTFIELDS, %s);', + JSON.stringify(source.postData.text) + ); } - code.blank() - .push('CURLcode ret = curl_easy_perform(hnd);') + code.blank().push('CURLcode ret = curl_easy_perform(hnd);'); - return code.join() -} + return code.join(); +}; module.exports.info = { key: 'libcurl', title: 'Libcurl', link: 'http://curl.haxx.se/libcurl/', description: 'Simple REST and HTTP API Client for C' -} +}; diff --git a/packages/insomnia-httpsnippet/src/targets/csharp/index.js b/packages/insomnia-httpsnippet/src/targets/csharp/index.js index 226dd69f42..849eb9f16d 100755 --- a/packages/insomnia-httpsnippet/src/targets/csharp/index.js +++ b/packages/insomnia-httpsnippet/src/targets/csharp/index.js @@ -1,4 +1,4 @@ -'use strict' +'use strict'; module.exports = { info: { @@ -9,4 +9,4 @@ module.exports = { }, restsharp: require('./restsharp') -} +}; diff --git a/packages/insomnia-httpsnippet/src/targets/csharp/restsharp.js b/packages/insomnia-httpsnippet/src/targets/csharp/restsharp.js index 0b8fc27355..7e7ed490bd 100755 --- a/packages/insomnia-httpsnippet/src/targets/csharp/restsharp.js +++ b/packages/insomnia-httpsnippet/src/targets/csharp/restsharp.js @@ -1,46 +1,53 @@ -'use strict' +'use strict'; -var CodeBuilder = require('../../helpers/code-builder') +var CodeBuilder = require('../../helpers/code-builder'); -module.exports = function (source, options) { - var code = new CodeBuilder() - var methods = [ 'GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS' ] +module.exports = function(source, options) { + var code = new CodeBuilder(); + var methods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS']; if (methods.indexOf(source.method.toUpperCase()) === -1) { - return 'Method not supported' + return 'Method not supported'; } else { - code.push('var client = new RestClient("%s");', source.fullUrl) - code.push('var request = new RestRequest(Method.%s);', source.method.toUpperCase()) + code.push('var client = new RestClient("%s");', source.fullUrl); + code.push( + 'var request = new RestRequest(Method.%s);', + source.method.toUpperCase() + ); } // Add headers, including the cookies - var headers = Object.keys(source.headersObj) + var headers = Object.keys(source.headersObj); // construct headers if (headers.length) { - headers.forEach(function (key) { - code.push('request.AddHeader("%s", "%s");', key, source.headersObj[key]) - }) + headers.forEach(function(key) { + code.push('request.AddHeader("%s", "%s");', key, source.headersObj[key]); + }); } // construct cookies if (source.cookies.length) { - source.cookies.forEach(function (cookie) { - code.push('request.AddCookie("%s", "%s");', cookie.name, cookie.value) - }) + source.cookies.forEach(function(cookie) { + code.push('request.AddCookie("%s", "%s");', cookie.name, cookie.value); + }); } if (source.postData.text) { - code.push('request.AddParameter("%s", %s, ParameterType.RequestBody);', source.allHeaders['content-type'], JSON.stringify(source.postData.text)) + code.push( + 'request.AddParameter("%s", %s, ParameterType.RequestBody);', + source.allHeaders['content-type'], + JSON.stringify(source.postData.text) + ); } - code.push('IRestResponse response = client.Execute(request);') - return code.join() -} + code.push('IRestResponse response = client.Execute(request);'); + return code.join(); +}; module.exports.info = { key: 'restsharp', title: 'RestSharp', link: 'http://restsharp.org/', description: 'Simple REST and HTTP API Client for .NET' -} +}; diff --git a/packages/insomnia-httpsnippet/src/targets/go/index.js b/packages/insomnia-httpsnippet/src/targets/go/index.js index 64630875a4..62ac777af6 100755 --- a/packages/insomnia-httpsnippet/src/targets/go/index.js +++ b/packages/insomnia-httpsnippet/src/targets/go/index.js @@ -1,4 +1,4 @@ -'use strict' +'use strict'; module.exports = { info: { @@ -9,4 +9,4 @@ module.exports = { }, native: require('./native') -} +}; diff --git a/packages/insomnia-httpsnippet/src/targets/go/native.js b/packages/insomnia-httpsnippet/src/targets/go/native.js index 7ba90e0f00..d9bc51e3b3 100755 --- a/packages/insomnia-httpsnippet/src/targets/go/native.js +++ b/packages/insomnia-httpsnippet/src/targets/go/native.js @@ -8,131 +8,161 @@ * for any questions or issues regarding the generated code snippet, please open an issue mentioning the author. */ -'use strict' +'use strict'; -var util = require('util') -var CodeBuilder = require('../../helpers/code-builder') +var util = require('util'); +var CodeBuilder = require('../../helpers/code-builder'); -module.exports = function (source, options) { +module.exports = function(source, options) { // Let's Go! - var code = new CodeBuilder('\t') + var code = new CodeBuilder('\t'); // Define Options - var opts = util._extend({ - showBoilerplate: true, - checkErrors: false, - printBody: true, - timeout: -1 - }, options) + var opts = util._extend( + { + showBoilerplate: true, + checkErrors: false, + printBody: true, + timeout: -1 + }, + options + ); - var errorPlaceholder = opts.checkErrors ? 'err' : '_' + var errorPlaceholder = opts.checkErrors ? 'err' : '_'; - var indent = opts.showBoilerplate ? 1 : 0 + var indent = opts.showBoilerplate ? 1 : 0; - var errorCheck = function () { + var errorCheck = function() { if (opts.checkErrors) { - code.push(indent, 'if err != nil {') + code + .push(indent, 'if err != nil {') .push(indent + 1, 'panic(err)') - .push(indent, '}') + .push(indent, '}'); } - } + }; // Create boilerplate if (opts.showBoilerplate) { - code.push('package main') + code + .push('package main') .blank() .push('import (') - .push(indent, '"fmt"') + .push(indent, '"fmt"'); if (opts.timeout > 0) { - code.push(indent, '"time"') + code.push(indent, '"time"'); } if (source.postData.text) { - code.push(indent, '"strings"') + code.push(indent, '"strings"'); } - code.push(indent, '"net/http"') + code.push(indent, '"net/http"'); if (opts.printBody) { - code.push(indent, '"io/ioutil"') + code.push(indent, '"io/ioutil"'); } - code.push(')') + code + .push(')') .blank() .push('func main() {') - .blank() + .blank(); } // Create client - var client + var client; if (opts.timeout > 0) { - client = 'client' - code.push(indent, 'client := http.Client{') - .push(indent + 1, 'Timeout: time.Duration(%s * time.Second),', opts.timeout) + client = 'client'; + code + .push(indent, 'client := http.Client{') + .push( + indent + 1, + 'Timeout: time.Duration(%s * time.Second),', + opts.timeout + ) .push(indent, '}') - .blank() + .blank(); } else { - client = 'http.DefaultClient' + client = 'http.DefaultClient'; } - code.push(indent, 'url := "%s"', source.fullUrl) - .blank() + code.push(indent, 'url := "%s"', source.fullUrl).blank(); // If we have body content or not create the var and reader or nil if (source.postData.text) { - code.push(indent, 'payload := strings.NewReader(%s)', JSON.stringify(source.postData.text)) - .blank() - .push(indent, 'req, %s := http.NewRequest("%s", url, payload)', errorPlaceholder, source.method) + code + .push( + indent, + 'payload := strings.NewReader(%s)', + JSON.stringify(source.postData.text) + ) .blank() + .push( + indent, + 'req, %s := http.NewRequest("%s", url, payload)', + errorPlaceholder, + source.method + ) + .blank(); } else { - code.push(indent, 'req, %s := http.NewRequest("%s", url, nil)', errorPlaceholder, source.method) - .blank() + code + .push( + indent, + 'req, %s := http.NewRequest("%s", url, nil)', + errorPlaceholder, + source.method + ) + .blank(); } - errorCheck() + errorCheck(); // Add headers if (Object.keys(source.allHeaders).length) { - Object.keys(source.allHeaders).forEach(function (key) { - code.push(indent, 'req.Header.Add("%s", "%s")', key, source.allHeaders[key]) - }) + Object.keys(source.allHeaders).forEach(function(key) { + code.push( + indent, + 'req.Header.Add("%s", "%s")', + key, + source.allHeaders[key] + ); + }); - code.blank() + code.blank(); } // Make request - code.push(indent, 'res, %s := %s.Do(req)', errorPlaceholder, client) - errorCheck() + code.push(indent, 'res, %s := %s.Do(req)', errorPlaceholder, client); + errorCheck(); // Get Body if (opts.printBody) { - code.blank() + code + .blank() .push(indent, 'defer res.Body.Close()') - .push(indent, 'body, %s := ioutil.ReadAll(res.Body)', errorPlaceholder) - errorCheck() + .push(indent, 'body, %s := ioutil.ReadAll(res.Body)', errorPlaceholder); + errorCheck(); } // Print it - code.blank() - .push(indent, 'fmt.Println(res)') + code.blank().push(indent, 'fmt.Println(res)'); if (opts.printBody) { - code.push(indent, 'fmt.Println(string(body))') + code.push(indent, 'fmt.Println(string(body))'); } // End main block if (opts.showBoilerplate) { - code.blank() - .push('}') + code.blank().push('}'); } - return code.join() -} + return code.join(); +}; module.exports.info = { key: 'native', title: 'NewRequest', link: 'http://golang.org/pkg/net/http/#NewRequest', description: 'Golang HTTP client request' -} +}; diff --git a/packages/insomnia-httpsnippet/src/targets/index.js b/packages/insomnia-httpsnippet/src/targets/index.js index 228c828ee6..744e5a3a6c 100755 --- a/packages/insomnia-httpsnippet/src/targets/index.js +++ b/packages/insomnia-httpsnippet/src/targets/index.js @@ -1,4 +1,4 @@ -'use strict' +'use strict'; module.exports = { c: require('./c'), @@ -14,4 +14,4 @@ module.exports = { ruby: require('./ruby'), shell: require('./shell'), swift: require('./swift') -} +}; diff --git a/packages/insomnia-httpsnippet/src/targets/java/index.js b/packages/insomnia-httpsnippet/src/targets/java/index.js index 2d13eefa10..beb8c3c4a3 100755 --- a/packages/insomnia-httpsnippet/src/targets/java/index.js +++ b/packages/insomnia-httpsnippet/src/targets/java/index.js @@ -1,4 +1,4 @@ -'use strict' +'use strict'; module.exports = { info: { @@ -10,4 +10,4 @@ module.exports = { okhttp: require('./okhttp'), unirest: require('./unirest') -} +}; diff --git a/packages/insomnia-httpsnippet/src/targets/java/okhttp.js b/packages/insomnia-httpsnippet/src/targets/java/okhttp.js index 829d76a4b2..7d9439415f 100755 --- a/packages/insomnia-httpsnippet/src/targets/java/okhttp.js +++ b/packages/insomnia-httpsnippet/src/targets/java/okhttp.js @@ -8,72 +8,85 @@ * for any questions or issues regarding the generated code snippet, please open an issue mentioning the author. */ -'use strict' +'use strict'; -var util = require('util') -var CodeBuilder = require('../../helpers/code-builder') +var util = require('util'); +var CodeBuilder = require('../../helpers/code-builder'); -module.exports = function (source, options) { - var opts = util._extend({ - indent: ' ' - }, options) +module.exports = function(source, options) { + var opts = util._extend( + { + indent: ' ' + }, + options + ); - var code = new CodeBuilder(opts.indent) + var code = new CodeBuilder(opts.indent); - var methods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD'] + var methods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD']; - var methodsWithBody = ['POST', 'PUT', 'DELETE', 'PATCH'] + var methodsWithBody = ['POST', 'PUT', 'DELETE', 'PATCH']; - code.push('OkHttpClient client = new OkHttpClient();') - .blank() + code.push('OkHttpClient client = new OkHttpClient();').blank(); if (source.postData.text) { if (source.postData.boundary) { - code.push('MediaType mediaType = MediaType.parse("%s; boundary=%s");', source.postData.mimeType, source.postData.boundary) + code.push( + 'MediaType mediaType = MediaType.parse("%s; boundary=%s");', + source.postData.mimeType, + source.postData.boundary + ); } else { - code.push('MediaType mediaType = MediaType.parse("%s");', source.postData.mimeType) + code.push( + 'MediaType mediaType = MediaType.parse("%s");', + source.postData.mimeType + ); } - code.push('RequestBody body = RequestBody.create(mediaType, %s);', JSON.stringify(source.postData.text)) + code.push( + 'RequestBody body = RequestBody.create(mediaType, %s);', + JSON.stringify(source.postData.text) + ); } - code.push('Request request = new Request.Builder()') - code.push(1, '.url("%s")', source.fullUrl) + code.push('Request request = new Request.Builder()'); + code.push(1, '.url("%s")', source.fullUrl); if (methods.indexOf(source.method.toUpperCase()) === -1) { if (source.postData.text) { - code.push(1, '.method("%s", body)', source.method.toUpperCase()) + code.push(1, '.method("%s", body)', source.method.toUpperCase()); } else { - code.push(1, '.method("%s", null)', source.method.toUpperCase()) + code.push(1, '.method("%s", null)', source.method.toUpperCase()); } } else if (methodsWithBody.indexOf(source.method.toUpperCase()) >= 0) { if (source.postData.text) { - code.push(1, '.%s(body)', source.method.toLowerCase()) + code.push(1, '.%s(body)', source.method.toLowerCase()); } else { - code.push(1, '.%s(null)', source.method.toLowerCase()) + code.push(1, '.%s(null)', source.method.toLowerCase()); } } else { - code.push(1, '.%s()', source.method.toLowerCase()) + code.push(1, '.%s()', source.method.toLowerCase()); } // Add headers, including the cookies - var headers = Object.keys(source.allHeaders) + var headers = Object.keys(source.allHeaders); // construct headers if (headers.length) { - headers.forEach(function (key) { - code.push(1, '.addHeader("%s", "%s")', key, source.allHeaders[key]) - }) + headers.forEach(function(key) { + code.push(1, '.addHeader("%s", "%s")', key, source.allHeaders[key]); + }); } - code.push(1, '.build();') + code + .push(1, '.build();') .blank() - .push('Response response = client.newCall(request).execute();') + .push('Response response = client.newCall(request).execute();'); - return code.join() -} + return code.join(); +}; module.exports.info = { key: 'okhttp', title: 'OkHttp', link: 'http://square.github.io/okhttp/', description: 'An HTTP Request Client Library' -} +}; diff --git a/packages/insomnia-httpsnippet/src/targets/java/unirest.js b/packages/insomnia-httpsnippet/src/targets/java/unirest.js index 4d686520d1..45a580b32e 100755 --- a/packages/insomnia-httpsnippet/src/targets/java/unirest.js +++ b/packages/insomnia-httpsnippet/src/targets/java/unirest.js @@ -8,48 +8,59 @@ * for any questions or issues regarding the generated code snippet, please open an issue mentioning the author. */ -'use strict' +'use strict'; -var util = require('util') -var CodeBuilder = require('../../helpers/code-builder') +var util = require('util'); +var CodeBuilder = require('../../helpers/code-builder'); -module.exports = function (source, options) { - var opts = util._extend({ - indent: ' ' - }, options) +module.exports = function(source, options) { + var opts = util._extend( + { + indent: ' ' + }, + options + ); - var code = new CodeBuilder(opts.indent) + var code = new CodeBuilder(opts.indent); - var methods = [ 'GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS' ] + var methods = ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS']; if (methods.indexOf(source.method.toUpperCase()) === -1) { - code.push('HttpResponse response = Unirest.customMethod("%s","%s")', source.method.toUpperCase(), source.fullUrl) + code.push( + 'HttpResponse response = Unirest.customMethod("%s","%s")', + source.method.toUpperCase(), + source.fullUrl + ); } else { - code.push('HttpResponse response = Unirest.%s("%s")', source.method.toLowerCase(), source.fullUrl) + code.push( + 'HttpResponse response = Unirest.%s("%s")', + source.method.toLowerCase(), + source.fullUrl + ); } // Add headers, including the cookies - var headers = Object.keys(source.allHeaders) + var headers = Object.keys(source.allHeaders); // construct headers if (headers.length) { - headers.forEach(function (key) { - code.push(1, '.header("%s", "%s")', key, source.allHeaders[key]) - }) + headers.forEach(function(key) { + code.push(1, '.header("%s", "%s")', key, source.allHeaders[key]); + }); } if (source.postData.text) { - code.push(1, '.body(%s)', JSON.stringify(source.postData.text)) + code.push(1, '.body(%s)', JSON.stringify(source.postData.text)); } - code.push(1, '.asString();') + code.push(1, '.asString();'); - return code.join() -} + return code.join(); +}; module.exports.info = { key: 'unirest', title: 'Unirest', link: 'http://unirest.io/java.html', description: 'Lightweight HTTP Request Client Library' -} +}; diff --git a/packages/insomnia-httpsnippet/src/targets/javascript/index.js b/packages/insomnia-httpsnippet/src/targets/javascript/index.js index f04c6003e9..ca511a4916 100755 --- a/packages/insomnia-httpsnippet/src/targets/javascript/index.js +++ b/packages/insomnia-httpsnippet/src/targets/javascript/index.js @@ -1,4 +1,4 @@ -'use strict' +'use strict'; module.exports = { info: { @@ -10,4 +10,4 @@ module.exports = { jquery: require('./jquery'), xhr: require('./xhr') -} +}; diff --git a/packages/insomnia-httpsnippet/src/targets/javascript/jquery.js b/packages/insomnia-httpsnippet/src/targets/javascript/jquery.js index 4365ae588b..f85c81d17a 100755 --- a/packages/insomnia-httpsnippet/src/targets/javascript/jquery.js +++ b/packages/insomnia-httpsnippet/src/targets/javascript/jquery.js @@ -8,17 +8,20 @@ * for any questions or issues regarding the generated code snippet, please open an issue mentioning the author. */ -'use strict' +'use strict'; -var util = require('util') -var CodeBuilder = require('../../helpers/code-builder') +var util = require('util'); +var CodeBuilder = require('../../helpers/code-builder'); -module.exports = function (source, options) { - var opts = util._extend({ - indent: ' ' - }, options) +module.exports = function(source, options) { + var opts = util._extend( + { + indent: ' ' + }, + options + ); - var code = new CodeBuilder(opts.indent) + var code = new CodeBuilder(opts.indent); var settings = { async: true, @@ -26,55 +29,65 @@ module.exports = function (source, options) { url: source.fullUrl, method: source.method, headers: source.allHeaders - } + }; switch (source.postData.mimeType) { case 'application/x-www-form-urlencoded': - settings.data = source.postData.paramsObj ? source.postData.paramsObj : source.postData.text - break + settings.data = source.postData.paramsObj + ? source.postData.paramsObj + : source.postData.text; + break; case 'application/json': - settings.processData = false - settings.data = source.postData.text - break + settings.processData = false; + settings.data = source.postData.text; + break; case 'multipart/form-data': - code.push('var form = new FormData();') + code.push('var form = new FormData();'); - source.postData.params.forEach(function (param) { - code.push('form.append(%s, %s);', JSON.stringify(param.name), JSON.stringify(param.value || param.fileName || '')) - }) + source.postData.params.forEach(function(param) { + code.push( + 'form.append(%s, %s);', + JSON.stringify(param.name), + JSON.stringify(param.value || param.fileName || '') + ); + }); - settings.processData = false - settings.contentType = false - settings.mimeType = 'multipart/form-data' - settings.data = '[form]' + settings.processData = false; + settings.contentType = false; + settings.mimeType = 'multipart/form-data'; + settings.data = '[form]'; // remove the contentType header if (~settings.headers['content-type'].indexOf('boundary')) { - delete settings.headers['content-type'] + delete settings.headers['content-type']; } - code.blank() - break + code.blank(); + break; default: if (source.postData.text) { - settings.data = source.postData.text + settings.data = source.postData.text; } } - code.push('var settings = ' + JSON.stringify(settings, null, opts.indent).replace('"[form]"', 'form')) - .blank() - .push('$.ajax(settings).done(function (response) {') - .push(1, 'console.log(response);') - .push('});') + code + .push( + 'var settings = ' + + JSON.stringify(settings, null, opts.indent).replace('"[form]"', 'form') + ) + .blank() + .push('$.ajax(settings).done(function (response) {') + .push(1, 'console.log(response);') + .push('});'); - return code.join() -} + return code.join(); +}; module.exports.info = { key: 'jquery', title: 'jQuery', link: 'http://api.jquery.com/jquery.ajax/', description: 'Perform an asynchronous HTTP (Ajax) requests with jQuery' -} +}; diff --git a/packages/insomnia-httpsnippet/src/targets/javascript/xhr.js b/packages/insomnia-httpsnippet/src/targets/javascript/xhr.js index 3f7e69b71a..502ab9fa4b 100755 --- a/packages/insomnia-httpsnippet/src/targets/javascript/xhr.js +++ b/packages/insomnia-httpsnippet/src/targets/javascript/xhr.js @@ -8,73 +8,93 @@ * for any questions or issues regarding the generated code snippet, please open an issue mentioning the author. */ -'use strict' +'use strict'; -var util = require('util') -var CodeBuilder = require('../../helpers/code-builder') +var util = require('util'); +var CodeBuilder = require('../../helpers/code-builder'); -module.exports = function (source, options) { - var opts = util._extend({ - indent: ' ', - cors: true - }, options) +module.exports = function(source, options) { + var opts = util._extend( + { + indent: ' ', + cors: true + }, + options + ); - var code = new CodeBuilder(opts.indent) + var code = new CodeBuilder(opts.indent); switch (source.postData.mimeType) { case 'application/json': - code.push('var data = JSON.stringify(%s);', JSON.stringify(source.postData.jsonObj, null, opts.indent)) - .push(null) - break + code + .push( + 'var data = JSON.stringify(%s);', + JSON.stringify(source.postData.jsonObj, null, opts.indent) + ) + .push(null); + break; case 'multipart/form-data': - code.push('var data = new FormData();') + code.push('var data = new FormData();'); - source.postData.params.forEach(function (param) { - code.push('data.append(%s, %s);', JSON.stringify(param.name), JSON.stringify(param.value || param.fileName || '')) - }) + source.postData.params.forEach(function(param) { + code.push( + 'data.append(%s, %s);', + JSON.stringify(param.name), + JSON.stringify(param.value || param.fileName || '') + ); + }); // remove the contentType header if (source.allHeaders['content-type'].indexOf('boundary')) { - delete source.allHeaders['content-type'] + delete source.allHeaders['content-type']; } - code.blank() - break + code.blank(); + break; default: - code.push('var data = %s;', JSON.stringify(source.postData.text || null)) - .blank() + code + .push('var data = %s;', JSON.stringify(source.postData.text || null)) + .blank(); } - code.push('var xhr = new XMLHttpRequest();') + code.push('var xhr = new XMLHttpRequest();'); if (opts.cors) { - code.push('xhr.withCredentials = true;') + code.push('xhr.withCredentials = true;'); } - code.blank() - .push('xhr.addEventListener("readystatechange", function () {') - .push(1, 'if (this.readyState === this.DONE) {') - .push(2, 'console.log(this.responseText);') - .push(1, '}') - .push('});') - .blank() - .push('xhr.open(%s, %s);', JSON.stringify(source.method), JSON.stringify(source.fullUrl)) + code + .blank() + .push('xhr.addEventListener("readystatechange", function () {') + .push(1, 'if (this.readyState === this.DONE) {') + .push(2, 'console.log(this.responseText);') + .push(1, '}') + .push('});') + .blank() + .push( + 'xhr.open(%s, %s);', + JSON.stringify(source.method), + JSON.stringify(source.fullUrl) + ); - Object.keys(source.allHeaders).forEach(function (key) { - code.push('xhr.setRequestHeader(%s, %s);', JSON.stringify(key), JSON.stringify(source.allHeaders[key])) - }) + Object.keys(source.allHeaders).forEach(function(key) { + code.push( + 'xhr.setRequestHeader(%s, %s);', + JSON.stringify(key), + JSON.stringify(source.allHeaders[key]) + ); + }); - code.blank() - .push('xhr.send(data);') + code.blank().push('xhr.send(data);'); - return code.join() -} + return code.join(); +}; module.exports.info = { key: 'xhr', title: 'XMLHttpRequest', link: 'https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest', description: 'W3C Standard API that provides scripted client functionality' -} +}; diff --git a/packages/insomnia-httpsnippet/src/targets/node/index.js b/packages/insomnia-httpsnippet/src/targets/node/index.js index 1e4d9e3522..8ce68d1d8d 100755 --- a/packages/insomnia-httpsnippet/src/targets/node/index.js +++ b/packages/insomnia-httpsnippet/src/targets/node/index.js @@ -1,4 +1,4 @@ -'use strict' +'use strict'; module.exports = { info: { @@ -11,4 +11,4 @@ module.exports = { native: require('./native'), request: require('./request'), unirest: require('./unirest') -} +}; diff --git a/packages/insomnia-httpsnippet/src/targets/node/native.js b/packages/insomnia-httpsnippet/src/targets/node/native.js index 3d0f18923d..1229c1700c 100755 --- a/packages/insomnia-httpsnippet/src/targets/node/native.js +++ b/packages/insomnia-httpsnippet/src/targets/node/native.js @@ -8,17 +8,20 @@ * for any questions or issues regarding the generated code snippet, please open an issue mentioning the author. */ -'use strict' +'use strict'; -var util = require('util') -var CodeBuilder = require('../../helpers/code-builder') +var util = require('util'); +var CodeBuilder = require('../../helpers/code-builder'); -module.exports = function (source, options) { - var opts = util._extend({ - indent: ' ' - }, options) +module.exports = function(source, options) { + var opts = util._extend( + { + indent: ' ' + }, + options + ); - var code = new CodeBuilder(opts.indent) + var code = new CodeBuilder(opts.indent); var reqOpts = { method: source.method, @@ -26,59 +29,72 @@ module.exports = function (source, options) { port: source.uriObj.port, path: source.uriObj.path, headers: source.allHeaders - } + }; - code.push('var http = require("%s");', source.uriObj.protocol.replace(':', '')) + code.push( + 'var http = require("%s");', + source.uriObj.protocol.replace(':', '') + ); - code.blank() - .push('var options = %s;', JSON.stringify(reqOpts, null, opts.indent)) - .blank() - .push('var req = http.request(options, function (res) {') - .push(1, 'var chunks = [];') - .blank() - .push(1, 'res.on("data", function (chunk) {') - .push(2, 'chunks.push(chunk);') - .push(1, '});') - .blank() - .push(1, 'res.on("end", function () {') - .push(2, 'var body = Buffer.concat(chunks);') - .push(2, 'console.log(body.toString());') - .push(1, '});') - .push('});') - .blank() + code + .blank() + .push('var options = %s;', JSON.stringify(reqOpts, null, opts.indent)) + .blank() + .push('var req = http.request(options, function (res) {') + .push(1, 'var chunks = [];') + .blank() + .push(1, 'res.on("data", function (chunk) {') + .push(2, 'chunks.push(chunk);') + .push(1, '});') + .blank() + .push(1, 'res.on("end", function () {') + .push(2, 'var body = Buffer.concat(chunks);') + .push(2, 'console.log(body.toString());') + .push(1, '});') + .push('});') + .blank(); switch (source.postData.mimeType) { case 'application/x-www-form-urlencoded': if (source.postData.paramsObj) { - code.unshift('var qs = require("querystring");') - code.push('req.write(qs.stringify(%s));', util.inspect(source.postData.paramsObj, { - depth: null - })) + code.unshift('var qs = require("querystring");'); + code.push( + 'req.write(qs.stringify(%s));', + util.inspect(source.postData.paramsObj, { + depth: null + }) + ); } - break + break; case 'application/json': if (source.postData.jsonObj) { - code.push('req.write(JSON.stringify(%s));', util.inspect(source.postData.jsonObj, { - depth: null - })) + code.push( + 'req.write(JSON.stringify(%s));', + util.inspect(source.postData.jsonObj, { + depth: null + }) + ); } - break + break; default: if (source.postData.text) { - code.push('req.write(%s);', JSON.stringify(source.postData.text, null, opts.indent)) + code.push( + 'req.write(%s);', + JSON.stringify(source.postData.text, null, opts.indent) + ); } } - code.push('req.end();') + code.push('req.end();'); - return code.join() -} + return code.join(); +}; module.exports.info = { key: 'native', title: 'HTTP', link: 'http://nodejs.org/api/http.html#http_http_request_options_callback', description: 'Node.js native HTTP interface' -} +}; diff --git a/packages/insomnia-httpsnippet/src/targets/node/request.js b/packages/insomnia-httpsnippet/src/targets/node/request.js index ea0330784c..36c411de8e 100755 --- a/packages/insomnia-httpsnippet/src/targets/node/request.js +++ b/packages/insomnia-httpsnippet/src/targets/node/request.js @@ -8,118 +8,135 @@ * for any questions or issues regarding the generated code snippet, please open an issue mentioning the author. */ -'use strict' +'use strict'; -var util = require('util') -var CodeBuilder = require('../../helpers/code-builder') +var util = require('util'); +var CodeBuilder = require('../../helpers/code-builder'); -module.exports = function (source, options) { - var opts = util._extend({ - indent: ' ' - }, options) +module.exports = function(source, options) { + var opts = util._extend( + { + indent: ' ' + }, + options + ); - var includeFS = false - var code = new CodeBuilder(opts.indent) + var includeFS = false; + var code = new CodeBuilder(opts.indent); - code.push('var request = require("request");') - .blank() + code.push('var request = require("request");').blank(); var reqOpts = { method: source.method, url: source.url - } + }; if (Object.keys(source.queryObj).length) { - reqOpts.qs = source.queryObj + reqOpts.qs = source.queryObj; } if (Object.keys(source.headersObj).length) { - reqOpts.headers = source.headersObj + reqOpts.headers = source.headersObj; } switch (source.postData.mimeType) { case 'application/x-www-form-urlencoded': - reqOpts.form = source.postData.paramsObj - break + reqOpts.form = source.postData.paramsObj; + break; case 'application/json': if (source.postData.jsonObj) { - reqOpts.body = source.postData.jsonObj - reqOpts.json = true + reqOpts.body = source.postData.jsonObj; + reqOpts.json = true; } - break + break; case 'multipart/form-data': - reqOpts.formData = {} + reqOpts.formData = {}; - source.postData.params.forEach(function (param) { - var attachement = {} + source.postData.params.forEach(function(param) { + var attachement = {}; if (!param.fileName && !param.fileName && !param.contentType) { - reqOpts.formData[param.name] = param.value - return + reqOpts.formData[param.name] = param.value; + return; } if (param.fileName && !param.value) { - includeFS = true + includeFS = true; - attachement.value = 'fs.createReadStream("' + param.fileName + '")' + attachement.value = 'fs.createReadStream("' + param.fileName + '")'; } else if (param.value) { - attachement.value = param.value + attachement.value = param.value; } if (param.fileName) { attachement.options = { filename: param.fileName, contentType: param.contentType ? param.contentType : null - } + }; } - reqOpts.formData[param.name] = attachement - }) - break + reqOpts.formData[param.name] = attachement; + }); + break; default: if (source.postData.text) { - reqOpts.body = source.postData.text + reqOpts.body = source.postData.text; } } // construct cookies argument if (source.cookies.length) { - reqOpts.jar = 'JAR' + reqOpts.jar = 'JAR'; - code.push('var jar = request.jar();') + code.push('var jar = request.jar();'); - var url = source.url + var url = source.url; - source.cookies.forEach(function (cookie) { - code.push('jar.setCookie(request.cookie("%s=%s"), "%s");', encodeURIComponent(cookie.name), encodeURIComponent(cookie.value), url) - }) - code.blank() + source.cookies.forEach(function(cookie) { + code.push( + 'jar.setCookie(request.cookie("%s=%s"), "%s");', + encodeURIComponent(cookie.name), + encodeURIComponent(cookie.value), + url + ); + }); + code.blank(); } if (includeFS) { - code.unshift('var fs = require("fs");') + code.unshift('var fs = require("fs");'); } - code.push('var options = %s;', util.inspect(reqOpts, { depth: null })) + code + .push('var options = %s;', util.inspect(reqOpts, { depth: null })) + .blank(); + + code + .push( + util.format('request(options, %s', 'function (error, response, body) {') + ) + + .push(1, 'if (error) throw new Error(error);') .blank() + .push(1, 'console.log(body);') + .push('});') + .blank(); - code.push(util.format('request(options, %s', 'function (error, response, body) {')) - - .push(1, 'if (error) throw new Error(error);') - .blank() - .push(1, 'console.log(body);') - .push('});') - .blank() - - return code.join().replace('"JAR"', 'jar').replace(/"fs\.createReadStream\(\\\"(.+)\\\"\)\"/, 'fs.createReadStream("$1")') -} + return code + .join() + .replace('"JAR"', 'jar') + .replace( + /"fs\.createReadStream\(\\\"(.+)\\\"\)\"/, + 'fs.createReadStream("$1")' + ); +}; module.exports.info = { key: 'request', title: 'Request', link: 'https://github.com/request/request', description: 'Simplified HTTP request client' -} +}; diff --git a/packages/insomnia-httpsnippet/src/targets/node/unirest.js b/packages/insomnia-httpsnippet/src/targets/node/unirest.js index daa4bf8941..a984a1fdd1 100755 --- a/packages/insomnia-httpsnippet/src/targets/node/unirest.js +++ b/packages/insomnia-httpsnippet/src/targets/node/unirest.js @@ -8,109 +8,144 @@ * for any questions or issues regarding the generated code snippet, please open an issue mentioning the author. */ -'use strict' +'use strict'; -var util = require('util') -var CodeBuilder = require('../../helpers/code-builder') +var util = require('util'); +var CodeBuilder = require('../../helpers/code-builder'); -module.exports = function (source, options) { - var opts = util._extend({ - indent: ' ' - }, options) +module.exports = function(source, options) { + var opts = util._extend( + { + indent: ' ' + }, + options + ); - var includeFS = false - var code = new CodeBuilder(opts.indent) + var includeFS = false; + var code = new CodeBuilder(opts.indent); - code.push('var unirest = require("unirest");') - .blank() - .push('var req = unirest("%s", "%s");', source.method, source.url) - .blank() + code + .push('var unirest = require("unirest");') + .blank() + .push('var req = unirest("%s", "%s");', source.method, source.url) + .blank(); if (source.cookies.length) { - code.push('var CookieJar = unirest.jar();') + code.push('var CookieJar = unirest.jar();'); - source.cookies.forEach(function (cookie) { - code.push('CookieJar.add("%s=%s","%s");', encodeURIComponent(cookie.name), encodeURIComponent(cookie.value), source.url) - }) + source.cookies.forEach(function(cookie) { + code.push( + 'CookieJar.add("%s=%s","%s");', + encodeURIComponent(cookie.name), + encodeURIComponent(cookie.value), + source.url + ); + }); - code.push('req.jar(CookieJar);') - .blank() + code.push('req.jar(CookieJar);').blank(); } if (Object.keys(source.queryObj).length) { - code.push('req.query(%s);', JSON.stringify(source.queryObj, null, opts.indent)) - .blank() + code + .push( + 'req.query(%s);', + JSON.stringify(source.queryObj, null, opts.indent) + ) + .blank(); } if (Object.keys(source.headersObj).length) { - code.push('req.headers(%s);', JSON.stringify(source.headersObj, null, opts.indent)) - .blank() + code + .push( + 'req.headers(%s);', + JSON.stringify(source.headersObj, null, opts.indent) + ) + .blank(); } switch (source.postData.mimeType) { case 'application/x-www-form-urlencoded': if (source.postData.paramsObj) { - code.push('req.form(%s);', JSON.stringify(source.postData.paramsObj, null, opts.indent)) + code.push( + 'req.form(%s);', + JSON.stringify(source.postData.paramsObj, null, opts.indent) + ); } - break + break; case 'application/json': if (source.postData.jsonObj) { - code.push('req.type("json");') - .push('req.send(%s);', JSON.stringify(source.postData.jsonObj, null, opts.indent)) + code + .push('req.type("json");') + .push( + 'req.send(%s);', + JSON.stringify(source.postData.jsonObj, null, opts.indent) + ); } - break + break; case 'multipart/form-data': - var multipart = [] + var multipart = []; - source.postData.params.forEach(function (param) { - var part = {} + source.postData.params.forEach(function(param) { + var part = {}; if (param.fileName && !param.value) { - includeFS = true + includeFS = true; - part.body = 'fs.createReadStream("' + param.fileName + '")' + part.body = 'fs.createReadStream("' + param.fileName + '")'; } else if (param.value) { - part.body = param.value + part.body = param.value; } if (part.body) { if (param.contentType) { - part['content-type'] = param.contentType + part['content-type'] = param.contentType; } - multipart.push(part) + multipart.push(part); } - }) + }); - code.push('req.multipart(%s);', JSON.stringify(multipart, null, opts.indent)) - break + code.push( + 'req.multipart(%s);', + JSON.stringify(multipart, null, opts.indent) + ); + break; default: if (source.postData.text) { - code.push(opts.indent + 'req.send(%s);', JSON.stringify(source.postData.text, null, opts.indent)) + code.push( + opts.indent + 'req.send(%s);', + JSON.stringify(source.postData.text, null, opts.indent) + ); } } if (includeFS) { - code.unshift('var fs = require("fs");') + code.unshift('var fs = require("fs");'); } - code.blank() - .push('req.end(function (res) {') - .push(1, 'if (res.error) throw new Error(res.error);') - .blank() - .push(1, 'console.log(res.body);') - .push('});') - .blank() + code + .blank() + .push('req.end(function (res) {') + .push(1, 'if (res.error) throw new Error(res.error);') + .blank() + .push(1, 'console.log(res.body);') + .push('});') + .blank(); - return code.join().replace(/"fs\.createReadStream\(\\\"(.+)\\\"\)\"/, 'fs.createReadStream("$1")') -} + return code + .join() + .replace( + /"fs\.createReadStream\(\\\"(.+)\\\"\)\"/, + 'fs.createReadStream("$1")' + ); +}; module.exports.info = { key: 'unirest', title: 'Unirest', link: 'http://unirest.io/nodejs.html', description: 'Lightweight HTTP Request Client Library' -} +}; diff --git a/packages/insomnia-httpsnippet/src/targets/objc/helpers.js b/packages/insomnia-httpsnippet/src/targets/objc/helpers.js index fe651075f5..7adb85d110 100755 --- a/packages/insomnia-httpsnippet/src/targets/objc/helpers.js +++ b/packages/insomnia-httpsnippet/src/targets/objc/helpers.js @@ -1,6 +1,6 @@ -'use strict' +'use strict'; -var util = require('util') +var util = require('util'); module.exports = { /** @@ -9,8 +9,10 @@ module.exports = { * @param {number} length Length of the array to return * @return {string} */ - blankString: function (length) { - return Array.apply(null, new Array(length)).map(String.prototype.valueOf, ' ').join('') + blankString: function(length) { + return Array.apply(null, new Array(length)) + .map(String.prototype.valueOf, ' ') + .join(''); }, /** @@ -32,10 +34,13 @@ module.exports = { * // returns: * NSDictionary *params = @{ @"a": @"b", @"c": @"d" }; */ - nsDeclaration: function (nsClass, name, parameters, indent) { - var opening = nsClass + ' *' + name + ' = ' - var literal = this.literalRepresentation(parameters, indent ? opening.length : undefined) - return opening + literal + ';' + nsDeclaration: function(nsClass, name, parameters, indent) { + var opening = nsClass + ' *' + name + ' = '; + var literal = this.literalRepresentation( + parameters, + indent ? opening.length : undefined + ); + return opening + literal + ';'; }, /** @@ -44,27 +49,34 @@ module.exports = { * @param {*} value Any JavaScript literal * @return {string} */ - literalRepresentation: function (value, indentation) { - var join = indentation === undefined ? ', ' : ',\n ' + this.blankString(indentation) + literalRepresentation: function(value, indentation) { + var join = + indentation === undefined + ? ', ' + : ',\n ' + this.blankString(indentation); switch (Object.prototype.toString.call(value)) { case '[object Number]': - return '@' + value + return '@' + value; case '[object Array]': - var values_representation = value.map(function (v) { - return this.literalRepresentation(v) - }.bind(this)) - return '@[ ' + values_representation.join(join) + ' ]' + var values_representation = value.map( + function(v) { + return this.literalRepresentation(v); + }.bind(this) + ); + return '@[ ' + values_representation.join(join) + ' ]'; case '[object Object]': - var keyValuePairs = [] + var keyValuePairs = []; for (var k in value) { - keyValuePairs.push(util.format('@"%s": %s', k, this.literalRepresentation(value[k]))) + keyValuePairs.push( + util.format('@"%s": %s', k, this.literalRepresentation(value[k])) + ); } - return '@{ ' + keyValuePairs.join(join) + ' }' + return '@{ ' + keyValuePairs.join(join) + ' }'; case '[object Boolean]': - return value ? '@YES' : '@NO' + return value ? '@YES' : '@NO'; default: - return '@"' + value.toString().replace(/"/g, '\\"') + '"' + return '@"' + value.toString().replace(/"/g, '\\"') + '"'; } } -} +}; diff --git a/packages/insomnia-httpsnippet/src/targets/objc/index.js b/packages/insomnia-httpsnippet/src/targets/objc/index.js index 4f7d2550f3..9c63e146fb 100755 --- a/packages/insomnia-httpsnippet/src/targets/objc/index.js +++ b/packages/insomnia-httpsnippet/src/targets/objc/index.js @@ -1,4 +1,4 @@ -'use strict' +'use strict'; module.exports = { info: { @@ -9,4 +9,4 @@ module.exports = { }, nsurlsession: require('./nsurlsession') -} +}; diff --git a/packages/insomnia-httpsnippet/src/targets/objc/nsurlsession.js b/packages/insomnia-httpsnippet/src/targets/objc/nsurlsession.js index 1d68c271e8..904db26c56 100755 --- a/packages/insomnia-httpsnippet/src/targets/objc/nsurlsession.js +++ b/packages/insomnia-httpsnippet/src/targets/objc/nsurlsession.js @@ -8,129 +8,211 @@ * for any questions or issues regarding the generated code snippet, please open an issue mentioning the author. */ -'use strict' +'use strict'; -var util = require('util') -var helpers = require('./helpers') -var CodeBuilder = require('../../helpers/code-builder') +var util = require('util'); +var helpers = require('./helpers'); +var CodeBuilder = require('../../helpers/code-builder'); -module.exports = function (source, options) { - var opts = util._extend({ - indent: ' ', - pretty: true, - timeout: '10' - }, options) +module.exports = function(source, options) { + var opts = util._extend( + { + indent: ' ', + pretty: true, + timeout: '10' + }, + options + ); - var code = new CodeBuilder(opts.indent) + var code = new CodeBuilder(opts.indent); // Markers for headers to be created as litteral objects and later be set on the NSURLRequest if exist var req = { hasHeaders: false, hasBody: false - } + }; // We just want to make sure people understand that is the only dependency - code.push('#import ') + code.push('#import '); if (Object.keys(source.allHeaders).length) { - req.hasHeaders = true - code.blank() - .push(helpers.nsDeclaration('NSDictionary', 'headers', source.allHeaders, opts.pretty)) + req.hasHeaders = true; + code + .blank() + .push( + helpers.nsDeclaration( + 'NSDictionary', + 'headers', + source.allHeaders, + opts.pretty + ) + ); } - if (source.postData.text || source.postData.jsonObj || source.postData.params) { - req.hasBody = true + if ( + source.postData.text || + source.postData.jsonObj || + source.postData.params + ) { + req.hasBody = true; switch (source.postData.mimeType) { case 'application/x-www-form-urlencoded': // By appending parameters one by one in the resulting snippet, // we make it easier for the user to edit it according to his or her needs after pasting. // The user can just add/remove lines adding/removing body parameters. - code.blank() - .push('NSMutableData *postData = [[NSMutableData alloc] initWithData:[@"%s=%s" dataUsingEncoding:NSUTF8StringEncoding]];', - source.postData.params[0].name, source.postData.params[0].value) + code + .blank() + .push( + 'NSMutableData *postData = [[NSMutableData alloc] initWithData:[@"%s=%s" dataUsingEncoding:NSUTF8StringEncoding]];', + source.postData.params[0].name, + source.postData.params[0].value + ); for (var i = 1, len = source.postData.params.length; i < len; i++) { - code.push('[postData appendData:[@"&%s=%s" dataUsingEncoding:NSUTF8StringEncoding]];', - source.postData.params[i].name, source.postData.params[i].value) + code.push( + '[postData appendData:[@"&%s=%s" dataUsingEncoding:NSUTF8StringEncoding]];', + source.postData.params[i].name, + source.postData.params[i].value + ); } - break + break; case 'application/json': if (source.postData.jsonObj) { - code.push(helpers.nsDeclaration('NSDictionary', 'parameters', source.postData.jsonObj, opts.pretty)) - .blank() - .push('NSData *postData = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:nil];') + code + .push( + helpers.nsDeclaration( + 'NSDictionary', + 'parameters', + source.postData.jsonObj, + opts.pretty + ) + ) + .blank() + .push( + 'NSData *postData = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:nil];' + ); } - break + break; case 'multipart/form-data': // By appending multipart parameters one by one in the resulting snippet, // we make it easier for the user to edit it according to his or her needs after pasting. // The user can just edit the parameters NSDictionary or put this part of a snippet in a multipart builder method. - code.push(helpers.nsDeclaration('NSArray', 'parameters', source.postData.params, opts.pretty)) - .push('NSString *boundary = @"%s";', source.postData.boundary) - .blank() - .push('NSError *error;') - .push('NSMutableString *body = [NSMutableString string];') - .push('for (NSDictionary *param in parameters) {') - .push(1, '[body appendFormat:@"--%@\\r\\n", boundary];') - .push(1, 'if (param[@"fileName"]) {') - .push(2, '[body appendFormat:@"Content-Disposition:form-data; name=\\"%@\\"; filename=\\"%@\\"\\r\\n", param[@"name"], param[@"fileName"]];') - .push(2, '[body appendFormat:@"Content-Type: %@\\r\\n\\r\\n", param[@"contentType"]];') - .push(2, '[body appendFormat:@"%@", [NSString stringWithContentsOfFile:param[@"fileName"] encoding:NSUTF8StringEncoding error:&error]];') - .push(2, 'if (error) {') - .push(3, 'NSLog(@"%@", error);') - .push(2, '}') - .push(1, '} else {') - .push(2, '[body appendFormat:@"Content-Disposition:form-data; name=\\"%@\\"\\r\\n\\r\\n", param[@"name"]];') - .push(2, '[body appendFormat:@"%@", param[@"value"]];') - .push(1, '}') - .push('}') - .push('[body appendFormat:@"\\r\\n--%@--\\r\\n", boundary];') - .push('NSData *postData = [body dataUsingEncoding:NSUTF8StringEncoding];') - break + code + .push( + helpers.nsDeclaration( + 'NSArray', + 'parameters', + source.postData.params, + opts.pretty + ) + ) + .push('NSString *boundary = @"%s";', source.postData.boundary) + .blank() + .push('NSError *error;') + .push('NSMutableString *body = [NSMutableString string];') + .push('for (NSDictionary *param in parameters) {') + .push(1, '[body appendFormat:@"--%@\\r\\n", boundary];') + .push(1, 'if (param[@"fileName"]) {') + .push( + 2, + '[body appendFormat:@"Content-Disposition:form-data; name=\\"%@\\"; filename=\\"%@\\"\\r\\n", param[@"name"], param[@"fileName"]];' + ) + .push( + 2, + '[body appendFormat:@"Content-Type: %@\\r\\n\\r\\n", param[@"contentType"]];' + ) + .push( + 2, + '[body appendFormat:@"%@", [NSString stringWithContentsOfFile:param[@"fileName"] encoding:NSUTF8StringEncoding error:&error]];' + ) + .push(2, 'if (error) {') + .push(3, 'NSLog(@"%@", error);') + .push(2, '}') + .push(1, '} else {') + .push( + 2, + '[body appendFormat:@"Content-Disposition:form-data; name=\\"%@\\"\\r\\n\\r\\n", param[@"name"]];' + ) + .push(2, '[body appendFormat:@"%@", param[@"value"]];') + .push(1, '}') + .push('}') + .push('[body appendFormat:@"\\r\\n--%@--\\r\\n", boundary];') + .push( + 'NSData *postData = [body dataUsingEncoding:NSUTF8StringEncoding];' + ); + break; default: - code.blank() - .push('NSData *postData = [[NSData alloc] initWithData:[@"' + source.postData.text + '" dataUsingEncoding:NSUTF8StringEncoding]];') + code + .blank() + .push( + 'NSData *postData = [[NSData alloc] initWithData:[@"' + + source.postData.text + + '" dataUsingEncoding:NSUTF8StringEncoding]];' + ); } } - code.blank() - .push('NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"' + source.fullUrl + '"]') - // NSURLRequestUseProtocolCachePolicy is the default policy, let's just always set it to avoid confusion. - .push(' cachePolicy:NSURLRequestUseProtocolCachePolicy') - .push(' timeoutInterval:' + parseInt(opts.timeout, 10).toFixed(1) + '];') - .push('[request setHTTPMethod:@"' + source.method + '"];') + code + .blank() + .push( + 'NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"' + + source.fullUrl + + '"]' + ) + // NSURLRequestUseProtocolCachePolicy is the default policy, let's just always set it to avoid confusion. + .push( + ' cachePolicy:NSURLRequestUseProtocolCachePolicy' + ) + .push( + ' timeoutInterval:' + + parseInt(opts.timeout, 10).toFixed(1) + + '];' + ) + .push('[request setHTTPMethod:@"' + source.method + '"];'); if (req.hasHeaders) { - code.push('[request setAllHTTPHeaderFields:headers];') + code.push('[request setAllHTTPHeaderFields:headers];'); } if (req.hasBody) { - code.push('[request setHTTPBody:postData];') + code.push('[request setHTTPBody:postData];'); } - code.blank() - // Retrieving the shared session will be less verbose than creating a new one. - .push('NSURLSession *session = [NSURLSession sharedSession];') - .push('NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request') - .push(' completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {') - .push(1, ' if (error) {') - .push(2, ' NSLog(@"%@", error);') - .push(1, ' } else {') - // Casting the NSURLResponse to NSHTTPURLResponse so the user can see the status . - .push(2, ' NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;') - .push(2, ' NSLog(@"%@", httpResponse);') - .push(1, ' }') - .push(' }];') - .push('[dataTask resume];') + code + .blank() + // Retrieving the shared session will be less verbose than creating a new one. + .push('NSURLSession *session = [NSURLSession sharedSession];') + .push( + 'NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request' + ) + .push( + ' completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {' + ) + .push(1, ' if (error) {') + .push(2, ' NSLog(@"%@", error);') + .push(1, ' } else {') + // Casting the NSURLResponse to NSHTTPURLResponse so the user can see the status . + .push( + 2, + ' NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;' + ) + .push( + 2, + ' NSLog(@"%@", httpResponse);' + ) + .push(1, ' }') + .push(' }];') + .push('[dataTask resume];'); - return code.join() -} + return code.join(); +}; module.exports.info = { key: 'nsurlsession', title: 'NSURLSession', - link: 'https://developer.apple.com/library/mac/documentation/Foundation/Reference/NSURLSession_class/index.html', - description: 'Foundation\'s NSURLSession request' -} + link: + 'https://developer.apple.com/library/mac/documentation/Foundation/Reference/NSURLSession_class/index.html', + description: "Foundation's NSURLSession request" +}; diff --git a/packages/insomnia-httpsnippet/src/targets/ocaml/cohttp.js b/packages/insomnia-httpsnippet/src/targets/ocaml/cohttp.js index ae89592f9e..e10653ec2c 100755 --- a/packages/insomnia-httpsnippet/src/targets/ocaml/cohttp.js +++ b/packages/insomnia-httpsnippet/src/targets/ocaml/cohttp.js @@ -8,65 +8,81 @@ * for any questions or issues regarding the generated code snippet, please open an issue mentioning the author. */ -'use strict' +'use strict'; -var util = require('util') -var CodeBuilder = require('../../helpers/code-builder') +var util = require('util'); +var CodeBuilder = require('../../helpers/code-builder'); -module.exports = function (source, options) { - var opts = util._extend({ - indent: ' ' - }, options) +module.exports = function(source, options) { + var opts = util._extend( + { + indent: ' ' + }, + options + ); - var methods = ['get', 'post', 'head', 'delete', 'patch', 'put', 'options'] - var code = new CodeBuilder(opts.indent) + var methods = ['get', 'post', 'head', 'delete', 'patch', 'put', 'options']; + var code = new CodeBuilder(opts.indent); - code.push('open Cohttp_lwt_unix') - .push('open Cohttp') - .push('open Lwt') - .blank() - .push('let uri = Uri.of_string "%s" in', source.fullUrl) + code + .push('open Cohttp_lwt_unix') + .push('open Cohttp') + .push('open Lwt') + .blank() + .push('let uri = Uri.of_string "%s" in', source.fullUrl); // Add headers, including the cookies - var headers = Object.keys(source.allHeaders) + var headers = Object.keys(source.allHeaders); if (headers.length === 1) { - code.push('let headers = Header.add (Header.init ()) "%s" "%s" in', headers[0], source.allHeaders[headers[0]]) + code.push( + 'let headers = Header.add (Header.init ()) "%s" "%s" in', + headers[0], + source.allHeaders[headers[0]] + ); } else if (headers.length > 1) { - code.push('let headers = Header.add_list (Header.init ()) [') + code.push('let headers = Header.add_list (Header.init ()) ['); - headers.forEach(function (key) { - code.push(1, '("%s", "%s");', key, source.allHeaders[key]) - }) + headers.forEach(function(key) { + code.push(1, '("%s", "%s");', key, source.allHeaders[key]); + }); - code.push('] in') + code.push('] in'); } // Add body if (source.postData.text) { // Just text - code.push('let body = Cohttp_lwt_body.of_string %s in', JSON.stringify(source.postData.text)) + code.push( + 'let body = Cohttp_lwt_body.of_string %s in', + JSON.stringify(source.postData.text) + ); } // Do the request - code.blank() + code.blank(); - code.push('Client.call %s%s%s uri', + code.push( + 'Client.call %s%s%s uri', headers.length ? '~headers ' : '', source.postData.text ? '~body ' : '', - (methods.indexOf(source.method.toLowerCase()) >= 0 ? ('`' + source.method.toUpperCase()) : '(Code.method_of_string "' + source.method + '")') - ) + methods.indexOf(source.method.toLowerCase()) >= 0 + ? '`' + source.method.toUpperCase() + : '(Code.method_of_string "' + source.method + '")' + ); // Catch result - code.push('>>= fun (res, body_stream) ->') - .push(1, '(* Do stuff with the result *)') + code + .push('>>= fun (res, body_stream) ->') + .push(1, '(* Do stuff with the result *)'); - return code.join() -} + return code.join(); +}; module.exports.info = { key: 'cohttp', title: 'CoHTTP', link: 'https://github.com/mirage/ocaml-cohttp', - description: 'Cohttp is a very lightweight HTTP server using Lwt or Async for OCaml' -} + description: + 'Cohttp is a very lightweight HTTP server using Lwt or Async for OCaml' +}; diff --git a/packages/insomnia-httpsnippet/src/targets/ocaml/index.js b/packages/insomnia-httpsnippet/src/targets/ocaml/index.js index 6fe00a8886..7162b8d7cd 100755 --- a/packages/insomnia-httpsnippet/src/targets/ocaml/index.js +++ b/packages/insomnia-httpsnippet/src/targets/ocaml/index.js @@ -1,4 +1,4 @@ -'use strict' +'use strict'; module.exports = { info: { @@ -9,4 +9,4 @@ module.exports = { }, cohttp: require('./cohttp') -} +}; diff --git a/packages/insomnia-httpsnippet/src/targets/php/curl.js b/packages/insomnia-httpsnippet/src/targets/php/curl.js index 97aebc29dc..74f064d478 100755 --- a/packages/insomnia-httpsnippet/src/targets/php/curl.js +++ b/packages/insomnia-httpsnippet/src/targets/php/curl.js @@ -8,101 +8,127 @@ * for any questions or issues regarding the generated code snippet, please open an issue mentioning the author. */ -'use strict' +'use strict'; -var util = require('util') -var CodeBuilder = require('../../helpers/code-builder') +var util = require('util'); +var CodeBuilder = require('../../helpers/code-builder'); -module.exports = function (source, options) { - var opts = util._extend({ - closingTag: false, - indent: ' ', - maxRedirects: 10, - namedErrors: false, - noTags: false, - shortTags: false, - timeout: 30 - }, options) +module.exports = function(source, options) { + var opts = util._extend( + { + closingTag: false, + indent: ' ', + maxRedirects: 10, + namedErrors: false, + noTags: false, + shortTags: false, + timeout: 30 + }, + options + ); - var code = new CodeBuilder(opts.indent) + var code = new CodeBuilder(opts.indent); if (!opts.noTags) { - code.push(opts.shortTags ? ' %s,', option.name, option.escape ? JSON.stringify(option.value) : option.value)) + var curlOptions = [ + { + escape: true, + name: 'CURLOPT_PORT', + value: source.uriObj.port + }, + { + escape: true, + name: 'CURLOPT_URL', + value: source.fullUrl + }, + { + escape: false, + name: 'CURLOPT_RETURNTRANSFER', + value: 'true' + }, + { + escape: true, + name: 'CURLOPT_ENCODING', + value: '' + }, + { + escape: false, + name: 'CURLOPT_MAXREDIRS', + value: opts.maxRedirects + }, + { + escape: false, + name: 'CURLOPT_TIMEOUT', + value: opts.timeout + }, + { + escape: false, + name: 'CURLOPT_HTTP_VERSION', + value: + source.httpVersion === 'HTTP/1.0' + ? 'CURL_HTTP_VERSION_1_0' + : 'CURL_HTTP_VERSION_1_1' + }, + { + escape: true, + name: 'CURLOPT_CUSTOMREQUEST', + value: source.method + }, + { + escape: true, + name: 'CURLOPT_POSTFIELDS', + value: source.postData ? source.postData.text : undefined } - }) + ]; + + code.push('curl_setopt_array($curl, array('); + + var curlopts = new CodeBuilder(opts.indent, '\n' + opts.indent); + + curlOptions.forEach(function(option) { + if (!~[null, undefined].indexOf(option.value)) { + curlopts.push( + util.format( + '%s => %s,', + option.name, + option.escape ? JSON.stringify(option.value) : option.value + ) + ); + } + }); // construct cookies - var cookies = source.cookies.map(function (cookie) { - return encodeURIComponent(cookie.name) + '=' + encodeURIComponent(cookie.value) - }) + var cookies = source.cookies.map(function(cookie) { + return ( + encodeURIComponent(cookie.name) + '=' + encodeURIComponent(cookie.value) + ); + }); if (cookies.length) { - curlopts.push(util.format('CURLOPT_COOKIE => "%s",', cookies.join('; '))) + curlopts.push(util.format('CURLOPT_COOKIE => "%s",', cookies.join('; '))); } // construct cookies - var headers = Object.keys(source.headersObj).sort().map(function (key) { - return util.format('"%s: %s"', key, source.headersObj[key]) - }) + var headers = Object.keys(source.headersObj) + .sort() + .map(function(key) { + return util.format('"%s: %s"', key, source.headersObj[key]); + }); if (headers.length) { - curlopts.push('CURLOPT_HTTPHEADER => array(') + curlopts + .push('CURLOPT_HTTPHEADER => array(') .push(1, headers.join(',\n' + opts.indent + opts.indent)) - .push('),') + .push('),'); } - code.push(1, curlopts.join()) + code + .push(1, curlopts.join()) .push('));') .blank() .push('$response = curl_exec($curl);') @@ -110,29 +136,29 @@ module.exports = function (source, options) { .blank() .push('curl_close($curl);') .blank() - .push('if ($err) {') + .push('if ($err) {'); if (opts.namedErrors) { - code.push(1, 'echo array_flip(get_defined_constants(true)["curl"])[$err];') + code.push(1, 'echo array_flip(get_defined_constants(true)["curl"])[$err];'); } else { - code.push(1, 'echo "cURL Error #:" . $err;') + code.push(1, 'echo "cURL Error #:" . $err;'); } - code.push('} else {') + code + .push('} else {') .push(1, 'echo $response;') - .push('}') + .push('}'); if (!opts.noTags && opts.closingTag) { - code.blank() - .push('?>') + code.blank().push('?>'); } - return code.join() -} + return code.join(); +}; module.exports.info = { key: 'curl', title: 'cURL', link: 'http://php.net/manual/en/book.curl.php', description: 'PHP with ext-curl' -} +}; diff --git a/packages/insomnia-httpsnippet/src/targets/php/helpers.js b/packages/insomnia-httpsnippet/src/targets/php/helpers.js index c6b2562edc..c420f51e46 100755 --- a/packages/insomnia-httpsnippet/src/targets/php/helpers.js +++ b/packages/insomnia-httpsnippet/src/targets/php/helpers.js @@ -1,55 +1,71 @@ -'use strict' +'use strict'; -var convert = function (obj, indent, last_indent) { - var i, result +var convert = function(obj, indent, last_indent) { + var i, result; if (!last_indent) { - last_indent = '' + last_indent = ''; } switch (Object.prototype.toString.call(obj)) { case '[object Null]': - result = 'null' - break + result = 'null'; + break; case '[object Undefined]': - result = 'null' - break + result = 'null'; + break; case '[object String]': - result = "'" + obj.replace(/\\/g, '\\\\').replace(/\'/g, "\'") + "'" - break + result = "'" + obj.replace(/\\/g, '\\\\').replace(/\'/g, "'") + "'"; + break; case '[object Number]': - result = obj.toString() - break + result = obj.toString(); + break; case '[object Array]': - result = [] + result = []; - obj.forEach(function (item) { - result.push(convert(item, indent + indent, indent)) - }) + obj.forEach(function(item) { + result.push(convert(item, indent + indent, indent)); + }); - result = 'array(\n' + indent + result.join(',\n' + indent) + '\n' + last_indent + ')' - break + result = + 'array(\n' + + indent + + result.join(',\n' + indent) + + '\n' + + last_indent + + ')'; + break; case '[object Object]': - result = [] + result = []; for (i in obj) { if (obj.hasOwnProperty(i)) { - result.push(convert(i, indent) + ' => ' + convert(obj[i], indent + indent, indent)) + result.push( + convert(i, indent) + + ' => ' + + convert(obj[i], indent + indent, indent) + ); } } - result = 'array(\n' + indent + result.join(',\n' + indent) + '\n' + last_indent + ')' - break + result = + 'array(\n' + + indent + + result.join(',\n' + indent) + + '\n' + + last_indent + + ')'; + break; default: - result = 'null' + result = 'null'; } - return result -} + return result; +}; module.exports = { convert: convert, @@ -82,4 +98,4 @@ module.exports = { 'UPDATE', 'VERSION_CONTROL' ] -} +}; diff --git a/packages/insomnia-httpsnippet/src/targets/php/http1.js b/packages/insomnia-httpsnippet/src/targets/php/http1.js index b4429a4747..e5e3e65491 100755 --- a/packages/insomnia-httpsnippet/src/targets/php/http1.js +++ b/packages/insomnia-httpsnippet/src/targets/php/http1.js @@ -8,90 +8,119 @@ * for any questions or issues regarding the generated code snippet, please open an issue mentioning the author. */ -'use strict' +'use strict'; -var util = require('util') -var helpers = require('./helpers') -var CodeBuilder = require('../../helpers/code-builder') +var util = require('util'); +var helpers = require('./helpers'); +var CodeBuilder = require('../../helpers/code-builder'); -module.exports = function (source, options) { - var opts = util._extend({ - closingTag: false, - indent: ' ', - noTags: false, - shortTags: false - }, options) +module.exports = function(source, options) { + var opts = util._extend( + { + closingTag: false, + indent: ' ', + noTags: false, + shortTags: false + }, + options + ); - var code = new CodeBuilder(opts.indent) + var code = new CodeBuilder(opts.indent); if (!opts.noTags) { - code.push(opts.shortTags ? 'setUrl(%s);', helpers.convert(source.url)) + code + .push('$request = new HttpRequest();') + .push('$request->setUrl(%s);', helpers.convert(source.url)); if (~helpers.methods.indexOf(source.method.toUpperCase())) { - code.push('$request->setMethod(HTTP_METH_%s);', source.method.toUpperCase()) + code.push( + '$request->setMethod(HTTP_METH_%s);', + source.method.toUpperCase() + ); } else { - code.push('$request->setMethod(HttpRequest::HTTP_METH_%s);', source.method.toUpperCase()) + code.push( + '$request->setMethod(HttpRequest::HTTP_METH_%s);', + source.method.toUpperCase() + ); } - code.blank() + code.blank(); if (Object.keys(source.queryObj).length) { - code.push('$request->setQueryData(%s);', helpers.convert(source.queryObj, opts.indent)) - .blank() + code + .push( + '$request->setQueryData(%s);', + helpers.convert(source.queryObj, opts.indent) + ) + .blank(); } if (Object.keys(source.headersObj).length) { - code.push('$request->setHeaders(%s);', helpers.convert(source.headersObj, opts.indent)) - .blank() + code + .push( + '$request->setHeaders(%s);', + helpers.convert(source.headersObj, opts.indent) + ) + .blank(); } if (Object.keys(source.cookiesObj).length) { - code.push('$request->setCookies(%s);', helpers.convert(source.cookiesObj, opts.indent)) - .blank() + code + .push( + '$request->setCookies(%s);', + helpers.convert(source.cookiesObj, opts.indent) + ) + .blank(); } switch (source.postData.mimeType) { case 'application/x-www-form-urlencoded': - code.push('$request->setContentType(%s);', helpers.convert(source.postData.mimeType)) - .push('$request->setPostFields(%s);', helpers.convert(source.postData.paramsObj, opts.indent)) - .blank() - break + code + .push( + '$request->setContentType(%s);', + helpers.convert(source.postData.mimeType) + ) + .push( + '$request->setPostFields(%s);', + helpers.convert(source.postData.paramsObj, opts.indent) + ) + .blank(); + break; default: if (source.postData.text) { - code.push('$request->setBody(%s);', helpers.convert(source.postData.text)) - .blank() + code + .push('$request->setBody(%s);', helpers.convert(source.postData.text)) + .blank(); } } - code.push('try {') - .push(1, '$response = $request->send();') - .blank() - .push(1, 'echo $response->getBody();') - .push('} catch (HttpException $ex) {') - .push(1, 'echo $ex;') - .push('}') + code + .push('try {') + .push(1, '$response = $request->send();') + .blank() + .push(1, 'echo $response->getBody();') + .push('} catch (HttpException $ex) {') + .push(1, 'echo $ex;') + .push('}'); if (!opts.noTags && opts.closingTag) { - code.blank() - .push('?>') + code.blank().push('?>'); } - return code.join() -} + return code.join(); +}; module.exports.info = { key: 'http1', title: 'HTTP v1', link: 'http://php.net/manual/en/book.http.php', description: 'PHP with pecl/http v1' -} +}; diff --git a/packages/insomnia-httpsnippet/src/targets/php/http2.js b/packages/insomnia-httpsnippet/src/targets/php/http2.js index 9b90617e7a..8ce9bb094e 100755 --- a/packages/insomnia-httpsnippet/src/targets/php/http2.js +++ b/packages/insomnia-httpsnippet/src/targets/php/http2.js @@ -8,122 +8,146 @@ * for any questions or issues regarding the generated code snippet, please open an issue mentioning the author. */ -'use strict' +'use strict'; -var util = require('util') -var helpers = require('./helpers') -var CodeBuilder = require('../../helpers/code-builder') +var util = require('util'); +var helpers = require('./helpers'); +var CodeBuilder = require('../../helpers/code-builder'); -module.exports = function (source, options) { - var opts = util._extend({ - closingTag: false, - indent: ' ', - noTags: false, - shortTags: false - }, options) +module.exports = function(source, options) { + var opts = util._extend( + { + closingTag: false, + indent: ' ', + noTags: false, + shortTags: false + }, + options + ); - var code = new CodeBuilder(opts.indent) - var hasBody = false + var code = new CodeBuilder(opts.indent); + var hasBody = false; if (!opts.noTags) { - code.push(opts.shortTags ? 'append(new http\\QueryString(%s));', helpers.convert(source.postData.paramsObj, opts.indent)) - .blank() - hasBody = true - break + code + .push('$body = new http\\Message\\Body;') + .push( + '$body->append(new http\\QueryString(%s));', + helpers.convert(source.postData.paramsObj, opts.indent) + ) + .blank(); + hasBody = true; + break; case 'multipart/form-data': - var files = [] - var fields = {} + var files = []; + var fields = {}; - source.postData.params.forEach(function (param) { + source.postData.params.forEach(function(param) { if (param.fileName) { files.push({ name: param.name, type: param.contentType, file: param.fileName, data: param.value - }) + }); } else if (param.value) { - fields[param.name] = param.value + fields[param.name] = param.value; } - }) + }); - code.push('$body = new http\\Message\\Body;') - .push('$body->addForm(%s, %s);', - Object.keys(fields).length ? helpers.convert(fields, opts.indent) : 'NULL', - files.length ? helpers.convert(files, opts.indent) : 'NULL' - ) + code + .push('$body = new http\\Message\\Body;') + .push( + '$body->addForm(%s, %s);', + Object.keys(fields).length + ? helpers.convert(fields, opts.indent) + : 'NULL', + files.length ? helpers.convert(files, opts.indent) : 'NULL' + ); // remove the contentType header if (~source.headersObj['content-type'].indexOf('boundary')) { - delete source.headersObj['content-type'] + delete source.headersObj['content-type']; } - code.blank() + code.blank(); - hasBody = true - break + hasBody = true; + break; default: if (source.postData.text) { - code.push('$body = new http\\Message\\Body;') - .push('$body->append(%s);', helpers.convert(source.postData.text)) - .blank() - hasBody = true + code + .push('$body = new http\\Message\\Body;') + .push('$body->append(%s);', helpers.convert(source.postData.text)) + .blank(); + hasBody = true; } } - code.push('$request->setRequestUrl(%s);', helpers.convert(source.url)) - .push('$request->setRequestMethod(%s);', helpers.convert(source.method)) + code + .push('$request->setRequestUrl(%s);', helpers.convert(source.url)) + .push('$request->setRequestMethod(%s);', helpers.convert(source.method)); if (hasBody) { - code.push('$request->setBody($body);') - .blank() + code.push('$request->setBody($body);').blank(); } if (Object.keys(source.queryObj).length) { - code.push('$request->setQuery(new http\\QueryString(%s));', helpers.convert(source.queryObj, opts.indent)) - .blank() + code + .push( + '$request->setQuery(new http\\QueryString(%s));', + helpers.convert(source.queryObj, opts.indent) + ) + .blank(); } if (Object.keys(source.headersObj).length) { - code.push('$request->setHeaders(%s);', helpers.convert(source.headersObj, opts.indent)) - .blank() + code + .push( + '$request->setHeaders(%s);', + helpers.convert(source.headersObj, opts.indent) + ) + .blank(); } if (Object.keys(source.cookiesObj).length) { - code.blank() - .push('$client->setCookies(%s);', helpers.convert(source.cookiesObj, opts.indent)) - .blank() + code + .blank() + .push( + '$client->setCookies(%s);', + helpers.convert(source.cookiesObj, opts.indent) + ) + .blank(); } - code.push('$client->enqueue($request)->send();') - .push('$response = $client->getResponse();') - .blank() - .push('echo $response->getBody();') + code + .push('$client->enqueue($request)->send();') + .push('$response = $client->getResponse();') + .blank() + .push('echo $response->getBody();'); if (!opts.noTags && opts.closingTag) { - code.blank() - .push('?>') + code.blank().push('?>'); } - return code.join() -} + return code.join(); +}; module.exports.info = { key: 'http2', title: 'HTTP v2', link: 'http://devel-m6w6.rhcloud.com/mdref/http', description: 'PHP with pecl/http v2' -} +}; diff --git a/packages/insomnia-httpsnippet/src/targets/php/index.js b/packages/insomnia-httpsnippet/src/targets/php/index.js index 39f6bfa1a1..0f727e781f 100755 --- a/packages/insomnia-httpsnippet/src/targets/php/index.js +++ b/packages/insomnia-httpsnippet/src/targets/php/index.js @@ -1,4 +1,4 @@ -'use strict' +'use strict'; module.exports = { info: { @@ -11,4 +11,4 @@ module.exports = { curl: require('./curl'), http1: require('./http1'), http2: require('./http2') -} +}; diff --git a/packages/insomnia-httpsnippet/src/targets/python/index.js b/packages/insomnia-httpsnippet/src/targets/python/index.js index 38f5ee7366..b4c04c2e69 100755 --- a/packages/insomnia-httpsnippet/src/targets/python/index.js +++ b/packages/insomnia-httpsnippet/src/targets/python/index.js @@ -1,4 +1,4 @@ -'use strict' +'use strict'; module.exports = { info: { @@ -10,4 +10,4 @@ module.exports = { python3: require('./python3'), requests: require('./requests') -} +}; diff --git a/packages/insomnia-httpsnippet/src/targets/python/python3.js b/packages/insomnia-httpsnippet/src/targets/python/python3.js index 753a6571af..29349f9ee9 100755 --- a/packages/insomnia-httpsnippet/src/targets/python/python3.js +++ b/packages/insomnia-httpsnippet/src/targets/python/python3.js @@ -8,85 +8,84 @@ * for any questions or issues regarding the generated code snippet, please open an issue mentioning the author. */ -'use strict' +'use strict'; -var CodeBuilder = require('../../helpers/code-builder') +var CodeBuilder = require('../../helpers/code-builder'); -module.exports = function (source, options) { - var code = new CodeBuilder() +module.exports = function(source, options) { + var code = new CodeBuilder(); // Start Request - code.push('import http.client') - .blank() + code.push('import http.client').blank(); // Check which protocol to be used for the client connection - var protocol = source.uriObj.protocol + var protocol = source.uriObj.protocol; if (protocol === 'https:') { - code.push('conn = http.client.HTTPSConnection("%s")', source.uriObj.host) - .blank() + code + .push('conn = http.client.HTTPSConnection("%s")', source.uriObj.host) + .blank(); } else { - code.push('conn = http.client.HTTPConnection("%s")', source.uriObj.host) - .blank() + code + .push('conn = http.client.HTTPConnection("%s")', source.uriObj.host) + .blank(); } // Create payload string if it exists - var payload = JSON.stringify(source.postData.text) + var payload = JSON.stringify(source.postData.text); if (payload) { - code.push('payload = %s', payload) - .blank() + code.push('payload = %s', payload).blank(); } // Create Headers - var header - var headers = source.allHeaders - var headerCount = Object.keys(headers).length + var header; + var headers = source.allHeaders; + var headerCount = Object.keys(headers).length; if (headerCount === 1) { for (header in headers) { - code.push('headers = { \'%s\': "%s" }', header, headers[header]) - .blank() + code.push('headers = { \'%s\': "%s" }', header, headers[header]).blank(); } } else if (headerCount > 1) { - var count = 1 + var count = 1; - code.push('headers = {') + code.push('headers = {'); for (header in headers) { if (count++ !== headerCount) { - code.push(' \'%s\': "%s",', header, headers[header]) + code.push(' \'%s\': "%s",', header, headers[header]); } else { - code.push(' \'%s\': "%s"', header, headers[header]) + code.push(' \'%s\': "%s"', header, headers[header]); } } - code.push(' }') - .blank() + code.push(' }').blank(); } // Make Request - var method = source.method - var path = source.uriObj.path + var method = source.method; + var path = source.uriObj.path; if (payload && headerCount) { - code.push('conn.request("%s", "%s", payload, headers)', method, path) + code.push('conn.request("%s", "%s", payload, headers)', method, path); } else if (payload && !headerCount) { - code.push('conn.request("%s", "%s", payload)', method, path) + code.push('conn.request("%s", "%s", payload)', method, path); } else if (!payload && headerCount) { - code.push('conn.request("%s", "%s", headers=headers)', method, path) + code.push('conn.request("%s", "%s", headers=headers)', method, path); } else { - code.push('conn.request("%s", "%s")', method, path) + code.push('conn.request("%s", "%s")', method, path); } // Get Response - code.blank() - .push('res = conn.getresponse()') - .push('data = res.read()') - .blank() - .push('print(data.decode("utf-8"))') + code + .blank() + .push('res = conn.getresponse()') + .push('data = res.read()') + .blank() + .push('print(data.decode("utf-8"))'); - return code.join() -} + return code.join(); +}; module.exports.info = { key: 'python3', title: 'http.client', link: 'https://docs.python.org/3/library/http.client.html', description: 'Python3 HTTP Client' -} +}; diff --git a/packages/insomnia-httpsnippet/src/targets/python/requests.js b/packages/insomnia-httpsnippet/src/targets/python/requests.js index 299eff9d79..ee84fb11ca 100755 --- a/packages/insomnia-httpsnippet/src/targets/python/requests.js +++ b/packages/insomnia-httpsnippet/src/targets/python/requests.js @@ -8,97 +8,93 @@ * for any questions or issues regarding the generated code snippet, please open an issue mentioning the author. */ -'use strict' +'use strict'; -var util = require('util') -var CodeBuilder = require('../../helpers/code-builder') +var util = require('util'); +var CodeBuilder = require('../../helpers/code-builder'); -module.exports = function (source, options) { +module.exports = function(source, options) { // Start snippet - var code = new CodeBuilder(' ') + var code = new CodeBuilder(' '); // Import requests - code.push('import requests') - .blank() + code.push('import requests').blank(); // Set URL - code.push('url = "%s"', source.url) - .blank() + code.push('url = "%s"', source.url).blank(); // Construct query string if (source.queryString.length) { - var qs = 'querystring = ' + JSON.stringify(source.queryObj) + var qs = 'querystring = ' + JSON.stringify(source.queryObj); - code.push(qs) - .blank() + code.push(qs).blank(); } // Construct payload - var payload = JSON.stringify(source.postData.text) + var payload = JSON.stringify(source.postData.text); if (payload) { - code.push('payload = %s', payload) + code.push('payload = %s', payload); } // Construct headers - var header - var headers = source.allHeaders - var headerCount = Object.keys(headers).length + var header; + var headers = source.allHeaders; + var headerCount = Object.keys(headers).length; if (headerCount === 1) { for (header in headers) { - code.push('headers = {\'%s\': \'%s\'}', header, headers[header]) - .blank() + code.push("headers = {'%s': '%s'}", header, headers[header]).blank(); } } else if (headerCount > 1) { - var count = 1 + var count = 1; - code.push('headers = {') + code.push('headers = {'); for (header in headers) { if (count++ !== headerCount) { - code.push(1, '\'%s\': "%s",', header, headers[header]) + code.push(1, '\'%s\': "%s",', header, headers[header]); } else { - code.push(1, '\'%s\': "%s"', header, headers[header]) + code.push(1, '\'%s\': "%s"', header, headers[header]); } } - code.push(1, '}') - .blank() + code.push(1, '}').blank(); } // Construct request - var method = source.method - var request = util.format('response = requests.request("%s", url', method) + var method = source.method; + var request = util.format('response = requests.request("%s", url', method); if (payload) { - request += ', data=payload' + request += ', data=payload'; } if (headerCount > 0) { - request += ', headers=headers' + request += ', headers=headers'; } if (qs) { - request += ', params=querystring' + request += ', params=querystring'; } - request += ')' + request += ')'; - code.push(request) - .blank() + code + .push(request) + .blank() - // Print response - .push('print(response.text)') + // Print response + .push('print(response.text)'); - return code.join() -} + return code.join(); +}; module.exports.info = { key: 'requests', title: 'Requests', link: 'http://docs.python-requests.org/en/latest/api/#requests.request', description: 'Requests HTTP library' -} +}; // response = requests.request("POST", url, data=payload, headers=headers, params=querystring) diff --git a/packages/insomnia-httpsnippet/src/targets/ruby/index.js b/packages/insomnia-httpsnippet/src/targets/ruby/index.js index 1118a1b804..3499f5060f 100755 --- a/packages/insomnia-httpsnippet/src/targets/ruby/index.js +++ b/packages/insomnia-httpsnippet/src/targets/ruby/index.js @@ -1,4 +1,4 @@ -'use strict' +'use strict'; module.exports = { info: { @@ -9,4 +9,4 @@ module.exports = { }, native: require('./native') -} +}; diff --git a/packages/insomnia-httpsnippet/src/targets/ruby/native.js b/packages/insomnia-httpsnippet/src/targets/ruby/native.js index 86d49af2c5..8e9f32e725 100755 --- a/packages/insomnia-httpsnippet/src/targets/ruby/native.js +++ b/packages/insomnia-httpsnippet/src/targets/ruby/native.js @@ -1,61 +1,81 @@ -'use strict' +'use strict'; -var CodeBuilder = require('../../helpers/code-builder') +var CodeBuilder = require('../../helpers/code-builder'); -module.exports = function (source, options) { - var code = new CodeBuilder() +module.exports = function(source, options) { + var code = new CodeBuilder(); - code.push('require \'uri\'') - .push('require \'net/http\'') - .blank() + code + .push("require 'uri'") + .push("require 'net/http'") + .blank(); // To support custom methods we check for the supported methods // and if doesn't exist then we build a custom class for it - var method = source.method.toUpperCase() - var methods = ['GET', 'POST', 'HEAD', 'DELETE', 'PATCH', 'PUT', 'OPTIONS', 'COPY', 'LOCK', 'UNLOCK', 'MOVE', 'TRACE'] - var capMethod = method.charAt(0) + method.substring(1).toLowerCase() + var method = source.method.toUpperCase(); + var methods = [ + 'GET', + 'POST', + 'HEAD', + 'DELETE', + 'PATCH', + 'PUT', + 'OPTIONS', + 'COPY', + 'LOCK', + 'UNLOCK', + 'MOVE', + 'TRACE' + ]; + var capMethod = method.charAt(0) + method.substring(1).toLowerCase(); if (methods.indexOf(method) < 0) { - code.push('class Net::HTTP::%s < Net::HTTPRequest', capMethod) - .push(' METHOD = \'%s\'', method.toUpperCase()) - .push(' REQUEST_HAS_BODY = \'%s\'', source.postData.text ? 'true' : 'false') - .push(' RESPONSE_HAS_BODY = true') - .push('end') - .blank() + code + .push('class Net::HTTP::%s < Net::HTTPRequest', capMethod) + .push(" METHOD = '%s'", method.toUpperCase()) + .push( + " REQUEST_HAS_BODY = '%s'", + source.postData.text ? 'true' : 'false' + ) + .push(' RESPONSE_HAS_BODY = true') + .push('end') + .blank(); } - code.push('url = URI("%s")', source.fullUrl) - .blank() - .push('http = Net::HTTP.new(url.host, url.port)') + code + .push('url = URI("%s")', source.fullUrl) + .blank() + .push('http = Net::HTTP.new(url.host, url.port)'); if (source.uriObj.protocol === 'https:') { - code.push('http.use_ssl = true') - .push('http.verify_mode = OpenSSL::SSL::VERIFY_NONE') + code + .push('http.use_ssl = true') + .push('http.verify_mode = OpenSSL::SSL::VERIFY_NONE'); } - code.blank() - .push('request = Net::HTTP::%s.new(url)', capMethod) + code.blank().push('request = Net::HTTP::%s.new(url)', capMethod); - var headers = Object.keys(source.allHeaders) + var headers = Object.keys(source.allHeaders); if (headers.length) { - headers.forEach(function (key) { - code.push('request["%s"] = \'%s\'', key, source.allHeaders[key]) - }) + headers.forEach(function(key) { + code.push('request["%s"] = \'%s\'', key, source.allHeaders[key]); + }); } if (source.postData.text) { - code.push('request.body = %s', JSON.stringify(source.postData.text)) + code.push('request.body = %s', JSON.stringify(source.postData.text)); } - code.blank() - .push('response = http.request(request)') - .push('puts response.read_body') + code + .blank() + .push('response = http.request(request)') + .push('puts response.read_body'); - return code.join() -} + return code.join(); +}; module.exports.info = { key: 'native', title: 'net::http', link: 'http://ruby-doc.org/stdlib-2.2.1/libdoc/net/http/rdoc/Net/HTTP.html', description: 'Ruby HTTP client' -} +}; diff --git a/packages/insomnia-httpsnippet/src/targets/shell/curl.js b/packages/insomnia-httpsnippet/src/targets/shell/curl.js index a364a18d16..87faadaf82 100755 --- a/packages/insomnia-httpsnippet/src/targets/shell/curl.js +++ b/packages/insomnia-httpsnippet/src/targets/shell/curl.js @@ -8,75 +8,99 @@ * for any questions or issues regarding the generated code snippet, please open an issue mentioning the author. */ -'use strict' +'use strict'; -var util = require('util') -var helpers = require('../../helpers/shell') -var CodeBuilder = require('../../helpers/code-builder') +var util = require('util'); +var helpers = require('../../helpers/shell'); +var CodeBuilder = require('../../helpers/code-builder'); -module.exports = function (source, options) { - var opts = util._extend({ - indent: ' ', - short: false, - binary: false - }, options) +module.exports = function(source, options) { + var opts = util._extend( + { + indent: ' ', + short: false, + binary: false + }, + options + ); - var code = new CodeBuilder(opts.indent, opts.indent !== false ? ' \\\n' + opts.indent : ' ') + var code = new CodeBuilder( + opts.indent, + opts.indent !== false ? ' \\\n' + opts.indent : ' ' + ); - code.push('curl %s %s', opts.short ? '-X' : '--request', source.method) - .push(util.format('%s%s', opts.short ? '' : '--url ', helpers.quote(source.fullUrl))) + code + .push('curl %s %s', opts.short ? '-X' : '--request', source.method) + .push( + util.format( + '%s%s', + opts.short ? '' : '--url ', + helpers.quote(source.fullUrl) + ) + ); if (source.httpVersion === 'HTTP/1.0') { - code.push(opts.short ? '-0' : '--http1.0') + code.push(opts.short ? '-0' : '--http1.0'); } // construct headers - Object.keys(source.headersObj).sort().forEach(function (key) { - var value = source.headersObj[key]; + Object.keys(source.headersObj) + .sort() + .forEach(function(key) { + var value = source.headersObj[key]; - // Remove content-type header if it's multipart because curl will add it's own (with boundary) - if (key.toLowerCase() === 'content-type' && value.indexOf('multipart/') === 0) { - return; - } + // Remove content-type header if it's multipart because curl will add it's own (with boundary) + if ( + key.toLowerCase() === 'content-type' && + value.indexOf('multipart/') === 0 + ) { + return; + } - var header = util.format('%s: %s', key, source.headersObj[key]) - code.push('%s %s', opts.short ? '-H' : '--header', helpers.quote(header)) - }) + var header = util.format('%s: %s', key, source.headersObj[key]); + code.push('%s %s', opts.short ? '-H' : '--header', helpers.quote(header)); + }); if (source.allHeaders.cookie) { - code.push('%s %s', opts.short ? '-b' : '--cookie', helpers.quote(source.allHeaders.cookie)) + code.push( + '%s %s', + opts.short ? '-b' : '--cookie', + helpers.quote(source.allHeaders.cookie) + ); } // construct post params switch (source.postData.mimeType) { case 'multipart/form-data': - source.postData.params.map(function (param) { - var post = util.format('%s=%s', param.name, param.value) + source.postData.params.map(function(param) { + var post = util.format('%s=%s', param.name, param.value); if (param.fileName && !param.value) { - post = util.format('%s=@%s', param.name, param.fileName) + post = util.format('%s=@%s', param.name, param.fileName); } - code.push('%s %s', opts.short ? '-F' : '--form', helpers.quote(post)) - }) - break + code.push('%s %s', opts.short ? '-F' : '--form', helpers.quote(post)); + }); + break; default: // raw request body if (source.postData.text) { code.push( - '%s %s', opts.binary ? '--data-binary' : (opts.short ? '-d' : '--data'), + '%s %s', + opts.binary ? '--data-binary' : opts.short ? '-d' : '--data', helpers.quote(source.postData.text) - ) + ); } } - return code.join() -} + return code.join(); +}; module.exports.info = { key: 'curl', title: 'cURL', link: 'http://curl.haxx.se/', - description: 'cURL is a command line tool and library for transferring data with URL syntax' -} + description: + 'cURL is a command line tool and library for transferring data with URL syntax' +}; diff --git a/packages/insomnia-httpsnippet/src/targets/shell/httpie.js b/packages/insomnia-httpsnippet/src/targets/shell/httpie.js index b5aff91de0..c3b3983635 100755 --- a/packages/insomnia-httpsnippet/src/targets/shell/httpie.js +++ b/packages/insomnia-httpsnippet/src/targets/shell/httpie.js @@ -8,116 +8,129 @@ * for any questions or issues regarding the generated code snippet, please open an issue mentioning the author. */ -'use strict' +'use strict'; -var util = require('util') -var shell = require('../../helpers/shell') -var CodeBuilder = require('../../helpers/code-builder') +var util = require('util'); +var shell = require('../../helpers/shell'); +var CodeBuilder = require('../../helpers/code-builder'); -module.exports = function (source, options) { - var opts = util._extend({ - body: false, - cert: false, - headers: false, - indent: ' ', - pretty: false, - print: false, - queryParams: false, - short: false, - style: false, - timeout: false, - verbose: false, - verify: false - }, options) +module.exports = function(source, options) { + var opts = util._extend( + { + body: false, + cert: false, + headers: false, + indent: ' ', + pretty: false, + print: false, + queryParams: false, + short: false, + style: false, + timeout: false, + verbose: false, + verify: false + }, + options + ); - var code = new CodeBuilder(opts.indent, opts.indent !== false ? ' \\\n' + opts.indent : ' ') + var code = new CodeBuilder( + opts.indent, + opts.indent !== false ? ' \\\n' + opts.indent : ' ' + ); - var raw = false - var flags = [] + var raw = false; + var flags = []; if (opts.headers) { - flags.push(opts.short ? '-h' : '--headers') + flags.push(opts.short ? '-h' : '--headers'); } if (opts.body) { - flags.push(opts.short ? '-b' : '--body') + flags.push(opts.short ? '-b' : '--body'); } if (opts.verbose) { - flags.push(opts.short ? '-v' : '--verbose') + flags.push(opts.short ? '-v' : '--verbose'); } if (opts.print) { - flags.push(util.format('%s=%s', opts.short ? '-p' : '--print', opts.print)) + flags.push(util.format('%s=%s', opts.short ? '-p' : '--print', opts.print)); } if (opts.verify) { - flags.push(util.format('--verify=%s', opts.verify)) + flags.push(util.format('--verify=%s', opts.verify)); } if (opts.cert) { - flags.push(util.format('--cert=%s', opts.cert)) + flags.push(util.format('--cert=%s', opts.cert)); } if (opts.pretty) { - flags.push(util.format('--pretty=%s', opts.pretty)) + flags.push(util.format('--pretty=%s', opts.pretty)); } if (opts.style) { - flags.push(util.format('--style=%s', opts.pretty)) + flags.push(util.format('--style=%s', opts.pretty)); } if (opts.timeout) { - flags.push(util.format('--timeout=%s', opts.timeout)) + flags.push(util.format('--timeout=%s', opts.timeout)); } // construct query params if (opts.queryParams) { - var queryStringKeys = Object.keys(source.queryObj) + var queryStringKeys = Object.keys(source.queryObj); - queryStringKeys.forEach(function (name) { - var value = source.queryObj[name] + queryStringKeys.forEach(function(name) { + var value = source.queryObj[name]; if (util.isArray(value)) { - value.forEach(function (val) { - code.push('%s==%s', name, shell.quote(val)) - }) + value.forEach(function(val) { + code.push('%s==%s', name, shell.quote(val)); + }); } else { - code.push('%s==%s', name, shell.quote(value)) + code.push('%s==%s', name, shell.quote(value)); } - }) + }); } // construct headers - Object.keys(source.allHeaders).sort().forEach(function (key) { - code.push('%s:%s', key, shell.quote(source.allHeaders[key])) - }) + Object.keys(source.allHeaders) + .sort() + .forEach(function(key) { + code.push('%s:%s', key, shell.quote(source.allHeaders[key])); + }); if (source.postData.mimeType === 'application/x-www-form-urlencoded') { // construct post params if (source.postData.params && source.postData.params.length) { - flags.push(opts.short ? '-f' : '--form') + flags.push(opts.short ? '-f' : '--form'); - source.postData.params.forEach(function (param) { - code.push('%s=%s', param.name, shell.quote(param.value)) - }) + source.postData.params.forEach(function(param) { + code.push('%s=%s', param.name, shell.quote(param.value)); + }); } } else { - raw = true + raw = true; } - code.unshift('http %s%s %s', flags.length ? flags.join(' ') + ' ' : '', source.method, shell.quote(opts.queryParams ? source.url : source.fullUrl)) + code.unshift( + 'http %s%s %s', + flags.length ? flags.join(' ') + ' ' : '', + source.method, + shell.quote(opts.queryParams ? source.url : source.fullUrl) + ); if (raw && source.postData.text) { - code.unshift('echo %s | ', shell.quote(source.postData.text)) + code.unshift('echo %s | ', shell.quote(source.postData.text)); } - return code.join() -} + return code.join(); +}; module.exports.info = { key: 'httpie', title: 'HTTPie', link: 'http://httpie.org/', description: 'a CLI, cURL-like tool for humans' -} +}; diff --git a/packages/insomnia-httpsnippet/src/targets/shell/index.js b/packages/insomnia-httpsnippet/src/targets/shell/index.js index 0f5fc05f0c..60d94839f4 100755 --- a/packages/insomnia-httpsnippet/src/targets/shell/index.js +++ b/packages/insomnia-httpsnippet/src/targets/shell/index.js @@ -1,4 +1,4 @@ -'use strict' +'use strict'; module.exports = { info: { @@ -11,4 +11,4 @@ module.exports = { curl: require('./curl'), httpie: require('./httpie'), wget: require('./wget') -} +}; diff --git a/packages/insomnia-httpsnippet/src/targets/shell/wget.js b/packages/insomnia-httpsnippet/src/targets/shell/wget.js index 5bce77ab0c..1eff0d737b 100755 --- a/packages/insomnia-httpsnippet/src/targets/shell/wget.js +++ b/packages/insomnia-httpsnippet/src/targets/shell/wget.js @@ -8,47 +8,56 @@ * for any questions or issues regarding the generated code snippet, please open an issue mentioning the author. */ -'use strict' +'use strict'; -var util = require('util') -var helpers = require('../../helpers/shell') -var CodeBuilder = require('../../helpers/code-builder') +var util = require('util'); +var helpers = require('../../helpers/shell'); +var CodeBuilder = require('../../helpers/code-builder'); -module.exports = function (source, options) { - var opts = util._extend({ - indent: ' ', - short: false, - verbose: false - }, options) +module.exports = function(source, options) { + var opts = util._extend( + { + indent: ' ', + short: false, + verbose: false + }, + options + ); - var code = new CodeBuilder(opts.indent, opts.indent !== false ? ' \\\n' + opts.indent : ' ') + var code = new CodeBuilder( + opts.indent, + opts.indent !== false ? ' \\\n' + opts.indent : ' ' + ); if (opts.verbose) { - code.push('wget %s', opts.short ? '-v' : '--verbose') + code.push('wget %s', opts.short ? '-v' : '--verbose'); } else { - code.push('wget %s', opts.short ? '-q' : '--quiet') + code.push('wget %s', opts.short ? '-q' : '--quiet'); } - code.push('--method %s', helpers.quote(source.method)) + code.push('--method %s', helpers.quote(source.method)); - Object.keys(source.allHeaders).forEach(function (key) { - var header = util.format('%s: %s', key, source.allHeaders[key]) - code.push('--header %s', helpers.quote(header)) - }) + Object.keys(source.allHeaders).forEach(function(key) { + var header = util.format('%s: %s', key, source.allHeaders[key]); + code.push('--header %s', helpers.quote(header)); + }); if (source.postData.text) { - code.push('--body-data ' + helpers.escape(helpers.quote(source.postData.text))) + code.push( + '--body-data ' + helpers.escape(helpers.quote(source.postData.text)) + ); } - code.push(opts.short ? '-O' : '--output-document') - .push('- %s', helpers.quote(source.fullUrl)) + code + .push(opts.short ? '-O' : '--output-document') + .push('- %s', helpers.quote(source.fullUrl)); - return code.join() -} + return code.join(); +}; module.exports.info = { key: 'wget', title: 'Wget', link: 'https://www.gnu.org/software/wget/', description: 'a free software package for retrieving files using HTTP, HTTPS' -} +}; diff --git a/packages/insomnia-httpsnippet/src/targets/swift/helpers.js b/packages/insomnia-httpsnippet/src/targets/swift/helpers.js index 74c85a0a12..0c41e6f72c 100755 --- a/packages/insomnia-httpsnippet/src/targets/swift/helpers.js +++ b/packages/insomnia-httpsnippet/src/targets/swift/helpers.js @@ -1,6 +1,6 @@ -'use strict' +'use strict'; -var util = require('util') +var util = require('util'); /** * Create a string of given length filled with blank spaces @@ -8,23 +8,27 @@ var util = require('util') * @param {number} length Length of the array to return * @return {string} */ -function buildString (length, str) { - return Array.apply(null, new Array(length)).map(String.prototype.valueOf, str).join('') +function buildString(length, str) { + return Array.apply(null, new Array(length)) + .map(String.prototype.valueOf, str) + .join(''); } /** * Create a string corresponding to a Dictionary or Array literal representation with pretty option * and indentation. */ -function concatArray (arr, pretty, indentation, indentLevel) { - var currentIndent = buildString(indentLevel, indentation) - var closingBraceIndent = buildString(indentLevel - 1, indentation) - var join = pretty ? ',\n' + currentIndent : ', ' +function concatArray(arr, pretty, indentation, indentLevel) { + var currentIndent = buildString(indentLevel, indentation); + var closingBraceIndent = buildString(indentLevel - 1, indentation); + var join = pretty ? ',\n' + currentIndent : ', '; if (pretty) { - return '[\n' + currentIndent + arr.join(join) + '\n' + closingBraceIndent + ']' + return ( + '[\n' + currentIndent + arr.join(join) + '\n' + closingBraceIndent + ']' + ); } else { - return '[' + arr.join(join) + ']' + return '[' + arr.join(join) + ']'; } } @@ -37,8 +41,12 @@ module.exports = { * @param {Object} opts Target options * @return {string} */ - literalDeclaration: function (name, parameters, opts) { - return util.format('let %s = %s', name, this.literalRepresentation(parameters, opts)) + literalDeclaration: function(name, parameters, opts) { + return util.format( + 'let %s = %s', + name, + this.literalRepresentation(parameters, opts) + ); }, /** @@ -48,33 +56,51 @@ module.exports = { * @param {Object} opts Target options * @return {string} */ - literalRepresentation: function (value, opts, indentLevel) { - indentLevel = indentLevel === undefined ? 1 : indentLevel + 1 + literalRepresentation: function(value, opts, indentLevel) { + indentLevel = indentLevel === undefined ? 1 : indentLevel + 1; switch (Object.prototype.toString.call(value)) { case '[object Number]': - return value + return value; case '[object Array]': // Don't prettify arrays to not take too much space - var pretty = false - var valuesRepresentation = value.map(function (v) { - // Switch to prettify if the value is a dictionary with multiple keys - if (Object.prototype.toString.call(v) === '[object Object]') { - pretty = Object.keys(v).length > 1 - } - return this.literalRepresentation(v, opts, indentLevel) - }.bind(this)) - return concatArray(valuesRepresentation, pretty, opts.indent, indentLevel) + var pretty = false; + var valuesRepresentation = value.map( + function(v) { + // Switch to prettify if the value is a dictionary with multiple keys + if (Object.prototype.toString.call(v) === '[object Object]') { + pretty = Object.keys(v).length > 1; + } + return this.literalRepresentation(v, opts, indentLevel); + }.bind(this) + ); + return concatArray( + valuesRepresentation, + pretty, + opts.indent, + indentLevel + ); case '[object Object]': - var keyValuePairs = [] + var keyValuePairs = []; for (var k in value) { - keyValuePairs.push(util.format('"%s": %s', k, this.literalRepresentation(value[k], opts, indentLevel))) + keyValuePairs.push( + util.format( + '"%s": %s', + k, + this.literalRepresentation(value[k], opts, indentLevel) + ) + ); } - return concatArray(keyValuePairs, opts.pretty && keyValuePairs.length > 1, opts.indent, indentLevel) + return concatArray( + keyValuePairs, + opts.pretty && keyValuePairs.length > 1, + opts.indent, + indentLevel + ); case '[object Boolean]': - return value.toString() + return value.toString(); default: - return '"' + value.toString().replace(/"/g, '\\"') + '"' + return '"' + value.toString().replace(/"/g, '\\"') + '"'; } } -} +}; diff --git a/packages/insomnia-httpsnippet/src/targets/swift/index.js b/packages/insomnia-httpsnippet/src/targets/swift/index.js index fba4dfea20..1a858ef3e6 100755 --- a/packages/insomnia-httpsnippet/src/targets/swift/index.js +++ b/packages/insomnia-httpsnippet/src/targets/swift/index.js @@ -1,4 +1,4 @@ -'use strict' +'use strict'; module.exports = { info: { @@ -9,4 +9,4 @@ module.exports = { }, nsurlsession: require('./nsurlsession') -} +}; diff --git a/packages/insomnia-httpsnippet/src/targets/swift/nsurlsession.js b/packages/insomnia-httpsnippet/src/targets/swift/nsurlsession.js index 6bf6f78194..7a618be38d 100755 --- a/packages/insomnia-httpsnippet/src/targets/swift/nsurlsession.js +++ b/packages/insomnia-httpsnippet/src/targets/swift/nsurlsession.js @@ -8,132 +8,189 @@ * for any questions or issues regarding the generated code snippet, please open an issue mentioning the author. */ -'use strict' +'use strict'; -var util = require('util') -var helpers = require('./helpers') -var CodeBuilder = require('../../helpers/code-builder') +var util = require('util'); +var helpers = require('./helpers'); +var CodeBuilder = require('../../helpers/code-builder'); -module.exports = function (source, options) { - var opts = util._extend({ - indent: ' ', - pretty: true, - timeout: '10' - }, options) +module.exports = function(source, options) { + var opts = util._extend( + { + indent: ' ', + pretty: true, + timeout: '10' + }, + options + ); - var code = new CodeBuilder(opts.indent) + var code = new CodeBuilder(opts.indent); // Markers for headers to be created as litteral objects and later be set on the NSURLRequest if exist var req = { hasHeaders: false, hasBody: false - } + }; // We just want to make sure people understand that is the only dependency - code.push('import Foundation') + code.push('import Foundation'); if (Object.keys(source.allHeaders).length) { - req.hasHeaders = true - code.blank() - .push(helpers.literalDeclaration('headers', source.allHeaders, opts)) + req.hasHeaders = true; + code + .blank() + .push(helpers.literalDeclaration('headers', source.allHeaders, opts)); } - if (source.postData.text || source.postData.jsonObj || source.postData.params) { - req.hasBody = true + if ( + source.postData.text || + source.postData.jsonObj || + source.postData.params + ) { + req.hasBody = true; switch (source.postData.mimeType) { case 'application/x-www-form-urlencoded': // By appending parameters one by one in the resulting snippet, // we make it easier for the user to edit it according to his or her needs after pasting. // The user can just add/remove lines adding/removing body parameters. - code.blank() - .push('let postData = NSMutableData(data: "%s=%s".data(using: String.Encoding.utf8)!)', source.postData.params[0].name, source.postData.params[0].value) + code + .blank() + .push( + 'let postData = NSMutableData(data: "%s=%s".data(using: String.Encoding.utf8)!)', + source.postData.params[0].name, + source.postData.params[0].value + ); for (var i = 1, len = source.postData.params.length; i < len; i++) { - code.push('postData.append("&%s=%s".data(using: String.Encoding.utf8)!)', source.postData.params[i].name, source.postData.params[i].value) + code.push( + 'postData.append("&%s=%s".data(using: String.Encoding.utf8)!)', + source.postData.params[i].name, + source.postData.params[i].value + ); } - break + break; case 'application/json': if (source.postData.jsonObj) { - code.push(helpers.literalDeclaration('parameters', source.postData.jsonObj, opts), 'as [String : Any]') - .blank() - .push('let postData = JSONSerialization.data(withJSONObject: parameters, options: [])') + code + .push( + helpers.literalDeclaration( + 'parameters', + source.postData.jsonObj, + opts + ), + 'as [String : Any]' + ) + .blank() + .push( + 'let postData = JSONSerialization.data(withJSONObject: parameters, options: [])' + ); } - break + break; case 'multipart/form-data': /** * By appending multipart parameters one by one in the resulting snippet, * we make it easier for the user to edit it according to his or her needs after pasting. * The user can just edit the parameters NSDictionary or put this part of a snippet in a multipart builder method. - */ - code.push(helpers.literalDeclaration('parameters', source.postData.params, opts)) - .blank() - .push('let boundary = "%s"', source.postData.boundary) - .blank() - .push('var body = ""') - .push('var error: NSError? = nil') - .push('for param in parameters {') - .push(1, 'let paramName = param["name"]!') - .push(1, 'body += "--\\(boundary)\\r\\n"') - .push(1, 'body += "Content-Disposition:form-data; name=\\"\\(paramName)\\""') - .push(1, 'if let filename = param["fileName"] {') - .push(2, 'let contentType = param["content-type"]!') - .push(2, 'let fileContent = String(contentsOfFile: filename, encoding: String.Encoding.utf8)') - .push(2, 'if (error != nil) {') - .push(3, 'print(error)') - .push(2, '}') - .push(2, 'body += "; filename=\\"\\(filename)\\"\\r\\n"') - .push(2, 'body += "Content-Type: \\(contentType)\\r\\n\\r\\n"') - .push(2, 'body += fileContent') - .push(1, '} else if let paramValue = param["value"] {') - .push(2, 'body += "\\r\\n\\r\\n\\(paramValue)"') - .push(1, '}') - .push('}') - break + */ + code + .push( + helpers.literalDeclaration( + 'parameters', + source.postData.params, + opts + ) + ) + .blank() + .push('let boundary = "%s"', source.postData.boundary) + .blank() + .push('var body = ""') + .push('var error: NSError? = nil') + .push('for param in parameters {') + .push(1, 'let paramName = param["name"]!') + .push(1, 'body += "--\\(boundary)\\r\\n"') + .push( + 1, + 'body += "Content-Disposition:form-data; name=\\"\\(paramName)\\""' + ) + .push(1, 'if let filename = param["fileName"] {') + .push(2, 'let contentType = param["content-type"]!') + .push( + 2, + 'let fileContent = String(contentsOfFile: filename, encoding: String.Encoding.utf8)' + ) + .push(2, 'if (error != nil) {') + .push(3, 'print(error)') + .push(2, '}') + .push(2, 'body += "; filename=\\"\\(filename)\\"\\r\\n"') + .push(2, 'body += "Content-Type: \\(contentType)\\r\\n\\r\\n"') + .push(2, 'body += fileContent') + .push(1, '} else if let paramValue = param["value"] {') + .push(2, 'body += "\\r\\n\\r\\n\\(paramValue)"') + .push(1, '}') + .push('}'); + break; default: - code.blank() - .push('let postData = NSData(data: "%s".data(using: String.Encoding.utf8)!)', source.postData.text) + code + .blank() + .push( + 'let postData = NSData(data: "%s".data(using: String.Encoding.utf8)!)', + source.postData.text + ); } } - code.blank() - // NSURLRequestUseProtocolCachePolicy is the default policy, let's just always set it to avoid confusion. - .push('let request = NSMutableURLRequest(url: NSURL(string: "%s")! as URL,', source.fullUrl) - .push(' cachePolicy: .useProtocolCachePolicy,') - .push(' timeoutInterval: %s)', parseInt(opts.timeout, 10).toFixed(1)) - .push('request.httpMethod = "%s"', source.method) + code + .blank() + // NSURLRequestUseProtocolCachePolicy is the default policy, let's just always set it to avoid confusion. + .push( + 'let request = NSMutableURLRequest(url: NSURL(string: "%s")! as URL,', + source.fullUrl + ) + .push( + ' cachePolicy: .useProtocolCachePolicy,' + ) + .push( + ' timeoutInterval: %s)', + parseInt(opts.timeout, 10).toFixed(1) + ) + .push('request.httpMethod = "%s"', source.method); if (req.hasHeaders) { - code.push('request.allHTTPHeaderFields = headers') + code.push('request.allHTTPHeaderFields = headers'); } if (req.hasBody) { - code.push('request.httpBody = postData as Data') + code.push('request.httpBody = postData as Data'); } - code.blank() - // Retrieving the shared session will be less verbose than creating a new one. - .push('let session = URLSession.shared') - .push('let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in') - .push(1, 'if (error != nil) {') - .push(2, 'print(error)') - .push(1, '} else {') - // Casting the NSURLResponse to NSHTTPURLResponse so the user can see the status . - .push(2, 'let httpResponse = response as? HTTPURLResponse') - .push(2, 'print(httpResponse)') - .push(1, '}') - .push('})') - .blank() - .push('dataTask.resume()') + code + .blank() + // Retrieving the shared session will be less verbose than creating a new one. + .push('let session = URLSession.shared') + .push( + 'let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in' + ) + .push(1, 'if (error != nil) {') + .push(2, 'print(error)') + .push(1, '} else {') + // Casting the NSURLResponse to NSHTTPURLResponse so the user can see the status . + .push(2, 'let httpResponse = response as? HTTPURLResponse') + .push(2, 'print(httpResponse)') + .push(1, '}') + .push('})') + .blank() + .push('dataTask.resume()'); - return code.join() -} + return code.join(); +}; module.exports.info = { key: 'nsurlsession', title: 'NSURLSession', - link: 'https://developer.apple.com/library/mac/documentation/Foundation/Reference/NSURLSession_class/index.html', - description: 'Foundation\'s NSURLSession request' -} + link: + 'https://developer.apple.com/library/mac/documentation/Foundation/Reference/NSURLSession_class/index.html', + description: "Foundation's NSURLSession request" +}; diff --git a/packages/insomnia-httpsnippet/test/fixtures/index.js b/packages/insomnia-httpsnippet/test/fixtures/index.js index da75cf83db..42b5edfcea 100755 --- a/packages/insomnia-httpsnippet/test/fixtures/index.js +++ b/packages/insomnia-httpsnippet/test/fixtures/index.js @@ -1,3 +1,3 @@ -'use strict' +'use strict'; -module.exports = require('require-directory')(module, {exclude: /output/}) +module.exports = require('require-directory')(module, { exclude: /output/ }); diff --git a/packages/insomnia-httpsnippet/test/fixtures/output/javascript/jquery/application-form-encoded.js b/packages/insomnia-httpsnippet/test/fixtures/output/javascript/jquery/application-form-encoded.js index dc296cc3e5..0c72727b9c 100755 --- a/packages/insomnia-httpsnippet/test/fixtures/output/javascript/jquery/application-form-encoded.js +++ b/packages/insomnia-httpsnippet/test/fixtures/output/javascript/jquery/application-form-encoded.js @@ -1,17 +1,17 @@ var settings = { - "async": true, - "crossDomain": true, - "url": "http://mockbin.com/har", - "method": "POST", - "headers": { - "content-type": "application/x-www-form-urlencoded" + async: true, + crossDomain: true, + url: 'http://mockbin.com/har', + method: 'POST', + headers: { + 'content-type': 'application/x-www-form-urlencoded' }, - "data": { - "foo": "bar", - "hello": "world" + data: { + foo: 'bar', + hello: 'world' } -} +}; -$.ajax(settings).done(function (response) { +$.ajax(settings).done(function(response) { console.log(response); }); diff --git a/packages/insomnia-httpsnippet/test/fixtures/output/javascript/jquery/application-json.js b/packages/insomnia-httpsnippet/test/fixtures/output/javascript/jquery/application-json.js index 0b53728b32..f7695a29da 100755 --- a/packages/insomnia-httpsnippet/test/fixtures/output/javascript/jquery/application-json.js +++ b/packages/insomnia-httpsnippet/test/fixtures/output/javascript/jquery/application-json.js @@ -1,15 +1,16 @@ var settings = { - "async": true, - "crossDomain": true, - "url": "http://mockbin.com/har", - "method": "POST", - "headers": { - "content-type": "application/json" + async: true, + crossDomain: true, + url: 'http://mockbin.com/har', + method: 'POST', + headers: { + 'content-type': 'application/json' }, - "processData": false, - "data": "{\"number\":1,\"string\":\"f\\\"oo\",\"arr\":[1,2,3],\"nested\":{\"a\":\"b\"},\"arr_mix\":[1,\"a\",{\"arr_mix_nested\":{}}],\"boolean\":false}" -} + processData: false, + data: + '{"number":1,"string":"f\\"oo","arr":[1,2,3],"nested":{"a":"b"},"arr_mix":[1,"a",{"arr_mix_nested":{}}],"boolean":false}' +}; -$.ajax(settings).done(function (response) { +$.ajax(settings).done(function(response) { console.log(response); }); diff --git a/packages/insomnia-httpsnippet/test/fixtures/output/javascript/jquery/cookies.js b/packages/insomnia-httpsnippet/test/fixtures/output/javascript/jquery/cookies.js index f65a8d048a..0dda795e15 100755 --- a/packages/insomnia-httpsnippet/test/fixtures/output/javascript/jquery/cookies.js +++ b/packages/insomnia-httpsnippet/test/fixtures/output/javascript/jquery/cookies.js @@ -1,13 +1,13 @@ var settings = { - "async": true, - "crossDomain": true, - "url": "http://mockbin.com/har", - "method": "POST", - "headers": { - "cookie": "foo=bar; bar=baz" + async: true, + crossDomain: true, + url: 'http://mockbin.com/har', + method: 'POST', + headers: { + cookie: 'foo=bar; bar=baz' } -} +}; -$.ajax(settings).done(function (response) { +$.ajax(settings).done(function(response) { console.log(response); }); diff --git a/packages/insomnia-httpsnippet/test/fixtures/output/javascript/jquery/custom-method.js b/packages/insomnia-httpsnippet/test/fixtures/output/javascript/jquery/custom-method.js index ba4185299a..384d9943bd 100755 --- a/packages/insomnia-httpsnippet/test/fixtures/output/javascript/jquery/custom-method.js +++ b/packages/insomnia-httpsnippet/test/fixtures/output/javascript/jquery/custom-method.js @@ -1,11 +1,11 @@ var settings = { - "async": true, - "crossDomain": true, - "url": "http://mockbin.com/har", - "method": "PROPFIND", - "headers": {} -} + async: true, + crossDomain: true, + url: 'http://mockbin.com/har', + method: 'PROPFIND', + headers: {} +}; -$.ajax(settings).done(function (response) { +$.ajax(settings).done(function(response) { console.log(response); }); diff --git a/packages/insomnia-httpsnippet/test/fixtures/output/javascript/jquery/full.js b/packages/insomnia-httpsnippet/test/fixtures/output/javascript/jquery/full.js index 50f7cf609c..fa5f751923 100755 --- a/packages/insomnia-httpsnippet/test/fixtures/output/javascript/jquery/full.js +++ b/packages/insomnia-httpsnippet/test/fixtures/output/javascript/jquery/full.js @@ -1,18 +1,18 @@ var settings = { - "async": true, - "crossDomain": true, - "url": "http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value", - "method": "POST", - "headers": { - "cookie": "foo=bar; bar=baz", - "accept": "application/json", - "content-type": "application/x-www-form-urlencoded" + async: true, + crossDomain: true, + url: 'http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value', + method: 'POST', + headers: { + cookie: 'foo=bar; bar=baz', + accept: 'application/json', + 'content-type': 'application/x-www-form-urlencoded' }, - "data": { - "foo": "bar" + data: { + foo: 'bar' } -} +}; -$.ajax(settings).done(function (response) { +$.ajax(settings).done(function(response) { console.log(response); }); diff --git a/packages/insomnia-httpsnippet/test/fixtures/output/javascript/jquery/headers.js b/packages/insomnia-httpsnippet/test/fixtures/output/javascript/jquery/headers.js index 030e7f6ff3..fb3cd69f3e 100755 --- a/packages/insomnia-httpsnippet/test/fixtures/output/javascript/jquery/headers.js +++ b/packages/insomnia-httpsnippet/test/fixtures/output/javascript/jquery/headers.js @@ -1,14 +1,14 @@ var settings = { - "async": true, - "crossDomain": true, - "url": "http://mockbin.com/har", - "method": "GET", - "headers": { - "accept": "application/json", - "x-foo": "Bar" + async: true, + crossDomain: true, + url: 'http://mockbin.com/har', + method: 'GET', + headers: { + accept: 'application/json', + 'x-foo': 'Bar' } -} +}; -$.ajax(settings).done(function (response) { +$.ajax(settings).done(function(response) { console.log(response); }); diff --git a/packages/insomnia-httpsnippet/test/fixtures/output/javascript/jquery/https.js b/packages/insomnia-httpsnippet/test/fixtures/output/javascript/jquery/https.js index 418bfba7f6..3597372b78 100755 --- a/packages/insomnia-httpsnippet/test/fixtures/output/javascript/jquery/https.js +++ b/packages/insomnia-httpsnippet/test/fixtures/output/javascript/jquery/https.js @@ -1,11 +1,11 @@ var settings = { - "async": true, - "crossDomain": true, - "url": "https://mockbin.com/har", - "method": "GET", - "headers": {} -} + async: true, + crossDomain: true, + url: 'https://mockbin.com/har', + method: 'GET', + headers: {} +}; -$.ajax(settings).done(function (response) { +$.ajax(settings).done(function(response) { console.log(response); }); diff --git a/packages/insomnia-httpsnippet/test/fixtures/output/javascript/jquery/multipart-data.js b/packages/insomnia-httpsnippet/test/fixtures/output/javascript/jquery/multipart-data.js index 8dea93d999..d5d0150304 100755 --- a/packages/insomnia-httpsnippet/test/fixtures/output/javascript/jquery/multipart-data.js +++ b/packages/insomnia-httpsnippet/test/fixtures/output/javascript/jquery/multipart-data.js @@ -1,18 +1,18 @@ var form = new FormData(); -form.append("foo", "Hello World"); +form.append('foo', 'Hello World'); var settings = { - "async": true, - "crossDomain": true, - "url": "http://mockbin.com/har", - "method": "POST", - "headers": {}, - "processData": false, - "contentType": false, - "mimeType": "multipart/form-data", - "data": form -} + async: true, + crossDomain: true, + url: 'http://mockbin.com/har', + method: 'POST', + headers: {}, + processData: false, + contentType: false, + mimeType: 'multipart/form-data', + data: form +}; -$.ajax(settings).done(function (response) { +$.ajax(settings).done(function(response) { console.log(response); }); diff --git a/packages/insomnia-httpsnippet/test/fixtures/output/javascript/jquery/multipart-file.js b/packages/insomnia-httpsnippet/test/fixtures/output/javascript/jquery/multipart-file.js index 12006dd895..3571113a5e 100755 --- a/packages/insomnia-httpsnippet/test/fixtures/output/javascript/jquery/multipart-file.js +++ b/packages/insomnia-httpsnippet/test/fixtures/output/javascript/jquery/multipart-file.js @@ -1,18 +1,18 @@ var form = new FormData(); -form.append("foo", "test/fixtures/files/hello.txt"); +form.append('foo', 'test/fixtures/files/hello.txt'); var settings = { - "async": true, - "crossDomain": true, - "url": "http://mockbin.com/har", - "method": "POST", - "headers": {}, - "processData": false, - "contentType": false, - "mimeType": "multipart/form-data", - "data": form -} + async: true, + crossDomain: true, + url: 'http://mockbin.com/har', + method: 'POST', + headers: {}, + processData: false, + contentType: false, + mimeType: 'multipart/form-data', + data: form +}; -$.ajax(settings).done(function (response) { +$.ajax(settings).done(function(response) { console.log(response); }); diff --git a/packages/insomnia-httpsnippet/test/fixtures/output/javascript/jquery/multipart-form-data.js b/packages/insomnia-httpsnippet/test/fixtures/output/javascript/jquery/multipart-form-data.js index 584b8d9ec1..de5aae4599 100755 --- a/packages/insomnia-httpsnippet/test/fixtures/output/javascript/jquery/multipart-form-data.js +++ b/packages/insomnia-httpsnippet/test/fixtures/output/javascript/jquery/multipart-form-data.js @@ -1,18 +1,18 @@ var form = new FormData(); -form.append("foo", "bar"); +form.append('foo', 'bar'); var settings = { - "async": true, - "crossDomain": true, - "url": "http://mockbin.com/har", - "method": "POST", - "headers": {}, - "processData": false, - "contentType": false, - "mimeType": "multipart/form-data", - "data": form -} + async: true, + crossDomain: true, + url: 'http://mockbin.com/har', + method: 'POST', + headers: {}, + processData: false, + contentType: false, + mimeType: 'multipart/form-data', + data: form +}; -$.ajax(settings).done(function (response) { +$.ajax(settings).done(function(response) { console.log(response); }); diff --git a/packages/insomnia-httpsnippet/test/fixtures/output/javascript/jquery/query.js b/packages/insomnia-httpsnippet/test/fixtures/output/javascript/jquery/query.js index 15a0663e4b..82efca08dd 100755 --- a/packages/insomnia-httpsnippet/test/fixtures/output/javascript/jquery/query.js +++ b/packages/insomnia-httpsnippet/test/fixtures/output/javascript/jquery/query.js @@ -1,11 +1,11 @@ var settings = { - "async": true, - "crossDomain": true, - "url": "http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value", - "method": "GET", - "headers": {} -} + async: true, + crossDomain: true, + url: 'http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value', + method: 'GET', + headers: {} +}; -$.ajax(settings).done(function (response) { +$.ajax(settings).done(function(response) { console.log(response); }); diff --git a/packages/insomnia-httpsnippet/test/fixtures/output/javascript/jquery/short.js b/packages/insomnia-httpsnippet/test/fixtures/output/javascript/jquery/short.js index 45e3bdd074..94e8485653 100755 --- a/packages/insomnia-httpsnippet/test/fixtures/output/javascript/jquery/short.js +++ b/packages/insomnia-httpsnippet/test/fixtures/output/javascript/jquery/short.js @@ -1,11 +1,11 @@ var settings = { - "async": true, - "crossDomain": true, - "url": "http://mockbin.com/har", - "method": "GET", - "headers": {} -} + async: true, + crossDomain: true, + url: 'http://mockbin.com/har', + method: 'GET', + headers: {} +}; -$.ajax(settings).done(function (response) { +$.ajax(settings).done(function(response) { console.log(response); }); diff --git a/packages/insomnia-httpsnippet/test/fixtures/output/javascript/jquery/text-plain.js b/packages/insomnia-httpsnippet/test/fixtures/output/javascript/jquery/text-plain.js index 58debb2de5..8536a73dca 100755 --- a/packages/insomnia-httpsnippet/test/fixtures/output/javascript/jquery/text-plain.js +++ b/packages/insomnia-httpsnippet/test/fixtures/output/javascript/jquery/text-plain.js @@ -1,14 +1,14 @@ var settings = { - "async": true, - "crossDomain": true, - "url": "http://mockbin.com/har", - "method": "POST", - "headers": { - "content-type": "text/plain" + async: true, + crossDomain: true, + url: 'http://mockbin.com/har', + method: 'POST', + headers: { + 'content-type': 'text/plain' }, - "data": "Hello World" -} + data: 'Hello World' +}; -$.ajax(settings).done(function (response) { +$.ajax(settings).done(function(response) { console.log(response); }); diff --git a/packages/insomnia-httpsnippet/test/fixtures/output/javascript/xhr/application-form-encoded.js b/packages/insomnia-httpsnippet/test/fixtures/output/javascript/xhr/application-form-encoded.js index 90cfc66a65..3806dc7ca2 100755 --- a/packages/insomnia-httpsnippet/test/fixtures/output/javascript/xhr/application-form-encoded.js +++ b/packages/insomnia-httpsnippet/test/fixtures/output/javascript/xhr/application-form-encoded.js @@ -1,15 +1,15 @@ -var data = "foo=bar&hello=world"; +var data = 'foo=bar&hello=world'; var xhr = new XMLHttpRequest(); xhr.withCredentials = true; -xhr.addEventListener("readystatechange", function () { +xhr.addEventListener('readystatechange', function() { if (this.readyState === this.DONE) { console.log(this.responseText); } }); -xhr.open("POST", "http://mockbin.com/har"); -xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded"); +xhr.open('POST', 'http://mockbin.com/har'); +xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded'); xhr.send(data); diff --git a/packages/insomnia-httpsnippet/test/fixtures/output/javascript/xhr/application-json.js b/packages/insomnia-httpsnippet/test/fixtures/output/javascript/xhr/application-json.js index 98508d8083..eed549fa72 100755 --- a/packages/insomnia-httpsnippet/test/fixtures/output/javascript/xhr/application-json.js +++ b/packages/insomnia-httpsnippet/test/fixtures/output/javascript/xhr/application-json.js @@ -1,34 +1,30 @@ var data = JSON.stringify({ - "number": 1, - "string": "f\"oo", - "arr": [ - 1, - 2, - 3 - ], - "nested": { - "a": "b" + number: 1, + string: 'f"oo', + arr: [1, 2, 3], + nested: { + a: 'b' }, - "arr_mix": [ + arr_mix: [ 1, - "a", + 'a', { - "arr_mix_nested": {} + arr_mix_nested: {} } ], - "boolean": false + boolean: false }); var xhr = new XMLHttpRequest(); xhr.withCredentials = true; -xhr.addEventListener("readystatechange", function () { +xhr.addEventListener('readystatechange', function() { if (this.readyState === this.DONE) { console.log(this.responseText); } }); -xhr.open("POST", "http://mockbin.com/har"); -xhr.setRequestHeader("content-type", "application/json"); +xhr.open('POST', 'http://mockbin.com/har'); +xhr.setRequestHeader('content-type', 'application/json'); xhr.send(data); diff --git a/packages/insomnia-httpsnippet/test/fixtures/output/javascript/xhr/cookies.js b/packages/insomnia-httpsnippet/test/fixtures/output/javascript/xhr/cookies.js index d110546eab..575ce3d027 100755 --- a/packages/insomnia-httpsnippet/test/fixtures/output/javascript/xhr/cookies.js +++ b/packages/insomnia-httpsnippet/test/fixtures/output/javascript/xhr/cookies.js @@ -3,13 +3,13 @@ var data = null; var xhr = new XMLHttpRequest(); xhr.withCredentials = true; -xhr.addEventListener("readystatechange", function () { +xhr.addEventListener('readystatechange', function() { if (this.readyState === this.DONE) { console.log(this.responseText); } }); -xhr.open("POST", "http://mockbin.com/har"); -xhr.setRequestHeader("cookie", "foo=bar; bar=baz"); +xhr.open('POST', 'http://mockbin.com/har'); +xhr.setRequestHeader('cookie', 'foo=bar; bar=baz'); xhr.send(data); diff --git a/packages/insomnia-httpsnippet/test/fixtures/output/javascript/xhr/custom-method.js b/packages/insomnia-httpsnippet/test/fixtures/output/javascript/xhr/custom-method.js index 6da6675c37..4d70806fe9 100755 --- a/packages/insomnia-httpsnippet/test/fixtures/output/javascript/xhr/custom-method.js +++ b/packages/insomnia-httpsnippet/test/fixtures/output/javascript/xhr/custom-method.js @@ -3,12 +3,12 @@ var data = null; var xhr = new XMLHttpRequest(); xhr.withCredentials = true; -xhr.addEventListener("readystatechange", function () { +xhr.addEventListener('readystatechange', function() { if (this.readyState === this.DONE) { console.log(this.responseText); } }); -xhr.open("PROPFIND", "http://mockbin.com/har"); +xhr.open('PROPFIND', 'http://mockbin.com/har'); xhr.send(data); diff --git a/packages/insomnia-httpsnippet/test/fixtures/output/javascript/xhr/full.js b/packages/insomnia-httpsnippet/test/fixtures/output/javascript/xhr/full.js index 55547738fc..909ea7b5c4 100755 --- a/packages/insomnia-httpsnippet/test/fixtures/output/javascript/xhr/full.js +++ b/packages/insomnia-httpsnippet/test/fixtures/output/javascript/xhr/full.js @@ -1,17 +1,17 @@ -var data = "foo=bar"; +var data = 'foo=bar'; var xhr = new XMLHttpRequest(); xhr.withCredentials = true; -xhr.addEventListener("readystatechange", function () { +xhr.addEventListener('readystatechange', function() { if (this.readyState === this.DONE) { console.log(this.responseText); } }); -xhr.open("POST", "http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value"); -xhr.setRequestHeader("cookie", "foo=bar; bar=baz"); -xhr.setRequestHeader("accept", "application/json"); -xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded"); +xhr.open('POST', 'http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value'); +xhr.setRequestHeader('cookie', 'foo=bar; bar=baz'); +xhr.setRequestHeader('accept', 'application/json'); +xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded'); xhr.send(data); diff --git a/packages/insomnia-httpsnippet/test/fixtures/output/javascript/xhr/headers.js b/packages/insomnia-httpsnippet/test/fixtures/output/javascript/xhr/headers.js index 27e9347bc8..04e2cd86f4 100755 --- a/packages/insomnia-httpsnippet/test/fixtures/output/javascript/xhr/headers.js +++ b/packages/insomnia-httpsnippet/test/fixtures/output/javascript/xhr/headers.js @@ -3,14 +3,14 @@ var data = null; var xhr = new XMLHttpRequest(); xhr.withCredentials = true; -xhr.addEventListener("readystatechange", function () { +xhr.addEventListener('readystatechange', function() { if (this.readyState === this.DONE) { console.log(this.responseText); } }); -xhr.open("GET", "http://mockbin.com/har"); -xhr.setRequestHeader("accept", "application/json"); -xhr.setRequestHeader("x-foo", "Bar"); +xhr.open('GET', 'http://mockbin.com/har'); +xhr.setRequestHeader('accept', 'application/json'); +xhr.setRequestHeader('x-foo', 'Bar'); xhr.send(data); diff --git a/packages/insomnia-httpsnippet/test/fixtures/output/javascript/xhr/https.js b/packages/insomnia-httpsnippet/test/fixtures/output/javascript/xhr/https.js index 6f2e8f34f0..57f7fea74a 100755 --- a/packages/insomnia-httpsnippet/test/fixtures/output/javascript/xhr/https.js +++ b/packages/insomnia-httpsnippet/test/fixtures/output/javascript/xhr/https.js @@ -3,12 +3,12 @@ var data = null; var xhr = new XMLHttpRequest(); xhr.withCredentials = true; -xhr.addEventListener("readystatechange", function () { +xhr.addEventListener('readystatechange', function() { if (this.readyState === this.DONE) { console.log(this.responseText); } }); -xhr.open("GET", "https://mockbin.com/har"); +xhr.open('GET', 'https://mockbin.com/har'); xhr.send(data); diff --git a/packages/insomnia-httpsnippet/test/fixtures/output/javascript/xhr/multipart-data.js b/packages/insomnia-httpsnippet/test/fixtures/output/javascript/xhr/multipart-data.js index 2b7f425799..d1bdeeda64 100755 --- a/packages/insomnia-httpsnippet/test/fixtures/output/javascript/xhr/multipart-data.js +++ b/packages/insomnia-httpsnippet/test/fixtures/output/javascript/xhr/multipart-data.js @@ -1,15 +1,15 @@ var data = new FormData(); -data.append("foo", "Hello World"); +data.append('foo', 'Hello World'); var xhr = new XMLHttpRequest(); xhr.withCredentials = true; -xhr.addEventListener("readystatechange", function () { +xhr.addEventListener('readystatechange', function() { if (this.readyState === this.DONE) { console.log(this.responseText); } }); -xhr.open("POST", "http://mockbin.com/har"); +xhr.open('POST', 'http://mockbin.com/har'); xhr.send(data); diff --git a/packages/insomnia-httpsnippet/test/fixtures/output/javascript/xhr/multipart-file.js b/packages/insomnia-httpsnippet/test/fixtures/output/javascript/xhr/multipart-file.js index a5326f2a31..25e967fe03 100755 --- a/packages/insomnia-httpsnippet/test/fixtures/output/javascript/xhr/multipart-file.js +++ b/packages/insomnia-httpsnippet/test/fixtures/output/javascript/xhr/multipart-file.js @@ -1,15 +1,15 @@ var data = new FormData(); -data.append("foo", "test/fixtures/files/hello.txt"); +data.append('foo', 'test/fixtures/files/hello.txt'); var xhr = new XMLHttpRequest(); xhr.withCredentials = true; -xhr.addEventListener("readystatechange", function () { +xhr.addEventListener('readystatechange', function() { if (this.readyState === this.DONE) { console.log(this.responseText); } }); -xhr.open("POST", "http://mockbin.com/har"); +xhr.open('POST', 'http://mockbin.com/har'); xhr.send(data); diff --git a/packages/insomnia-httpsnippet/test/fixtures/output/javascript/xhr/multipart-form-data.js b/packages/insomnia-httpsnippet/test/fixtures/output/javascript/xhr/multipart-form-data.js index 574bafff52..329aa6a558 100755 --- a/packages/insomnia-httpsnippet/test/fixtures/output/javascript/xhr/multipart-form-data.js +++ b/packages/insomnia-httpsnippet/test/fixtures/output/javascript/xhr/multipart-form-data.js @@ -1,15 +1,15 @@ var data = new FormData(); -data.append("foo", "bar"); +data.append('foo', 'bar'); var xhr = new XMLHttpRequest(); xhr.withCredentials = true; -xhr.addEventListener("readystatechange", function () { +xhr.addEventListener('readystatechange', function() { if (this.readyState === this.DONE) { console.log(this.responseText); } }); -xhr.open("POST", "http://mockbin.com/har"); +xhr.open('POST', 'http://mockbin.com/har'); xhr.send(data); diff --git a/packages/insomnia-httpsnippet/test/fixtures/output/javascript/xhr/query.js b/packages/insomnia-httpsnippet/test/fixtures/output/javascript/xhr/query.js index b9cfa0d238..158e102b9d 100755 --- a/packages/insomnia-httpsnippet/test/fixtures/output/javascript/xhr/query.js +++ b/packages/insomnia-httpsnippet/test/fixtures/output/javascript/xhr/query.js @@ -3,12 +3,12 @@ var data = null; var xhr = new XMLHttpRequest(); xhr.withCredentials = true; -xhr.addEventListener("readystatechange", function () { +xhr.addEventListener('readystatechange', function() { if (this.readyState === this.DONE) { console.log(this.responseText); } }); -xhr.open("GET", "http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value"); +xhr.open('GET', 'http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value'); xhr.send(data); diff --git a/packages/insomnia-httpsnippet/test/fixtures/output/javascript/xhr/short.js b/packages/insomnia-httpsnippet/test/fixtures/output/javascript/xhr/short.js index af35e76752..fe04e89a43 100755 --- a/packages/insomnia-httpsnippet/test/fixtures/output/javascript/xhr/short.js +++ b/packages/insomnia-httpsnippet/test/fixtures/output/javascript/xhr/short.js @@ -3,12 +3,12 @@ var data = null; var xhr = new XMLHttpRequest(); xhr.withCredentials = true; -xhr.addEventListener("readystatechange", function () { +xhr.addEventListener('readystatechange', function() { if (this.readyState === this.DONE) { console.log(this.responseText); } }); -xhr.open("GET", "http://mockbin.com/har"); +xhr.open('GET', 'http://mockbin.com/har'); xhr.send(data); diff --git a/packages/insomnia-httpsnippet/test/fixtures/output/javascript/xhr/text-plain.js b/packages/insomnia-httpsnippet/test/fixtures/output/javascript/xhr/text-plain.js index 6b6ca51715..1db6890b6d 100755 --- a/packages/insomnia-httpsnippet/test/fixtures/output/javascript/xhr/text-plain.js +++ b/packages/insomnia-httpsnippet/test/fixtures/output/javascript/xhr/text-plain.js @@ -1,15 +1,15 @@ -var data = "Hello World"; +var data = 'Hello World'; var xhr = new XMLHttpRequest(); xhr.withCredentials = true; -xhr.addEventListener("readystatechange", function () { +xhr.addEventListener('readystatechange', function() { if (this.readyState === this.DONE) { console.log(this.responseText); } }); -xhr.open("POST", "http://mockbin.com/har"); -xhr.setRequestHeader("content-type", "text/plain"); +xhr.open('POST', 'http://mockbin.com/har'); +xhr.setRequestHeader('content-type', 'text/plain'); xhr.send(data); diff --git a/packages/insomnia-httpsnippet/test/fixtures/output/node/native/application-form-encoded.js b/packages/insomnia-httpsnippet/test/fixtures/output/node/native/application-form-encoded.js index 8989be7cf3..35217edac4 100755 --- a/packages/insomnia-httpsnippet/test/fixtures/output/node/native/application-form-encoded.js +++ b/packages/insomnia-httpsnippet/test/fixtures/output/node/native/application-form-encoded.js @@ -1,24 +1,24 @@ -var qs = require("querystring"); -var http = require("http"); +var qs = require('querystring'); +var http = require('http'); var options = { - "method": "POST", - "hostname": "mockbin.com", - "port": null, - "path": "/har", - "headers": { - "content-type": "application/x-www-form-urlencoded" + method: 'POST', + hostname: 'mockbin.com', + port: null, + path: '/har', + headers: { + 'content-type': 'application/x-www-form-urlencoded' } }; -var req = http.request(options, function (res) { +var req = http.request(options, function(res) { var chunks = []; - res.on("data", function (chunk) { + res.on('data', function(chunk) { chunks.push(chunk); }); - res.on("end", function () { + res.on('end', function() { var body = Buffer.concat(chunks); console.log(body.toString()); }); diff --git a/packages/insomnia-httpsnippet/test/fixtures/output/node/native/application-json.js b/packages/insomnia-httpsnippet/test/fixtures/output/node/native/application-json.js index 5d972636d8..89b93dc231 100755 --- a/packages/insomnia-httpsnippet/test/fixtures/output/node/native/application-json.js +++ b/packages/insomnia-httpsnippet/test/fixtures/output/node/native/application-json.js @@ -1,32 +1,36 @@ -var http = require("http"); +var http = require('http'); var options = { - "method": "POST", - "hostname": "mockbin.com", - "port": null, - "path": "/har", - "headers": { - "content-type": "application/json" + method: 'POST', + hostname: 'mockbin.com', + port: null, + path: '/har', + headers: { + 'content-type': 'application/json' } }; -var req = http.request(options, function (res) { +var req = http.request(options, function(res) { var chunks = []; - res.on("data", function (chunk) { + res.on('data', function(chunk) { chunks.push(chunk); }); - res.on("end", function () { + res.on('end', function() { var body = Buffer.concat(chunks); console.log(body.toString()); }); }); -req.write(JSON.stringify({ number: 1, - string: 'f"oo', - arr: [ 1, 2, 3 ], - nested: { a: 'b' }, - arr_mix: [ 1, 'a', { arr_mix_nested: {} } ], - boolean: false })); +req.write( + JSON.stringify({ + number: 1, + string: 'f"oo', + arr: [1, 2, 3], + nested: { a: 'b' }, + arr_mix: [1, 'a', { arr_mix_nested: {} }], + boolean: false + }) +); req.end(); diff --git a/packages/insomnia-httpsnippet/test/fixtures/output/node/native/cookies.js b/packages/insomnia-httpsnippet/test/fixtures/output/node/native/cookies.js index 39e75389d0..89d4f91ff4 100755 --- a/packages/insomnia-httpsnippet/test/fixtures/output/node/native/cookies.js +++ b/packages/insomnia-httpsnippet/test/fixtures/output/node/native/cookies.js @@ -1,23 +1,23 @@ -var http = require("http"); +var http = require('http'); var options = { - "method": "POST", - "hostname": "mockbin.com", - "port": null, - "path": "/har", - "headers": { - "cookie": "foo=bar; bar=baz" + method: 'POST', + hostname: 'mockbin.com', + port: null, + path: '/har', + headers: { + cookie: 'foo=bar; bar=baz' } }; -var req = http.request(options, function (res) { +var req = http.request(options, function(res) { var chunks = []; - res.on("data", function (chunk) { + res.on('data', function(chunk) { chunks.push(chunk); }); - res.on("end", function () { + res.on('end', function() { var body = Buffer.concat(chunks); console.log(body.toString()); }); diff --git a/packages/insomnia-httpsnippet/test/fixtures/output/node/native/custom-method.js b/packages/insomnia-httpsnippet/test/fixtures/output/node/native/custom-method.js index f87f77499e..1c58544ca5 100755 --- a/packages/insomnia-httpsnippet/test/fixtures/output/node/native/custom-method.js +++ b/packages/insomnia-httpsnippet/test/fixtures/output/node/native/custom-method.js @@ -1,21 +1,21 @@ -var http = require("http"); +var http = require('http'); var options = { - "method": "PROPFIND", - "hostname": "mockbin.com", - "port": null, - "path": "/har", - "headers": {} + method: 'PROPFIND', + hostname: 'mockbin.com', + port: null, + path: '/har', + headers: {} }; -var req = http.request(options, function (res) { +var req = http.request(options, function(res) { var chunks = []; - res.on("data", function (chunk) { + res.on('data', function(chunk) { chunks.push(chunk); }); - res.on("end", function () { + res.on('end', function() { var body = Buffer.concat(chunks); console.log(body.toString()); }); diff --git a/packages/insomnia-httpsnippet/test/fixtures/output/node/native/full.js b/packages/insomnia-httpsnippet/test/fixtures/output/node/native/full.js index f094004ec6..612aa98e30 100755 --- a/packages/insomnia-httpsnippet/test/fixtures/output/node/native/full.js +++ b/packages/insomnia-httpsnippet/test/fixtures/output/node/native/full.js @@ -1,26 +1,26 @@ -var qs = require("querystring"); -var http = require("http"); +var qs = require('querystring'); +var http = require('http'); var options = { - "method": "POST", - "hostname": "mockbin.com", - "port": null, - "path": "/har?foo=bar&foo=baz&baz=abc&key=value", - "headers": { - "cookie": "foo=bar; bar=baz", - "accept": "application/json", - "content-type": "application/x-www-form-urlencoded" + method: 'POST', + hostname: 'mockbin.com', + port: null, + path: '/har?foo=bar&foo=baz&baz=abc&key=value', + headers: { + cookie: 'foo=bar; bar=baz', + accept: 'application/json', + 'content-type': 'application/x-www-form-urlencoded' } }; -var req = http.request(options, function (res) { +var req = http.request(options, function(res) { var chunks = []; - res.on("data", function (chunk) { + res.on('data', function(chunk) { chunks.push(chunk); }); - res.on("end", function () { + res.on('end', function() { var body = Buffer.concat(chunks); console.log(body.toString()); }); diff --git a/packages/insomnia-httpsnippet/test/fixtures/output/node/native/headers.js b/packages/insomnia-httpsnippet/test/fixtures/output/node/native/headers.js index 21d094b48e..0c4d79ae62 100755 --- a/packages/insomnia-httpsnippet/test/fixtures/output/node/native/headers.js +++ b/packages/insomnia-httpsnippet/test/fixtures/output/node/native/headers.js @@ -1,24 +1,24 @@ -var http = require("http"); +var http = require('http'); var options = { - "method": "GET", - "hostname": "mockbin.com", - "port": null, - "path": "/har", - "headers": { - "accept": "application/json", - "x-foo": "Bar" + method: 'GET', + hostname: 'mockbin.com', + port: null, + path: '/har', + headers: { + accept: 'application/json', + 'x-foo': 'Bar' } }; -var req = http.request(options, function (res) { +var req = http.request(options, function(res) { var chunks = []; - res.on("data", function (chunk) { + res.on('data', function(chunk) { chunks.push(chunk); }); - res.on("end", function () { + res.on('end', function() { var body = Buffer.concat(chunks); console.log(body.toString()); }); diff --git a/packages/insomnia-httpsnippet/test/fixtures/output/node/native/https.js b/packages/insomnia-httpsnippet/test/fixtures/output/node/native/https.js index 5dd0a44b66..ffa32af181 100755 --- a/packages/insomnia-httpsnippet/test/fixtures/output/node/native/https.js +++ b/packages/insomnia-httpsnippet/test/fixtures/output/node/native/https.js @@ -1,21 +1,21 @@ -var http = require("https"); +var http = require('https'); var options = { - "method": "GET", - "hostname": "mockbin.com", - "port": null, - "path": "/har", - "headers": {} + method: 'GET', + hostname: 'mockbin.com', + port: null, + path: '/har', + headers: {} }; -var req = http.request(options, function (res) { +var req = http.request(options, function(res) { var chunks = []; - res.on("data", function (chunk) { + res.on('data', function(chunk) { chunks.push(chunk); }); - res.on("end", function () { + res.on('end', function() { var body = Buffer.concat(chunks); console.log(body.toString()); }); diff --git a/packages/insomnia-httpsnippet/test/fixtures/output/node/native/multipart-data.js b/packages/insomnia-httpsnippet/test/fixtures/output/node/native/multipart-data.js index 61d527c1f0..4254f95a83 100755 --- a/packages/insomnia-httpsnippet/test/fixtures/output/node/native/multipart-data.js +++ b/packages/insomnia-httpsnippet/test/fixtures/output/node/native/multipart-data.js @@ -1,27 +1,29 @@ -var http = require("http"); +var http = require('http'); var options = { - "method": "POST", - "hostname": "mockbin.com", - "port": null, - "path": "/har", - "headers": { - "content-type": "multipart/form-data; boundary=---011000010111000001101001" + method: 'POST', + hostname: 'mockbin.com', + port: null, + path: '/har', + headers: { + 'content-type': 'multipart/form-data; boundary=---011000010111000001101001' } }; -var req = http.request(options, function (res) { +var req = http.request(options, function(res) { var chunks = []; - res.on("data", function (chunk) { + res.on('data', function(chunk) { chunks.push(chunk); }); - res.on("end", function () { + res.on('end', function() { var body = Buffer.concat(chunks); console.log(body.toString()); }); }); -req.write("-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"foo\"; filename=\"hello.txt\"\r\nContent-Type: text/plain\r\n\r\nHello World\r\n-----011000010111000001101001--\r\n"); +req.write( + '-----011000010111000001101001\r\nContent-Disposition: form-data; name="foo"; filename="hello.txt"\r\nContent-Type: text/plain\r\n\r\nHello World\r\n-----011000010111000001101001--\r\n' +); req.end(); diff --git a/packages/insomnia-httpsnippet/test/fixtures/output/node/native/multipart-file.js b/packages/insomnia-httpsnippet/test/fixtures/output/node/native/multipart-file.js index 17023a88d1..79b7044aba 100755 --- a/packages/insomnia-httpsnippet/test/fixtures/output/node/native/multipart-file.js +++ b/packages/insomnia-httpsnippet/test/fixtures/output/node/native/multipart-file.js @@ -1,27 +1,29 @@ -var http = require("http"); +var http = require('http'); var options = { - "method": "POST", - "hostname": "mockbin.com", - "port": null, - "path": "/har", - "headers": { - "content-type": "multipart/form-data; boundary=---011000010111000001101001" + method: 'POST', + hostname: 'mockbin.com', + port: null, + path: '/har', + headers: { + 'content-type': 'multipart/form-data; boundary=---011000010111000001101001' } }; -var req = http.request(options, function (res) { +var req = http.request(options, function(res) { var chunks = []; - res.on("data", function (chunk) { + res.on('data', function(chunk) { chunks.push(chunk); }); - res.on("end", function () { + res.on('end', function() { var body = Buffer.concat(chunks); console.log(body.toString()); }); }); -req.write("-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"foo\"; filename=\"hello.txt\"\r\nContent-Type: text/plain\r\n\r\n\r\n-----011000010111000001101001--\r\n"); +req.write( + '-----011000010111000001101001\r\nContent-Disposition: form-data; name="foo"; filename="hello.txt"\r\nContent-Type: text/plain\r\n\r\n\r\n-----011000010111000001101001--\r\n' +); req.end(); diff --git a/packages/insomnia-httpsnippet/test/fixtures/output/node/native/multipart-form-data.js b/packages/insomnia-httpsnippet/test/fixtures/output/node/native/multipart-form-data.js index 55244c4440..436ba18e0a 100755 --- a/packages/insomnia-httpsnippet/test/fixtures/output/node/native/multipart-form-data.js +++ b/packages/insomnia-httpsnippet/test/fixtures/output/node/native/multipart-form-data.js @@ -1,27 +1,29 @@ -var http = require("http"); +var http = require('http'); var options = { - "method": "POST", - "hostname": "mockbin.com", - "port": null, - "path": "/har", - "headers": { - "content-type": "multipart/form-data; boundary=---011000010111000001101001" + method: 'POST', + hostname: 'mockbin.com', + port: null, + path: '/har', + headers: { + 'content-type': 'multipart/form-data; boundary=---011000010111000001101001' } }; -var req = http.request(options, function (res) { +var req = http.request(options, function(res) { var chunks = []; - res.on("data", function (chunk) { + res.on('data', function(chunk) { chunks.push(chunk); }); - res.on("end", function () { + res.on('end', function() { var body = Buffer.concat(chunks); console.log(body.toString()); }); }); -req.write("-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"foo\"\r\n\r\nbar\r\n-----011000010111000001101001--\r\n"); +req.write( + '-----011000010111000001101001\r\nContent-Disposition: form-data; name="foo"\r\n\r\nbar\r\n-----011000010111000001101001--\r\n' +); req.end(); diff --git a/packages/insomnia-httpsnippet/test/fixtures/output/node/native/query.js b/packages/insomnia-httpsnippet/test/fixtures/output/node/native/query.js index c706f8217f..7aa588067e 100755 --- a/packages/insomnia-httpsnippet/test/fixtures/output/node/native/query.js +++ b/packages/insomnia-httpsnippet/test/fixtures/output/node/native/query.js @@ -1,21 +1,21 @@ -var http = require("http"); +var http = require('http'); var options = { - "method": "GET", - "hostname": "mockbin.com", - "port": null, - "path": "/har?foo=bar&foo=baz&baz=abc&key=value", - "headers": {} + method: 'GET', + hostname: 'mockbin.com', + port: null, + path: '/har?foo=bar&foo=baz&baz=abc&key=value', + headers: {} }; -var req = http.request(options, function (res) { +var req = http.request(options, function(res) { var chunks = []; - res.on("data", function (chunk) { + res.on('data', function(chunk) { chunks.push(chunk); }); - res.on("end", function () { + res.on('end', function() { var body = Buffer.concat(chunks); console.log(body.toString()); }); diff --git a/packages/insomnia-httpsnippet/test/fixtures/output/node/native/short.js b/packages/insomnia-httpsnippet/test/fixtures/output/node/native/short.js index 1c25ff7012..9920e93d50 100755 --- a/packages/insomnia-httpsnippet/test/fixtures/output/node/native/short.js +++ b/packages/insomnia-httpsnippet/test/fixtures/output/node/native/short.js @@ -1,21 +1,21 @@ -var http = require("http"); +var http = require('http'); var options = { - "method": "GET", - "hostname": "mockbin.com", - "port": null, - "path": "/har", - "headers": {} + method: 'GET', + hostname: 'mockbin.com', + port: null, + path: '/har', + headers: {} }; -var req = http.request(options, function (res) { +var req = http.request(options, function(res) { var chunks = []; - res.on("data", function (chunk) { + res.on('data', function(chunk) { chunks.push(chunk); }); - res.on("end", function () { + res.on('end', function() { var body = Buffer.concat(chunks); console.log(body.toString()); }); diff --git a/packages/insomnia-httpsnippet/test/fixtures/output/node/native/text-plain.js b/packages/insomnia-httpsnippet/test/fixtures/output/node/native/text-plain.js index f733d8149a..c7e1421888 100755 --- a/packages/insomnia-httpsnippet/test/fixtures/output/node/native/text-plain.js +++ b/packages/insomnia-httpsnippet/test/fixtures/output/node/native/text-plain.js @@ -1,27 +1,27 @@ -var http = require("http"); +var http = require('http'); var options = { - "method": "POST", - "hostname": "mockbin.com", - "port": null, - "path": "/har", - "headers": { - "content-type": "text/plain" + method: 'POST', + hostname: 'mockbin.com', + port: null, + path: '/har', + headers: { + 'content-type': 'text/plain' } }; -var req = http.request(options, function (res) { +var req = http.request(options, function(res) { var chunks = []; - res.on("data", function (chunk) { + res.on('data', function(chunk) { chunks.push(chunk); }); - res.on("end", function () { + res.on('end', function() { var body = Buffer.concat(chunks); console.log(body.toString()); }); }); -req.write("Hello World"); +req.write('Hello World'); req.end(); diff --git a/packages/insomnia-httpsnippet/test/fixtures/output/node/request/application-form-encoded.js b/packages/insomnia-httpsnippet/test/fixtures/output/node/request/application-form-encoded.js index d3fcebd663..5c3224fa1b 100755 --- a/packages/insomnia-httpsnippet/test/fixtures/output/node/request/application-form-encoded.js +++ b/packages/insomnia-httpsnippet/test/fixtures/output/node/request/application-form-encoded.js @@ -1,13 +1,14 @@ -var request = require("request"); +var request = require('request'); -var options = { method: 'POST', +var options = { + method: 'POST', url: 'http://mockbin.com/har', headers: { 'content-type': 'application/x-www-form-urlencoded' }, - form: { foo: 'bar', hello: 'world' } }; + form: { foo: 'bar', hello: 'world' } +}; -request(options, function (error, response, body) { +request(options, function(error, response, body) { if (error) throw new Error(error); console.log(body); }); - diff --git a/packages/insomnia-httpsnippet/test/fixtures/output/node/request/application-json.js b/packages/insomnia-httpsnippet/test/fixtures/output/node/request/application-json.js index ac63778287..08ae8c6420 100755 --- a/packages/insomnia-httpsnippet/test/fixtures/output/node/request/application-json.js +++ b/packages/insomnia-httpsnippet/test/fixtures/output/node/request/application-json.js @@ -1,20 +1,22 @@ -var request = require("request"); +var request = require('request'); -var options = { method: 'POST', +var options = { + method: 'POST', url: 'http://mockbin.com/har', headers: { 'content-type': 'application/json' }, - body: - { number: 1, - string: 'f"oo', - arr: [ 1, 2, 3 ], - nested: { a: 'b' }, - arr_mix: [ 1, 'a', { arr_mix_nested: {} } ], - boolean: false }, - json: true }; + body: { + number: 1, + string: 'f"oo', + arr: [1, 2, 3], + nested: { a: 'b' }, + arr_mix: [1, 'a', { arr_mix_nested: {} }], + boolean: false + }, + json: true +}; -request(options, function (error, response, body) { +request(options, function(error, response, body) { if (error) throw new Error(error); console.log(body); }); - diff --git a/packages/insomnia-httpsnippet/test/fixtures/output/node/request/cookies.js b/packages/insomnia-httpsnippet/test/fixtures/output/node/request/cookies.js index 65a3b2f5c8..083001205d 100755 --- a/packages/insomnia-httpsnippet/test/fixtures/output/node/request/cookies.js +++ b/packages/insomnia-httpsnippet/test/fixtures/output/node/request/cookies.js @@ -1,14 +1,13 @@ -var request = require("request"); +var request = require('request'); var jar = request.jar(); -jar.setCookie(request.cookie("foo=bar"), "http://mockbin.com/har"); -jar.setCookie(request.cookie("bar=baz"), "http://mockbin.com/har"); +jar.setCookie(request.cookie('foo=bar'), 'http://mockbin.com/har'); +jar.setCookie(request.cookie('bar=baz'), 'http://mockbin.com/har'); var options = { method: 'POST', url: 'http://mockbin.com/har', jar: 'JAR' }; -request(options, function (error, response, body) { +request(options, function(error, response, body) { if (error) throw new Error(error); console.log(body); }); - diff --git a/packages/insomnia-httpsnippet/test/fixtures/output/node/request/custom-method.js b/packages/insomnia-httpsnippet/test/fixtures/output/node/request/custom-method.js index 951498c59a..558a5e8bc4 100755 --- a/packages/insomnia-httpsnippet/test/fixtures/output/node/request/custom-method.js +++ b/packages/insomnia-httpsnippet/test/fixtures/output/node/request/custom-method.js @@ -1,10 +1,9 @@ -var request = require("request"); +var request = require('request'); var options = { method: 'PROPFIND', url: 'http://mockbin.com/har' }; -request(options, function (error, response, body) { +request(options, function(error, response, body) { if (error) throw new Error(error); console.log(body); }); - diff --git a/packages/insomnia-httpsnippet/test/fixtures/output/node/request/full.js b/packages/insomnia-httpsnippet/test/fixtures/output/node/request/full.js index 76b2ad68b3..a9a57a018d 100755 --- a/packages/insomnia-httpsnippet/test/fixtures/output/node/request/full.js +++ b/packages/insomnia-httpsnippet/test/fixtures/output/node/request/full.js @@ -1,21 +1,23 @@ -var request = require("request"); +var request = require('request'); var jar = request.jar(); -jar.setCookie(request.cookie("foo=bar"), "http://mockbin.com/har"); -jar.setCookie(request.cookie("bar=baz"), "http://mockbin.com/har"); +jar.setCookie(request.cookie('foo=bar'), 'http://mockbin.com/har'); +jar.setCookie(request.cookie('bar=baz'), 'http://mockbin.com/har'); -var options = { method: 'POST', +var options = { + method: 'POST', url: 'http://mockbin.com/har', - qs: { foo: [ 'bar', 'baz' ], baz: 'abc', key: 'value' }, - headers: - { 'content-type': 'application/x-www-form-urlencoded', - accept: 'application/json' }, + qs: { foo: ['bar', 'baz'], baz: 'abc', key: 'value' }, + headers: { + 'content-type': 'application/x-www-form-urlencoded', + accept: 'application/json' + }, form: { foo: 'bar' }, - jar: 'JAR' }; + jar: 'JAR' +}; -request(options, function (error, response, body) { +request(options, function(error, response, body) { if (error) throw new Error(error); console.log(body); }); - diff --git a/packages/insomnia-httpsnippet/test/fixtures/output/node/request/headers.js b/packages/insomnia-httpsnippet/test/fixtures/output/node/request/headers.js index d3b8c88fb0..953972a607 100755 --- a/packages/insomnia-httpsnippet/test/fixtures/output/node/request/headers.js +++ b/packages/insomnia-httpsnippet/test/fixtures/output/node/request/headers.js @@ -1,12 +1,13 @@ -var request = require("request"); +var request = require('request'); -var options = { method: 'GET', +var options = { + method: 'GET', url: 'http://mockbin.com/har', - headers: { 'x-foo': 'Bar', accept: 'application/json' } }; + headers: { 'x-foo': 'Bar', accept: 'application/json' } +}; -request(options, function (error, response, body) { +request(options, function(error, response, body) { if (error) throw new Error(error); console.log(body); }); - diff --git a/packages/insomnia-httpsnippet/test/fixtures/output/node/request/https.js b/packages/insomnia-httpsnippet/test/fixtures/output/node/request/https.js index bb29e04a22..ccdbdcc9f5 100755 --- a/packages/insomnia-httpsnippet/test/fixtures/output/node/request/https.js +++ b/packages/insomnia-httpsnippet/test/fixtures/output/node/request/https.js @@ -1,10 +1,9 @@ -var request = require("request"); +var request = require('request'); var options = { method: 'GET', url: 'https://mockbin.com/har' }; -request(options, function (error, response, body) { +request(options, function(error, response, body) { if (error) throw new Error(error); console.log(body); }); - diff --git a/packages/insomnia-httpsnippet/test/fixtures/output/node/request/multipart-data.js b/packages/insomnia-httpsnippet/test/fixtures/output/node/request/multipart-data.js index c7aee53ca1..7e709d0362 100755 --- a/packages/insomnia-httpsnippet/test/fixtures/output/node/request/multipart-data.js +++ b/packages/insomnia-httpsnippet/test/fixtures/output/node/request/multipart-data.js @@ -1,16 +1,21 @@ -var request = require("request"); +var request = require('request'); -var options = { method: 'POST', +var options = { + method: 'POST', url: 'http://mockbin.com/har', - headers: { 'content-type': 'multipart/form-data; boundary=---011000010111000001101001' }, - formData: - { foo: - { value: 'Hello World', - options: { filename: 'hello.txt', contentType: 'text/plain' } } } }; + headers: { + 'content-type': 'multipart/form-data; boundary=---011000010111000001101001' + }, + formData: { + foo: { + value: 'Hello World', + options: { filename: 'hello.txt', contentType: 'text/plain' } + } + } +}; -request(options, function (error, response, body) { +request(options, function(error, response, body) { if (error) throw new Error(error); console.log(body); }); - diff --git a/packages/insomnia-httpsnippet/test/fixtures/output/node/request/multipart-file.js b/packages/insomnia-httpsnippet/test/fixtures/output/node/request/multipart-file.js index 13793258b4..33a2d1cf56 100755 --- a/packages/insomnia-httpsnippet/test/fixtures/output/node/request/multipart-file.js +++ b/packages/insomnia-httpsnippet/test/fixtures/output/node/request/multipart-file.js @@ -1,19 +1,25 @@ -var fs = require("fs"); -var request = require("request"); +var fs = require('fs'); +var request = require('request'); -var options = { method: 'POST', +var options = { + method: 'POST', url: 'http://mockbin.com/har', - headers: { 'content-type': 'multipart/form-data; boundary=---011000010111000001101001' }, - formData: - { foo: - { value: 'fs.createReadStream("test/fixtures/files/hello.txt")', - options: - { filename: 'test/fixtures/files/hello.txt', - contentType: 'text/plain' } } } }; + headers: { + 'content-type': 'multipart/form-data; boundary=---011000010111000001101001' + }, + formData: { + foo: { + value: 'fs.createReadStream("test/fixtures/files/hello.txt")', + options: { + filename: 'test/fixtures/files/hello.txt', + contentType: 'text/plain' + } + } + } +}; -request(options, function (error, response, body) { +request(options, function(error, response, body) { if (error) throw new Error(error); console.log(body); }); - diff --git a/packages/insomnia-httpsnippet/test/fixtures/output/node/request/multipart-form-data.js b/packages/insomnia-httpsnippet/test/fixtures/output/node/request/multipart-form-data.js index 45a2306572..1307b2f50b 100755 --- a/packages/insomnia-httpsnippet/test/fixtures/output/node/request/multipart-form-data.js +++ b/packages/insomnia-httpsnippet/test/fixtures/output/node/request/multipart-form-data.js @@ -1,13 +1,16 @@ -var request = require("request"); +var request = require('request'); -var options = { method: 'POST', +var options = { + method: 'POST', url: 'http://mockbin.com/har', - headers: { 'content-type': 'multipart/form-data; boundary=---011000010111000001101001' }, - formData: { foo: 'bar' } }; + headers: { + 'content-type': 'multipart/form-data; boundary=---011000010111000001101001' + }, + formData: { foo: 'bar' } +}; -request(options, function (error, response, body) { +request(options, function(error, response, body) { if (error) throw new Error(error); console.log(body); }); - diff --git a/packages/insomnia-httpsnippet/test/fixtures/output/node/request/query.js b/packages/insomnia-httpsnippet/test/fixtures/output/node/request/query.js index 73dc806d7d..6674c7ce14 100755 --- a/packages/insomnia-httpsnippet/test/fixtures/output/node/request/query.js +++ b/packages/insomnia-httpsnippet/test/fixtures/output/node/request/query.js @@ -1,12 +1,13 @@ -var request = require("request"); +var request = require('request'); -var options = { method: 'GET', +var options = { + method: 'GET', url: 'http://mockbin.com/har', - qs: { foo: [ 'bar', 'baz' ], baz: 'abc', key: 'value' } }; + qs: { foo: ['bar', 'baz'], baz: 'abc', key: 'value' } +}; -request(options, function (error, response, body) { +request(options, function(error, response, body) { if (error) throw new Error(error); console.log(body); }); - diff --git a/packages/insomnia-httpsnippet/test/fixtures/output/node/request/short.js b/packages/insomnia-httpsnippet/test/fixtures/output/node/request/short.js index 0bb35585be..04ccb1cd37 100755 --- a/packages/insomnia-httpsnippet/test/fixtures/output/node/request/short.js +++ b/packages/insomnia-httpsnippet/test/fixtures/output/node/request/short.js @@ -1,10 +1,9 @@ -var request = require("request"); +var request = require('request'); var options = { method: 'GET', url: 'http://mockbin.com/har' }; -request(options, function (error, response, body) { +request(options, function(error, response, body) { if (error) throw new Error(error); console.log(body); }); - diff --git a/packages/insomnia-httpsnippet/test/fixtures/output/node/request/text-plain.js b/packages/insomnia-httpsnippet/test/fixtures/output/node/request/text-plain.js index 359506daba..47aac183e8 100755 --- a/packages/insomnia-httpsnippet/test/fixtures/output/node/request/text-plain.js +++ b/packages/insomnia-httpsnippet/test/fixtures/output/node/request/text-plain.js @@ -1,13 +1,14 @@ -var request = require("request"); +var request = require('request'); -var options = { method: 'POST', +var options = { + method: 'POST', url: 'http://mockbin.com/har', headers: { 'content-type': 'text/plain' }, - body: 'Hello World' }; + body: 'Hello World' +}; -request(options, function (error, response, body) { +request(options, function(error, response, body) { if (error) throw new Error(error); console.log(body); }); - diff --git a/packages/insomnia-httpsnippet/test/fixtures/output/node/unirest/application-form-encoded.js b/packages/insomnia-httpsnippet/test/fixtures/output/node/unirest/application-form-encoded.js index 5f410768b3..a5a0ddaed2 100755 --- a/packages/insomnia-httpsnippet/test/fixtures/output/node/unirest/application-form-encoded.js +++ b/packages/insomnia-httpsnippet/test/fixtures/output/node/unirest/application-form-encoded.js @@ -1,19 +1,18 @@ -var unirest = require("unirest"); +var unirest = require('unirest'); -var req = unirest("POST", "http://mockbin.com/har"); +var req = unirest('POST', 'http://mockbin.com/har'); req.headers({ - "content-type": "application/x-www-form-urlencoded" + 'content-type': 'application/x-www-form-urlencoded' }); req.form({ - "foo": "bar", - "hello": "world" + foo: 'bar', + hello: 'world' }); -req.end(function (res) { +req.end(function(res) { if (res.error) throw new Error(res.error); console.log(res.body); }); - diff --git a/packages/insomnia-httpsnippet/test/fixtures/output/node/unirest/application-json.js b/packages/insomnia-httpsnippet/test/fixtures/output/node/unirest/application-json.js index ba8d8202a6..7672042edb 100755 --- a/packages/insomnia-httpsnippet/test/fixtures/output/node/unirest/application-json.js +++ b/packages/insomnia-httpsnippet/test/fixtures/output/node/unirest/application-json.js @@ -1,36 +1,31 @@ -var unirest = require("unirest"); +var unirest = require('unirest'); -var req = unirest("POST", "http://mockbin.com/har"); +var req = unirest('POST', 'http://mockbin.com/har'); req.headers({ - "content-type": "application/json" + 'content-type': 'application/json' }); -req.type("json"); +req.type('json'); req.send({ - "number": 1, - "string": "f\"oo", - "arr": [ - 1, - 2, - 3 - ], - "nested": { - "a": "b" + number: 1, + string: 'f"oo', + arr: [1, 2, 3], + nested: { + a: 'b' }, - "arr_mix": [ + arr_mix: [ 1, - "a", + 'a', { - "arr_mix_nested": {} + arr_mix_nested: {} } ], - "boolean": false + boolean: false }); -req.end(function (res) { +req.end(function(res) { if (res.error) throw new Error(res.error); console.log(res.body); }); - diff --git a/packages/insomnia-httpsnippet/test/fixtures/output/node/unirest/cookies.js b/packages/insomnia-httpsnippet/test/fixtures/output/node/unirest/cookies.js index 6d8d62d415..c266227171 100755 --- a/packages/insomnia-httpsnippet/test/fixtures/output/node/unirest/cookies.js +++ b/packages/insomnia-httpsnippet/test/fixtures/output/node/unirest/cookies.js @@ -1,16 +1,14 @@ -var unirest = require("unirest"); +var unirest = require('unirest'); -var req = unirest("POST", "http://mockbin.com/har"); +var req = unirest('POST', 'http://mockbin.com/har'); var CookieJar = unirest.jar(); -CookieJar.add("foo=bar","http://mockbin.com/har"); -CookieJar.add("bar=baz","http://mockbin.com/har"); +CookieJar.add('foo=bar', 'http://mockbin.com/har'); +CookieJar.add('bar=baz', 'http://mockbin.com/har'); req.jar(CookieJar); - -req.end(function (res) { +req.end(function(res) { if (res.error) throw new Error(res.error); console.log(res.body); }); - diff --git a/packages/insomnia-httpsnippet/test/fixtures/output/node/unirest/custom-method.js b/packages/insomnia-httpsnippet/test/fixtures/output/node/unirest/custom-method.js index 3e5bb5fa59..9f4979bcf8 100755 --- a/packages/insomnia-httpsnippet/test/fixtures/output/node/unirest/custom-method.js +++ b/packages/insomnia-httpsnippet/test/fixtures/output/node/unirest/custom-method.js @@ -1,11 +1,9 @@ -var unirest = require("unirest"); +var unirest = require('unirest'); -var req = unirest("PROPFIND", "http://mockbin.com/har"); +var req = unirest('PROPFIND', 'http://mockbin.com/har'); - -req.end(function (res) { +req.end(function(res) { if (res.error) throw new Error(res.error); console.log(res.body); }); - diff --git a/packages/insomnia-httpsnippet/test/fixtures/output/node/unirest/full.js b/packages/insomnia-httpsnippet/test/fixtures/output/node/unirest/full.js index 1a92d1fac9..5db656fdff 100755 --- a/packages/insomnia-httpsnippet/test/fixtures/output/node/unirest/full.js +++ b/packages/insomnia-httpsnippet/test/fixtures/output/node/unirest/full.js @@ -1,33 +1,29 @@ -var unirest = require("unirest"); +var unirest = require('unirest'); -var req = unirest("POST", "http://mockbin.com/har"); +var req = unirest('POST', 'http://mockbin.com/har'); var CookieJar = unirest.jar(); -CookieJar.add("foo=bar","http://mockbin.com/har"); -CookieJar.add("bar=baz","http://mockbin.com/har"); +CookieJar.add('foo=bar', 'http://mockbin.com/har'); +CookieJar.add('bar=baz', 'http://mockbin.com/har'); req.jar(CookieJar); req.query({ - "foo": [ - "bar", - "baz" - ], - "baz": "abc", - "key": "value" + foo: ['bar', 'baz'], + baz: 'abc', + key: 'value' }); req.headers({ - "content-type": "application/x-www-form-urlencoded", - "accept": "application/json" + 'content-type': 'application/x-www-form-urlencoded', + accept: 'application/json' }); req.form({ - "foo": "bar" + foo: 'bar' }); -req.end(function (res) { +req.end(function(res) { if (res.error) throw new Error(res.error); console.log(res.body); }); - diff --git a/packages/insomnia-httpsnippet/test/fixtures/output/node/unirest/headers.js b/packages/insomnia-httpsnippet/test/fixtures/output/node/unirest/headers.js index 9d8be3811f..14b841124c 100755 --- a/packages/insomnia-httpsnippet/test/fixtures/output/node/unirest/headers.js +++ b/packages/insomnia-httpsnippet/test/fixtures/output/node/unirest/headers.js @@ -1,16 +1,14 @@ -var unirest = require("unirest"); +var unirest = require('unirest'); -var req = unirest("GET", "http://mockbin.com/har"); +var req = unirest('GET', 'http://mockbin.com/har'); req.headers({ - "x-foo": "Bar", - "accept": "application/json" + 'x-foo': 'Bar', + accept: 'application/json' }); - -req.end(function (res) { +req.end(function(res) { if (res.error) throw new Error(res.error); console.log(res.body); }); - diff --git a/packages/insomnia-httpsnippet/test/fixtures/output/node/unirest/https.js b/packages/insomnia-httpsnippet/test/fixtures/output/node/unirest/https.js index ec5faf3379..59dbe6215a 100755 --- a/packages/insomnia-httpsnippet/test/fixtures/output/node/unirest/https.js +++ b/packages/insomnia-httpsnippet/test/fixtures/output/node/unirest/https.js @@ -1,11 +1,9 @@ -var unirest = require("unirest"); +var unirest = require('unirest'); -var req = unirest("GET", "https://mockbin.com/har"); +var req = unirest('GET', 'https://mockbin.com/har'); - -req.end(function (res) { +req.end(function(res) { if (res.error) throw new Error(res.error); console.log(res.body); }); - diff --git a/packages/insomnia-httpsnippet/test/fixtures/output/node/unirest/multipart-data.js b/packages/insomnia-httpsnippet/test/fixtures/output/node/unirest/multipart-data.js index bdf8da5153..72b186ad0e 100755 --- a/packages/insomnia-httpsnippet/test/fixtures/output/node/unirest/multipart-data.js +++ b/packages/insomnia-httpsnippet/test/fixtures/output/node/unirest/multipart-data.js @@ -1,21 +1,20 @@ -var unirest = require("unirest"); +var unirest = require('unirest'); -var req = unirest("POST", "http://mockbin.com/har"); +var req = unirest('POST', 'http://mockbin.com/har'); req.headers({ - "content-type": "multipart/form-data; boundary=---011000010111000001101001" + 'content-type': 'multipart/form-data; boundary=---011000010111000001101001' }); req.multipart([ { - "body": "Hello World", - "content-type": "text/plain" + body: 'Hello World', + 'content-type': 'text/plain' } ]); -req.end(function (res) { +req.end(function(res) { if (res.error) throw new Error(res.error); console.log(res.body); }); - diff --git a/packages/insomnia-httpsnippet/test/fixtures/output/node/unirest/multipart-file.js b/packages/insomnia-httpsnippet/test/fixtures/output/node/unirest/multipart-file.js index c8efe878af..bb9c9254f2 100755 --- a/packages/insomnia-httpsnippet/test/fixtures/output/node/unirest/multipart-file.js +++ b/packages/insomnia-httpsnippet/test/fixtures/output/node/unirest/multipart-file.js @@ -1,22 +1,21 @@ -var fs = require("fs"); -var unirest = require("unirest"); +var fs = require('fs'); +var unirest = require('unirest'); -var req = unirest("POST", "http://mockbin.com/har"); +var req = unirest('POST', 'http://mockbin.com/har'); req.headers({ - "content-type": "multipart/form-data; boundary=---011000010111000001101001" + 'content-type': 'multipart/form-data; boundary=---011000010111000001101001' }); req.multipart([ { - "body": fs.createReadStream("test/fixtures/files/hello.txt"), - "content-type": "text/plain" + body: fs.createReadStream('test/fixtures/files/hello.txt'), + 'content-type': 'text/plain' } ]); -req.end(function (res) { +req.end(function(res) { if (res.error) throw new Error(res.error); console.log(res.body); }); - diff --git a/packages/insomnia-httpsnippet/test/fixtures/output/node/unirest/multipart-form-data.js b/packages/insomnia-httpsnippet/test/fixtures/output/node/unirest/multipart-form-data.js index ea358a350f..6e1651435c 100755 --- a/packages/insomnia-httpsnippet/test/fixtures/output/node/unirest/multipart-form-data.js +++ b/packages/insomnia-httpsnippet/test/fixtures/output/node/unirest/multipart-form-data.js @@ -1,20 +1,19 @@ -var unirest = require("unirest"); +var unirest = require('unirest'); -var req = unirest("POST", "http://mockbin.com/har"); +var req = unirest('POST', 'http://mockbin.com/har'); req.headers({ - "content-type": "multipart/form-data; boundary=---011000010111000001101001" + 'content-type': 'multipart/form-data; boundary=---011000010111000001101001' }); req.multipart([ { - "body": "bar" + body: 'bar' } ]); -req.end(function (res) { +req.end(function(res) { if (res.error) throw new Error(res.error); console.log(res.body); }); - diff --git a/packages/insomnia-httpsnippet/test/fixtures/output/node/unirest/query.js b/packages/insomnia-httpsnippet/test/fixtures/output/node/unirest/query.js index 464e2f9414..ac93b8f85e 100755 --- a/packages/insomnia-httpsnippet/test/fixtures/output/node/unirest/query.js +++ b/packages/insomnia-httpsnippet/test/fixtures/output/node/unirest/query.js @@ -1,20 +1,15 @@ -var unirest = require("unirest"); +var unirest = require('unirest'); -var req = unirest("GET", "http://mockbin.com/har"); +var req = unirest('GET', 'http://mockbin.com/har'); req.query({ - "foo": [ - "bar", - "baz" - ], - "baz": "abc", - "key": "value" + foo: ['bar', 'baz'], + baz: 'abc', + key: 'value' }); - -req.end(function (res) { +req.end(function(res) { if (res.error) throw new Error(res.error); console.log(res.body); }); - diff --git a/packages/insomnia-httpsnippet/test/fixtures/output/node/unirest/short.js b/packages/insomnia-httpsnippet/test/fixtures/output/node/unirest/short.js index 95a778b521..1255eb21ca 100755 --- a/packages/insomnia-httpsnippet/test/fixtures/output/node/unirest/short.js +++ b/packages/insomnia-httpsnippet/test/fixtures/output/node/unirest/short.js @@ -1,11 +1,9 @@ -var unirest = require("unirest"); +var unirest = require('unirest'); -var req = unirest("GET", "http://mockbin.com/har"); +var req = unirest('GET', 'http://mockbin.com/har'); - -req.end(function (res) { +req.end(function(res) { if (res.error) throw new Error(res.error); console.log(res.body); }); - diff --git a/packages/insomnia-httpsnippet/test/fixtures/output/node/unirest/text-plain.js b/packages/insomnia-httpsnippet/test/fixtures/output/node/unirest/text-plain.js index bffa7ee03d..7b73ba2271 100755 --- a/packages/insomnia-httpsnippet/test/fixtures/output/node/unirest/text-plain.js +++ b/packages/insomnia-httpsnippet/test/fixtures/output/node/unirest/text-plain.js @@ -1,16 +1,15 @@ -var unirest = require("unirest"); +var unirest = require('unirest'); -var req = unirest("POST", "http://mockbin.com/har"); +var req = unirest('POST', 'http://mockbin.com/har'); req.headers({ - "content-type": "text/plain" + 'content-type': 'text/plain' }); - req.send("Hello World"); +req.send('Hello World'); -req.end(function (res) { +req.end(function(res) { if (res.error) throw new Error(res.error); console.log(res.body); }); - diff --git a/packages/insomnia-httpsnippet/test/index.js b/packages/insomnia-httpsnippet/test/index.js index 62a8371648..8205292190 100755 --- a/packages/insomnia-httpsnippet/test/index.js +++ b/packages/insomnia-httpsnippet/test/index.js @@ -1,116 +1,122 @@ /* global describe, it */ -'use strict' +'use strict'; -var fixtures = require('./fixtures') -var HTTPSnippet = require('../src') +var fixtures = require('./fixtures'); +var HTTPSnippet = require('../src'); -var should = require('should') +var should = require('should'); -describe('HTTPSnippet', function () { - it('should return false if no matching target', function (done) { - var snippet = new HTTPSnippet(fixtures.requests.short) +describe('HTTPSnippet', function() { + it('should return false if no matching target', function(done) { + var snippet = new HTTPSnippet(fixtures.requests.short); - snippet.convert(null).should.eql(false) + snippet.convert(null).should.eql(false); - done() - }) + done(); + }); - it('should fail validation', function (done) { + it('should fail validation', function(done) { var snippet; /* eslint-disable no-extra-parens */ - (function () { - snippet = new HTTPSnippet({yolo: 'foo'}) - }).should.throw(Error) + (function() { + snippet = new HTTPSnippet({ yolo: 'foo' }); + }.should.throw(Error)); - should.not.exist(snippet) + should.not.exist(snippet); - done() - }) + done(); + }); - it('should parse HAR file with multiple entries', function (done) { - var snippet = new HTTPSnippet(fixtures.har) + it('should parse HAR file with multiple entries', function(done) { + var snippet = new HTTPSnippet(fixtures.har); - snippet.should.have.property('requests').and.be.an.Array - snippet.requests.length.should.equal(2) + snippet.should.have.property('requests').and.be.an.Array; + snippet.requests.length.should.equal(2); - var results = snippet.convert('shell') + var results = snippet.convert('shell'); - results.should.be.an.Array - results.length.should.equal(2) + results.should.be.an.Array; + results.length.should.equal(2); - done() - }) + done(); + }); - it('should convert multipart/mixed to multipart/form-data', function (done) { - var req = new HTTPSnippet(fixtures.mimetypes['multipart/mixed']).requests[0] + it('should convert multipart/mixed to multipart/form-data', function(done) { + var req = new HTTPSnippet(fixtures.mimetypes['multipart/mixed']) + .requests[0]; - req.postData.mimeType.should.eql('multipart/form-data') + req.postData.mimeType.should.eql('multipart/form-data'); - done() - }) + done(); + }); - it('should convert multipart/related to multipart/form-data', function (done) { - var req = new HTTPSnippet(fixtures.mimetypes['multipart/related']).requests[0] + it('should convert multipart/related to multipart/form-data', function(done) { + var req = new HTTPSnippet(fixtures.mimetypes['multipart/related']) + .requests[0]; - req.postData.mimeType.should.eql('multipart/form-data') + req.postData.mimeType.should.eql('multipart/form-data'); - done() - }) + done(); + }); - it('should convert multipart/alternative to multipart/form-data', function (done) { - var req = new HTTPSnippet(fixtures.mimetypes['multipart/alternative']).requests[0] + it('should convert multipart/alternative to multipart/form-data', function(done) { + var req = new HTTPSnippet(fixtures.mimetypes['multipart/alternative']) + .requests[0]; - req.postData.mimeType.should.eql('multipart/form-data') + req.postData.mimeType.should.eql('multipart/form-data'); - done() - }) + done(); + }); - it('should convert text/json to application/json', function (done) { - var req = new HTTPSnippet(fixtures.mimetypes['text/json']).requests[0] + it('should convert text/json to application/json', function(done) { + var req = new HTTPSnippet(fixtures.mimetypes['text/json']).requests[0]; - req.postData.mimeType.should.eql('application/json') + req.postData.mimeType.should.eql('application/json'); - done() - }) + done(); + }); - it('should convert text/x-json to application/json', function (done) { - var req = new HTTPSnippet(fixtures.mimetypes['text/x-json']).requests[0] + it('should convert text/x-json to application/json', function(done) { + var req = new HTTPSnippet(fixtures.mimetypes['text/x-json']).requests[0]; - req.postData.mimeType.should.eql('application/json') + req.postData.mimeType.should.eql('application/json'); - done() - }) + done(); + }); - it('should convert application/x-json to application/json', function (done) { - var req = new HTTPSnippet(fixtures.mimetypes['application/x-json']).requests[0] + it('should convert application/x-json to application/json', function(done) { + var req = new HTTPSnippet(fixtures.mimetypes['application/x-json']) + .requests[0]; - req.postData.mimeType.should.eql('application/json') + req.postData.mimeType.should.eql('application/json'); - done() - }) + done(); + }); - it('should gracefully fallback if not able to parse JSON', function (done) { - var req = new HTTPSnippet(fixtures.mimetypes['invalid-json']).requests[0] + it('should gracefully fallback if not able to parse JSON', function(done) { + var req = new HTTPSnippet(fixtures.mimetypes['invalid-json']).requests[0]; - req.postData.mimeType.should.eql('text/plain') + req.postData.mimeType.should.eql('text/plain'); - done() - }) + done(); + }); - it('should set postData.text = empty string when postData.params === undefined in application/x-www-form-urlencoded', function (done) { - var req = new HTTPSnippet(fixtures.mimetypes['application/x-www-form-urlencoded']).requests[0] + it('should set postData.text = empty string when postData.params === undefined in application/x-www-form-urlencoded', function(done) { + var req = new HTTPSnippet( + fixtures.mimetypes['application/x-www-form-urlencoded'] + ).requests[0]; - req.postData.text.should.eql('') + req.postData.text.should.eql(''); - done() - }) + done(); + }); - it('should add "uriObj" to source object', function (done) { - var req = new HTTPSnippet(fixtures.requests.query).requests[0] + it('should add "uriObj" to source object', function(done) { + var req = new HTTPSnippet(fixtures.requests.query).requests[0]; - req.uriObj.should.be.an.Object + req.uriObj.should.be.an.Object; req.uriObj.should.eql({ auth: null, hash: null, @@ -124,70 +130,66 @@ describe('HTTPSnippet', function () { query: { baz: 'abc', key: 'value', - foo: [ - 'bar', - 'baz' - ] + foo: ['bar', 'baz'] }, search: 'foo=bar&foo=baz&baz=abc&key=value', slashes: true - }) + }); - done() - }) + done(); + }); - it('should add "queryObj" to source object', function (done) { - var req = new HTTPSnippet(fixtures.requests.query).requests[0] + it('should add "queryObj" to source object', function(done) { + var req = new HTTPSnippet(fixtures.requests.query).requests[0]; - req.queryObj.should.be.an.Object + req.queryObj.should.be.an.Object; req.queryObj.should.eql({ baz: 'abc', key: 'value', - foo: [ - 'bar', - 'baz' - ] - }) + foo: ['bar', 'baz'] + }); - done() - }) + done(); + }); - it('should add "headersObj" to source object', function (done) { - var req = new HTTPSnippet(fixtures.requests.headers).requests[0] + it('should add "headersObj" to source object', function(done) { + var req = new HTTPSnippet(fixtures.requests.headers).requests[0]; - req.headersObj.should.be.an.Object + req.headersObj.should.be.an.Object; req.headersObj.should.eql({ - 'accept': 'application/json', + accept: 'application/json', 'x-foo': 'Bar' - }) + }); - done() - }) + done(); + }); - it('should modify orignal url to strip query string', function (done) { - var req = new HTTPSnippet(fixtures.requests.query).requests[0] + it('should modify orignal url to strip query string', function(done) { + var req = new HTTPSnippet(fixtures.requests.query).requests[0]; - req.url.should.be.a.String - req.url.should.eql('http://mockbin.com/har') + req.url.should.be.a.String; + req.url.should.eql('http://mockbin.com/har'); - done() - }) + done(); + }); - it('should add "fullUrl" to source object', function (done) { - var req = new HTTPSnippet(fixtures.requests.query).requests[0] + it('should add "fullUrl" to source object', function(done) { + var req = new HTTPSnippet(fixtures.requests.query).requests[0]; - req.fullUrl.should.be.a.String - req.fullUrl.should.eql('http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value') + req.fullUrl.should.be.a.String; + req.fullUrl.should.eql( + 'http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value' + ); - done() - }) + done(); + }); - it('should fix "path" property of "uriObj" to match queryString', function (done) { - var req = new HTTPSnippet(fixtures.requests.query).requests[0] + it('should fix "path" property of "uriObj" to match queryString', function(done) { + var req = new HTTPSnippet(fixtures.requests.query).requests[0]; - req.uriObj.path.should.be.a.String - req.uriObj.path.should.eql('/har?foo=bar&foo=baz&baz=abc&key=value') + req.uriObj.path.should.be.a.String; + req.uriObj.path.should.eql('/har?foo=bar&foo=baz&baz=abc&key=value'); - done() - }) -}) + done(); + }); +}); diff --git a/packages/insomnia-httpsnippet/test/reducer.js b/packages/insomnia-httpsnippet/test/reducer.js index 2bbbbedd86..6baae996c3 100755 --- a/packages/insomnia-httpsnippet/test/reducer.js +++ b/packages/insomnia-httpsnippet/test/reducer.js @@ -1,38 +1,38 @@ /* global describe, it */ -'use strict' +'use strict'; -var reducer = require('../src/helpers/reducer') +var reducer = require('../src/helpers/reducer'); -require('should') +require('should'); -describe('Reducer', function () { - it('should convert array object pair to key-value object', function (done) { +describe('Reducer', function() { + it('should convert array object pair to key-value object', function(done) { var query = [ - {name: 'key', value: 'value'}, - {name: 'foo', value: 'bar'} - ] + { name: 'key', value: 'value' }, + { name: 'foo', value: 'bar' } + ]; - var obj = query.reduce(reducer, {}) + var obj = query.reduce(reducer, {}); - obj.should.be.an.Object - obj.should.eql({key: 'value', foo: 'bar'}) + obj.should.be.an.Object; + obj.should.eql({ key: 'value', foo: 'bar' }); - done() - }) + done(); + }); - it('should convert multi-dimensional arrays to key=[array] object', function (done) { + it('should convert multi-dimensional arrays to key=[array] object', function(done) { var query = [ - {name: 'key', value: 'value'}, - {name: 'foo', value: 'bar1'}, - {name: 'foo', value: 'bar2'} - ] + { name: 'key', value: 'value' }, + { name: 'foo', value: 'bar1' }, + { name: 'foo', value: 'bar2' } + ]; - var obj = query.reduce(reducer, {}) + var obj = query.reduce(reducer, {}); - obj.should.be.an.Object - obj.should.eql({key: 'value', foo: ['bar1', 'bar2']}) + obj.should.be.an.Object; + obj.should.eql({ key: 'value', foo: ['bar1', 'bar2'] }); - done() - }) -}) + done(); + }); +}); diff --git a/packages/insomnia-httpsnippet/test/requests.js b/packages/insomnia-httpsnippet/test/requests.js index ae3abb9302..c8ba43e47c 100755 --- a/packages/insomnia-httpsnippet/test/requests.js +++ b/packages/insomnia-httpsnippet/test/requests.js @@ -1,17 +1,18 @@ /* global describe, it */ -'use strict' +'use strict'; -var fixtures = require('./fixtures') -var HTTPSnippet = require('../src') -var targets = require('../src/targets') -var shell = require('child_process') -var util = require('util') +var fixtures = require('./fixtures'); +var HTTPSnippet = require('../src'); +var targets = require('../src/targets'); +var shell = require('child_process'); +var util = require('util'); -require('should') +require('should'); -var base = './test/fixtures/output/' -var requests = [ 'application-form-encoded', +var base = './test/fixtures/output/'; +var requests = [ + 'application-form-encoded', 'application-json', 'cookies', 'custom-method', @@ -20,49 +21,65 @@ var requests = [ 'application-form-encoded', 'multipart-data', 'multipart-form-data', 'short' -] +]; // test all the things! -fixtures.cli.forEach(function (cli) { - describe(targets[cli.target].info.title + ' Request Validation', function () { - cli.clients.forEach(function (client) { - requests.forEach(function (request) { - it(client + ' request should match mock for ' + request, function (done) { - var stdout = '' - var fixture = cli.target + '/' + client + '/' + request + HTTPSnippet.extname(cli.target) - var command = util.format(cli.run, base + fixture) +fixtures.cli.forEach(function(cli) { + describe(targets[cli.target].info.title + ' Request Validation', function() { + cli.clients.forEach(function(client) { + requests.forEach(function(request) { + it(client + ' request should match mock for ' + request, function( + done + ) { + var stdout = ''; + var fixture = + cli.target + + '/' + + client + + '/' + + request + + HTTPSnippet.extname(cli.target); + var command = util.format(cli.run, base + fixture); - var ls = shell.exec(command) + var ls = shell.exec(command); - ls.stdout.on('data', function (data) { - stdout += data - }) + ls.stdout.on('data', function(data) { + stdout += data; + }); - ls.on('exit', function (code) { + ls.on('exit', function(code) { try { - var har = JSON.parse(stdout) + var har = JSON.parse(stdout); } catch (err) { - err.should.be.null + err.should.be.null; } // make an exception for multipart/form-data if (fixtures.requests[request].headers) { - fixtures.requests[request].headers.forEach(function (header, index) { - if (header.name === 'content-type' && header.value === 'multipart/form-data') { - delete fixtures.requests[request].headers[index] + fixtures.requests[request].headers.forEach(function( + header, + index + ) { + if ( + header.name === 'content-type' && + header.value === 'multipart/form-data' + ) { + delete fixtures.requests[request].headers[index]; } - }) + }); } - har.should.have.property('log') - har.log.should.have.property('entries').and.be.Array - har.log.entries[0].should.have.property('request') - har.log.entries[0].request.should.containDeep(fixtures.requests[request]) + har.should.have.property('log'); + har.log.should.have.property('entries').and.be.Array; + har.log.entries[0].should.have.property('request'); + har.log.entries[0].request.should.containDeep( + fixtures.requests[request] + ); - done() - }) - }) - }) - }) - }) -}) + done(); + }); + }); + }); + }); + }); +}); diff --git a/packages/insomnia-httpsnippet/test/targets.js b/packages/insomnia-httpsnippet/test/targets.js index be1aa0dde2..e7f1840c22 100755 --- a/packages/insomnia-httpsnippet/test/targets.js +++ b/packages/insomnia-httpsnippet/test/targets.js @@ -1,102 +1,126 @@ /* global describe, it */ -'use strict' +'use strict'; -var fixtures = require('./fixtures') -var fs = require('fs') -var glob = require('glob') -var HTTPSnippet = require('../src') -var path = require('path') -var should = require('should') -var targets = require('../src/targets') +var fixtures = require('./fixtures'); +var fs = require('fs'); +var glob = require('glob'); +var HTTPSnippet = require('../src'); +var path = require('path'); +var should = require('should'); +var targets = require('../src/targets'); -var base = './test/fixtures/output/' +var base = './test/fixtures/output/'; // read all output files -var output = glob.sync('**/*', {cwd: base, nodir: true}).reduce(function (obj, name) { - obj[name] = fs.readFileSync(base + name) - return obj -}, {}) +var output = glob + .sync('**/*', { cwd: base, nodir: true }) + .reduce(function(obj, name) { + obj[name] = fs.readFileSync(base + name); + return obj; + }, {}); -var clearInfo = function (key) { - return !~['info', 'index'].indexOf(key) -} +var clearInfo = function(key) { + return !~['info', 'index'].indexOf(key); +}; -var itShouldHaveTests = function (target, client) { - it(target + ' should have tests', function (done) { - fs.readdir(path.join(__dirname, 'targets', target), function (err, files) { - should.not.exist(err) - files.length.should.be.above(0) - files.should.containEql(client + '.js') - done() - }) - }) -} +var itShouldHaveTests = function(target, client) { + it(target + ' should have tests', function(done) { + fs.readdir(path.join(__dirname, 'targets', target), function(err, files) { + should.not.exist(err); + files.length.should.be.above(0); + files.should.containEql(client + '.js'); + done(); + }); + }); +}; -var itShouldHaveInfo = function (name, obj) { - it(name + ' should have info method', function () { - obj.should.have.property('info').and.be.an.Object - obj.info.key.should.equal(name).and.be.a.String - obj.info.title.should.be.a.String - }) -} +var itShouldHaveInfo = function(name, obj) { + it(name + ' should have info method', function() { + obj.should.have.property('info').and.be.an.Object; + obj.info.key.should.equal(name).and.be.a.String; + obj.info.title.should.be.a.String; + }); +}; -var itShouldHaveRequestTestOutputFixture = function (request, target, path) { - var fixture = target + '/' + path + request + HTTPSnippet.extname(target) +var itShouldHaveRequestTestOutputFixture = function(request, target, path) { + var fixture = target + '/' + path + request + HTTPSnippet.extname(target); - it('should have output test for ' + request, function () { - Object.keys(output).indexOf(fixture).should.be.greaterThan(-1, 'Missing ' + fixture + ' fixture file for target: ' + target + '. Snippet tests will be skipped.') - }) -} + it('should have output test for ' + request, function() { + Object.keys(output) + .indexOf(fixture) + .should.be.greaterThan( + -1, + 'Missing ' + + fixture + + ' fixture file for target: ' + + target + + '. Snippet tests will be skipped.' + ); + }); +}; -var itShouldGenerateOutput = function (request, path, target, client) { - var fixture = path + request + HTTPSnippet.extname(target) +var itShouldGenerateOutput = function(request, path, target, client) { + var fixture = path + request + HTTPSnippet.extname(target); - it('should generate ' + request + ' snippet', function () { + it('should generate ' + request + ' snippet', function() { if (Object.keys(output).indexOf(fixture) === -1) { - this.skip() + this.skip(); } - var instance = new HTTPSnippet(fixtures.requests[request]) - var result = instance.convert(target, client) + '\n' + var instance = new HTTPSnippet(fixtures.requests[request]); + var result = instance.convert(target, client) + '\n'; - result.should.be.a.String - result.should.equal(output[fixture].toString()) - }) -} + result.should.be.a.String; + result.should.equal(output[fixture].toString()); + }); +}; -describe('Available Targets', function () { - var targets = HTTPSnippet.availableTargets() +describe('Available Targets', function() { + var targets = HTTPSnippet.availableTargets(); - targets.forEach(function (target) { - it('available-targets.json should include ' + target.title, function () { - fixtures['available-targets'].should.containEql(target) - }) - }) -}) + targets.forEach(function(target) { + it('available-targets.json should include ' + target.title, function() { + fixtures['available-targets'].should.containEql(target); + }); + }); +}); // test all the things! -Object.keys(targets).forEach(function (target) { - describe(targets[target].info.title, function () { - itShouldHaveInfo(target, targets[target]) +Object.keys(targets).forEach(function(target) { + describe(targets[target].info.title, function() { + itShouldHaveInfo(target, targets[target]); - Object.keys(targets[target]).filter(clearInfo).forEach(function (client) { - describe(client, function () { - itShouldHaveInfo(client, targets[target][client]) + Object.keys(targets[target]) + .filter(clearInfo) + .forEach(function(client) { + describe(client, function() { + itShouldHaveInfo(client, targets[target][client]); - itShouldHaveTests(target, client) + itShouldHaveTests(target, client); - var test = require(path.join(__dirname, 'targets', target, client)) + var test = require(path.join(__dirname, 'targets', target, client)); - test(HTTPSnippet, fixtures) + test(HTTPSnippet, fixtures); - describe('snippets', function () { - Object.keys(fixtures.requests).filter(clearInfo).forEach(function (request) { - itShouldHaveRequestTestOutputFixture(request, target, client + '/') + describe('snippets', function() { + Object.keys(fixtures.requests) + .filter(clearInfo) + .forEach(function(request) { + itShouldHaveRequestTestOutputFixture( + request, + target, + client + '/' + ); - itShouldGenerateOutput(request, target + '/' + client + '/', target, client) - }) - }) - }) - }) - }) -}) + itShouldGenerateOutput( + request, + target + '/' + client + '/', + target, + client + ); + }); + }); + }); + }); + }); +}); diff --git a/packages/insomnia-httpsnippet/test/targets/c/libcurl.js b/packages/insomnia-httpsnippet/test/targets/c/libcurl.js index 9ad8c1790d..a8d3935d26 100755 --- a/packages/insomnia-httpsnippet/test/targets/c/libcurl.js +++ b/packages/insomnia-httpsnippet/test/targets/c/libcurl.js @@ -1,5 +1,5 @@ -'use strict' +'use strict'; -require('should') +require('should'); -module.exports = function (snippet, fixtures) {} +module.exports = function(snippet, fixtures) {}; diff --git a/packages/insomnia-httpsnippet/test/targets/csharp/restsharp.js b/packages/insomnia-httpsnippet/test/targets/csharp/restsharp.js index 9ad8c1790d..a8d3935d26 100755 --- a/packages/insomnia-httpsnippet/test/targets/csharp/restsharp.js +++ b/packages/insomnia-httpsnippet/test/targets/csharp/restsharp.js @@ -1,5 +1,5 @@ -'use strict' +'use strict'; -require('should') +require('should'); -module.exports = function (snippet, fixtures) {} +module.exports = function(snippet, fixtures) {}; diff --git a/packages/insomnia-httpsnippet/test/targets/go/native.js b/packages/insomnia-httpsnippet/test/targets/go/native.js index a2afafcf54..477e638f98 100755 --- a/packages/insomnia-httpsnippet/test/targets/go/native.js +++ b/packages/insomnia-httpsnippet/test/targets/go/native.js @@ -1,40 +1,64 @@ /* global it */ -'use strict' +'use strict'; -require('should') +require('should'); -module.exports = function (HTTPSnippet, fixtures) { - it('should support false boilerplate option', function () { - var result = new HTTPSnippet(fixtures.requests.full).convert('go', 'native', { - showBoilerplate: false - }) +module.exports = function(HTTPSnippet, fixtures) { + it('should support false boilerplate option', function() { + var result = new HTTPSnippet(fixtures.requests.full).convert( + 'go', + 'native', + { + showBoilerplate: false + } + ); - result.should.be.a.String - result.should.eql('url := \"http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value\"\n\npayload := strings.NewReader(\"foo=bar\")\n\nreq, _ := http.NewRequest(\"POST\", url, payload)\n\nreq.Header.Add(\"cookie\", \"foo=bar; bar=baz\")\nreq.Header.Add(\"accept\", \"application/json\")\nreq.Header.Add(\"content-type\", \"application/x-www-form-urlencoded\")\n\nres, _ := http.DefaultClient.Do(req)\n\ndefer res.Body.Close()\nbody, _ := ioutil.ReadAll(res.Body)\n\nfmt.Println(res)\nfmt.Println(string(body))') - }) - it('should support checkErrors option', function () { - var result = new HTTPSnippet(fixtures.requests.full).convert('go', 'native', { - checkErrors: true - }) + result.should.be.a.String; + result.should.eql( + 'url := "http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value"\n\npayload := strings.NewReader("foo=bar")\n\nreq, _ := http.NewRequest("POST", url, payload)\n\nreq.Header.Add("cookie", "foo=bar; bar=baz")\nreq.Header.Add("accept", "application/json")\nreq.Header.Add("content-type", "application/x-www-form-urlencoded")\n\nres, _ := http.DefaultClient.Do(req)\n\ndefer res.Body.Close()\nbody, _ := ioutil.ReadAll(res.Body)\n\nfmt.Println(res)\nfmt.Println(string(body))' + ); + }); + it('should support checkErrors option', function() { + var result = new HTTPSnippet(fixtures.requests.full).convert( + 'go', + 'native', + { + checkErrors: true + } + ); - result.should.be.a.String - result.should.eql('package main\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"net/http\"\n\t\"io/ioutil\"\n)\n\nfunc main() {\n\n\turl := \"http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value\"\n\n\tpayload := strings.NewReader(\"foo=bar\")\n\n\treq, err := http.NewRequest(\"POST\", url, payload)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treq.Header.Add(\"cookie\", \"foo=bar; bar=baz\")\n\treq.Header.Add(\"accept\", \"application/json\")\n\treq.Header.Add(\"content-type\", \"application/x-www-form-urlencoded\")\n\n\tres, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tdefer res.Body.Close()\n\tbody, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tfmt.Println(res)\n\tfmt.Println(string(body))\n\n}') - }) - it('should support printBody option', function () { - var result = new HTTPSnippet(fixtures.requests.full).convert('go', 'native', { - printBody: false - }) + result.should.be.a.String; + result.should.eql( + 'package main\n\nimport (\n\t"fmt"\n\t"strings"\n\t"net/http"\n\t"io/ioutil"\n)\n\nfunc main() {\n\n\turl := "http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value"\n\n\tpayload := strings.NewReader("foo=bar")\n\n\treq, err := http.NewRequest("POST", url, payload)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treq.Header.Add("cookie", "foo=bar; bar=baz")\n\treq.Header.Add("accept", "application/json")\n\treq.Header.Add("content-type", "application/x-www-form-urlencoded")\n\n\tres, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tdefer res.Body.Close()\n\tbody, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tfmt.Println(res)\n\tfmt.Println(string(body))\n\n}' + ); + }); + it('should support printBody option', function() { + var result = new HTTPSnippet(fixtures.requests.full).convert( + 'go', + 'native', + { + printBody: false + } + ); - result.should.be.a.String - result.should.eql('package main\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\t\"net/http\"\n)\n\nfunc main() {\n\n\turl := \"http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value\"\n\n\tpayload := strings.NewReader(\"foo=bar\")\n\n\treq, _ := http.NewRequest(\"POST\", url, payload)\n\n\treq.Header.Add(\"cookie\", \"foo=bar; bar=baz\")\n\treq.Header.Add(\"accept\", \"application/json\")\n\treq.Header.Add(\"content-type\", \"application/x-www-form-urlencoded\")\n\n\tres, _ := http.DefaultClient.Do(req)\n\n\tfmt.Println(res)\n\n}') - }) - it('should support timeout option', function () { - var result = new HTTPSnippet(fixtures.requests.full).convert('go', 'native', { - timeout: 30 - }) + result.should.be.a.String; + result.should.eql( + 'package main\n\nimport (\n\t"fmt"\n\t"strings"\n\t"net/http"\n)\n\nfunc main() {\n\n\turl := "http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value"\n\n\tpayload := strings.NewReader("foo=bar")\n\n\treq, _ := http.NewRequest("POST", url, payload)\n\n\treq.Header.Add("cookie", "foo=bar; bar=baz")\n\treq.Header.Add("accept", "application/json")\n\treq.Header.Add("content-type", "application/x-www-form-urlencoded")\n\n\tres, _ := http.DefaultClient.Do(req)\n\n\tfmt.Println(res)\n\n}' + ); + }); + it('should support timeout option', function() { + var result = new HTTPSnippet(fixtures.requests.full).convert( + 'go', + 'native', + { + timeout: 30 + } + ); - result.should.be.a.String - result.should.eql('package main\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\t\"strings\"\n\t\"net/http\"\n\t\"io/ioutil\"\n)\n\nfunc main() {\n\n\tclient := http.Client{\n\t\tTimeout: time.Duration(30 * time.Second),\n\t}\n\n\turl := \"http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value\"\n\n\tpayload := strings.NewReader(\"foo=bar\")\n\n\treq, _ := http.NewRequest(\"POST\", url, payload)\n\n\treq.Header.Add(\"cookie\", \"foo=bar; bar=baz\")\n\treq.Header.Add(\"accept\", \"application/json\")\n\treq.Header.Add(\"content-type\", \"application/x-www-form-urlencoded\")\n\n\tres, _ := client.Do(req)\n\n\tdefer res.Body.Close()\n\tbody, _ := ioutil.ReadAll(res.Body)\n\n\tfmt.Println(res)\n\tfmt.Println(string(body))\n\n}') - }) -} + result.should.be.a.String; + result.should.eql( + 'package main\n\nimport (\n\t"fmt"\n\t"time"\n\t"strings"\n\t"net/http"\n\t"io/ioutil"\n)\n\nfunc main() {\n\n\tclient := http.Client{\n\t\tTimeout: time.Duration(30 * time.Second),\n\t}\n\n\turl := "http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value"\n\n\tpayload := strings.NewReader("foo=bar")\n\n\treq, _ := http.NewRequest("POST", url, payload)\n\n\treq.Header.Add("cookie", "foo=bar; bar=baz")\n\treq.Header.Add("accept", "application/json")\n\treq.Header.Add("content-type", "application/x-www-form-urlencoded")\n\n\tres, _ := client.Do(req)\n\n\tdefer res.Body.Close()\n\tbody, _ := ioutil.ReadAll(res.Body)\n\n\tfmt.Println(res)\n\tfmt.Println(string(body))\n\n}' + ); + }); +}; diff --git a/packages/insomnia-httpsnippet/test/targets/java/okhttp.js b/packages/insomnia-httpsnippet/test/targets/java/okhttp.js index 9ad8c1790d..a8d3935d26 100755 --- a/packages/insomnia-httpsnippet/test/targets/java/okhttp.js +++ b/packages/insomnia-httpsnippet/test/targets/java/okhttp.js @@ -1,5 +1,5 @@ -'use strict' +'use strict'; -require('should') +require('should'); -module.exports = function (snippet, fixtures) {} +module.exports = function(snippet, fixtures) {}; diff --git a/packages/insomnia-httpsnippet/test/targets/java/unirest.js b/packages/insomnia-httpsnippet/test/targets/java/unirest.js index 9ad8c1790d..a8d3935d26 100755 --- a/packages/insomnia-httpsnippet/test/targets/java/unirest.js +++ b/packages/insomnia-httpsnippet/test/targets/java/unirest.js @@ -1,5 +1,5 @@ -'use strict' +'use strict'; -require('should') +require('should'); -module.exports = function (snippet, fixtures) {} +module.exports = function(snippet, fixtures) {}; diff --git a/packages/insomnia-httpsnippet/test/targets/javascript/jquery.js b/packages/insomnia-httpsnippet/test/targets/javascript/jquery.js index b77cc77e7c..3dc1cbe56d 100755 --- a/packages/insomnia-httpsnippet/test/targets/javascript/jquery.js +++ b/packages/insomnia-httpsnippet/test/targets/javascript/jquery.js @@ -1,3 +1,3 @@ -'use strict' +'use strict'; -module.exports = function (snippet, fixtures) {} +module.exports = function(snippet, fixtures) {}; diff --git a/packages/insomnia-httpsnippet/test/targets/javascript/xhr.js b/packages/insomnia-httpsnippet/test/targets/javascript/xhr.js index a4ff8528dd..c3ab3a4b30 100755 --- a/packages/insomnia-httpsnippet/test/targets/javascript/xhr.js +++ b/packages/insomnia-httpsnippet/test/targets/javascript/xhr.js @@ -1,16 +1,24 @@ /* global it */ -'use strict' +'use strict'; -require('should') +require('should'); -module.exports = function (HTTPSnippet, fixtures) { - it('should not use cors', function () { - var result = new HTTPSnippet(fixtures.requests.short).convert('javascript', 'xhr', { - cors: false - }) +module.exports = function(HTTPSnippet, fixtures) { + it('should not use cors', function() { + var result = new HTTPSnippet(fixtures.requests.short).convert( + 'javascript', + 'xhr', + { + cors: false + } + ); - result.should.be.a.String - result.replace(/\n/g, '').should.eql('var data = null;var xhr = new XMLHttpRequest();xhr.addEventListener("readystatechange", function () { if (this.readyState === this.DONE) { console.log(this.responseText); }});xhr.open("GET", "http://mockbin.com/har");xhr.send(data);') - }) -} + result.should.be.a.String; + result + .replace(/\n/g, '') + .should.eql( + 'var data = null;var xhr = new XMLHttpRequest();xhr.addEventListener("readystatechange", function () { if (this.readyState === this.DONE) { console.log(this.responseText); }});xhr.open("GET", "http://mockbin.com/har");xhr.send(data);' + ); + }); +}; diff --git a/packages/insomnia-httpsnippet/test/targets/node/native.js b/packages/insomnia-httpsnippet/test/targets/node/native.js index b77cc77e7c..3dc1cbe56d 100755 --- a/packages/insomnia-httpsnippet/test/targets/node/native.js +++ b/packages/insomnia-httpsnippet/test/targets/node/native.js @@ -1,3 +1,3 @@ -'use strict' +'use strict'; -module.exports = function (snippet, fixtures) {} +module.exports = function(snippet, fixtures) {}; diff --git a/packages/insomnia-httpsnippet/test/targets/node/request.js b/packages/insomnia-httpsnippet/test/targets/node/request.js index b77cc77e7c..3dc1cbe56d 100755 --- a/packages/insomnia-httpsnippet/test/targets/node/request.js +++ b/packages/insomnia-httpsnippet/test/targets/node/request.js @@ -1,3 +1,3 @@ -'use strict' +'use strict'; -module.exports = function (snippet, fixtures) {} +module.exports = function(snippet, fixtures) {}; diff --git a/packages/insomnia-httpsnippet/test/targets/node/unirest.js b/packages/insomnia-httpsnippet/test/targets/node/unirest.js index b77cc77e7c..3dc1cbe56d 100755 --- a/packages/insomnia-httpsnippet/test/targets/node/unirest.js +++ b/packages/insomnia-httpsnippet/test/targets/node/unirest.js @@ -1,3 +1,3 @@ -'use strict' +'use strict'; -module.exports = function (snippet, fixtures) {} +module.exports = function(snippet, fixtures) {}; diff --git a/packages/insomnia-httpsnippet/test/targets/objc/nsurlsession.js b/packages/insomnia-httpsnippet/test/targets/objc/nsurlsession.js index 011e0149ea..a0378d1e39 100755 --- a/packages/insomnia-httpsnippet/test/targets/objc/nsurlsession.js +++ b/packages/insomnia-httpsnippet/test/targets/objc/nsurlsession.js @@ -1,32 +1,44 @@ /* global it */ -'use strict' +'use strict'; -require('should') +require('should'); -module.exports = function (HTTPSnippet, fixtures) { - it('should support an indent option', function () { +module.exports = function(HTTPSnippet, fixtures) { + it('should support an indent option', function() { var result = new HTTPSnippet(fixtures.requests.short).convert('objc', { indent: ' ' - }) + }); - result.should.be.a.String - result.replace(/\n/g, '').should.eql('#import NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://mockbin.com/har"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0];[request setHTTPMethod:@"GET"];NSURLSession *session = [NSURLSession sharedSession];NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { if (error) { NSLog(@"%@", error); } else { NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response; NSLog(@"%@", httpResponse); } }];[dataTask resume];') - }) - it('should support a timeout option', function () { + result.should.be.a.String; + result + .replace(/\n/g, '') + .should.eql( + '#import NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://mockbin.com/har"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0];[request setHTTPMethod:@"GET"];NSURLSession *session = [NSURLSession sharedSession];NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { if (error) { NSLog(@"%@", error); } else { NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response; NSLog(@"%@", httpResponse); } }];[dataTask resume];' + ); + }); + it('should support a timeout option', function() { var result = new HTTPSnippet(fixtures.requests.short).convert('objc', { timeout: 5 - }) + }); - result.should.be.a.String - result.replace(/\n/g, '').should.eql('#import NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://mockbin.com/har"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:5.0];[request setHTTPMethod:@"GET"];NSURLSession *session = [NSURLSession sharedSession];NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { if (error) { NSLog(@"%@", error); } else { NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response; NSLog(@"%@", httpResponse); } }];[dataTask resume];') - }) - it('should support pretty option', function () { + result.should.be.a.String; + result + .replace(/\n/g, '') + .should.eql( + '#import NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://mockbin.com/har"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:5.0];[request setHTTPMethod:@"GET"];NSURLSession *session = [NSURLSession sharedSession];NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { if (error) { NSLog(@"%@", error); } else { NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response; NSLog(@"%@", httpResponse); } }];[dataTask resume];' + ); + }); + it('should support pretty option', function() { var result = new HTTPSnippet(fixtures.requests.full).convert('objc', { pretty: false - }) + }); - result.should.be.a.String - result.replace(/\n/g, '').should.eql('#import NSDictionary *headers = @{ @"cookie": @"foo=bar; bar=baz", @"accept": @"application/json", @"content-type": @"application/x-www-form-urlencoded" };NSMutableData *postData = [[NSMutableData alloc] initWithData:[@"foo=bar" dataUsingEncoding:NSUTF8StringEncoding]];NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0];[request setHTTPMethod:@"POST"];[request setAllHTTPHeaderFields:headers];[request setHTTPBody:postData];NSURLSession *session = [NSURLSession sharedSession];NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { if (error) { NSLog(@"%@", error); } else { NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response; NSLog(@"%@", httpResponse); } }];[dataTask resume];') - }) -} + result.should.be.a.String; + result + .replace(/\n/g, '') + .should.eql( + '#import NSDictionary *headers = @{ @"cookie": @"foo=bar; bar=baz", @"accept": @"application/json", @"content-type": @"application/x-www-form-urlencoded" };NSMutableData *postData = [[NSMutableData alloc] initWithData:[@"foo=bar" dataUsingEncoding:NSUTF8StringEncoding]];NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0];[request setHTTPMethod:@"POST"];[request setAllHTTPHeaderFields:headers];[request setHTTPBody:postData];NSURLSession *session = [NSURLSession sharedSession];NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { if (error) { NSLog(@"%@", error); } else { NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response; NSLog(@"%@", httpResponse); } }];[dataTask resume];' + ); + }); +}; diff --git a/packages/insomnia-httpsnippet/test/targets/ocaml/cohttp.js b/packages/insomnia-httpsnippet/test/targets/ocaml/cohttp.js index b77cc77e7c..3dc1cbe56d 100755 --- a/packages/insomnia-httpsnippet/test/targets/ocaml/cohttp.js +++ b/packages/insomnia-httpsnippet/test/targets/ocaml/cohttp.js @@ -1,3 +1,3 @@ -'use strict' +'use strict'; -module.exports = function (snippet, fixtures) {} +module.exports = function(snippet, fixtures) {}; diff --git a/packages/insomnia-httpsnippet/test/targets/php/curl.js b/packages/insomnia-httpsnippet/test/targets/php/curl.js index b77cc77e7c..3dc1cbe56d 100755 --- a/packages/insomnia-httpsnippet/test/targets/php/curl.js +++ b/packages/insomnia-httpsnippet/test/targets/php/curl.js @@ -1,3 +1,3 @@ -'use strict' +'use strict'; -module.exports = function (snippet, fixtures) {} +module.exports = function(snippet, fixtures) {}; diff --git a/packages/insomnia-httpsnippet/test/targets/php/http1.js b/packages/insomnia-httpsnippet/test/targets/php/http1.js index b77cc77e7c..3dc1cbe56d 100755 --- a/packages/insomnia-httpsnippet/test/targets/php/http1.js +++ b/packages/insomnia-httpsnippet/test/targets/php/http1.js @@ -1,3 +1,3 @@ -'use strict' +'use strict'; -module.exports = function (snippet, fixtures) {} +module.exports = function(snippet, fixtures) {}; diff --git a/packages/insomnia-httpsnippet/test/targets/php/http2.js b/packages/insomnia-httpsnippet/test/targets/php/http2.js index b77cc77e7c..3dc1cbe56d 100755 --- a/packages/insomnia-httpsnippet/test/targets/php/http2.js +++ b/packages/insomnia-httpsnippet/test/targets/php/http2.js @@ -1,3 +1,3 @@ -'use strict' +'use strict'; -module.exports = function (snippet, fixtures) {} +module.exports = function(snippet, fixtures) {}; diff --git a/packages/insomnia-httpsnippet/test/targets/python/python3.js b/packages/insomnia-httpsnippet/test/targets/python/python3.js index ce4678eb9c..a8d3935d26 100755 --- a/packages/insomnia-httpsnippet/test/targets/python/python3.js +++ b/packages/insomnia-httpsnippet/test/targets/python/python3.js @@ -1,6 +1,5 @@ -'use strict' +'use strict'; -require('should') +require('should'); -module.exports = function (snippet, fixtures) { -} +module.exports = function(snippet, fixtures) {}; diff --git a/packages/insomnia-httpsnippet/test/targets/python/requests.js b/packages/insomnia-httpsnippet/test/targets/python/requests.js index ce4678eb9c..a8d3935d26 100755 --- a/packages/insomnia-httpsnippet/test/targets/python/requests.js +++ b/packages/insomnia-httpsnippet/test/targets/python/requests.js @@ -1,6 +1,5 @@ -'use strict' +'use strict'; -require('should') +require('should'); -module.exports = function (snippet, fixtures) { -} +module.exports = function(snippet, fixtures) {}; diff --git a/packages/insomnia-httpsnippet/test/targets/ruby/native.js b/packages/insomnia-httpsnippet/test/targets/ruby/native.js index b77cc77e7c..3dc1cbe56d 100755 --- a/packages/insomnia-httpsnippet/test/targets/ruby/native.js +++ b/packages/insomnia-httpsnippet/test/targets/ruby/native.js @@ -1,3 +1,3 @@ -'use strict' +'use strict'; -module.exports = function (snippet, fixtures) {} +module.exports = function(snippet, fixtures) {}; diff --git a/packages/insomnia-httpsnippet/test/targets/shell/curl.js b/packages/insomnia-httpsnippet/test/targets/shell/curl.js index 2206a6e3da..6b20b355b8 100755 --- a/packages/insomnia-httpsnippet/test/targets/shell/curl.js +++ b/packages/insomnia-httpsnippet/test/targets/shell/curl.js @@ -1,46 +1,68 @@ /* global it */ -'use strict' +'use strict'; -require('should') +require('should'); -module.exports = function (HTTPSnippet, fixtures) { - it('should use short options', function () { - var result = new HTTPSnippet(fixtures.requests.full).convert('shell', 'curl', { - short: true, - indent: false - }) +module.exports = function(HTTPSnippet, fixtures) { + it('should use short options', function() { + var result = new HTTPSnippet(fixtures.requests.full).convert( + 'shell', + 'curl', + { + short: true, + indent: false + } + ); - result.should.be.a.String - result.should.eql("curl -X POST 'http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value' -H 'accept: application/json' -H 'content-type: application/x-www-form-urlencoded' -b 'foo=bar; bar=baz' -d foo=bar") - }) + result.should.be.a.String; + result.should.eql( + "curl -X POST 'http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value' -H 'accept: application/json' -H 'content-type: application/x-www-form-urlencoded' -b 'foo=bar; bar=baz' -d foo=bar" + ); + }); - it('should use binary option', function () { - var result = new HTTPSnippet(fixtures.requests.full).convert('shell', 'curl', { - short: true, - indent: false, - binary: true - }) + it('should use binary option', function() { + var result = new HTTPSnippet(fixtures.requests.full).convert( + 'shell', + 'curl', + { + short: true, + indent: false, + binary: true + } + ); - result.should.be.a.String - result.should.eql("curl -X POST 'http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value' -H 'accept: application/json' -H 'content-type: application/x-www-form-urlencoded' -b 'foo=bar; bar=baz' --data-binary foo=bar") - }) + result.should.be.a.String; + result.should.eql( + "curl -X POST 'http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value' -H 'accept: application/json' -H 'content-type: application/x-www-form-urlencoded' -b 'foo=bar; bar=baz' --data-binary foo=bar" + ); + }); - it('should use --http1.0 for HTTP/1.0', function () { + it('should use --http1.0 for HTTP/1.0', function() { var result = new HTTPSnippet(fixtures.curl.http1).convert('shell', 'curl', { indent: false - }) + }); - result.should.be.a.String - result.should.eql('curl --request GET --url http://mockbin.com/request --http1.0') - }) + result.should.be.a.String; + result.should.eql( + 'curl --request GET --url http://mockbin.com/request --http1.0' + ); + }); - it('should use custom indentation', function () { - var result = new HTTPSnippet(fixtures.requests.full).convert('shell', 'curl', { - indent: '@' - }) + it('should use custom indentation', function() { + var result = new HTTPSnippet(fixtures.requests.full).convert( + 'shell', + 'curl', + { + indent: '@' + } + ); - result.should.be.a.String - result.replace(/\\\n/g, '').should.eql("curl --request POST @--url 'http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value' @--header 'accept: application/json' @--header 'content-type: application/x-www-form-urlencoded' @--cookie 'foo=bar; bar=baz' @--data foo=bar") - }) -} + result.should.be.a.String; + result + .replace(/\\\n/g, '') + .should.eql( + "curl --request POST @--url 'http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value' @--header 'accept: application/json' @--header 'content-type: application/x-www-form-urlencoded' @--cookie 'foo=bar; bar=baz' @--data foo=bar" + ); + }); +}; diff --git a/packages/insomnia-httpsnippet/test/targets/shell/httpie.js b/packages/insomnia-httpsnippet/test/targets/shell/httpie.js index 8a07a86553..09f6013b81 100755 --- a/packages/insomnia-httpsnippet/test/targets/shell/httpie.js +++ b/packages/insomnia-httpsnippet/test/targets/shell/httpie.js @@ -1,94 +1,140 @@ /* global it */ -'use strict' +'use strict'; -require('should') +require('should'); -module.exports = function (HTTPSnippet, fixtures) { - it('should ask for verbose output', function () { - var result = new HTTPSnippet(fixtures.requests.short).convert('shell', 'httpie', { - indent: false, - verbose: true - }) +module.exports = function(HTTPSnippet, fixtures) { + it('should ask for verbose output', function() { + var result = new HTTPSnippet(fixtures.requests.short).convert( + 'shell', + 'httpie', + { + indent: false, + verbose: true + } + ); - result.should.be.a.String - result.should.eql('http --verbose GET http://mockbin.com/har') - }) + result.should.be.a.String; + result.should.eql('http --verbose GET http://mockbin.com/har'); + }); - it('should use short flags', function () { - var result = new HTTPSnippet(fixtures.requests.short).convert('shell', 'httpie', { - body: true, - cert: 'foo', - headers: true, - indent: false, - pretty: 'x', - print: 'x', - short: true, - style: 'x', - timeout: 1, - verbose: true, - verify: 'x' - }) + it('should use short flags', function() { + var result = new HTTPSnippet(fixtures.requests.short).convert( + 'shell', + 'httpie', + { + body: true, + cert: 'foo', + headers: true, + indent: false, + pretty: 'x', + print: 'x', + short: true, + style: 'x', + timeout: 1, + verbose: true, + verify: 'x' + } + ); - result.should.be.a.String - result.should.eql('http -h -b -v -p=x --verify=x --cert=foo --pretty=x --style=x --timeout=1 GET http://mockbin.com/har') - }) + result.should.be.a.String; + result.should.eql( + 'http -h -b -v -p=x --verify=x --cert=foo --pretty=x --style=x --timeout=1 GET http://mockbin.com/har' + ); + }); - it('should use long flags', function () { - var result = new HTTPSnippet(fixtures.requests.short).convert('shell', 'httpie', { - body: true, - cert: 'foo', - headers: true, - indent: false, - pretty: 'x', - print: 'x', - style: 'x', - timeout: 1, - verbose: true, - verify: 'x' - }) + it('should use long flags', function() { + var result = new HTTPSnippet(fixtures.requests.short).convert( + 'shell', + 'httpie', + { + body: true, + cert: 'foo', + headers: true, + indent: false, + pretty: 'x', + print: 'x', + style: 'x', + timeout: 1, + verbose: true, + verify: 'x' + } + ); - result.should.be.a.String - result.should.eql('http --headers --body --verbose --print=x --verify=x --cert=foo --pretty=x --style=x --timeout=1 GET http://mockbin.com/har') - }) + result.should.be.a.String; + result.should.eql( + 'http --headers --body --verbose --print=x --verify=x --cert=foo --pretty=x --style=x --timeout=1 GET http://mockbin.com/har' + ); + }); - it('should use custom indentation', function () { - var result = new HTTPSnippet(fixtures.requests.full).convert('shell', 'httpie', { - indent: '@' - }) + it('should use custom indentation', function() { + var result = new HTTPSnippet(fixtures.requests.full).convert( + 'shell', + 'httpie', + { + indent: '@' + } + ); - result.should.be.a.String - result.replace(/\\\n/g, '').should.eql("http --form POST 'http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value' @accept:application/json @content-type:application/x-www-form-urlencoded @cookie:'foo=bar; bar=baz' @foo=bar") - }) + result.should.be.a.String; + result + .replace(/\\\n/g, '') + .should.eql( + "http --form POST 'http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value' @accept:application/json @content-type:application/x-www-form-urlencoded @cookie:'foo=bar; bar=baz' @foo=bar" + ); + }); - it('should use queryString parameters', function () { - var result = new HTTPSnippet(fixtures.requests.query).convert('shell', 'httpie', { - indent: false, - queryParams: true - }) + it('should use queryString parameters', function() { + var result = new HTTPSnippet(fixtures.requests.query).convert( + 'shell', + 'httpie', + { + indent: false, + queryParams: true + } + ); - result.should.be.a.String - result.replace(/\\\n/g, '').should.eql('http GET http://mockbin.com/har foo==bar foo==baz baz==abc key==value') - }) + result.should.be.a.String; + result + .replace(/\\\n/g, '') + .should.eql( + 'http GET http://mockbin.com/har foo==bar foo==baz baz==abc key==value' + ); + }); - it('should build parameterized output of query string', function () { - var result = new HTTPSnippet(fixtures.requests.query).convert('shell', 'httpie', { - indent: false, - queryParams: true - }) + it('should build parameterized output of query string', function() { + var result = new HTTPSnippet(fixtures.requests.query).convert( + 'shell', + 'httpie', + { + indent: false, + queryParams: true + } + ); - result.should.be.a.String - result.replace(/\\\n/g, '').should.eql('http GET http://mockbin.com/har foo==bar foo==baz baz==abc key==value') - }) + result.should.be.a.String; + result + .replace(/\\\n/g, '') + .should.eql( + 'http GET http://mockbin.com/har foo==bar foo==baz baz==abc key==value' + ); + }); - it('should build parameterized output of post data', function () { - var result = new HTTPSnippet(fixtures.requests['application-form-encoded']).convert('shell', 'httpie', { + it('should build parameterized output of post data', function() { + var result = new HTTPSnippet( + fixtures.requests['application-form-encoded'] + ).convert('shell', 'httpie', { short: true, indent: false, queryParams: true - }) + }); - result.should.be.a.String - result.replace(/\\\n/g, '').should.eql('http -f POST http://mockbin.com/har content-type:application/x-www-form-urlencoded foo=bar hello=world') - }) -} + result.should.be.a.String; + result + .replace(/\\\n/g, '') + .should.eql( + 'http -f POST http://mockbin.com/har content-type:application/x-www-form-urlencoded foo=bar hello=world' + ); + }); +}; diff --git a/packages/insomnia-httpsnippet/test/targets/shell/wget.js b/packages/insomnia-httpsnippet/test/targets/shell/wget.js index 3b3386a281..e15504b35c 100755 --- a/packages/insomnia-httpsnippet/test/targets/shell/wget.js +++ b/packages/insomnia-httpsnippet/test/targets/shell/wget.js @@ -1,48 +1,72 @@ /* global it */ -'use strict' +'use strict'; -require('should') +require('should'); -module.exports = function (HTTPSnippet, fixtures) { - it('should use short options', function () { - var result = new HTTPSnippet(fixtures.requests.full).convert('shell', 'wget', { - short: true, - indent: false - }) +module.exports = function(HTTPSnippet, fixtures) { + it('should use short options', function() { + var result = new HTTPSnippet(fixtures.requests.full).convert( + 'shell', + 'wget', + { + short: true, + indent: false + } + ); - result.should.be.a.String - result.should.eql("wget -q --method POST --header 'cookie: foo=bar; bar=baz' --header 'accept: application/json' --header 'content-type: application/x-www-form-urlencoded' --body-data foo=bar -O - 'http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value'") - }) + result.should.be.a.String; + result.should.eql( + "wget -q --method POST --header 'cookie: foo=bar; bar=baz' --header 'accept: application/json' --header 'content-type: application/x-www-form-urlencoded' --body-data foo=bar -O - 'http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value'" + ); + }); - it('should ask for -v output', function () { - var result = new HTTPSnippet(fixtures.requests.short).convert('shell', 'wget', { - short: true, - indent: false, - verbose: true - }) + it('should ask for -v output', function() { + var result = new HTTPSnippet(fixtures.requests.short).convert( + 'shell', + 'wget', + { + short: true, + indent: false, + verbose: true + } + ); - result.should.be.a.String - result.should.eql('wget -v --method GET -O - http://mockbin.com/har') - }) + result.should.be.a.String; + result.should.eql('wget -v --method GET -O - http://mockbin.com/har'); + }); - it('should ask for --verbose output', function () { - var result = new HTTPSnippet(fixtures.requests.short).convert('shell', 'wget', { - short: false, - indent: false, - verbose: true - }) + it('should ask for --verbose output', function() { + var result = new HTTPSnippet(fixtures.requests.short).convert( + 'shell', + 'wget', + { + short: false, + indent: false, + verbose: true + } + ); - result.should.be.a.String - result.should.eql('wget --verbose --method GET --output-document - http://mockbin.com/har') - }) + result.should.be.a.String; + result.should.eql( + 'wget --verbose --method GET --output-document - http://mockbin.com/har' + ); + }); - it('should use custom indentation', function () { - var result = new HTTPSnippet(fixtures.requests.full).convert('shell', 'wget', { - indent: '@' - }) + it('should use custom indentation', function() { + var result = new HTTPSnippet(fixtures.requests.full).convert( + 'shell', + 'wget', + { + indent: '@' + } + ); - result.should.be.a.String - result.replace(/\\\n/g, '').should.eql("wget --quiet @--method POST @--header 'cookie: foo=bar; bar=baz' @--header 'accept: application/json' @--header 'content-type: application/x-www-form-urlencoded' @--body-data foo=bar @--output-document @- 'http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value'") - }) -} + result.should.be.a.String; + result + .replace(/\\\n/g, '') + .should.eql( + "wget --quiet @--method POST @--header 'cookie: foo=bar; bar=baz' @--header 'accept: application/json' @--header 'content-type: application/x-www-form-urlencoded' @--body-data foo=bar @--output-document @- 'http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value'" + ); + }); +}; diff --git a/packages/insomnia-httpsnippet/test/targets/swift/nsurlsession.js b/packages/insomnia-httpsnippet/test/targets/swift/nsurlsession.js index 5aefd4ea52..19a918fd3a 100755 --- a/packages/insomnia-httpsnippet/test/targets/swift/nsurlsession.js +++ b/packages/insomnia-httpsnippet/test/targets/swift/nsurlsession.js @@ -1,32 +1,44 @@ /* global it */ -'use strict' +'use strict'; -require('should') +require('should'); -module.exports = function (HTTPSnippet, fixtures) { - it('should support an indent option', function () { +module.exports = function(HTTPSnippet, fixtures) { + it('should support an indent option', function() { var result = new HTTPSnippet(fixtures.requests.short).convert('swift', { indent: ' ' - }) + }); - result.should.be.a.String - result.replace(/\n/g, '').should.eql('import Foundationlet request = NSMutableURLRequest(url: NSURL(string: "http://mockbin.com/har")! as URL, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10.0)request.httpMethod = "GET"let session = URLSession.sharedlet dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in if (error != nil) { print(error) } else { let httpResponse = response as? HTTPURLResponse print(httpResponse) }})dataTask.resume()') - }) - it('should support a timeout option', function () { + result.should.be.a.String; + result + .replace(/\n/g, '') + .should.eql( + 'import Foundationlet request = NSMutableURLRequest(url: NSURL(string: "http://mockbin.com/har")! as URL, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10.0)request.httpMethod = "GET"let session = URLSession.sharedlet dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in if (error != nil) { print(error) } else { let httpResponse = response as? HTTPURLResponse print(httpResponse) }})dataTask.resume()' + ); + }); + it('should support a timeout option', function() { var result = new HTTPSnippet(fixtures.requests.short).convert('swift', { timeout: 5 - }) + }); - result.should.be.a.String - result.replace(/\n/g, '').should.eql('import Foundationlet request = NSMutableURLRequest(url: NSURL(string: "http://mockbin.com/har")! as URL, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 5.0)request.httpMethod = "GET"let session = URLSession.sharedlet dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in if (error != nil) { print(error) } else { let httpResponse = response as? HTTPURLResponse print(httpResponse) }})dataTask.resume()') - }) - it('should support pretty option', function () { + result.should.be.a.String; + result + .replace(/\n/g, '') + .should.eql( + 'import Foundationlet request = NSMutableURLRequest(url: NSURL(string: "http://mockbin.com/har")! as URL, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 5.0)request.httpMethod = "GET"let session = URLSession.sharedlet dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in if (error != nil) { print(error) } else { let httpResponse = response as? HTTPURLResponse print(httpResponse) }})dataTask.resume()' + ); + }); + it('should support pretty option', function() { var result = new HTTPSnippet(fixtures.requests.full).convert('swift', { pretty: false - }) + }); - result.should.be.a.String - result.replace(/\n/g, '').should.eql('import Foundationlet headers = ["cookie": "foo=bar; bar=baz", "accept": "application/json", "content-type": "application/x-www-form-urlencoded"]let postData = NSMutableData(data: "foo=bar".data(using: String.Encoding.utf8)!)let request = NSMutableURLRequest(url: NSURL(string: "http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value")! as URL, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10.0)request.httpMethod = "POST"request.allHTTPHeaderFields = headersrequest.httpBody = postData as Datalet session = URLSession.sharedlet dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in if (error != nil) { print(error) } else { let httpResponse = response as? HTTPURLResponse print(httpResponse) }})dataTask.resume()') - }) -} + result.should.be.a.String; + result + .replace(/\n/g, '') + .should.eql( + 'import Foundationlet headers = ["cookie": "foo=bar; bar=baz", "accept": "application/json", "content-type": "application/x-www-form-urlencoded"]let postData = NSMutableData(data: "foo=bar".data(using: String.Encoding.utf8)!)let request = NSMutableURLRequest(url: NSURL(string: "http://mockbin.com/har?foo=bar&foo=baz&baz=abc&key=value")! as URL, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10.0)request.httpMethod = "POST"request.allHTTPHeaderFields = headersrequest.httpBody = postData as Datalet session = URLSession.sharedlet dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in if (error != nil) { print(error) } else { let httpResponse = response as? HTTPURLResponse print(httpResponse) }})dataTask.resume()' + ); + }); +}; diff --git a/packages/insomnia-importers/index.js b/packages/insomnia-importers/index.js index 7866f5e9eb..5626785d46 100755 --- a/packages/insomnia-importers/index.js +++ b/packages/insomnia-importers/index.js @@ -11,7 +11,7 @@ const importers = [ require('./src/importers/swagger2') ]; -module.exports.convert = async function (contents) { +module.exports.convert = async function(contents) { for (const importer of importers) { const resources = await importer.convert(contents); @@ -27,9 +27,9 @@ module.exports.convert = async function (contents) { __export_format: 3, __export_date: utils.getDateString(), __export_source: 'insomnia.importers:v0.1.0', - resources: resources.map(utils.setDefaults), + resources: resources.map(utils.setDefaults) } - } + }; } } diff --git a/packages/insomnia-importers/src/__tests__/fixtures.test.js b/packages/insomnia-importers/src/__tests__/fixtures.test.js index a2be50a9f0..3920fbfc8b 100755 --- a/packages/insomnia-importers/src/__tests__/fixtures.test.js +++ b/packages/insomnia-importers/src/__tests__/fixtures.test.js @@ -7,11 +7,11 @@ const importers = require('../../index'); const fixturesPath = path.join(__dirname, './fixtures'); const fixtures = fs.readdirSync(fixturesPath); - describe('Fixtures', () => { for (const name of fixtures) { const dir = path.join(fixturesPath, `./${name}`); - const inputs = fs.readdirSync(dir) + const inputs = fs + .readdirSync(dir) .filter(name => !!name.match(/^(.+)-?input\.[^.]+$/)); for (const input of inputs) { @@ -19,7 +19,6 @@ describe('Fixtures', () => { const output = `${prefix}-output.json`; it(`Import ${name} ${input}`, async () => { - expect(typeof input).toBe('string'); expect(typeof output).toBe('string'); @@ -35,7 +34,7 @@ describe('Fixtures', () => { expected.__export_date = results.data.__export_date; expect(results.data).toEqual(expected); - }) + }); } } }); diff --git a/packages/insomnia-importers/src/__tests__/import-errors.test.js b/packages/insomnia-importers/src/__tests__/import-errors.test.js index 8bd7d16d38..885c96821a 100755 --- a/packages/insomnia-importers/src/__tests__/import-errors.test.js +++ b/packages/insomnia-importers/src/__tests__/import-errors.test.js @@ -6,9 +6,9 @@ describe('Import errors', () => { it('fail to find importer', async () => { try { await importers.convert('foo'); - fail("Should have thrown error") + fail('Should have thrown error'); } catch (err) { - expect(err.message).toBe('No importers found for file') + expect(err.message).toBe('No importers found for file'); } - }) + }); }); diff --git a/packages/insomnia-importers/src/__tests__/utils.test.js b/packages/insomnia-importers/src/__tests__/utils.test.js index c0eb8e33c1..4bea2807d8 100755 --- a/packages/insomnia-importers/src/__tests__/utils.test.js +++ b/packages/insomnia-importers/src/__tests__/utils.test.js @@ -4,16 +4,16 @@ const utils = require('../../src/utils'); describe('setDefaults()', () => { it('should leave non-objects alone', () => { - expect(utils.setDefaults(null)).toBe(null) + expect(utils.setDefaults(null)).toBe(null); }); it('should leave unrecognized types alone', () => { - const obj = {_type: 'weird'}; - expect(utils.setDefaults(obj)).toBe(obj) + const obj = { _type: 'weird' }; + expect(utils.setDefaults(obj)).toBe(obj); }); it('should set correct request defaults', () => { - expect(utils.setDefaults({_type: 'request'})).toEqual({ + expect(utils.setDefaults({ _type: 'request' })).toEqual({ _type: 'request', parentId: '__WORKSPACE_ID__', name: 'Imported', @@ -22,25 +22,25 @@ describe('setDefaults()', () => { method: 'GET', parameters: [], headers: [], - authentication: {}, - }) + authentication: {} + }); }); it('should set correct request_group defaults', () => { - expect(utils.setDefaults({_type: 'request_group'})).toEqual({ + expect(utils.setDefaults({ _type: 'request_group' })).toEqual({ _type: 'request_group', parentId: '__WORKSPACE_ID__', name: 'Imported', - environment: {}, - }) + environment: {} + }); }); it('should set correct environment defaults', () => { - expect(utils.setDefaults({_type: 'environment'})).toEqual({ + expect(utils.setDefaults({ _type: 'environment' })).toEqual({ _type: 'environment', parentId: '__BASE_ENVIRONMENT_ID__', name: 'Imported Environment', - data: {}, - }) + data: {} + }); }); }); diff --git a/packages/insomnia-importers/src/cli.js b/packages/insomnia-importers/src/cli.js index d94a38f9bd..f15acf7822 100755 --- a/packages/insomnia-importers/src/cli.js +++ b/packages/insomnia-importers/src/cli.js @@ -4,9 +4,9 @@ const program = require('commander'); const path = require('path'); const importers = require('../index'); const fs = require('fs'); -const {version} = require('../package.json'); +const { version } = require('../package.json'); -module.exports.go = async function () { +module.exports.go = async function() { // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // Configure the arguments parsing // // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // diff --git a/packages/insomnia-importers/src/importers/curl.js b/packages/insomnia-importers/src/importers/curl.js index 47a3e0489b..55d587250f 100755 --- a/packages/insomnia-importers/src/importers/curl.js +++ b/packages/insomnia-importers/src/importers/curl.js @@ -1,6 +1,6 @@ 'use strict'; -const {parse} = require('shell-quote'); +const { parse } = require('shell-quote'); let requestCount = 1; @@ -8,7 +8,7 @@ module.exports.id = 'curl'; module.exports.name = 'cURL'; module.exports.description = 'cURL command line tool'; -module.exports.convert = function (rawData) { +module.exports.convert = function(rawData) { requestCount = 1; if (!rawData.match(/^\s*curl /)) { @@ -20,7 +20,6 @@ module.exports.convert = function (rawData) { // Parse the whole thing into one big tokenized list const allArgs = parse(rawData); - // ~~~~~~~~~~~~~~~~~~~~~~ // // Aggregate the commands // // ~~~~~~~~~~~~~~~~~~~~~~ // @@ -55,8 +54,7 @@ module.exports.convert = function (rawData) { return requests; }; -function importArgs (args) { - +function importArgs(args) { // ~~~~~~~~~~~~~~~~~~~~~ // // Collect all the flags // // ~~~~~~~~~~~~~~~~~~~~~ // @@ -102,77 +100,90 @@ function importArgs (args) { const url = getPairValue(pairs, singletons[0] || '', 'url'); // Authentication - const [username, password] = getPairValue(pairs, '', 'u', 'user').split(/:(.*)$/); + const [username, password] = getPairValue(pairs, '', 'u', 'user').split( + /:(.*)$/ + ); const authentication = username - ? {username: username.trim(), password: password.trim()} + ? { username: username.trim(), password: password.trim() } : {}; // Headers - const headers = [ - ...(pairs['header'] || []), - ...(pairs['H'] || []) - ].map(str => { - const [name, value] = str.split(/:(.*)$/); - return {name: name.trim(), value: value.trim()}; - }); + const headers = [...(pairs['header'] || []), ...(pairs['H'] || [])].map( + str => { + const [name, value] = str.split(/:(.*)$/); + return { name: name.trim(), value: value.trim() }; + } + ); // Cookies - const cookieHeaderValue = [ - ...(pairs.cookie || []), - ...(pairs.b || []) - ].map(str => { - const name = str.split('=', 1)[0]; - const value = str.replace(`${name}=`, ''); - return `${name}=${value}`; - }).join('; '); + const cookieHeaderValue = [...(pairs.cookie || []), ...(pairs.b || [])] + .map(str => { + const name = str.split('=', 1)[0]; + const value = str.replace(`${name}=`, ''); + return `${name}=${value}`; + }) + .join('; '); // Convert cookie value to header - const existingCookieHeader = headers.find(h => h.name.toLowerCase() === 'cookie'); + const existingCookieHeader = headers.find( + h => h.name.toLowerCase() === 'cookie' + ); if (cookieHeaderValue && existingCookieHeader) { // Has existing cookie header, so let's update it existingCookieHeader.value += `; ${cookieHeaderValue}`; } else if (cookieHeaderValue) { // No existing cookie header, so let's make a new one - headers.push({name: 'Cookie', value: cookieHeaderValue}); + headers.push({ name: 'Cookie', value: cookieHeaderValue }); } // Body (Text or Blob) const bodyAsGET = getPairValue(pairs, false, 'G', 'get'); const textBody = getPairValue( - pairs, null, 'd', 'data', 'data-raw', 'data-urlencode', 'data-binary', 'data-ascii'); - const contentTypeHeader = headers.find(h => h.name.toLowerCase() === 'content-type'); - const mimeType = contentTypeHeader ? contentTypeHeader.value.split(';')[0] : null; + pairs, + null, + 'd', + 'data', + 'data-raw', + 'data-urlencode', + 'data-binary', + 'data-ascii' + ); + const contentTypeHeader = headers.find( + h => h.name.toLowerCase() === 'content-type' + ); + const mimeType = contentTypeHeader + ? contentTypeHeader.value.split(';')[0] + : null; // Body (Multipart Form Data) - const formDataParams = [ - ...(pairs['form'] || []), - ...(pairs['F'] || []) - ].map(str => { - const [name, value] = str.split('='); - const item = {name}; + const formDataParams = [...(pairs['form'] || []), ...(pairs['F'] || [])].map( + str => { + const [name, value] = str.split('='); + const item = { name }; - if (value.indexOf('@') === 0) { - item.fileName = value.slice(1); - item.type = 'file'; - } else { - item.value = value; - item.type = 'text'; + if (value.indexOf('@') === 0) { + item.fileName = value.slice(1); + item.type = 'file'; + } else { + item.value = value; + item.type = 'text'; + } + return item; } - return item; - }); + ); // Body let parameters = []; - let body = mimeType ? {mimeType: mimeType} : {}; + let body = mimeType ? { mimeType: mimeType } : {}; if (textBody && bodyAsGET) { parameters = textBody.split('&').map(v => { const [name, value] = v.split('='); - return {name: name || '', value: value || ''}; + return { name: name || '', value: value || '' }; }); } else if (textBody && mimeType === 'application/x-www-form-urlencoded') { body.params = textBody.split('&').map(v => { const [name, value] = v.split('='); - return {name: name || '', value: value || ''}; + return { name: name || '', value: value || '' }; }); } else if (textBody) { body.text = textBody; @@ -185,7 +196,7 @@ function importArgs (args) { // Method let method = getPairValue(pairs, '__UNSET__', 'X', 'request').toUpperCase(); if (method === '__UNSET__') { - method = (body.text || body.params) ? 'POST' : 'GET'; + method = body.text || body.params ? 'POST' : 'GET'; } const count = requestCount++; @@ -199,11 +210,11 @@ function importArgs (args) { method, headers, authentication, - body, + body }; } -function getPairValue (pairs, defaultValue, ...names) { +function getPairValue(pairs, defaultValue, ...names) { for (const name of names) { if (pairs[name] && pairs[name].length) { return pairs[name][0]; diff --git a/packages/insomnia-importers/src/importers/har.js b/packages/insomnia-importers/src/importers/har.js index d71fc03857..5641f4bbe6 100755 --- a/packages/insomnia-importers/src/importers/har.js +++ b/packages/insomnia-importers/src/importers/har.js @@ -8,7 +8,7 @@ module.exports.id = 'har'; module.exports.name = 'HAR 1.2'; module.exports.description = 'Importer for HTTP Archive 1.2'; -module.exports.convert = function (rawData) { +module.exports.convert = function(rawData) { requestCount = 1; let data; @@ -21,18 +21,23 @@ module.exports.convert = function (rawData) { } }; -function importRequest (request) { - const cookieHeaderValue = mapImporter(request.cookies, importCookieToHeaderString).join('; '); +function importRequest(request) { + const cookieHeaderValue = mapImporter( + request.cookies, + importCookieToHeaderString + ).join('; '); const headers = mapImporter(request.headers, importHeader); // Convert cookie value to header - const existingCookieHeader = headers.find(h => h.name.toLowerCase() === 'cookie'); + const existingCookieHeader = headers.find( + h => h.name.toLowerCase() === 'cookie' + ); if (cookieHeaderValue && existingCookieHeader) { // Has existing cookie header, so let's update it existingCookieHeader.value += `; ${cookieHeaderValue}`; } else if (cookieHeaderValue) { // No existing cookie header, so let's make a new one - headers.push({name: 'Cookie', value: cookieHeaderValue}); + headers.push({ name: 'Cookie', value: cookieHeaderValue }); } const count = requestCount++; @@ -51,31 +56,31 @@ function importRequest (request) { // Authentication isn't part of HAR, but we should be able to // sniff for things like Basic Authentication headers and pull // out the auth info - authentication: {}, + authentication: {} }; } -function importUrl (url) { +function importUrl(url) { return url; } -function importMethod (method) { +function importMethod(method) { return method.toUpperCase(); } -function importCookieToHeaderString (obj) { - return `${obj.name}=${obj.value}` +function importCookieToHeaderString(obj) { + return `${obj.name}=${obj.value}`; } -function importHeader (obj) { +function importHeader(obj) { return removeComment(obj); } -function importQueryString (obj) { +function importQueryString(obj) { return removeComment(obj); } -function importPostData (obj) { +function importPostData(obj) { if (!obj) { return {}; } @@ -83,7 +88,7 @@ function importPostData (obj) { if (obj.params && obj.params.length) { const mimeType = obj.mimeType || 'application/x-www-form-urlencoded'; const params = obj.params.map(p => { - const item = {name: p.name}; + const item = { name: p.name }; if (p.fileName) { item.fileName = p.fileName; } else { @@ -92,7 +97,7 @@ function importPostData (obj) { return item; }); - return {params, mimeType}; + return { params, mimeType }; } else { return { mimeType: obj.mimeType || '', @@ -101,21 +106,21 @@ function importPostData (obj) { } } -function removeComment (obj) { +function removeComment(obj) { const newObj = Object.assign({}, obj); delete newObj['comment']; return newObj; } -function mapImporter (arr, importFn) { +function mapImporter(arr, importFn) { if (!arr) { return []; } else { - return arr.map(importFn) + return arr.map(importFn); } } -function extractRequests (harRoot) { +function extractRequests(harRoot) { const requests = []; const log = harRoot.log; diff --git a/packages/insomnia-importers/src/importers/insomnia-1.js b/packages/insomnia-importers/src/importers/insomnia-1.js index a227e5c770..ed0faf3788 100755 --- a/packages/insomnia-importers/src/importers/insomnia-1.js +++ b/packages/insomnia-importers/src/importers/insomnia-1.js @@ -14,7 +14,7 @@ module.exports.id = 'insomnia-1'; module.exports.name = 'Insomnia v1'; module.exports.description = 'Legacy Insomnia format'; -module.exports.convert = function (rawData) { +module.exports.convert = function(rawData) { requestCount = 1; requestGroupCount = 1; @@ -33,7 +33,7 @@ module.exports.convert = function (rawData) { return importItems(data.items, '__WORKSPACE_ID__'); }; -function importItems (items, parentId) { +function importItems(items, parentId) { let resources = []; for (const item of items) { @@ -48,7 +48,7 @@ function importItems (items, parentId) { return resources; } -function importRequestGroupItem (item, parentId) { +function importRequestGroupItem(item, parentId) { let environment = {}; if (item.environments && item.environments.base) { environment = item.environments.base; @@ -60,11 +60,11 @@ function importRequestGroupItem (item, parentId) { _id: `__GRP_${count}__`, parentId, environment, - name: item.name || `Imported Folder ${count}`, - } + name: item.name || `Imported Folder ${count}` + }; } -function importRequestItem (item, parentId) { +function importRequestItem(item, parentId) { let authentication = {}; if (item.authentication) { authentication.username = item.authentication.username; @@ -72,20 +72,22 @@ function importRequestItem (item, parentId) { } const headers = item.headers || []; - let contentTypeHeader = headers.find(h => h.name.toLowerCase() === 'content-type'); + let contentTypeHeader = headers.find( + h => h.name.toLowerCase() === 'content-type' + ); if (item.__insomnia && item.__insomnia.format) { const contentType = FORMAT_MAP[item.__insomnia.format]; if (!contentTypeHeader) { - contentTypeHeader = {name: 'Content-Type', value: contentType}; + contentTypeHeader = { name: 'Content-Type', value: contentType }; headers.push(contentTypeHeader); } } let body = {}; - if (contentTypeHeader && ( - contentTypeHeader.value.match(/^application\/x-www-form-urlencoded/i) || - contentTypeHeader.value.match(/^multipart\/form-encoded/i) - ) + if ( + contentTypeHeader && + (contentTypeHeader.value.match(/^application\/x-www-form-urlencoded/i) || + contentTypeHeader.value.match(/^multipart\/form-encoded/i)) ) { body.mimeType = contentTypeHeader.value.split(';')[0]; body.params = (item.body || '').split('&').map(v => { @@ -94,12 +96,12 @@ function importRequestItem (item, parentId) { name: decodeURIComponent(name), value: decodeURIComponent(value || '') }; - }) + }); } else if (item.body) { body = { mimeType: FORMAT_MAP[item.__insomnia.format] || '', - text: item.body, - } + text: item.body + }; } const count = requestCount++; @@ -113,6 +115,6 @@ function importRequestItem (item, parentId) { body: body, parameters: item.params || [], headers, - authentication, - } + authentication + }; } diff --git a/packages/insomnia-importers/src/importers/insomnia-2.js b/packages/insomnia-importers/src/importers/insomnia-2.js index 2187ce9f1e..624f6c7a3a 100755 --- a/packages/insomnia-importers/src/importers/insomnia-2.js +++ b/packages/insomnia-importers/src/importers/insomnia-2.js @@ -6,7 +6,7 @@ module.exports.id = 'insomnia-2'; module.exports.name = 'Insomnia v2'; module.exports.description = 'Insomnia export format 2'; -module.exports.convert = function (rawData) { +module.exports.convert = function(rawData) { let data; try { data = JSON.parse(rawData); @@ -27,8 +27,12 @@ module.exports.convert = function (rawData) { // Convert old String request bodies to new (HAR) schema const headers = resource.headers || []; - const contentTypeHeader = headers.find(h => h.name.toLowerCase() === 'content-type'); - const mimeType = contentTypeHeader ? contentTypeHeader.value.split(';')[0] : null; + const contentTypeHeader = headers.find( + h => h.name.toLowerCase() === 'content-type' + ); + const mimeType = contentTypeHeader + ? contentTypeHeader.value.split(';')[0] + : null; resource.body = { mimeType: mimeType || '', text: resource.body diff --git a/packages/insomnia-importers/src/importers/insomnia-3.js b/packages/insomnia-importers/src/importers/insomnia-3.js index 9f6ea9f5a7..eadddeb9fc 100755 --- a/packages/insomnia-importers/src/importers/insomnia-3.js +++ b/packages/insomnia-importers/src/importers/insomnia-3.js @@ -6,7 +6,7 @@ module.exports.id = 'insomnia-3'; module.exports.name = 'Insomnia v3'; module.exports.description = 'Insomnia export format 3'; -module.exports.convert = function (rawData) { +module.exports.convert = function(rawData) { let data; try { data = JSON.parse(rawData); diff --git a/packages/insomnia-importers/src/importers/postman-env.js b/packages/insomnia-importers/src/importers/postman-env.js index 7c87c4d662..b7abd9b8b9 100755 --- a/packages/insomnia-importers/src/importers/postman-env.js +++ b/packages/insomnia-importers/src/importers/postman-env.js @@ -4,8 +4,7 @@ module.exports.id = 'postman-environment'; module.exports.name = 'Postman Environment'; module.exports.description = 'Importer for Postman environments'; -module.exports.convert = function (rawData) { - +module.exports.convert = function(rawData) { let data; try { data = JSON.parse(rawData); @@ -19,7 +18,7 @@ module.exports.convert = function (rawData) { return null; }; -function importEnvironment (environment) { +function importEnvironment(environment) { const newEnvironment = { _id: '__ENV_1__', _type: 'environment', diff --git a/packages/insomnia-importers/src/importers/postman.js b/packages/insomnia-importers/src/importers/postman.js index ca6dcb6f65..e8ec236894 100755 --- a/packages/insomnia-importers/src/importers/postman.js +++ b/packages/insomnia-importers/src/importers/postman.js @@ -7,14 +7,17 @@ module.exports.description = 'Importer for Postman collections'; let requestCount = 1; let requestGroupCount = 1; -module.exports.convert = function (rawData) { +module.exports.convert = function(rawData) { requestCount = 1; requestGroupCount = 1; let data; try { data = JSON.parse(rawData); - if (data.info.schema === 'https://schema.getpostman.com/json/collection/v2.0.0/collection.json') { + if ( + data.info.schema === + 'https://schema.getpostman.com/json/collection/v2.0.0/collection.json' + ) { return importCollection(data); } } catch (e) { @@ -24,29 +27,26 @@ module.exports.convert = function (rawData) { return null; }; -function importCollection (collection) { +function importCollection(collection) { const collectionFolder = { parentId: '__WORKSPACE_ID__', _id: `__GRP_${requestGroupCount++}__`, _type: 'request_group', name: collection.info.name, - description: collection.info.description, + description: collection.info.description }; return [ collectionFolder, ...importItem(collection.item, collectionFolder._id) - ] + ]; } -function importItem (items, parentId = '__WORKSPACE_ID__') { +function importItem(items, parentId = '__WORKSPACE_ID__') { let resources = []; for (const item of items) { if (item.hasOwnProperty('request')) { - resources = [ - ...resources, - importRequestItem(item, parentId) - ]; + resources = [...resources, importRequestItem(item, parentId)]; } else { const requestGroup = importFolderItem(item, parentId); resources = [ @@ -60,18 +60,18 @@ function importItem (items, parentId = '__WORKSPACE_ID__') { return resources; } -function importFolderItem (item, parentId) { +function importFolderItem(item, parentId) { return { parentId, _id: `__GRP_${requestGroupCount++}__`, _type: 'request_group', name: item.name, - description: item.description || '', - } + description: item.description || '' + }; } -function importRequestItem (item, parentId) { - const {request} = item; +function importRequestItem(item, parentId) { + const { request } = item; return { parentId, _id: `__REQ_${requestCount++}__`, @@ -81,18 +81,18 @@ function importRequestItem (item, parentId) { url: importUrl(request.url), method: request.method || 'GET', headers: mapImporter(request.header, importHeader), - body: importBody(request.body), - } + body: importBody(request.body) + }; } -function importHeader (header) { +function importHeader(header) { return Object.assign({ name: header.key, - value: header.value, - }) + value: header.value + }); } -function importUrl (url) { +function importUrl(url) { if (!url) { return ''; } @@ -104,23 +104,23 @@ function importUrl (url) { return url; } -function importBody (body) { +function importBody(body) { if (!body) { return {}; } else if (body.mode === 'raw') { - return importBodyRaw(body.raw) + return importBodyRaw(body.raw); } else if (body.mode === 'urlencoded') { - return importBodyFormUrlEncoded(body.urlencoded) + return importBodyFormUrlEncoded(body.urlencoded); } else if (body.mode === 'formdata') { // TODO: Handle this as properly as multipart/form-data - return importBodyFormdata(body.formdata) + return importBodyFormdata(body.formdata); } else { return {}; } } -function importBodyFormdata (formdata) { - const params = formdata.map(({key, value, type, enabled, src}) => { +function importBodyFormdata(formdata) { + const params = formdata.map(({ key, value, type, enabled, src }) => { const item = { type, name: key, @@ -138,12 +138,12 @@ function importBodyFormdata (formdata) { return { params, - mimeType: 'multipart/form-data', - } + mimeType: 'multipart/form-data' + }; } -function importBodyFormUrlEncoded (urlEncoded) { - const params = urlEncoded.map(({key, value, enabled}) => ({ +function importBodyFormUrlEncoded(urlEncoded) { + const params = urlEncoded.map(({ key, value, enabled }) => ({ value, name: key, disabled: !enabled @@ -151,21 +151,21 @@ function importBodyFormUrlEncoded (urlEncoded) { return { params, - mimeType: 'application/x-www-form-urlencoded', - } + mimeType: 'application/x-www-form-urlencoded' + }; } -function importBodyRaw (raw) { +function importBodyRaw(raw) { return { mimeType: '', text: raw }; } -function mapImporter (arr, importFn) { +function mapImporter(arr, importFn) { if (!arr) { return []; } else { - return arr.map(importFn) + return arr.map(importFn); } } diff --git a/packages/insomnia-importers/src/importers/swagger2.js b/packages/insomnia-importers/src/importers/swagger2.js index 70729f4352..4cb32e41a7 100644 --- a/packages/insomnia-importers/src/importers/swagger2.js +++ b/packages/insomnia-importers/src/importers/swagger2.js @@ -7,9 +7,10 @@ const WORKSPACE_ID = '__WORKSPACE_1__'; module.exports.id = 'swagger2'; module.exports.name = 'Swagger 2.0'; -module.exports.description = 'Importer for Swagger 2.0 specification (json/yaml)'; +module.exports.description = + 'Importer for Swagger 2.0 specification (json/yaml)'; -module.exports.convert = async function (rawData) { +module.exports.convert = async function(rawData) { // Validate const api = await parseDocument(rawData); if (!api || api.swagger !== SUPPORTED_SWAGGER_VERSION) { @@ -42,22 +43,16 @@ module.exports.convert = async function (rawData) { name: 'Swagger env', data: { base_path: api.basePath || '', - scheme: (api.schemes || ["http"])[0], + scheme: (api.schemes || ['http'])[0], host: api.host || '' } }; const endpoints = parseEndpoints(api); - return [ - workspace, - baseEnv, - swaggerEnv, - ...endpoints - ]; + return [workspace, baseEnv, swaggerEnv, ...endpoints]; }; - /** * Parse string data into swagger 2.0 object (https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#swagger-object) * @@ -65,9 +60,10 @@ module.exports.convert = async function (rawData) { * * @returns {Object|null} Swagger 2.0 object */ -async function parseDocument (rawData) { +async function parseDocument(rawData) { try { - const api = unthrowableParseJson(rawData) || SwaggerParser.YAML.parse(rawData); + const api = + unthrowableParseJson(rawData) || SwaggerParser.YAML.parse(rawData); if (!api) { return null; } @@ -78,9 +74,9 @@ async function parseDocument (rawData) { return null; } - function unthrowableParseJson (rawData) { + function unthrowableParseJson(rawData) { try { - return JSON.parse(rawData) + return JSON.parse(rawData); } catch (err) { return null; } @@ -94,22 +90,24 @@ async function parseDocument (rawData) { * * @returns {Object[]} array of insomnia endpoints definitions */ -function parseEndpoints (document) { +function parseEndpoints(document) { const defaultParent = WORKSPACE_ID; const globalMimeTypes = document.consumes; const paths = Object.keys(document.paths); - const endpointsSchemas = paths.map(path => { - const schemasPerMethod = document.paths[path]; - const methods = Object.keys(schemasPerMethod); + const endpointsSchemas = paths + .map(path => { + const schemasPerMethod = document.paths[path]; + const methods = Object.keys(schemasPerMethod); - return methods.map(method => ( - Object.assign({}, schemasPerMethod[method], {path, method}) - )) - }).reduce((flat, arr) => flat.concat(arr), []); //flat single array + return methods.map(method => + Object.assign({}, schemasPerMethod[method], { path, method }) + ); + }) + .reduce((flat, arr) => flat.concat(arr), []); //flat single array return endpointsSchemas.map((endpointSchema, index) => { - let {path, method, operationId: _id, summary} = endpointSchema; + let { path, method, operationId: _id, summary } = endpointSchema; const name = summary || `${method} ${path}`; return { @@ -122,7 +120,7 @@ function parseEndpoints (document) { body: prepareBody(endpointSchema, globalMimeTypes), headers: prepareHeaders(endpointSchema), parameters: prepareQueryParams(endpointSchema) - } + }; }); } @@ -134,7 +132,7 @@ function parseEndpoints (document) { * @param {string} path * @returns {string} */ -function pathWithParamsAsVariables (path) { +function pathWithParamsAsVariables(path) { return path.replace(/{([^}]+)}/g, '{{ $1 }}'); } @@ -144,7 +142,7 @@ function pathWithParamsAsVariables (path) { * @param {Object} endpointSchema - swagger 2.0 endpoint schema * @returns {Object[]} array of parameters definitions */ -function prepareQueryParams (endpointSchema) { +function prepareQueryParams(endpointSchema) { const isSendInQuery = p => p.in === 'query'; const parameters = endpointSchema.parameters || []; const queryParameters = parameters.filter(isSendInQuery); @@ -157,7 +155,7 @@ function prepareQueryParams (endpointSchema) { * @param {Object} endpointSchema - swagger 2.0 endpoint schema * @returns {Object[]} array of parameters definitions */ -function prepareHeaders (endpointSchema) { +function prepareHeaders(endpointSchema) { const isSendInHeader = p => p.in === 'header'; const parameters = endpointSchema.parameters || []; const headerParameters = parameters.filter(isSendInHeader); @@ -174,7 +172,7 @@ function prepareHeaders (endpointSchema) { * * @return {Object} insomnia request's body definition */ -function prepareBody (endpointSchema, globalMimeTypes) { +function prepareBody(endpointSchema, globalMimeTypes) { const mimeTypes = endpointSchema.consumes || globalMimeTypes || []; const isAvailable = m => mimeTypes.includes(m); const supportedMimeType = SUPPORTED_MIME_TYPES.find(isAvailable); @@ -186,15 +184,17 @@ function prepareBody (endpointSchema, globalMimeTypes) { if (!bodyParameter) { return { mimeType: supportedMimeType - } + }; } - const example = (bodyParameter) ? generateParameterExample(bodyParameter.schema) : undefined; + const example = bodyParameter + ? generateParameterExample(bodyParameter.schema) + : undefined; const text = JSON.stringify(example, null, 2); return { mimeType: supportedMimeType, text - } + }; } if (mimeTypes && mimeTypes.length) { @@ -212,15 +212,15 @@ function prepareBody (endpointSchema, globalMimeTypes) { * @param {Object[]} parameters - array of swagger schemas of parameters * @returns {Object[]} array of insomnia parameters definitions */ -function convertParameters (parameters) { +function convertParameters(parameters) { return parameters.map(parameter => { - const {required, name} = parameter; + const { required, name } = parameter; return { name, disabled: required !== true, value: `${generateParameterExample(parameter)}` - } - }) + }; + }); } /** @@ -232,28 +232,30 @@ function convertParameters (parameters) { * * @returns {*} */ -function generateParameterExample (schema) { +function generateParameterExample(schema) { const typeExamples = { - 'string': () => 'string', - 'string_email': () => 'user@example.com', + string: () => 'string', + string_email: () => 'user@example.com', 'string_date-time': () => new Date().toISOString(), - 'string_byte': () => 'ZXhhbXBsZQ==', - 'number': () => 0, - 'number_float': () => 0.0, - 'number_double': () => 0.0, - 'integer': () => 0, - 'boolean': () => true, - 'object': schema => { + string_byte: () => 'ZXhhbXBsZQ==', + number: () => 0, + number_float: () => 0.0, + number_double: () => 0.0, + integer: () => 0, + boolean: () => true, + object: schema => { const example = {}; - const {properties} = schema; + const { properties } = schema; Object.keys(properties).forEach(propertyName => { - example[propertyName] = generateParameterExample(properties[propertyName]); + example[propertyName] = generateParameterExample( + properties[propertyName] + ); }); return example; }, - 'array': schema => { + array: schema => { const value = generateParameterExample(schema.items); if (schema.collectionFormat === 'csv') { return value; @@ -268,7 +270,7 @@ function generateParameterExample (schema) { } if (schema instanceof Object) { - const {type, format, example, default: defaultValue} = schema; + const { type, format, example, default: defaultValue } = schema; if (example) { return example; diff --git a/packages/insomnia-importers/src/utils.js b/packages/insomnia-importers/src/utils.js index decac6a3d3..b84188e9d5 100755 --- a/packages/insomnia-importers/src/utils.js +++ b/packages/insomnia-importers/src/utils.js @@ -1,5 +1,4 @@ - -module.exports.setDefaults = function (obj) { +module.exports.setDefaults = function(obj) { if (!obj || !obj._type) { return obj; } else if (obj._type === 'request') { @@ -13,36 +12,45 @@ module.exports.setDefaults = function (obj) { } }; -module.exports.setDefaultsRequest = function (request) { +module.exports.setDefaultsRequest = function(request) { request.method = (request.method || 'GET').toUpperCase(); - return Object.assign({ - parentId: '__WORKSPACE_ID__', - name: 'Imported', - url: '', - body: '', - method: 'GET', - parameters: [], - headers: [], - authentication: {}, - }, request) + return Object.assign( + { + parentId: '__WORKSPACE_ID__', + name: 'Imported', + url: '', + body: '', + method: 'GET', + parameters: [], + headers: [], + authentication: {} + }, + request + ); }; -module.exports.setDefaultsRequestGroup = function (requestGroup) { - return Object.assign({ - parentId: '__WORKSPACE_ID__', - name: 'Imported', - environment: {}, - }, requestGroup) +module.exports.setDefaultsRequestGroup = function(requestGroup) { + return Object.assign( + { + parentId: '__WORKSPACE_ID__', + name: 'Imported', + environment: {} + }, + requestGroup + ); }; -module.exports.setDefaultsEnvironment = function (environment) { - return Object.assign({ - parentId: '__BASE_ENVIRONMENT_ID__', - name: 'Imported Environment', - data: {}, - }, environment) +module.exports.setDefaultsEnvironment = function(environment) { + return Object.assign( + { + parentId: '__BASE_ENVIRONMENT_ID__', + name: 'Imported Environment', + data: {} + }, + environment + ); }; -module.exports.getDateString = function () { +module.exports.getDateString = function() { return new Date().toISOString(); }; diff --git a/packages/insomnia-libcurl/src/curl.js b/packages/insomnia-libcurl/src/curl.js index 0ee09ad95a..668960baa4 100644 --- a/packages/insomnia-libcurl/src/curl.js +++ b/packages/insomnia-libcurl/src/curl.js @@ -1,14 +1,14 @@ const nodeLibcurl = require('insomnia-node-libcurl'); class Curl { - constructor () { + constructor() { this._handle = null; this._options = []; this._features = []; this._handle = new nodeLibcurl.Curl(); } - setOpt (option, value) { + setOpt(option, value) { if (!Object.keys(Curl.option).find(k => Curl.option[k])) { throw new Error(`Cannot setOpt for unknown option ${option}`); } @@ -20,26 +20,30 @@ class Curl { if (disabledOpts[option]) { const name = Curl.optName(option); const newName = disabledOpts[option].name; - throw new Error(`setOpt(${name}) is deprecated. Please use ${newName}() instead`); + throw new Error( + `setOpt(${name}) is deprecated. Please use ${newName}() instead` + ); } this._handle.setOpt(option, value); } - setUrl (url) { + setUrl(url) { this._handle.setOpt(Curl.option.URL, url); } - static getVersion () { + static getVersion() { return nodeLibcurl.Curl.getVersion(); } - static optName (opt) { - const name = Object.keys(Curl.option).find(name => Curl.option[name] === opt); + static optName(opt) { + const name = Object.keys(Curl.option).find( + name => Curl.option[name] === opt + ); return name || opt; } - getInfo (property) { + getInfo(property) { if (!Object.keys(Curl.info).find(k => Curl.info[k])) { throw new Error(`Cannot getInfo for unknown option ${property}`); } @@ -47,7 +51,7 @@ class Curl { return this._handle.getInfo(property); } - enable (feature) { + enable(feature) { if (!Object.keys(Curl.feature).find(k => Curl.feature[k])) { throw new Error(`Cannot enable unknown feature ${feature}`); } @@ -55,11 +59,11 @@ class Curl { this._handle.enable(feature); } - perform () { + perform() { this._handle.perform(); } - close () { + close() { if (this._handle) { try { this._handle.close(); @@ -69,12 +73,12 @@ class Curl { } } - cancel () { + cancel() { // TODO this.close(); } - on (name, fn) { + on(name, fn) { this._handle.on(name, fn); } } diff --git a/packages/insomnia-prettify/src/__tests__/json.test.js b/packages/insomnia-prettify/src/__tests__/json.test.js index e609fb36e7..e1df99098d 100644 --- a/packages/insomnia-prettify/src/__tests__/json.test.js +++ b/packages/insomnia-prettify/src/__tests__/json.test.js @@ -1,6 +1,6 @@ const fs = require('fs'); const path = require('path'); -const {prettify} = require('../json'); +const { prettify } = require('../json'); describe('prettify()', () => { const basePath = path.join(__dirname, '../__fixtures__'); @@ -14,8 +14,12 @@ describe('prettify()', () => { const name = slug.replace(/-/g, ' '); it(`handles ${name}`, () => { - const input = fs.readFileSync(path.join(basePath, `${slug}-input.json`), 'utf8').trim(); - const output = fs.readFileSync(path.join(basePath, `${slug}-output.json`), 'utf8').trim(); + const input = fs + .readFileSync(path.join(basePath, `${slug}-input.json`), 'utf8') + .trim(); + const output = fs + .readFileSync(path.join(basePath, `${slug}-output.json`), 'utf8') + .trim(); const result = prettify(input, ' '); expect(result).toBe(output); }); diff --git a/packages/insomnia-prettify/src/json.js b/packages/insomnia-prettify/src/json.js index 3eff992f5e..ac7884a495 100644 --- a/packages/insomnia-prettify/src/json.js +++ b/packages/insomnia-prettify/src/json.js @@ -25,7 +25,7 @@ const NUNJUCKS_CLOSE_STATES = { * @param indentChars * @returns {string} */ -module.exports.prettify = function (json, indentChars = '\t') { +module.exports.prettify = function(json, indentChars = '\t') { if (!json) { return ''; } @@ -154,7 +154,7 @@ module.exports.prettify = function (json, indentChars = '\t') { return newJson.replace(/^\s*\n/gm, ''); }; -function _repeatString (s, count) { +function _repeatString(s, count) { return new Array(count + 1).join(s); } @@ -166,7 +166,7 @@ function _repeatString (s, count) { * @returns {string} * @private */ -function _convertUnicode (originalStr) { +function _convertUnicode(originalStr) { let m; let c; let lastI = 0; diff --git a/packages/insomnia-url/src/__tests__/protocol.test.js b/packages/insomnia-url/src/__tests__/protocol.test.js index fb01044495..8ade52e69d 100644 --- a/packages/insomnia-url/src/__tests__/protocol.test.js +++ b/packages/insomnia-url/src/__tests__/protocol.test.js @@ -1,4 +1,4 @@ -const {setDefaultProtocol} = require('../protocol'); +const { setDefaultProtocol } = require('../protocol'); describe('setDefaultProtocol()', () => { it('no-ops on empty url', () => { @@ -26,5 +26,3 @@ describe('setDefaultProtocol()', () => { expect(url).toBe('httbad://google.com'); }); }); - - diff --git a/packages/insomnia-url/src/__tests__/querystring.test.js b/packages/insomnia-url/src/__tests__/querystring.test.js index 2009288b34..f847c9a33a 100644 --- a/packages/insomnia-url/src/__tests__/querystring.test.js +++ b/packages/insomnia-url/src/__tests__/querystring.test.js @@ -1,5 +1,5 @@ const querystring = require('../querystring'); -const {getJoiner} = querystring._internal; +const { getJoiner } = querystring._internal; const { joinUrlAndQueryString, buildQueryParameter, @@ -36,27 +36,19 @@ describe('querystring', () => { }); it('gets joiner for URL with ampersand', () => { - const joiner = getJoiner( - 'http://google.com?foo=bar&baz=qux' - ); + const joiner = getJoiner('http://google.com?foo=bar&baz=qux'); expect(joiner).toBe('&'); }); }); describe('joinUrlAndQueryString()', () => { it('joins bare URL', () => { - const url = joinUrlAndQueryString( - 'http://google.com', - 'foo=bar' - ); + const url = joinUrlAndQueryString('http://google.com', 'foo=bar'); expect(url).toBe('http://google.com?foo=bar'); }); it('joins with hash', () => { - const url = joinUrlAndQueryString( - 'http://google.com#hash', - 'foo=bar' - ); + const url = joinUrlAndQueryString('http://google.com#hash', 'foo=bar'); expect(url).toBe('http://google.com?foo=bar#hash'); }); @@ -87,23 +79,23 @@ describe('querystring', () => { describe('build()', () => { it('builds simple param', () => { - const str = buildQueryParameter({name: 'foo', value: 'bar??'}); + const str = buildQueryParameter({ name: 'foo', value: 'bar??' }); expect(str).toBe('foo=bar%3F%3F'); }); it('builds param without value', () => { - const str = buildQueryParameter({name: 'foo'}); + const str = buildQueryParameter({ name: 'foo' }); expect(str).toBe('foo'); }); it('builds empty param without name', () => { - const str = buildQueryParameter({value: 'bar'}); + const str = buildQueryParameter({ value: 'bar' }); expect(str).toBe(''); }); it('builds with numbers', () => { - const str = buildQueryParameter({name: 'number', value: 10}); - const str2 = buildQueryParameter({name: 'number', value: 0}); + const str = buildQueryParameter({ name: 'number', value: 10 }); + const str2 = buildQueryParameter({ name: 'number', value: 0 }); expect(str).toBe('number=10'); expect(str2).toBe('number=0'); @@ -113,25 +105,30 @@ describe('querystring', () => { describe('buildFromParams()', () => { it('builds from params', () => { const str = buildQueryStringFromParams([ - {name: 'foo', value: 'bar??'}, - {name: 'hello'}, - {name: 'hi there', value: 'bar??'}, - {name: '', value: 'bar??'}, - {name: '', value: ''} + { name: 'foo', value: 'bar??' }, + { name: 'hello' }, + { name: 'hi there', value: 'bar??' }, + { name: '', value: 'bar??' }, + { name: '', value: '' } ]); expect(str).toBe('foo=bar%3F%3F&hello&hi%20there=bar%3F%3F'); }); it('builds from params', () => { - const str = buildQueryStringFromParams([ - {name: 'foo', value: 'bar??'}, - {name: 'hello'}, - {name: 'hi there', value: 'bar??'}, - {name: '', value: 'bar??'}, - {name: '', value: ''} - ], false); + const str = buildQueryStringFromParams( + [ + { name: 'foo', value: 'bar??' }, + { name: 'hello' }, + { name: 'hi there', value: 'bar??' }, + { name: '', value: 'bar??' }, + { name: '', value: '' } + ], + false + ); - expect(str).toBe('foo=bar%3F%3F&hello=&hi%20there=bar%3F%3F&=bar%3F%3F&='); + expect(str).toBe( + 'foo=bar%3F%3F&hello=&hi%20there=bar%3F%3F&=bar%3F%3F&=' + ); }); }); @@ -142,20 +139,18 @@ describe('querystring', () => { ); expect(str).toEqual([ - {name: 'foo', value: 'bar??'}, - {name: 'hello', value: ''}, - {name: 'hi there', value: 'bar??'} + { name: 'foo', value: 'bar??' }, + { name: 'hello', value: '' }, + { name: 'hi there', value: 'bar??' } ]); }); it('builds from params with =', () => { - const str = deconstructQueryStringToParams( - 'foo=bar&1=2=3=4&hi' - ); + const str = deconstructQueryStringToParams('foo=bar&1=2=3=4&hi'); expect(str).toEqual([ - {name: 'foo', value: 'bar'}, - {name: '1', value: '2=3=4'}, - {name: 'hi', value: ''} + { name: 'foo', value: 'bar' }, + { name: '1', value: '2=3=4' }, + { name: 'hi', value: '' } ]); }); @@ -166,11 +161,11 @@ describe('querystring', () => { ); expect(str).toEqual([ - {name: 'foo', value: 'bar??'}, - {name: 'hello', value: ''}, - {name: 'hi there', value: 'bar??'}, - {name: '', value: ''}, - {name: '', value: 'val'} + { name: 'foo', value: 'bar??' }, + { name: 'hello', value: '' }, + { name: 'hi there', value: 'bar??' }, + { name: '', value: '' }, + { name: '', value: 'val' } ]); }); }); @@ -192,12 +187,18 @@ describe('querystring', () => { }); it('encodes pathname mixed encoding', () => { - const url = smartEncodeUrl('https://google.com/foo bar baz%20qux/100%/foo%25'); - expect(url).toBe('https://google.com/foo%20bar%20baz%20qux/100%25/foo%25'); + const url = smartEncodeUrl( + 'https://google.com/foo bar baz%20qux/100%/foo%25' + ); + expect(url).toBe( + 'https://google.com/foo%20bar%20baz%20qux/100%25/foo%25' + ); }); it('leaves already encoded pathname', () => { - const url = smartEncodeUrl('https://google.com/foo%20bar%20baz/100%25/foo'); + const url = smartEncodeUrl( + 'https://google.com/foo%20bar%20baz/100%25/foo' + ); expect(url).toBe('https://google.com/foo%20bar%20baz/100%25/foo'); }); @@ -212,11 +213,15 @@ describe('querystring', () => { }); it('encodes querystring with repeated keys', () => { - const url = smartEncodeUrl('https://google.com/;@,!?s=foo,;@-!&s=foo %20100%'); - expect(url).toBe('https://google.com/;@,!?s=foo,%3B%40-!&s=foo%20%20100%25'); + const url = smartEncodeUrl( + 'https://google.com/;@,!?s=foo,;@-!&s=foo %20100%' + ); + expect(url).toBe( + 'https://google.com/;@,!?s=foo,%3B%40-!&s=foo%20%20100%25' + ); }); - it('doesn\'t decode ignored characters', () => { + it("doesn't decode ignored characters", () => { // Encoded should skip raw versions of @ ; , const url = smartEncodeUrl('https://google.com/@;,&^+'); expect(url).toBe('https://google.com/@;,%26%5E+'); @@ -231,7 +236,7 @@ describe('querystring', () => { expect(url).toBe('https://google.com/%2B%2A%2F%3E'); }); - it('doesn\'t encode if last param set', () => { + it("doesn't encode if last param set", () => { const url = smartEncodeUrl('https://google.com/%%?foo=%%', false); expect(url).toBe('https://google.com/%%?foo=%%'); }); diff --git a/packages/insomnia-url/src/protocol.js b/packages/insomnia-url/src/protocol.js index fe616b1124..dece4f7fff 100644 --- a/packages/insomnia-url/src/protocol.js +++ b/packages/insomnia-url/src/protocol.js @@ -4,7 +4,7 @@ * @param [defaultProto='http:'] {string} - default protocol * @returns {string} */ -module.exports.setDefaultProtocol = function (url, defaultProto) { +module.exports.setDefaultProtocol = function(url, defaultProto) { defaultProto = defaultProto || 'http:'; // If no url, don't bother returning anything diff --git a/packages/insomnia-url/src/querystring.js b/packages/insomnia-url/src/querystring.js index 0fc58e5077..e22d013d88 100644 --- a/packages/insomnia-url/src/querystring.js +++ b/packages/insomnia-url/src/querystring.js @@ -1,5 +1,5 @@ -const {parse: urlParse, format: urlFormat} = require('url'); -const {setDefaultProtocol} = require('./protocol'); +const { parse: urlParse, format: urlFormat } = require('url'); +const { setDefaultProtocol } = require('./protocol'); const ESCAPE_REGEX_MATCH = /[-[\]/{}()*+?.\\^$|]/g; const URL_PATH_CHARACTER_WHITELIST = '+,;@=:'; @@ -10,7 +10,7 @@ const URL_PATH_CHARACTER_WHITELIST = '+,;@=:'; * @param qs {string} * @returns {string} */ -module.exports.joinUrlAndQueryString = function (url, qs) { +module.exports.joinUrlAndQueryString = function(url, qs) { if (!qs) { return url; } @@ -33,7 +33,7 @@ module.exports.joinUrlAndQueryString = function (url, qs) { * @param url {string} * @returns {string} */ -module.exports.extractQueryStringFromUrl = function (url) { +module.exports.extractQueryStringFromUrl = function(url) { if (!url) { return ''; } @@ -54,7 +54,7 @@ module.exports.extractQueryStringFromUrl = function (url) { * @param [strict=true] {boolean} * @returns {string} */ -module.exports.buildQueryParameter = function (param, strict) { +module.exports.buildQueryParameter = function(param, strict) { strict = strict === undefined ? true : strict; // Skip non-name ones in strict mode @@ -69,7 +69,9 @@ module.exports.buildQueryParameter = function (param, strict) { if (!strict || param.value) { // Don't encode ',' in values - const value = module.exports.flexibleEncodeComponent(param.value || '').replace(/%2C/gi, ','); + const value = module.exports + .flexibleEncodeComponent(param.value || '') + .replace(/%2C/gi, ','); const name = module.exports.flexibleEncodeComponent(param.name || ''); return `${name}=${value}`; @@ -84,7 +86,7 @@ module.exports.buildQueryParameter = function (param, strict) { * @param [strict=true] {boolean} - allow empty names and values * @returns {string} */ -module.exports.buildQueryStringFromParams = function (parameters, strict) { +module.exports.buildQueryStringFromParams = function(parameters, strict) { strict = strict === undefined ? true : strict; let items = []; @@ -107,7 +109,7 @@ module.exports.buildQueryStringFromParams = function (parameters, strict) { * @param [strict=true] {boolean} - allow empty names and values * @returns {{name: string, value: string}[]} */ -module.exports.deconstructQueryStringToParams = function (qs, strict) { +module.exports.deconstructQueryStringToParams = function(qs, strict) { strict = strict === undefined ? true : strict; const pairs = []; @@ -142,7 +144,7 @@ module.exports.deconstructQueryStringToParams = function (qs, strict) { continue; } - pairs.push({name, value}); + pairs.push({ name, value }); } return pairs; @@ -154,7 +156,7 @@ module.exports.deconstructQueryStringToParams = function (qs, strict) { * @param [encode=true] - enable encoding * @returns {string} */ -module.exports.smartEncodeUrl = function (url, encode) { +module.exports.smartEncodeUrl = function(url, encode) { // Default autoEncode = true if not passed encode = encode === undefined ? true : encode; @@ -172,9 +174,14 @@ module.exports.smartEncodeUrl = function (url, encode) { if (parsedUrl.pathname) { const segments = parsedUrl.pathname.split('/'); - parsedUrl.pathname = segments.map( - s => module.exports.flexibleEncodeComponent(s, URL_PATH_CHARACTER_WHITELIST) - ).join('/'); + parsedUrl.pathname = segments + .map(s => + module.exports.flexibleEncodeComponent( + s, + URL_PATH_CHARACTER_WHITELIST + ) + ) + .join('/'); } // ~~~~~~~~~~~~~~ // @@ -182,16 +189,20 @@ module.exports.smartEncodeUrl = function (url, encode) { // ~~~~~~~~~~~~~~ // if (parsedUrl.query) { - const qsParams = module.exports.deconstructQueryStringToParams(parsedUrl.query); + const qsParams = module.exports.deconstructQueryStringToParams( + parsedUrl.query + ); const encodedQsParams = []; - for (const {name, value} of qsParams) { + for (const { name, value } of qsParams) { encodedQsParams.push({ name: module.exports.flexibleEncodeComponent(name), value: module.exports.flexibleEncodeComponent(value) }); } - parsedUrl.query = module.exports.buildQueryStringFromParams(encodedQsParams); + parsedUrl.query = module.exports.buildQueryStringFromParams( + encodedQsParams + ); parsedUrl.search = `?${parsedUrl.query}`; } @@ -205,7 +216,7 @@ module.exports.smartEncodeUrl = function (url, encode) { * @param [ignore=''] {string} - characters to ignore * @returns {string} */ -module.exports.flexibleEncodeComponent = function (str, ignore) { +module.exports.flexibleEncodeComponent = function(str, ignore) { ignore = ignore || ''; // Sometimes spaces screw things up because of url.parse str = str.replace(/%20/g, ' '); @@ -243,7 +254,7 @@ module.exports.flexibleEncodeComponent = function (str, ignore) { return str; }; -function _getJoiner (url) { +function _getJoiner(url) { url = url || ''; return url.indexOf('?') === -1 ? '?' : '&'; } diff --git a/packages/insomnia-xpath/__tests__/index.test.js b/packages/insomnia-xpath/__tests__/index.test.js index 938093b750..94e231be54 100644 --- a/packages/insomnia-xpath/__tests__/index.test.js +++ b/packages/insomnia-xpath/__tests__/index.test.js @@ -1,40 +1,38 @@ -const {query} = require('..'); +const { query } = require('..'); -function q (description, args, result) { +function q(description, args, result) { it(description, () => { expect(query(...args)).toEqual(result); }); } describe('query()', () => { - q('handles missing query', - [''], - [] - ); + q('handles missing query', [''], []); - q('handles basic query', + q( + 'handles basic query', ['foobar', '//y'], [ - {inner: 'foo', outer: 'foo'}, - {inner: 'bar', outer: 'bar'} + { inner: 'foo', outer: 'foo' }, + { inner: 'bar', outer: 'bar' } ] ); - q('handles attribute query', + q( + 'handles attribute query', ['foobar', '//*[@foo="bar"]'], - [ - {inner: 'foo', outer: 'foo'} - ] + [{ inner: 'foo', outer: 'foo' }] ); - q('handles string query', + q( + 'handles string query', ['foobar', 'substring(//y[1], 2)'], - [ - {inner: 'oo', outer: 'oo'} - ] + [{ inner: 'oo', outer: 'oo' }] ); it('handles invalid query', () => { - expect(() => query('there', '//[]')).toThrowError('Invalid XPath query: //[]'); + expect(() => query('there', '//[]')).toThrowError( + 'Invalid XPath query: //[]' + ); }); }); diff --git a/packages/insomnia-xpath/index.js b/packages/insomnia-xpath/index.js index 1e282dc0f0..d49489b30e 100644 --- a/packages/insomnia-xpath/index.js +++ b/packages/insomnia-xpath/index.js @@ -1,5 +1,5 @@ const xpath = require('xpath'); -const {DOMParser} = require('xmldom'); +const { DOMParser } = require('xmldom'); /** * Query an XML blob with XPath @@ -7,7 +7,7 @@ const {DOMParser} = require('xmldom'); * @param query {string} * @returns {Array<{outer: string, inner: string}>} */ -module.exports.query = function (xml, query) { +module.exports.query = function(xml, query) { const dom = new DOMParser().parseFromString(xml); let rawResults = []; diff --git a/plugins/insomnia-plugin-base64/__tests__/index.test.js b/plugins/insomnia-plugin-base64/__tests__/index.test.js index 2b78ef34e6..d0c4ff3407 100644 --- a/plugins/insomnia-plugin-base64/__tests__/index.test.js +++ b/plugins/insomnia-plugin-base64/__tests__/index.test.js @@ -1,14 +1,14 @@ const tag = require('..').templateTags[0]; -function assertTemplate (args, expected) { - return async function () { +function assertTemplate(args, expected) { + return async function() { const result = await tag.run(null, ...args); expect(result).toBe(expected); }; } -function assertTemplateFails (args, expected) { - return async function () { +function assertTemplateFails(args, expected) { + return async function() { try { await tag.run(null, ...args); fail(`Render should have thrown ${expected}`); @@ -20,8 +20,20 @@ function assertTemplateFails (args, expected) { describe('Base64EncodeExtension', () => { it('encodes nothing', assertTemplate(['encode'], '')); - it('encodes something', assertTemplate(['encode', 'my string'], 'bXkgc3RyaW5n')); + it( + 'encodes something', + assertTemplate(['encode', 'my string'], 'bXkgc3RyaW5n') + ); it('decodes nothing', assertTemplate(['decode'], '')); - it('decodes something', assertTemplate(['decode', 'bXkgc3RyaW5n'], 'my string')); - it('fails on invalid op', assertTemplateFails(['foo'], 'Unsupported operation "foo". Must be encode or decode.')); + it( + 'decodes something', + assertTemplate(['decode', 'bXkgc3RyaW5n'], 'my string') + ); + it( + 'fails on invalid op', + assertTemplateFails( + ['foo'], + 'Unsupported operation "foo". Must be encode or decode.' + ) + ); }); diff --git a/plugins/insomnia-plugin-base64/index.js b/plugins/insomnia-plugin-base64/index.js index f6f7160157..1bcc91a536 100644 --- a/plugins/insomnia-plugin-base64/index.js +++ b/plugins/insomnia-plugin-base64/index.js @@ -1,31 +1,35 @@ -module.exports.templateTags = [{ - name: 'base64', - displayName: 'Base64', - description: 'encode or decode values', - args: [ - { - displayName: 'Action', - type: 'enum', - options: [ - {displayName: 'Encode', value: 'encode'}, - {displayName: 'Decode', value: 'decode'} - ] - }, - { - displayName: 'Value', - type: 'string', - placeholder: 'My text' - } - ], - run (context, op, text) { - text = text || ''; +module.exports.templateTags = [ + { + name: 'base64', + displayName: 'Base64', + description: 'encode or decode values', + args: [ + { + displayName: 'Action', + type: 'enum', + options: [ + { displayName: 'Encode', value: 'encode' }, + { displayName: 'Decode', value: 'decode' } + ] + }, + { + displayName: 'Value', + type: 'string', + placeholder: 'My text' + } + ], + run(context, op, text) { + text = text || ''; - if (op === 'encode') { - return Buffer.from(text, 'utf8').toString('base64'); - } else if (op === 'decode') { - return Buffer.from(text, 'base64').toString('utf8'); - } else { - throw new Error('Unsupported operation "' + op + '". Must be encode or decode.'); + if (op === 'encode') { + return Buffer.from(text, 'utf8').toString('base64'); + } else if (op === 'decode') { + return Buffer.from(text, 'base64').toString('utf8'); + } else { + throw new Error( + 'Unsupported operation "' + op + '". Must be encode or decode.' + ); + } } } -}]; +]; diff --git a/plugins/insomnia-plugin-default-headers/index.js b/plugins/insomnia-plugin-default-headers/index.js index 871f2bc45a..bd72bb0927 100644 --- a/plugins/insomnia-plugin-default-headers/index.js +++ b/plugins/insomnia-plugin-default-headers/index.js @@ -1,3 +1 @@ -module.exports.requestHooks = [ - require('./src/default-headers') -]; +module.exports.requestHooks = [require('./src/default-headers')]; diff --git a/plugins/insomnia-plugin-default-headers/src/default-headers.js b/plugins/insomnia-plugin-default-headers/src/default-headers.js index 0a082d4cf5..8263a3566a 100644 --- a/plugins/insomnia-plugin-default-headers/src/default-headers.js +++ b/plugins/insomnia-plugin-default-headers/src/default-headers.js @@ -1,4 +1,4 @@ -module.exports = function (context) { +module.exports = function(context) { const headers = context.request.getEnvironmentVariable('DEFAULT_HEADERS'); if (!headers) { @@ -8,7 +8,9 @@ module.exports = function (context) { for (const name of Object.keys(headers)) { const value = headers[name]; if (context.request.hasHeader(name)) { - console.log(`[header] Skip setting default header ${name}. Already set to ${value}`); + console.log( + `[header] Skip setting default header ${name}. Already set to ${value}` + ); continue; } diff --git a/plugins/insomnia-plugin-file/__tests__/index.test.js b/plugins/insomnia-plugin-file/__tests__/index.test.js index f480d70238..d18b5c3ddb 100644 --- a/plugins/insomnia-plugin-file/__tests__/index.test.js +++ b/plugins/insomnia-plugin-file/__tests__/index.test.js @@ -1,15 +1,15 @@ const path = require('path'); const tag = require('..').templateTags[0]; -function assertTemplate (args, expected) { - return async function () { +function assertTemplate(args, expected) { + return async function() { const result = await tag.run(null, ...args); expect(result).toBe(expected); }; } -function assertTemplateFails (args, expected) { - return async function () { +function assertTemplateFails(args, expected) { + return async function() { try { await tag.run(null, ...args); fail(`Render should have thrown ${expected}`); @@ -23,6 +23,12 @@ describe('FileExtension', () => { const filename = path.resolve(__dirname, path.join('./test.txt')); const escaped = filename.replace(/\\/g, '\\\\'); it('reads from string', assertTemplate([escaped], 'Hello World!')); - it('fails on missing file', assertTemplateFails(['/foo'], `ENOENT: no such file or directory, open '${path.resolve('/foo')}'`)); + it( + 'fails on missing file', + assertTemplateFails( + ['/foo'], + `ENOENT: no such file or directory, open '${path.resolve('/foo')}'` + ) + ); it('fails on no 2nd param', assertTemplateFails([], 'No file selected')); }); diff --git a/plugins/insomnia-plugin-file/index.js b/plugins/insomnia-plugin-file/index.js index 361d2fde37..95df1c9950 100644 --- a/plugins/insomnia-plugin-file/index.js +++ b/plugins/insomnia-plugin-file/index.js @@ -1,20 +1,22 @@ const fs = require('fs'); -module.exports.templateTags = [{ - name: 'file', - displayName: 'File', - description: 'read contents from a file', - args: [ - { - displayName: 'Choose File', - type: 'file' - } - ], - run (context, path) { - if (!path) { - throw new Error('No file selected'); - } +module.exports.templateTags = [ + { + name: 'file', + displayName: 'File', + description: 'read contents from a file', + args: [ + { + displayName: 'Choose File', + type: 'file' + } + ], + run(context, path) { + if (!path) { + throw new Error('No file selected'); + } - return fs.readFileSync(path, 'utf8'); + return fs.readFileSync(path, 'utf8'); + } } -}]; +]; diff --git a/plugins/insomnia-plugin-hash/__tests__/index.test.js b/plugins/insomnia-plugin-hash/__tests__/index.test.js index 9df1099d46..a96b99d0f0 100644 --- a/plugins/insomnia-plugin-hash/__tests__/index.test.js +++ b/plugins/insomnia-plugin-hash/__tests__/index.test.js @@ -1,14 +1,14 @@ const tag = require('..').templateTags[0]; -function assertTemplate (args, expected) { - return async function () { +function assertTemplate(args, expected) { + return async function() { const result = await tag.run(null, ...args); expect(result).toBe(expected); }; } -function assertTemplateFails (args, expected) { - return async function () { +function assertTemplateFails(args, expected) { + return async function() { try { await tag.run(null, ...args); fail(`Render should have thrown ${expected}`); @@ -20,52 +20,64 @@ function assertTemplateFails (args, expected) { describe('Plugin', () => { // Algorithms - it('hashes sha1', assertTemplate( - ['sha1', 'hex', 'foo'], - '0beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33' - )); - it('hashes sha256', assertTemplate( - ['sha256', 'hex', 'foo'], - '2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae' - )); - it('hashes md5', assertTemplate( - ['md5', 'hex', 'foo'], - 'acbd18db4cc2f85cedef654fccc4a4d8' - )); - it('fails to hash invalid algorithm', assertTemplateFails( - ['bad', 'hex', 'foo'], - 'Digest method not supported' - )); + it( + 'hashes sha1', + assertTemplate( + ['sha1', 'hex', 'foo'], + '0beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33' + ) + ); + it( + 'hashes sha256', + assertTemplate( + ['sha256', 'hex', 'foo'], + '2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae' + ) + ); + it( + 'hashes md5', + assertTemplate(['md5', 'hex', 'foo'], 'acbd18db4cc2f85cedef654fccc4a4d8') + ); + it( + 'fails to hash invalid algorithm', + assertTemplateFails(['bad', 'hex', 'foo'], 'Digest method not supported') + ); // Digests - it('hashes to latin1', assertTemplate( - ['md5', 'latin1', 'foo'], - '¬½ÛLÂø\\íïeOÌĤØ' - )); - it('hashes to hex', assertTemplate( - ['md5', 'hex', 'foo'], - 'acbd18db4cc2f85cedef654fccc4a4d8' - )); - it('hashes to base64', assertTemplate( - ['md5', 'base64', 'foo'], - 'rL0Y20zC+Fzt72VPzMSk2A==' - )); - it('fails to hash to invalid', assertTemplateFails( - ['md5', 'bad', 'foo'], - 'Invalid encoding bad. Choices are hex, latin1, base64' - )); + it( + 'hashes to latin1', + assertTemplate(['md5', 'latin1', 'foo'], '¬½ÛLÂø\\íïeOÌĤØ') + ); + it( + 'hashes to hex', + assertTemplate(['md5', 'hex', 'foo'], 'acbd18db4cc2f85cedef654fccc4a4d8') + ); + it( + 'hashes to base64', + assertTemplate(['md5', 'base64', 'foo'], 'rL0Y20zC+Fzt72VPzMSk2A==') + ); + it( + 'fails to hash to invalid', + assertTemplateFails( + ['md5', 'bad', 'foo'], + 'Invalid encoding bad. Choices are hex, latin1, base64' + ) + ); // Values - it('hashes empty string', assertTemplate( - ['md5', 'hex', ''], - 'd41d8cd98f00b204e9800998ecf8427e' - )); - it('hashes no string', assertTemplate( - ['md5', 'hex'], - 'd41d8cd98f00b204e9800998ecf8427e' - )); - it('fails to hash non string', assertTemplateFails( - ['md5', 'hex', true], - 'Cannot hash value of type "boolean"' - )); + it( + 'hashes empty string', + assertTemplate(['md5', 'hex', ''], 'd41d8cd98f00b204e9800998ecf8427e') + ); + it( + 'hashes no string', + assertTemplate(['md5', 'hex'], 'd41d8cd98f00b204e9800998ecf8427e') + ); + it( + 'fails to hash non string', + assertTemplateFails( + ['md5', 'hex', true], + 'Cannot hash value of type "boolean"' + ) + ); }); diff --git a/plugins/insomnia-plugin-hash/index.js b/plugins/insomnia-plugin-hash/index.js index 143b9b7be0..396a700e72 100644 --- a/plugins/insomnia-plugin-hash/index.js +++ b/plugins/insomnia-plugin-hash/index.js @@ -1,47 +1,55 @@ const crypto = require('crypto'); -module.exports.templateTags = [{ - name: 'hash', - displayName: 'Hash', - description: 'Apply hash to a value', - args: [ - { - displayName: 'Algorithm', - type: 'enum', - options: [ - {displayName: 'MD5', value: 'md5'}, - {displayName: 'SHA1', value: 'sha1'}, - {displayName: 'SHA256', value: 'sha256'}, - {displayName: 'SHA512', value: 'sha512'} - ] - }, - { - displayName: 'Digest Encoding', - description: 'The encoding of the output', - type: 'enum', - options: [ - {displayName: 'Hexadecimal', value: 'hex'}, - {displayName: 'Base64', value: 'base64'} - ] - }, - { - displayName: 'Input', - type: 'string', - placeholder: 'Value to hash' - } - ], - run (context, algorithm, encoding, value = '') { - if (encoding !== 'hex' && encoding !== 'latin1' && encoding !== 'base64') { - throw new Error(`Invalid encoding ${encoding}. Choices are hex, latin1, base64`); - } +module.exports.templateTags = [ + { + name: 'hash', + displayName: 'Hash', + description: 'Apply hash to a value', + args: [ + { + displayName: 'Algorithm', + type: 'enum', + options: [ + { displayName: 'MD5', value: 'md5' }, + { displayName: 'SHA1', value: 'sha1' }, + { displayName: 'SHA256', value: 'sha256' }, + { displayName: 'SHA512', value: 'sha512' } + ] + }, + { + displayName: 'Digest Encoding', + description: 'The encoding of the output', + type: 'enum', + options: [ + { displayName: 'Hexadecimal', value: 'hex' }, + { displayName: 'Base64', value: 'base64' } + ] + }, + { + displayName: 'Input', + type: 'string', + placeholder: 'Value to hash' + } + ], + run(context, algorithm, encoding, value = '') { + if ( + encoding !== 'hex' && + encoding !== 'latin1' && + encoding !== 'base64' + ) { + throw new Error( + `Invalid encoding ${encoding}. Choices are hex, latin1, base64` + ); + } - const valueType = typeof value; - if (valueType !== 'string') { - throw new Error(`Cannot hash value of type "${valueType}"`); - } + const valueType = typeof value; + if (valueType !== 'string') { + throw new Error(`Cannot hash value of type "${valueType}"`); + } - const hash = crypto.createHash(algorithm); - hash.update(value || '', 'utf8'); - return hash.digest(encoding); + const hash = crypto.createHash(algorithm); + hash.update(value || '', 'utf8'); + return hash.digest(encoding); + } } -}]; +]; diff --git a/plugins/insomnia-plugin-jsonpath/index.js b/plugins/insomnia-plugin-jsonpath/index.js index 42ca5922fa..d77f44a9e7 100644 --- a/plugins/insomnia-plugin-jsonpath/index.js +++ b/plugins/insomnia-plugin-jsonpath/index.js @@ -1,35 +1,40 @@ const jq = require('jsonpath'); -module.exports.templateTags = [{ - displayName: 'JSONPath', - name: 'jsonpath', - description: 'Pull data from JSON strings with JSONPath', - args: [{ - displayName: 'JSON string', - type: 'string' - }, { - displayName: 'JSONPath Filter', - type: 'string' - }], - run (context, jsonString, filter) { - let body; - try { - body = JSON.parse(jsonString); - } catch (err) { - throw new Error(`Invalid JSON: ${err.message}`); - } +module.exports.templateTags = [ + { + displayName: 'JSONPath', + name: 'jsonpath', + description: 'Pull data from JSON strings with JSONPath', + args: [ + { + displayName: 'JSON string', + type: 'string' + }, + { + displayName: 'JSONPath Filter', + type: 'string' + } + ], + run(context, jsonString, filter) { + let body; + try { + body = JSON.parse(jsonString); + } catch (err) { + throw new Error(`Invalid JSON: ${err.message}`); + } - let results; - try { - results = jq.query(body, filter); - } catch (err) { - throw new Error(`Invalid JSONPath query: ${filter}`); - } + let results; + try { + results = jq.query(body, filter); + } catch (err) { + throw new Error(`Invalid JSONPath query: ${filter}`); + } - if (results.length === 0) { - throw new Error(`JSONPath query returned no results: ${filter}`); - } + if (results.length === 0) { + throw new Error(`JSONPath query returned no results: ${filter}`); + } - return results[0]; + return results[0]; + } } -}]; +]; diff --git a/plugins/insomnia-plugin-now/__tests__/index.test.js b/plugins/insomnia-plugin-now/__tests__/index.test.js index 5c99c9fb92..3b312c6e1e 100644 --- a/plugins/insomnia-plugin-now/__tests__/index.test.js +++ b/plugins/insomnia-plugin-now/__tests__/index.test.js @@ -1,7 +1,7 @@ const tag = require('..').templateTags[0]; -function assertTemplate (args, expected) { - return async function () { +function assertTemplate(args, expected) { + return async function() { const result = await tag.run(null, ...args); if (expected instanceof RegExp) { expect(result).toMatch(expected); @@ -11,8 +11,8 @@ function assertTemplate (args, expected) { }; } -function assertTemplateFails (args, expected) { - return async function () { +function assertTemplateFails(args, expected) { + return async function() { try { await tag.run(null, ...args); fail(`Render should have thrown ${expected}`); diff --git a/plugins/insomnia-plugin-now/index.js b/plugins/insomnia-plugin-now/index.js index 96ef6de0c4..aa3422faa0 100644 --- a/plugins/insomnia-plugin-now/index.js +++ b/plugins/insomnia-plugin-now/index.js @@ -1,58 +1,61 @@ const moment = require('moment'); -module.exports.templateTags = [{ - name: 'now', - displayName: 'Timestamp', - description: 'get the current time', - args: [ - { - displayName: 'Timestamp Format', - type: 'enum', - options: [ - {displayName: 'ISO-8601', value: 'iso-8601'}, - {displayName: 'Milliseconds', value: 'millis'}, - {displayName: 'Unix', value: 'unix'}, - {displayName: 'Custom Format', value: 'custom'} - ] - }, - { - help: 'moment.js format string', - displayName: 'Custom Format Template', - type: 'string', - placeholder: 'MMMM Do YYYY, h:mm:ss a', - hide: args => args[0].value !== 'custom' - } - ], - run (context, dateType = 'iso-8601', formatStr = '') { - if (typeof dateType === 'string') { - dateType = dateType.toLowerCase(); - } +module.exports.templateTags = [ + { + name: 'now', + displayName: 'Timestamp', + description: 'get the current time', + args: [ + { + displayName: 'Timestamp Format', + type: 'enum', + options: [ + { displayName: 'ISO-8601', value: 'iso-8601' }, + { displayName: 'Milliseconds', value: 'millis' }, + { displayName: 'Unix', value: 'unix' }, + { displayName: 'Custom Format', value: 'custom' } + ] + }, + { + help: 'moment.js format string', + displayName: 'Custom Format Template', + type: 'string', + placeholder: 'MMMM Do YYYY, h:mm:ss a', + hide: args => args[0].value !== 'custom' + } + ], + run(context, dateType = 'iso-8601', formatStr = '') { + if (typeof dateType === 'string') { + dateType = dateType.toLowerCase(); + } - const now = new Date(); + const now = new Date(); - switch (dateType) { - case 'millis': - case 'ms': - return now.getTime() + ''; - case 'unix': - case 'seconds': - case 's': - return Math.round(now.getTime() / 1000) + ''; - case 'iso-8601': - return now.toISOString(); - case 'custom': - return moment(now).format(formatStr); - default: - throw new Error(`Invalid date type "${dateType}"`); + switch (dateType) { + case 'millis': + case 'ms': + return now.getTime() + ''; + case 'unix': + case 'seconds': + case 's': + return Math.round(now.getTime() / 1000) + ''; + case 'iso-8601': + return now.toISOString(); + case 'custom': + return moment(now).format(formatStr); + default: + throw new Error(`Invalid date type "${dateType}"`); + } + } + }, + { + // Old deprecated "timestamp" tag + deprecated: true, + name: 'timestamp', + displayName: 'Timestamp', + description: 'generate timestamp in milliseconds', + run(context) { + return Date.now(); } } -}, { - // Old deprecated "timestamp" tag - deprecated: true, - name: 'timestamp', - displayName: 'Timestamp', - description: 'generate timestamp in milliseconds', - run (context) { - return Date.now(); - } -}]; +]; diff --git a/plugins/insomnia-plugin-os/index.js b/plugins/insomnia-plugin-os/index.js index 4149146940..c2163855b1 100644 --- a/plugins/insomnia-plugin-os/index.js +++ b/plugins/insomnia-plugin-os/index.js @@ -1,47 +1,49 @@ const os = require('os'); const jsonPath = require('jsonpath'); -const FILTERABLE = [ - 'userInfo', - 'cpus' -]; +const FILTERABLE = ['userInfo', 'cpus']; -module.exports.templateTags = [{ - displayName: 'OS', - name: 'os', - description: 'get OS info', - args: [{ - displayName: 'Function', - type: 'enum', - options: [ - {displayName: 'arch', value: 'arch'}, - {displayName: 'cpus', value: 'cpus'}, - {displayName: 'freemem', value: 'freemem'}, - {displayName: 'hostname', value: 'hostname'}, - {displayName: 'platform', value: 'platform'}, - {displayName: 'release', value: 'release'}, - {displayName: 'userInfo', value: 'userInfo'} - ] - }, { - displayName: 'JSONPath Filter', - help: 'Some OS functions return objects. Use JSONPath queries to extract desired values.', - hide: args => !FILTERABLE.includes(args[0].value), - type: 'string', - }], - run (context, fnName, filter) { - let value = os[fnName](); +module.exports.templateTags = [ + { + displayName: 'OS', + name: 'os', + description: 'get OS info', + args: [ + { + displayName: 'Function', + type: 'enum', + options: [ + { displayName: 'arch', value: 'arch' }, + { displayName: 'cpus', value: 'cpus' }, + { displayName: 'freemem', value: 'freemem' }, + { displayName: 'hostname', value: 'hostname' }, + { displayName: 'platform', value: 'platform' }, + { displayName: 'release', value: 'release' }, + { displayName: 'userInfo', value: 'userInfo' } + ] + }, + { + displayName: 'JSONPath Filter', + help: + 'Some OS functions return objects. Use JSONPath queries to extract desired values.', + hide: args => !FILTERABLE.includes(args[0].value), + type: 'string' + } + ], + run(context, fnName, filter) { + let value = os[fnName](); - if (jsonPath && FILTERABLE.includes(fnName)) { - try { - value = jsonPath.query(value, filter)[0]; - } catch (err) { + if (jsonPath && FILTERABLE.includes(fnName)) { + try { + value = jsonPath.query(value, filter)[0]; + } catch (err) {} + } + + if (typeof value !== 'string') { + return JSON.stringify(value); + } else { + return value; } } - - if (typeof value !== 'string') { - return JSON.stringify(value); - } else { - return value; - } } -}]; +]; diff --git a/plugins/insomnia-plugin-prompt/index.js b/plugins/insomnia-plugin-prompt/index.js index d353a8ce73..4f0b79b418 100644 --- a/plugins/insomnia-plugin-prompt/index.js +++ b/plugins/insomnia-plugin-prompt/index.js @@ -1,41 +1,53 @@ const STORE = {}; -module.exports.templateTags = [{ - displayName: 'Prompt', - name: 'prompt', - description: 'prompt user for input', - args: [{ - displayName: 'Title', - type: 'string' - }, { - displayName: 'Label', - type: 'string' - }, { - displayName: 'Default Value', - type: 'string', - help: 'This value is used to pre-populate the prompt dialog, but is ALSO used ' + - 'when the app renders preview values (like the one below). This is to prevent the ' + - 'prompt from displaying too frequently during general app use.' - }, { - displayName: 'Storage Key', - type: 'string', - help: 'If this is set, the value will be stored in memory under this key until the app is ' + - 'closed. To force this tag to re-prompt the user, simply change this key\'s value to ' + - 'something else.' - }], - async run (context, title, label, defaultValue, storageKey) { - if (STORE[storageKey]) { - console.log(`[prompt] Used cached value under ${storageKey}`); - return STORE[storageKey]; +module.exports.templateTags = [ + { + displayName: 'Prompt', + name: 'prompt', + description: 'prompt user for input', + args: [ + { + displayName: 'Title', + type: 'string' + }, + { + displayName: 'Label', + type: 'string' + }, + { + displayName: 'Default Value', + type: 'string', + help: + 'This value is used to pre-populate the prompt dialog, but is ALSO used ' + + 'when the app renders preview values (like the one below). This is to prevent the ' + + 'prompt from displaying too frequently during general app use.' + }, + { + displayName: 'Storage Key', + type: 'string', + help: + 'If this is set, the value will be stored in memory under this key until the app is ' + + "closed. To force this tag to re-prompt the user, simply change this key's value to " + + 'something else.' + } + ], + async run(context, title, label, defaultValue, storageKey) { + if (STORE[storageKey]) { + console.log(`[prompt] Used cached value under ${storageKey}`); + return STORE[storageKey]; + } + + const value = await context.app.prompt(title || 'Enter Value', { + label, + defaultValue + }); + + // Store if a key is set + if (storageKey) { + console.log(`[prompt] Stored value under ${storageKey}`); + STORE[storageKey] = value; + } + + return value; } - - const value = await context.app.prompt(title || 'Enter Value', {label, defaultValue}); - - // Store if a key is set - if (storageKey) { - console.log(`[prompt] Stored value under ${storageKey}`); - STORE[storageKey] = value; - } - - return value; } -}]; +]; diff --git a/plugins/insomnia-plugin-request/__tests__/index.test.js b/plugins/insomnia-plugin-request/__tests__/index.test.js index 3abeaf01f1..9386c62d52 100644 --- a/plugins/insomnia-plugin-request/__tests__/index.test.js +++ b/plugins/insomnia-plugin-request/__tests__/index.test.js @@ -1,21 +1,26 @@ -const {jarFromCookies, cookiesFromJar} = require('insomnia-cookies'); +const { jarFromCookies, cookiesFromJar } = require('insomnia-cookies'); const tag = require('..').templateTags[0]; describe('plugin', () => { describe('RequestExtension cookie', async () => { it('should get cookie by name', async () => { const jar = jarFromCookies([]); - jar.setCookieSync([ - 'foo=bar', - 'path=/', - 'domain=.insomnia.rest', - 'HttpOnly Cache-Control: public, no-cache' - ].join('; '), 'https://insomnia.rest'); + jar.setCookieSync( + [ + 'foo=bar', + 'path=/', + 'domain=.insomnia.rest', + 'HttpOnly Cache-Control: public, no-cache' + ].join('; '), + 'https://insomnia.rest' + ); const cookies = await cookiesFromJar(jar); - const requests = [{_id: 'req_1', parameters: [], url: 'https://insomnia.rest/foo/bar'}]; - const jars = [{_id: 'jar_1', parentId: 'wrk_1', cookies}]; - const context = _getTestContext([{_id: 'wrk_1'}], requests, jars); + const requests = [ + { _id: 'req_1', parameters: [], url: 'https://insomnia.rest/foo/bar' } + ]; + const jars = [{ _id: 'jar_1', parentId: 'wrk_1', cookies }]; + const context = _getTestContext([{ _id: 'wrk_1' }], requests, jars); const result = await tag.run(context, 'cookie', 'foo'); expect(result).toBe('bar'); @@ -24,24 +29,28 @@ describe('plugin', () => { describe('RequestExtension url', async () => { it('should get url', async () => { - const requests = [{ - _id: 'req_1', - parameters: [{name: 'foo', value: 'bar'}], - url: 'https://insomnia.rest/foo/bar' - }]; - const context = _getTestContext([{_id: 'wrk_1'}], requests); + const requests = [ + { + _id: 'req_1', + parameters: [{ name: 'foo', value: 'bar' }], + url: 'https://insomnia.rest/foo/bar' + } + ]; + const context = _getTestContext([{ _id: 'wrk_1' }], requests); const result = await tag.run(context, 'url'); expect(result).toBe('https://insomnia.rest/foo/bar?foo=bar'); }); it('should get rendered url', async () => { - const requests = [{ - _id: 'req_1', - parameters: [{name: 'foo', value: '{{ foo }}'}], - url: 'https://insomnia.rest/foo/bar' - }]; - const context = _getTestContext([{_id: 'wrk_1'}], requests); + const requests = [ + { + _id: 'req_1', + parameters: [{ name: 'foo', value: '{{ foo }}' }], + url: 'https://insomnia.rest/foo/bar' + } + ]; + const context = _getTestContext([{ _id: 'wrk_1' }], requests); const result = await tag.run(context, 'url'); expect(result).toBe('https://insomnia.rest/foo/bar?foo=bar'); @@ -50,12 +59,14 @@ describe('plugin', () => { describe('RequestExtension header', async () => { it('should get url', async () => { - const requests = [{ - _id: 'req_1', - headers: [{name: 'foo', value: '{{ foo }}'}], - url: 'https://insomnia.rest/foo/bar' - }]; - const context = _getTestContext([{_id: 'wrk_1'}], requests); + const requests = [ + { + _id: 'req_1', + headers: [{ name: 'foo', value: '{{ foo }}' }], + url: 'https://insomnia.rest/foo/bar' + } + ]; + const context = _getTestContext([{ _id: 'wrk_1' }], requests); const result = await tag.run(context, 'header', 'foo'); expect(result).toBe('bar'); @@ -63,7 +74,7 @@ describe('plugin', () => { }); }); -function _getTestContext (workspaces, requests, jars) { +function _getTestContext(workspaces, requests, jars) { jars = jars || []; return { meta: { @@ -71,26 +82,28 @@ function _getTestContext (workspaces, requests, jars) { workspaceId: workspaces[0]._id }, util: { - render (str) { + render(str) { return str.replace(/{{ foo }}/g, 'bar'); }, models: { request: { - getById (id) { + getById(id) { return requests.find(r => r._id === id); } }, workspace: { - getById (id) { + getById(id) { return workspaces.find(w => w._id === id); } }, cookieJar: { - getOrCreateForWorkspace (workspace) { - return jars.find(j => j.parentId === workspace._id) || { - parentId: workspace._id, - cookies: [] - }; + getOrCreateForWorkspace(workspace) { + return ( + jars.find(j => j.parentId === workspace._id) || { + parentId: workspace._id, + cookies: [] + } + ); } } } diff --git a/plugins/insomnia-plugin-request/index.js b/plugins/insomnia-plugin-request/index.js index 383c69f8a3..a215aee30f 100644 --- a/plugins/insomnia-plugin-request/index.js +++ b/plugins/insomnia-plugin-request/index.js @@ -1,107 +1,148 @@ -const {buildQueryStringFromParams, joinUrlAndQueryString, smartEncodeUrl} = require('insomnia-url'); -const {jarFromCookies} = require('insomnia-cookies'); +const { + buildQueryStringFromParams, + joinUrlAndQueryString, + smartEncodeUrl +} = require('insomnia-url'); +const { jarFromCookies } = require('insomnia-cookies'); -module.exports.templateTags = [{ - name: 'request', - displayName: 'Request', - description: 'reference value from current request', - args: [ - { - displayName: 'Attribute', - type: 'enum', - options: [ - {displayName: 'Name', value: 'name', description: 'name of request'}, - {displayName: 'Folder', value: 'folder', description: 'name of immediate parent folder (or workspace)'}, - {displayName: 'URL', value: 'url', description: 'fully qualified URL'}, - {displayName: 'Cookie', value: 'cookie', description: 'cookie value by name'}, - {displayName: 'Header', value: 'header', description: 'header value by name'}, - {displayName: 'OAuth 2.0 Token', value: 'oauth2', description: 'access token'} - ] - }, - { - type: 'string', - hide: args => ['url', 'oauth2', 'name', 'folder'].includes(args[0].value), - displayName: args => { - switch (args[0].value) { - case 'cookie': - return 'Cookie Name'; - case 'header': - return 'Header Name'; - default: - return 'Name'; - } - } - } - ], - - async run (context, attribute, name) { - const {meta} = context; - - if (!meta.requestId || !meta.workspaceId) { - return null; - } - - const request = await context.util.models.request.getById(meta.requestId); - const workspace = await context.util.models.workspace.getById(meta.workspaceId); - - if (!request) { - throw new Error(`Request not found for ${meta.requestId}`); - } - - if (!workspace) { - throw new Error(`Workspace not found for ${meta.workspaceId}`); - } - - switch (attribute) { - case 'url': - return getRequestUrl(context, request); - case 'cookie': - if (!name) { - throw new Error('No cookie specified'); - } - - const cookieJar = await context.util.models.cookieJar.getOrCreateForWorkspace(workspace); - const url = await getRequestUrl(context, request); - return getCookieValue(cookieJar, url, name); - case 'header': - if (!name) { - throw new Error('No header specified'); - } - - const names = []; - - if (request.headers.length === 0) { - throw new Error(`No headers available`); - } - - for (const header of request.headers) { - const headerName = await context.util.render(header.name); - names.push(headerName); - if (headerName.toLowerCase() === name.toLowerCase()) { - return context.util.render(header.value); +module.exports.templateTags = [ + { + name: 'request', + displayName: 'Request', + description: 'reference value from current request', + args: [ + { + displayName: 'Attribute', + type: 'enum', + options: [ + { + displayName: 'Name', + value: 'name', + description: 'name of request' + }, + { + displayName: 'Folder', + value: 'folder', + description: 'name of immediate parent folder (or workspace)' + }, + { + displayName: 'URL', + value: 'url', + description: 'fully qualified URL' + }, + { + displayName: 'Cookie', + value: 'cookie', + description: 'cookie value by name' + }, + { + displayName: 'Header', + value: 'header', + description: 'header value by name' + }, + { + displayName: 'OAuth 2.0 Token', + value: 'oauth2', + description: 'access token' + } + ] + }, + { + type: 'string', + hide: args => + ['url', 'oauth2', 'name', 'folder'].includes(args[0].value), + displayName: args => { + switch (args[0].value) { + case 'cookie': + return 'Cookie Name'; + case 'header': + return 'Header Name'; + default: + return 'Name'; } } + } + ], - const namesStr = names.map(n => `"${n}"`).join(',\n\t'); - throw new Error(`No header with name "${name}".\nChoices are [\n\t${namesStr}\n]`); - case 'oauth2': - const token = await context.util.models.oAuth2Token.getByRequestId(request._id); - if (!token) { - throw new Error('No OAuth 2.0 tokens found for request'); - } - return token.accessToken; - case 'name': - return request.name; - case 'folder': - const requestGroup = await context.util.models.requestGroup.getById(request.parentId); - return requestGroup ? requestGroup.name : workspace.name; + async run(context, attribute, name) { + const { meta } = context; + + if (!meta.requestId || !meta.workspaceId) { + return null; + } + + const request = await context.util.models.request.getById(meta.requestId); + const workspace = await context.util.models.workspace.getById( + meta.workspaceId + ); + + if (!request) { + throw new Error(`Request not found for ${meta.requestId}`); + } + + if (!workspace) { + throw new Error(`Workspace not found for ${meta.workspaceId}`); + } + + switch (attribute) { + case 'url': + return getRequestUrl(context, request); + case 'cookie': + if (!name) { + throw new Error('No cookie specified'); + } + + const cookieJar = await context.util.models.cookieJar.getOrCreateForWorkspace( + workspace + ); + const url = await getRequestUrl(context, request); + return getCookieValue(cookieJar, url, name); + case 'header': + if (!name) { + throw new Error('No header specified'); + } + + const names = []; + + if (request.headers.length === 0) { + throw new Error(`No headers available`); + } + + for (const header of request.headers) { + const headerName = await context.util.render(header.name); + names.push(headerName); + if (headerName.toLowerCase() === name.toLowerCase()) { + return context.util.render(header.value); + } + } + + const namesStr = names.map(n => `"${n}"`).join(',\n\t'); + throw new Error( + `No header with name "${name}".\nChoices are [\n\t${namesStr}\n]` + ); + case 'oauth2': + const token = await context.util.models.oAuth2Token.getByRequestId( + request._id + ); + if (!token) { + throw new Error('No OAuth 2.0 tokens found for request'); + } + return token.accessToken; + case 'name': + return request.name; + case 'folder': + const requestGroup = await context.util.models.requestGroup.getById( + request.parentId + ); + return requestGroup ? requestGroup.name : workspace.name; + } + + return null; } - - return null; } -}]; +]; -async function getRequestUrl (context, request) { +async function getRequestUrl(context, request) { const url = await context.util.render(request.url); const parameters = []; for (const p of request.parameters) { @@ -117,7 +158,7 @@ async function getRequestUrl (context, request) { return smartEncodeUrl(finalUrl, request.settingEncodeUrl); } -function getCookieValue (cookieJar, url, name) { +function getCookieValue(cookieJar, url, name) { return new Promise((resolve, reject) => { const jar = jarFromCookies(cookieJar.cookies); @@ -133,7 +174,9 @@ function getCookieValue (cookieJar, url, name) { const cookie = cookies.find(cookie => cookie.key === name); if (!cookie) { const names = cookies.map(c => `"${c.key}"`).join(',\n\t'); - throw new Error(`No cookie with name "${name}".\nChoices are [\n\t${names}\n] for url "${url}"`); + throw new Error( + `No cookie with name "${name}".\nChoices are [\n\t${names}\n] for url "${url}"` + ); } else { resolve(cookie ? cookie.value : null); } diff --git a/plugins/insomnia-plugin-response/__tests__/index.test.js b/plugins/insomnia-plugin-response/__tests__/index.test.js index 51a20a5b95..9f0a831845 100644 --- a/plugins/insomnia-plugin-response/__tests__/index.test.js +++ b/plugins/insomnia-plugin-response/__tests__/index.test.js @@ -4,7 +4,7 @@ const iconv = require('iconv-lite'); describe('Response tag', () => { describe('General', () => { it('fails on no responses', async () => { - const requests = [{_id: 'req_1', parentId: 'wrk_1'}]; + const requests = [{ _id: 'req_1', parentId: 'wrk_1' }]; const context = _genTestContext(requests); @@ -17,14 +17,16 @@ describe('Response tag', () => { }); it('fails on no request', async () => { - const requests = [{_id: 'req_1', parentId: 'wrk_1'}]; + const requests = [{ _id: 'req_1', parentId: 'wrk_1' }]; - const responses = [{ - _id: 'res_1', - parentId: 'req_1', - statusCode: 200, - _body: '{"foo": "bar"}' - }]; + const responses = [ + { + _id: 'res_1', + parentId: 'req_1', + statusCode: 200, + _body: '{"foo": "bar"}' + } + ]; const context = _genTestContext(requests, responses); @@ -37,14 +39,16 @@ describe('Response tag', () => { }); it('fails on empty filter', async () => { - const requests = [{_id: 'req_1', parentId: 'wrk_1'}]; + const requests = [{ _id: 'req_1', parentId: 'wrk_1' }]; - const responses = [{ - _id: 'res_1', - parentId: 'req_1', - statusCode: 200, - _body: '{"foo": "bar"}' - }]; + const responses = [ + { + _id: 'res_1', + parentId: 'req_1', + statusCode: 200, + _body: '{"foo": "bar"}' + } + ]; const context = _genTestContext(requests, responses); @@ -59,15 +63,17 @@ describe('Response tag', () => { describe('JSONPath', () => { it('basic query', async () => { - const requests = [{_id: 'req_1', parentId: 'wrk_1'}]; + const requests = [{ _id: 'req_1', parentId: 'wrk_1' }]; - const responses = [{ - _id: 'res_1', - parentId: 'req_1', - statusCode: 200, - contentType: 'application/json', - _body: '{"foo": "bar"}' - }]; + const responses = [ + { + _id: 'res_1', + parentId: 'req_1', + statusCode: 200, + contentType: 'application/json', + _body: '{"foo": "bar"}' + } + ]; const context = _genTestContext(requests, responses); const result = await tag.run(context, 'body', 'req_1', '$.foo'); @@ -76,15 +82,17 @@ describe('Response tag', () => { }); it('fails on invalid JSON', async () => { - const requests = [{_id: 'req_1', parentId: 'wrk_1'}]; + const requests = [{ _id: 'req_1', parentId: 'wrk_1' }]; - const responses = [{ - _id: 'res_1', - parentId: 'req_1', - statusCode: 200, - contentType: 'application/json', - _body: '{"foo": "' - }]; + const responses = [ + { + _id: 'res_1', + parentId: 'req_1', + statusCode: 200, + contentType: 'application/json', + _body: '{"foo": "' + } + ]; const context = _genTestContext(requests, responses); @@ -92,20 +100,24 @@ describe('Response tag', () => { await tag.run(context, 'body', 'req_1', '$.foo'); fail('JSON should have failed'); } catch (err) { - expect(err.message).toContain('Invalid JSON: Unexpected end of JSON input'); + expect(err.message).toContain( + 'Invalid JSON: Unexpected end of JSON input' + ); } }); it('fails on invalid query', async () => { - const requests = [{_id: 'req_1', parentId: 'wrk_1'}]; + const requests = [{ _id: 'req_1', parentId: 'wrk_1' }]; - const responses = [{ - _id: 'res_1', - parentId: 'req_1', - statusCode: 200, - contentType: 'application/json', - _body: '{"foo": "bar"}' - }]; + const responses = [ + { + _id: 'res_1', + parentId: 'req_1', + statusCode: 200, + contentType: 'application/json', + _body: '{"foo": "bar"}' + } + ]; const context = _genTestContext(requests, responses); @@ -118,15 +130,17 @@ describe('Response tag', () => { }); it('fails on no results', async () => { - const requests = [{_id: 'req_1', parentId: 'wrk_1'}]; + const requests = [{ _id: 'req_1', parentId: 'wrk_1' }]; - const responses = [{ - _id: 'res_1', - parentId: 'req_1', - statusCode: 200, - contentType: 'application/json', - _body: '{"foo": "bar"}' - }]; + const responses = [ + { + _id: 'res_1', + parentId: 'req_1', + statusCode: 200, + contentType: 'application/json', + _body: '{"foo": "bar"}' + } + ]; const context = _genTestContext(requests, responses); @@ -139,15 +153,17 @@ describe('Response tag', () => { }); it('fails on more than 1 result', async () => { - const requests = [{_id: 'req_1', parentId: 'wrk_1'}]; + const requests = [{ _id: 'req_1', parentId: 'wrk_1' }]; - const responses = [{ - _id: 'res_1', - parentId: 'req_1', - statusCode: 200, - contentType: 'application/json', - _body: '{"array": ["bar", "baz"]}' - }]; + const responses = [ + { + _id: 'res_1', + parentId: 'req_1', + statusCode: 200, + contentType: 'application/json', + _body: '{"array": ["bar", "baz"]}' + } + ]; const context = _genTestContext(requests, responses); @@ -155,20 +171,24 @@ describe('Response tag', () => { await tag.run(context, 'body', 'req_1', '$.array.*'); fail('JSON should have failed to parse'); } catch (err) { - expect(err.message).toContain('Returned more than one result: $.array.*'); + expect(err.message).toContain( + 'Returned more than one result: $.array.*' + ); } }); it('works with utf-16 encoding', async () => { - const requests = [{_id: 'req_1', parentId: 'wrk_1'}]; + const requests = [{ _id: 'req_1', parentId: 'wrk_1' }]; - const responses = [{ - _id: 'res_1', - parentId: 'req_1', - statusCode: 200, - contentType: 'application/json; charset=UTF-16', - _body: iconv.encode('{"array": ["bar", "baz"]}', 'UTF-16') - }]; + const responses = [ + { + _id: 'res_1', + parentId: 'req_1', + statusCode: 200, + contentType: 'application/json; charset=UTF-16', + _body: iconv.encode('{"array": ["bar", "baz"]}', 'UTF-16') + } + ]; const context = _genTestContext(requests, responses); @@ -178,15 +198,17 @@ describe('Response tag', () => { describe('XPath', async () => { it('renders basic response "body" query', async () => { - const requests = [{_id: 'req_1', parentId: 'wrk_1'}]; + const requests = [{ _id: 'req_1', parentId: 'wrk_1' }]; - const responses = [{ - _id: 'res_1', - parentId: 'req_1', - statusCode: 200, - contentType: 'application/xml', - _body: 'Hello World!' - }]; + const responses = [ + { + _id: 'res_1', + parentId: 'req_1', + statusCode: 200, + contentType: 'application/xml', + _body: 'Hello World!' + } + ]; const context = _genTestContext(requests, responses); const result = await tag.run(context, 'body', 'req_1', '/foo/bar'); @@ -195,15 +217,17 @@ describe('Response tag', () => { }); it('renders basic response "body" attribute query', async () => { - const requests = [{_id: 'req_1', parentId: 'wrk_1'}]; + const requests = [{ _id: 'req_1', parentId: 'wrk_1' }]; - const responses = [{ - _id: 'res_1', - parentId: 'req_1', - statusCode: 200, - contentType: 'application/xml', - _body: 'Hello World!' - }]; + const responses = [ + { + _id: 'res_1', + parentId: 'req_1', + statusCode: 200, + contentType: 'application/xml', + _body: 'Hello World!' + } + ]; const context = _genTestContext(requests, responses); const result = await tag.run(context, 'body', 'req_1', '/foo/bar/@hello'); @@ -212,32 +236,41 @@ describe('Response tag', () => { }); it('renders query that does not start with slash', async () => { - const requests = [{_id: 'req_1', parentId: 'wrk_1'}]; + const requests = [{ _id: 'req_1', parentId: 'wrk_1' }]; - const responses = [{ - _id: 'res_1', - parentId: 'req_1', - statusCode: 200, - contentType: 'application/xml', - _body: 'Hello World!' - }]; + const responses = [ + { + _id: 'res_1', + parentId: 'req_1', + statusCode: 200, + contentType: 'application/xml', + _body: 'Hello World!' + } + ]; const context = _genTestContext(requests, responses); - const result = await tag.run(context, 'body', 'req_1', 'substring(/foo/bar, 7)'); + const result = await tag.run( + context, + 'body', + 'req_1', + 'substring(/foo/bar, 7)' + ); expect(result).toBe('World!'); }); it('no results on invalid XML', async () => { - const requests = [{_id: 'req_1', parentId: 'wrk_1'}]; + const requests = [{ _id: 'req_1', parentId: 'wrk_1' }]; - const responses = [{ - _id: 'res_1', - parentId: 'req_1', - statusCode: 200, - contentType: 'application/xml', - _body: '' - }]; + const responses = [ + { + _id: 'res_1', + parentId: 'req_1', + statusCode: 200, + contentType: 'application/xml', + _body: '' + } + ]; const context = _genTestContext(requests, responses); @@ -250,15 +283,17 @@ describe('Response tag', () => { }); it('fails on invalid query', async () => { - const requests = [{_id: 'req_1', parentId: 'wrk_1'}]; + const requests = [{ _id: 'req_1', parentId: 'wrk_1' }]; - const responses = [{ - _id: 'res_1', - parentId: 'req_1', - statusCode: 200, - contentType: 'application/xml', - _body: '' - }]; + const responses = [ + { + _id: 'res_1', + parentId: 'req_1', + statusCode: 200, + contentType: 'application/xml', + _body: '' + } + ]; const context = _genTestContext(requests, responses); @@ -271,15 +306,17 @@ describe('Response tag', () => { }); it('fails on no results', async () => { - const requests = [{_id: 'req_1', parentId: 'wrk_1'}]; + const requests = [{ _id: 'req_1', parentId: 'wrk_1' }]; - const responses = [{ - _id: 'res_1', - parentId: 'req_1', - statusCode: 200, - contentType: 'application/xml', - _body: '' - }]; + const responses = [ + { + _id: 'res_1', + parentId: 'req_1', + statusCode: 200, + contentType: 'application/xml', + _body: '' + } + ]; const context = _genTestContext(requests, responses); @@ -292,15 +329,17 @@ describe('Response tag', () => { }); it('fails on more than 1 result', async () => { - const requests = [{_id: 'req_1', parentId: 'wrk_1'}]; + const requests = [{ _id: 'req_1', parentId: 'wrk_1' }]; - const responses = [{ - _id: 'res_1', - parentId: 'req_1', - statusCode: 200, - contentType: 'application/xml', - _body: 'Hello World!And again!' - }]; + const responses = [ + { + _id: 'res_1', + parentId: 'req_1', + statusCode: 200, + contentType: 'application/xml', + _body: 'Hello World!And again!' + } + ]; const context = _genTestContext(requests, responses); @@ -315,39 +354,51 @@ describe('Response tag', () => { describe('ResponseExtension Header', async () => { it('renders basic response "header"', async () => { - const requests = [{_id: 'req_1', parentId: 'wrk_1'}]; + const requests = [{ _id: 'req_1', parentId: 'wrk_1' }]; - const responses = [{ - _id: 'res_1', - parentId: 'req_1', - statusCode: 200, - contentType: '', - headers: [ - {name: 'Content-Type', value: 'application/json'}, - {name: 'Content-Length', value: '20'} - ] - }]; + const responses = [ + { + _id: 'res_1', + parentId: 'req_1', + statusCode: 200, + contentType: '', + headers: [ + { name: 'Content-Type', value: 'application/json' }, + { name: 'Content-Length', value: '20' } + ] + } + ]; const context = _genTestContext(requests, responses); - expect(await tag.run(context, 'header', 'req_1', 'content-type')).toBe('application/json'); - expect(await tag.run(context, 'header', 'req_1', 'Content-Type')).toBe('application/json'); - expect(await tag.run(context, 'header', 'req_1', 'CONTENT-type')).toBe('application/json'); - expect(await tag.run(context, 'header', 'req_1', 'CONTENT-type ')).toBe('application/json'); + expect(await tag.run(context, 'header', 'req_1', 'content-type')).toBe( + 'application/json' + ); + expect(await tag.run(context, 'header', 'req_1', 'Content-Type')).toBe( + 'application/json' + ); + expect(await tag.run(context, 'header', 'req_1', 'CONTENT-type')).toBe( + 'application/json' + ); + expect( + await tag.run(context, 'header', 'req_1', 'CONTENT-type ') + ).toBe('application/json'); }); it('no results on missing header', async () => { - const requests = [{_id: 'req_1', parentId: 'wrk_1'}]; + const requests = [{ _id: 'req_1', parentId: 'wrk_1' }]; - const responses = [{ - _id: 'res_1', - parentId: 'req_1', - statusCode: 200, - headers: [ - {name: 'Content-Type', value: 'application/json'}, - {name: 'Content-Length', value: '20'} - ] - }]; + const responses = [ + { + _id: 'res_1', + parentId: 'req_1', + statusCode: 200, + headers: [ + { name: 'Content-Type', value: 'application/json' }, + { name: 'Content-Length', value: '20' } + ] + } + ]; const context = _genTestContext(requests, responses); @@ -355,23 +406,27 @@ describe('Response tag', () => { await tag.run(context, 'header', 'req_1', 'missing'); fail('should have failed'); } catch (err) { - expect(err.message).toBe('No header with name "missing".\n' + - 'Choices are [\n\t"Content-Type",\n\t"Content-Length"\n]'); + expect(err.message).toBe( + 'No header with name "missing".\n' + + 'Choices are [\n\t"Content-Type",\n\t"Content-Length"\n]' + ); } }); }); describe('Raw', async () => { it('renders basic response', async () => { - const requests = [{_id: 'req_1', parentId: 'wrk_1'}]; + const requests = [{ _id: 'req_1', parentId: 'wrk_1' }]; - const responses = [{ - _id: 'res_1', - parentId: 'req_1', - statusCode: 200, - contentType: 'text/plain', - _body: 'Hello World!' - }]; + const responses = [ + { + _id: 'res_1', + parentId: 'req_1', + statusCode: 200, + contentType: 'text/plain', + _body: 'Hello World!' + } + ]; const context = _genTestContext(requests, responses); @@ -380,7 +435,7 @@ describe('Response tag', () => { }); }); -function _genTestContext (requests, responses) { +function _genTestContext(requests, responses) { requests = requests || []; responses = responses || []; const bodies = {}; @@ -392,15 +447,15 @@ function _genTestContext (requests, responses) { util: { models: { request: { - getById (requestId) { + getById(requestId) { return requests.find(r => r._id === requestId) || null; } }, response: { - getLatestForRequestId (requestId) { + getLatestForRequestId(requestId) { return responses.find(r => r.parentId === requestId) || null; }, - getBodyBuffer (response) { + getBodyBuffer(response) { const strOrBuffer = bodies[response._id]; if (typeof strOrBuffer === 'string') { diff --git a/plugins/insomnia-plugin-response/index.js b/plugins/insomnia-plugin-response/index.js index 6cae019fea..8ab8f8e728 100644 --- a/plugins/insomnia-plugin-response/index.js +++ b/plugins/insomnia-plugin-response/index.js @@ -1,114 +1,136 @@ const jq = require('jsonpath'); const iconv = require('iconv-lite'); -const {query: queryXPath} = require('insomnia-xpath'); +const { query: queryXPath } = require('insomnia-xpath'); -module.exports.templateTags = [{ - name: 'response', - displayName: 'Response', - description: 'reference values from other request\'s responses', - args: [ - { - displayName: 'Attribute', - type: 'enum', - options: [ - {displayName: 'Body Attribute', description: 'value of response body', value: 'body'}, - {displayName: 'Raw Body', description: 'entire response body', value: 'raw'}, - {displayName: 'Header', description: 'value of response header', value: 'header'} - ] - }, - { - displayName: 'Request', - type: 'model', - model: 'Request' - }, - { - type: 'string', - hide: args => args[0].value === 'raw', - displayName: args => { - switch (args[0].value) { - case 'body': - return 'Filter (JSONPath or XPath)'; - case 'header': - return 'Header Name'; - default : - return 'Filter'; +module.exports.templateTags = [ + { + name: 'response', + displayName: 'Response', + description: "reference values from other request's responses", + args: [ + { + displayName: 'Attribute', + type: 'enum', + options: [ + { + displayName: 'Body Attribute', + description: 'value of response body', + value: 'body' + }, + { + displayName: 'Raw Body', + description: 'entire response body', + value: 'raw' + }, + { + displayName: 'Header', + description: 'value of response header', + value: 'header' + } + ] + }, + { + displayName: 'Request', + type: 'model', + model: 'Request' + }, + { + type: 'string', + hide: args => args[0].value === 'raw', + displayName: args => { + switch (args[0].value) { + case 'body': + return 'Filter (JSONPath or XPath)'; + case 'header': + return 'Header Name'; + default: + return 'Filter'; + } } } - } - ], + ], - async run (context, field, id, filter) { - filter = filter || ''; + async run(context, field, id, filter) { + filter = filter || ''; - if (!['body', 'header', 'raw'].includes(field)) { - throw new Error(`Invalid response field ${field}`); - } - - if (!id) { - throw new Error('No request specified'); - } - - const request = await context.util.models.request.getById(id); - if (!request) { - throw new Error(`Could not find request ${id}`); - } - - const response = await context.util.models.response.getLatestForRequestId(id); - - if (!response) { - throw new Error('No responses for request'); - } - - if (!response.statusCode) { - throw new Error('No successful responses for request'); - } - - if (field !== 'raw' && !filter) { - throw new Error(`No ${field} filter specified`); - } - - const sanitizedFilter = filter.trim(); - - if (field === 'header') { - return matchHeader(response.headers, sanitizedFilter); - } else if (field === 'raw') { - const bodyBuffer = context.util.models.response.getBodyBuffer(response, ''); - const match = response.contentType.match(/charset=([\w-]+)/); - const charset = (match && match.length >= 2) ? match[1] : 'utf-8'; - - // Sometimes iconv conversion fails so fallback to regular buffer - try { - return iconv.decode(bodyBuffer, charset); - } catch (err) { - console.warn('[response] Failed to decode body', err); - return bodyBuffer.toString(); - } - } else if (field === 'body') { - const bodyBuffer = context.util.models.response.getBodyBuffer(response, ''); - const match = response.contentType.match(/charset=([\w-]+)/); - const charset = (match && match.length >= 2) ? match[1] : 'utf-8'; - - // Sometimes iconv conversion fails so fallback to regular buffer - let body; - try { - body = iconv.decode(bodyBuffer, charset); - } catch (err) { - body = bodyBuffer.toString(); - console.warn('[response] Failed to decode body', err); + if (!['body', 'header', 'raw'].includes(field)) { + throw new Error(`Invalid response field ${field}`); } - if (sanitizedFilter.indexOf('$') === 0) { - return matchJSONPath(body, sanitizedFilter); + if (!id) { + throw new Error('No request specified'); + } + + const request = await context.util.models.request.getById(id); + if (!request) { + throw new Error(`Could not find request ${id}`); + } + + const response = await context.util.models.response.getLatestForRequestId( + id + ); + + if (!response) { + throw new Error('No responses for request'); + } + + if (!response.statusCode) { + throw new Error('No successful responses for request'); + } + + if (field !== 'raw' && !filter) { + throw new Error(`No ${field} filter specified`); + } + + const sanitizedFilter = filter.trim(); + + if (field === 'header') { + return matchHeader(response.headers, sanitizedFilter); + } else if (field === 'raw') { + const bodyBuffer = context.util.models.response.getBodyBuffer( + response, + '' + ); + const match = response.contentType.match(/charset=([\w-]+)/); + const charset = match && match.length >= 2 ? match[1] : 'utf-8'; + + // Sometimes iconv conversion fails so fallback to regular buffer + try { + return iconv.decode(bodyBuffer, charset); + } catch (err) { + console.warn('[response] Failed to decode body', err); + return bodyBuffer.toString(); + } + } else if (field === 'body') { + const bodyBuffer = context.util.models.response.getBodyBuffer( + response, + '' + ); + const match = response.contentType.match(/charset=([\w-]+)/); + const charset = match && match.length >= 2 ? match[1] : 'utf-8'; + + // Sometimes iconv conversion fails so fallback to regular buffer + let body; + try { + body = iconv.decode(bodyBuffer, charset); + } catch (err) { + body = bodyBuffer.toString(); + console.warn('[response] Failed to decode body', err); + } + + if (sanitizedFilter.indexOf('$') === 0) { + return matchJSONPath(body, sanitizedFilter); + } else { + return matchXPath(body, sanitizedFilter); + } } else { - return matchXPath(body, sanitizedFilter); + throw new Error(`Unknown field ${field}`); } - } else { - throw new Error(`Unknown field ${field}`); } } -}]; +]; -function matchJSONPath (bodyStr, query) { +function matchJSONPath(bodyStr, query) { let body; let results; @@ -137,7 +159,7 @@ function matchJSONPath (bodyStr, query) { } } -function matchXPath (bodyStr, query) { +function matchXPath(bodyStr, query) { const results = queryXPath(bodyStr, query); if (results.length === 0) { @@ -149,20 +171,19 @@ function matchXPath (bodyStr, query) { return results[0].inner; } -function matchHeader (headers, name) { +function matchHeader(headers, name) { if (!headers.length) { throw new Error(`No headers available`); } - const header = headers.find( - h => h.name.toLowerCase() === name.toLowerCase() - ); + const header = headers.find(h => h.name.toLowerCase() === name.toLowerCase()); if (!header) { const names = headers.map(c => `"${c.name}"`).join(',\n\t'); - throw new Error(`No header with name "${name}".\nChoices are [\n\t${names}\n]`); + throw new Error( + `No header with name "${name}".\nChoices are [\n\t${names}\n]` + ); } return header.value; } - diff --git a/plugins/insomnia-plugin-uuid/__tests__/index.test.js b/plugins/insomnia-plugin-uuid/__tests__/index.test.js index d0189241c8..653c874299 100644 --- a/plugins/insomnia-plugin-uuid/__tests__/index.test.js +++ b/plugins/insomnia-plugin-uuid/__tests__/index.test.js @@ -1,7 +1,7 @@ const tag = require('..').templateTags[0]; -function assertTemplate (args, expected) { - return async function () { +function assertTemplate(args, expected) { + return async function() { const result = await tag.run(null, ...args); if (expected instanceof RegExp) { expect(result).toMatch(expected); @@ -11,8 +11,8 @@ function assertTemplate (args, expected) { }; } -function assertTemplateFails (args, expected) { - return async function () { +function assertTemplateFails(args, expected) { + return async function() { try { await tag.run(null, ...args); fail(`Render should have thrown ${expected}`); diff --git a/plugins/insomnia-plugin-uuid/index.js b/plugins/insomnia-plugin-uuid/index.js index a0abf7d5c3..f7bf511bf1 100644 --- a/plugins/insomnia-plugin-uuid/index.js +++ b/plugins/insomnia-plugin-uuid/index.js @@ -1,33 +1,37 @@ const uuid = require('uuid'); -module.exports.templateTags = [{ - displayName: 'UUID', - name: 'uuid', - description: 'generate v1 or v4 UUIDs', - args: [{ - displayName: 'Version', - type: 'enum', - options: [ - {displayName: 'Version 4', value: 'v4'}, - {displayName: 'Version 1', value: 'v1'} - ] - }], - run (context, uuidType = 'v4') { - if (typeof uuidType === 'number') { - uuidType += ''; - } else if (typeof uuidType === 'string') { - uuidType = uuidType.toLowerCase(); - } +module.exports.templateTags = [ + { + displayName: 'UUID', + name: 'uuid', + description: 'generate v1 or v4 UUIDs', + args: [ + { + displayName: 'Version', + type: 'enum', + options: [ + { displayName: 'Version 4', value: 'v4' }, + { displayName: 'Version 1', value: 'v1' } + ] + } + ], + run(context, uuidType = 'v4') { + if (typeof uuidType === 'number') { + uuidType += ''; + } else if (typeof uuidType === 'string') { + uuidType = uuidType.toLowerCase(); + } - switch (uuidType) { - case '1': - case 'v1': - return uuid.v1(); - case '4': - case 'v4': - return uuid.v4(); - default: - throw new Error(`Invalid UUID type "${uuidType}"`); + switch (uuidType) { + case '1': + case 'v1': + return uuid.v1(); + case '4': + case 'v4': + return uuid.v4(); + default: + throw new Error(`Invalid UUID type "${uuidType}"`); + } } } -}]; +];