From d08d0458cf373fc8880e038d0336ec656d5269b8 Mon Sep 17 00:00:00 2001 From: Amin Mahboubi Date: Thu, 16 Jul 2020 12:27:25 +0200 Subject: [PATCH 01/69] typescript init --- .babelrc | 7 +- .eslintignore | 1 + .eslintrc.js | 39 +++++++++ babel-register.js | 2 + package.json | 21 +++-- tsconfig.json | 16 ++++ webpack.config.js | 8 +- yarn.lock | 214 +++++++++++++++++++++++++++++++++++++++++++--- 8 files changed, 283 insertions(+), 25 deletions(-) create mode 100644 babel-register.js create mode 100644 tsconfig.json diff --git a/.babelrc b/.babelrc index 8d81ddd1..2b529c1a 100644 --- a/.babelrc +++ b/.babelrc @@ -1,14 +1,13 @@ { "presets": [ - [ - "@babel/preset-env", - { "targets": { "browsers": ["last 2 versions", "ie >= 10"] } } - ] + ["@babel/preset-env", { "targets": { "browsers": ["last 2 versions", "ie >= 10"] } }], + "@babel/preset-typescript" ], "sourceType": "unambiguous", "plugins": [ "@babel/plugin-transform-object-assign", "@babel/plugin-transform-runtime", + "@babel/proposal-object-rest-spread", "@babel/plugin-proposal-class-properties" ], "ignore": ["node_modules", "dist", "lib"] diff --git a/.eslintignore b/.eslintignore index 8ceb4255..bce3ae64 100644 --- a/.eslintignore +++ b/.eslintignore @@ -5,4 +5,5 @@ test/integration/utils/kjur.js /bin/ /.git/ /docs/ +/types **/*.sh diff --git a/.eslintrc.js b/.eslintrc.js index d71bf1e6..f8da6d80 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -1,4 +1,5 @@ module.exports = { + root: true, plugins: ['prettier', 'chai-friendly'], extends: [ 'airbnb-base', @@ -17,10 +18,18 @@ module.exports = { globals: { process: true, }, + settings: { + 'import/resolver': { + node: { + extensions: ['.js', '.ts'], + }, + }, + }, rules: { 'consistent-return': 0, 'no-underscore-dangle': 0, 'import/prefer-default-export': 0, + 'import/extensions': ['error', 'never', { json: 'always' }], 'func-names': 0, 'no-param-reassign': 0, 'prefer-destructuring': ['error', { object: true, array: false }], @@ -31,4 +40,34 @@ module.exports = { 'sonarjs/no-duplicate-string': 0, 'sonarjs/no-identical-functions': 0, }, + overrides: [ + { + files: ['**/*.ts'], + plugins: ['prettier', '@typescript-eslint'], + extends: [ + 'airbnb-base', + 'eslint:recommended', + 'plugin:prettier/recommended', + 'prettier/@typescript-eslint', + 'plugin:@typescript-eslint/recommended', + 'plugin:sonarjs/recommended', + ], + parser: '@typescript-eslint/parser', + rules: { + 'consistent-return': 0, + 'no-underscore-dangle': 0, + 'import/prefer-default-export': 0, + 'import/extensions': ['error', 'never', { json: 'always' }], + 'func-names': 0, + 'no-param-reassign': 0, + 'prefer-destructuring': ['error', { object: true, array: false }], + 'max-classes-per-file': 0, + 'no-plusplus': 0, + 'sonarjs/cognitive-complexity': 0, + 'sonarjs/no-collapsible-if': 0, + 'sonarjs/no-duplicate-string': 0, + 'sonarjs/no-identical-functions': 0, + }, + }, + ], }; diff --git a/babel-register.js b/babel-register.js new file mode 100644 index 00000000..48c4ad80 --- /dev/null +++ b/babel-register.js @@ -0,0 +1,2 @@ +/* eslint-disable import/no-extraneous-dependencies */ +require('@babel/register')({ extensions: ['.js', '.ts'] }); diff --git a/package.json b/package.json index e4ba1791..5c2bc358 100644 --- a/package.json +++ b/package.json @@ -13,17 +13,18 @@ "license": "BSD-3-Clause", "version": "5.0.1", "scripts": { - "build": "babel src --out-dir lib", + "types": "tsc --outFile types/index --declaration true --declarationMap true --emitDeclarationOnly true", + "build": "babel src --out-dir lib --extensions '.js,.ts'", "dtslint": "dtslint types/getstream", - "eslint": "eslint '**/*.js' --max-warnings 0", + "eslint": "eslint '**/*.{js,ts}' --max-warnings 0", "prettier": "prettier --list-different '**/*.{js,ts}'", "lint": "yarn run prettier && yarn run eslint", - "lint-fix": "prettier --write '**/*.{js,ts}' && eslint --fix '**/*.js'", + "lint-fix": "prettier --write '**/*.{js,ts}' && eslint --fix '**/*.{js,ts}'", "test": "yarn run test-unit-node", - "test-unit-node": "mocha --require @babel/register test/unit/common test/unit/node", - "test-integration-node": "mocha --require @babel/register test/integration/common test/integration/node --exit", - "test-cloud": "mocha --require @babel/register test/integration/cloud --timeout 40000", - "test-cloud-local": "LOCAL=true mocha --require @babel/register test/integration/cloud --timeout 40000 -i --grep 'Files|Images'", + "test-unit-node": "mocha --require ./babel-register.js test/unit/common test/unit/node", + "test-integration-node": "mocha --require ./babel-register.js test/integration/common test/integration/node --exit", + "test-cloud": "mocha --require ./babel-register.js test/integration/cloud --timeout 40000", + "test-cloud-local": "LOCAL=true mocha --require ./babel-register.js test/integration/cloud --timeout 40000 -i --grep 'Files|Images'", "test-browser": "karma start karma.config.js", "generate-docs": "jsdoc -c .jsdoc", "coverage": "nyc yarn run test-unit-node && nyc report --reporter=text-lcov | codecov --pipe", @@ -58,11 +59,15 @@ "@babel/core": "^7.10.4", "@babel/node": "^7.10.4", "@babel/plugin-proposal-class-properties": "^7.10.4", + "@babel/plugin-proposal-object-rest-spread": "^7.10.4", "@babel/plugin-transform-object-assign": "^7.10.4", "@babel/plugin-transform-runtime": "^7.10.4", "@babel/preset-env": "^7.10.4", + "@babel/preset-typescript": "^7.10.4", "@babel/register": "^7.10.4", "@types/node": "^14.0.14", + "@typescript-eslint/eslint-plugin": "^3.6.1", + "@typescript-eslint/parser": "^3.6.1", "babel-eslint": "^10.1.0", "babel-loader": "^8.1.0", "chai": "^4.2.0", @@ -92,7 +97,7 @@ "prettier": "^2.0.5", "request": "^2.88.2", "testdouble": "^3.16.0", - "typescript": "^3.9.5", + "typescript": "^3.9.6", "uglifyjs-webpack-plugin": "^2.2.0", "webpack": "^4.43.0", "webpack-cli": "^3.3.12" diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 00000000..8bd05c16 --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "outDir": "types", + "allowJs": true, + "allowSyntheticDefaultImports": true, + "esModuleInterop": true, + "resolveJsonModule": true, + "noImplicitAny": true, + "strictNullChecks": true, + "strict": true, + "lib": ["DOM", "ES6"], + "target": "ES5" + }, + "include": ["src/**/*"], + "exclude": ["node_modules", "test", "lib", "dist", "types"] +} diff --git a/webpack.config.js b/webpack.config.js index 0532fa20..f658935f 100644 --- a/webpack.config.js +++ b/webpack.config.js @@ -13,13 +13,17 @@ module.exports = (env, argv = []) => ({ use: 'null-loader', }, { - test: /\.js$/, - exclude: /(node_modules|bower_components)/, + test: /\.(js|ts)$/, use: 'babel-loader', + exclude: /node_modules/, }, ], }, + resolve: { + extensions: ['.js', '.ts'], + }, + node: { console: false, Buffer: false, diff --git a/yarn.lock b/yarn.lock index 6533def3..e88a4e66 100644 --- a/yarn.lock +++ b/yarn.lock @@ -105,6 +105,15 @@ lodash "^4.17.13" source-map "^0.5.0" +"@babel/generator@^7.10.5": + version "7.10.5" + resolved "https://registry.yarnpkg.com/@babel/generator/-/generator-7.10.5.tgz#1b903554bc8c583ee8d25f1e8969732e6b829a69" + integrity sha512-3vXxr3FEW7E7lJZiWQ3bM4+v/Vyr9C+hpolQ8BGFr9Y8Ri2tFLWTixmwKBafDujO1WVah4fhZBeU1bieKdghig== + dependencies: + "@babel/types" "^7.10.5" + jsesc "^2.5.1" + source-map "^0.5.0" + "@babel/helper-annotate-as-pure@^7.10.1": version "7.10.1" resolved "https://registry.yarnpkg.com/@babel/helper-annotate-as-pure/-/helper-annotate-as-pure-7.10.1.tgz#f6d08acc6f70bbd59b436262553fb2e259a1a268" @@ -150,6 +159,18 @@ "@babel/helper-replace-supers" "^7.10.4" "@babel/helper-split-export-declaration" "^7.10.4" +"@babel/helper-create-class-features-plugin@^7.10.5": + version "7.10.5" + resolved "https://registry.yarnpkg.com/@babel/helper-create-class-features-plugin/-/helper-create-class-features-plugin-7.10.5.tgz#9f61446ba80e8240b0a5c85c6fdac8459d6f259d" + integrity sha512-0nkdeijB7VlZoLT3r/mY3bUkw3T8WG/hNw+FATs/6+pG2039IJWjTYL0VTISqsNHMUTEnwbVnc89WIJX9Qed0A== + dependencies: + "@babel/helper-function-name" "^7.10.4" + "@babel/helper-member-expression-to-functions" "^7.10.5" + "@babel/helper-optimise-call-expression" "^7.10.4" + "@babel/helper-plugin-utils" "^7.10.4" + "@babel/helper-replace-supers" "^7.10.4" + "@babel/helper-split-export-declaration" "^7.10.4" + "@babel/helper-create-regexp-features-plugin@^7.10.1": version "7.10.1" resolved "https://registry.yarnpkg.com/@babel/helper-create-regexp-features-plugin/-/helper-create-regexp-features-plugin-7.10.1.tgz#1b8feeab1594cbcfbf3ab5a3bbcabac0468efdbd" @@ -238,6 +259,13 @@ dependencies: "@babel/types" "^7.10.4" +"@babel/helper-member-expression-to-functions@^7.10.5": + version "7.10.5" + resolved "https://registry.yarnpkg.com/@babel/helper-member-expression-to-functions/-/helper-member-expression-to-functions-7.10.5.tgz#172f56e7a63e78112f3a04055f24365af702e7ee" + integrity sha512-HiqJpYD5+WopCXIAbQDG0zye5XYVvcO9w/DHp5GsaGkRUaamLj2bEtu6i8rnGGprAhHM3qidCMgp71HF4endhA== + dependencies: + "@babel/types" "^7.10.5" + "@babel/helper-module-imports@^7.10.1": version "7.10.1" resolved "https://registry.yarnpkg.com/@babel/helper-module-imports/-/helper-module-imports-7.10.1.tgz#dd331bd45bccc566ce77004e9d05fe17add13876" @@ -447,7 +475,7 @@ resolve "^1.13.1" v8flags "^3.1.1" -"@babel/parser@^7.10.1", "@babel/parser@^7.10.2", "@babel/parser@^7.7.0", "@babel/parser@^7.9.4": +"@babel/parser@^7.10.1", "@babel/parser@^7.10.2", "@babel/parser@^7.9.4": version "7.10.2" resolved "https://registry.yarnpkg.com/@babel/parser/-/parser-7.10.2.tgz#871807f10442b92ff97e4783b9b54f6a0ca812d0" integrity sha512-PApSXlNMJyB4JiGVhCOlzKIif+TKFTvu0aQAhnTvfP/z3vVSN6ZypH5bfUNwFXXjRQtUEBNFd2PtmCmG2Py3qQ== @@ -457,6 +485,11 @@ resolved "https://registry.yarnpkg.com/@babel/parser/-/parser-7.10.4.tgz#9eedf27e1998d87739fb5028a5120557c06a1a64" integrity sha512-8jHII4hf+YVDsskTF6WuMB3X4Eh+PsUkC2ljq22so5rHvH+T8BzyL94VOdyFLNR8tBSVXOTbNHOKpR4TfRxVtA== +"@babel/parser@^7.10.5", "@babel/parser@^7.7.0": + version "7.10.5" + resolved "https://registry.yarnpkg.com/@babel/parser/-/parser-7.10.5.tgz#e7c6bf5a7deff957cec9f04b551e2762909d826b" + integrity sha512-wfryxy4bE1UivvQKSQDU4/X6dr+i8bctjUjj8Zyt3DQy7NtPizJXT8M52nqpNKL+nq2PW8lxk4ZqLj0fD4B4hQ== + "@babel/plugin-proposal-async-generator-functions@^7.10.4": version "7.10.4" resolved "https://registry.yarnpkg.com/@babel/plugin-proposal-async-generator-functions/-/plugin-proposal-async-generator-functions-7.10.4.tgz#4b65abb3d9bacc6c657aaa413e56696f9f170fc6" @@ -625,6 +658,13 @@ dependencies: "@babel/helper-plugin-utils" "^7.10.4" +"@babel/plugin-syntax-typescript@^7.10.4": + version "7.10.4" + resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-typescript/-/plugin-syntax-typescript-7.10.4.tgz#2f55e770d3501e83af217d782cb7517d7bb34d25" + integrity sha512-oSAEz1YkBCAKr5Yiq8/BNtvSAPwkp/IyUnwZogd8p+F0RuYQQrLeRUzIQhueQTTBy/F+a40uS7OFKxnkRvmvFQ== + dependencies: + "@babel/helper-plugin-utils" "^7.10.4" + "@babel/plugin-transform-arrow-functions@^7.10.4": version "7.10.4" resolved "https://registry.yarnpkg.com/@babel/plugin-transform-arrow-functions/-/plugin-transform-arrow-functions-7.10.4.tgz#e22960d77e697c74f41c501d44d73dbf8a6a64cd" @@ -886,6 +926,15 @@ dependencies: "@babel/helper-plugin-utils" "^7.10.4" +"@babel/plugin-transform-typescript@^7.10.4": + version "7.10.5" + resolved "https://registry.yarnpkg.com/@babel/plugin-transform-typescript/-/plugin-transform-typescript-7.10.5.tgz#edf353944e979f40d8ff9fe4e9975d0a465037c5" + integrity sha512-YCyYsFrrRMZ3qR7wRwtSSJovPG5vGyG4ZdcSAivGwTfoasMp3VOB/AKhohu3dFtmB4cCDcsndCSxGtrdliCsZQ== + dependencies: + "@babel/helper-create-class-features-plugin" "^7.10.5" + "@babel/helper-plugin-utils" "^7.10.4" + "@babel/plugin-syntax-typescript" "^7.10.4" + "@babel/plugin-transform-unicode-escapes@^7.10.4": version "7.10.4" resolved "https://registry.yarnpkg.com/@babel/plugin-transform-unicode-escapes/-/plugin-transform-unicode-escapes-7.10.4.tgz#feae523391c7651ddac115dae0a9d06857892007" @@ -982,6 +1031,14 @@ "@babel/types" "^7.4.4" esutils "^2.0.2" +"@babel/preset-typescript@^7.10.4": + version "7.10.4" + resolved "https://registry.yarnpkg.com/@babel/preset-typescript/-/preset-typescript-7.10.4.tgz#7d5d052e52a682480d6e2cc5aa31be61c8c25e36" + integrity sha512-SdYnvGPv+bLlwkF2VkJnaX/ni1sMNetcGI1+nThF1gyv6Ph8Qucc4ZZAjM5yZcE/AKRXIOTZz7eSRDWOEjPyRQ== + dependencies: + "@babel/helper-plugin-utils" "^7.10.4" + "@babel/plugin-transform-typescript" "^7.10.4" + "@babel/register@^7.10.4": version "7.10.4" resolved "https://registry.yarnpkg.com/@babel/register/-/register-7.10.4.tgz#53004ba8b04c4af3cbd84508e03ad150669746e4" @@ -1025,7 +1082,7 @@ "@babel/parser" "^7.10.4" "@babel/types" "^7.10.4" -"@babel/traverse@^7.10.1", "@babel/traverse@^7.7.0": +"@babel/traverse@^7.10.1": version "7.10.1" resolved "https://registry.yarnpkg.com/@babel/traverse/-/traverse-7.10.1.tgz#bbcef3031e4152a6c0b50147f4958df54ca0dd27" integrity sha512-C/cTuXeKt85K+p08jN6vMDz8vSV0vZcI0wmQ36o6mjbuo++kPMdpOYw23W2XH04dbRt9/nMEfA4W3eR21CD+TQ== @@ -1055,7 +1112,22 @@ globals "^11.1.0" lodash "^4.17.13" -"@babel/types@^7.10.1", "@babel/types@^7.10.2", "@babel/types@^7.4.4", "@babel/types@^7.7.0": +"@babel/traverse@^7.7.0": + version "7.10.5" + resolved "https://registry.yarnpkg.com/@babel/traverse/-/traverse-7.10.5.tgz#77ce464f5b258be265af618d8fddf0536f20b564" + integrity sha512-yc/fyv2gUjPqzTz0WHeRJH2pv7jA9kA7mBX2tXl/x5iOE81uaVPuGPtaYk7wmkx4b67mQ7NqI8rmT2pF47KYKQ== + dependencies: + "@babel/code-frame" "^7.10.4" + "@babel/generator" "^7.10.5" + "@babel/helper-function-name" "^7.10.4" + "@babel/helper-split-export-declaration" "^7.10.4" + "@babel/parser" "^7.10.5" + "@babel/types" "^7.10.5" + debug "^4.1.0" + globals "^11.1.0" + lodash "^4.17.19" + +"@babel/types@^7.10.1", "@babel/types@^7.10.2", "@babel/types@^7.4.4": version "7.10.2" resolved "https://registry.yarnpkg.com/@babel/types/-/types-7.10.2.tgz#30283be31cad0dbf6fb00bd40641ca0ea675172d" integrity sha512-AD3AwWBSz0AWF0AkCN9VPiWrvldXq+/e3cHa4J89vo4ymjz1XwrBFFVZmkJTsQIPNk+ZVomPSXUJqq8yyjZsng== @@ -1073,6 +1145,15 @@ lodash "^4.17.13" to-fast-properties "^2.0.0" +"@babel/types@^7.10.5", "@babel/types@^7.7.0": + version "7.10.5" + resolved "https://registry.yarnpkg.com/@babel/types/-/types-7.10.5.tgz#d88ae7e2fde86bfbfe851d4d81afa70a997b5d15" + integrity sha512-ixV66KWfCI6GKoA/2H9v6bQdbfXEwwpOdQ8cRvb4F+eyvhlaHxWFMQB4+3d9QFJXZsiiiqVrewNV0DFEQpyT4Q== + dependencies: + "@babel/helper-validator-identifier" "^7.10.4" + lodash "^4.17.19" + to-fast-properties "^2.0.0" + "@definitelytyped/header-parser@0.0.34": version "0.0.34" resolved "https://registry.yarnpkg.com/@definitelytyped/header-parser/-/header-parser-0.0.34.tgz#892c83ae0cdbc52ee439dfc3ac34244903b8a5ee" @@ -1168,12 +1249,17 @@ resolved "https://registry.yarnpkg.com/@types/color-name/-/color-name-1.1.1.tgz#1c1261bbeaa10a8055bbc5d8ab84b7b2afc846a0" integrity sha512-rr+OQyAjxze7GgWrSaJwydHStIhHq2lvY3BOC2Mj7KnzI7XK0Uw1TOOdI9lDoajEbSWLiYgoo4f1R51erQfhPQ== +"@types/eslint-visitor-keys@^1.0.0": + version "1.0.0" + resolved "https://registry.yarnpkg.com/@types/eslint-visitor-keys/-/eslint-visitor-keys-1.0.0.tgz#1ee30d79544ca84d68d4b3cdb0af4f205663dd2d" + integrity sha512-OCutwjDZ4aFS6PB1UZ988C4YgwlBHJd6wCeQqaLdmadZ/7e+w79+hbMUFC1QXDNCmdyoRfAFdm0RypzwR+Qpag== + "@types/http-cache-semantics@*": version "4.0.0" resolved "https://registry.yarnpkg.com/@types/http-cache-semantics/-/http-cache-semantics-4.0.0.tgz#9140779736aa2655635ee756e2467d787cfe8a2a" integrity sha512-c3Xy026kOF7QOTn00hbIllV1dLR9hG9NkSrLQgCVs8NF6sBU+VGWjD3wLPhmh1TYAc7ugCFsvHYMN4VcBN1U1A== -"@types/json-schema@^7.0.4": +"@types/json-schema@^7.0.3", "@types/json-schema@^7.0.4": version "7.0.5" resolved "https://registry.yarnpkg.com/@types/json-schema/-/json-schema-7.0.5.tgz#dcce4430e64b443ba8945f0290fb564ad5bac6dd" integrity sha512-7+2BITlgjgDhH0vvwZU/HZJVyk+2XUlvxXe8dFMedNX/aMkaOq++rMAFXc0tM7ij15QaWlbdQASBR9dihi+bDQ== @@ -1229,6 +1315,66 @@ dependencies: "@types/node" "*" +"@typescript-eslint/eslint-plugin@^3.6.1": + version "3.6.1" + resolved "https://registry.yarnpkg.com/@typescript-eslint/eslint-plugin/-/eslint-plugin-3.6.1.tgz#5ced8fd2087fbb83a76973dea4a0d39d9cb4a642" + integrity sha512-06lfjo76naNeOMDl+mWG9Fh/a0UHKLGhin+mGaIw72FUMbMGBkdi/FEJmgEDzh4eE73KIYzHWvOCYJ0ak7nrJQ== + dependencies: + "@typescript-eslint/experimental-utils" "3.6.1" + debug "^4.1.1" + functional-red-black-tree "^1.0.1" + regexpp "^3.0.0" + semver "^7.3.2" + tsutils "^3.17.1" + +"@typescript-eslint/experimental-utils@3.6.1": + version "3.6.1" + resolved "https://registry.yarnpkg.com/@typescript-eslint/experimental-utils/-/experimental-utils-3.6.1.tgz#b5a2738ebbceb3fa90c5b07d50bb1225403c4a54" + integrity sha512-oS+hihzQE5M84ewXrTlVx7eTgc52eu+sVmG7ayLfOhyZmJ8Unvf3osyFQNADHP26yoThFfbxcibbO0d2FjnYhg== + dependencies: + "@types/json-schema" "^7.0.3" + "@typescript-eslint/types" "3.6.1" + "@typescript-eslint/typescript-estree" "3.6.1" + eslint-scope "^5.0.0" + eslint-utils "^2.0.0" + +"@typescript-eslint/parser@^3.6.1": + version "3.6.1" + resolved "https://registry.yarnpkg.com/@typescript-eslint/parser/-/parser-3.6.1.tgz#216e8adf4ee9c629f77c985476a2ea07fb80e1dc" + integrity sha512-SLihQU8RMe77YJ/jGTqOt0lMq7k3hlPVfp7v/cxMnXA9T0bQYoMDfTsNgHXpwSJM1Iq2aAJ8WqekxUwGv5F67Q== + dependencies: + "@types/eslint-visitor-keys" "^1.0.0" + "@typescript-eslint/experimental-utils" "3.6.1" + "@typescript-eslint/types" "3.6.1" + "@typescript-eslint/typescript-estree" "3.6.1" + eslint-visitor-keys "^1.1.0" + +"@typescript-eslint/types@3.6.1": + version "3.6.1" + resolved "https://registry.yarnpkg.com/@typescript-eslint/types/-/types-3.6.1.tgz#87600fe79a1874235d3cc1cf5c7e1a12eea69eee" + integrity sha512-NPxd5yXG63gx57WDTW1rp0cF3XlNuuFFB5G+Kc48zZ+51ZnQn9yjDEsjTPQ+aWM+V+Z0I4kuTFKjKvgcT1F7xQ== + +"@typescript-eslint/typescript-estree@3.6.1": + version "3.6.1" + resolved "https://registry.yarnpkg.com/@typescript-eslint/typescript-estree/-/typescript-estree-3.6.1.tgz#a5c91fcc5497cce7922ff86bc37d5e5891dcdefa" + integrity sha512-G4XRe/ZbCZkL1fy09DPN3U0mR6SayIv1zSeBNquRFRk7CnVLgkC2ZPj8llEMJg5Y8dJ3T76SvTGtceytniaztQ== + dependencies: + "@typescript-eslint/types" "3.6.1" + "@typescript-eslint/visitor-keys" "3.6.1" + debug "^4.1.1" + glob "^7.1.6" + is-glob "^4.0.1" + lodash "^4.17.15" + semver "^7.3.2" + tsutils "^3.17.1" + +"@typescript-eslint/visitor-keys@3.6.1": + version "3.6.1" + resolved "https://registry.yarnpkg.com/@typescript-eslint/visitor-keys/-/visitor-keys-3.6.1.tgz#5c57a7772f4dd623cfeacc219303e7d46f963b37" + integrity sha512-qC8Olwz5ZyMTZrh4Wl3K4U6tfms0R/mzU4/5W3XeUZptVraGVmbptJbn6h2Ey6Rb3hOs3zWoAUebZk8t47KGiQ== + dependencies: + eslint-visitor-keys "^1.1.0" + "@wdio/config@6.1.14": version "6.1.14" resolved "https://registry.yarnpkg.com/@wdio/config/-/config-6.1.14.tgz#41dec1cebcc76e387b44ddef0302839ffac1f99f" @@ -3487,6 +3633,17 @@ eslint-import-resolver-node@^0.3.3: debug "^2.6.9" resolve "^1.13.1" +eslint-import-resolver-typescript@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/eslint-import-resolver-typescript/-/eslint-import-resolver-typescript-2.0.0.tgz#e95f126cc12d3018b9cc11692b4dbfd3e17d3ea6" + integrity sha512-bT5Frpl8UWoHBtY25vKUOMoVIMlJQOMefHLyQ4Tz3MQpIZ2N6yYKEEIHMo38bszBNUuMBW6M3+5JNYxeiGFH4w== + dependencies: + debug "^4.1.1" + is-glob "^4.0.1" + resolve "^1.12.0" + tiny-glob "^0.2.6" + tsconfig-paths "^3.9.0" + eslint-module-utils@^2.6.0: version "2.6.0" resolved "https://registry.yarnpkg.com/eslint-module-utils/-/eslint-module-utils-2.6.0.tgz#579ebd094f56af7797d19c9866c9c9486629bfa6" @@ -3539,7 +3696,7 @@ eslint-scope@^4.0.3: esrecurse "^4.1.0" estraverse "^4.1.1" -eslint-scope@^5.1.0: +eslint-scope@^5.0.0, eslint-scope@^5.1.0: version "5.1.0" resolved "https://registry.yarnpkg.com/eslint-scope/-/eslint-scope-5.1.0.tgz#d0f971dfe59c69e0cada684b23d49dbf82600ce5" integrity sha512-iiGRvtxWqgtx5m8EyQUJihBloE4EnYeGE/bz1wSPwJE6tZuJUtHlhqDM4Xj2ukE8Dyy1+HCZ4hE0fzIVMzb58w== @@ -3554,7 +3711,12 @@ eslint-utils@^2.0.0: dependencies: eslint-visitor-keys "^1.1.0" -eslint-visitor-keys@^1.0.0, eslint-visitor-keys@^1.1.0, eslint-visitor-keys@^1.2.0: +eslint-visitor-keys@^1.0.0: + version "1.3.0" + resolved "https://registry.yarnpkg.com/eslint-visitor-keys/-/eslint-visitor-keys-1.3.0.tgz#30ebd1ef7c2fdff01c3a4f151044af25fab0523e" + integrity sha512-6J72N8UNa462wa/KFODt/PJ3IU60SDpC3QXC1Hjc1BXXpfL2C9R5+AU7jhe0F6GREqVMh4Juu+NY7xn+6dipUQ== + +eslint-visitor-keys@^1.1.0, eslint-visitor-keys@^1.2.0: version "1.2.0" resolved "https://registry.yarnpkg.com/eslint-visitor-keys/-/eslint-visitor-keys-1.2.0.tgz#74415ac884874495f78ec2a97349525344c981fa" integrity sha512-WFb4ihckKil6hu3Dp798xdzSfddwKKU3+nGniKF6HfeW6OLd2OUDEPP7TcHtB5+QXOKg2s6B2DaMPE1Nn/kxKQ== @@ -4337,6 +4499,16 @@ globalthis@^1.0.1: dependencies: define-properties "^1.1.3" +globalyzer@^0.1.0: + version "0.1.4" + resolved "https://registry.yarnpkg.com/globalyzer/-/globalyzer-0.1.4.tgz#bc8e273afe1ac7c24eea8def5b802340c5cc534f" + integrity sha512-LeguVWaxgHN0MNbWC6YljNMzHkrCny9fzjmEUdnF1kQ7wATFD1RHFRqA1qxaX2tgxGENlcxjOflopBwj3YZiXA== + +globrex@^0.1.1: + version "0.1.2" + resolved "https://registry.yarnpkg.com/globrex/-/globrex-0.1.2.tgz#dd5d9ec826232730cd6793a5e33a9302985e6098" + integrity sha512-uHJgbwAMwNFf5mLst7IWLNg14x1CkeqglJb/K3doi4dw6q2IvAAmM/Y81kevy83wP+Sst+nutFTYOGg3d1lsxg== + got@^11.0.2, got@^11.1.4: version "11.3.0" resolved "https://registry.yarnpkg.com/got/-/got-11.3.0.tgz#25e8da8b0125b3b984613a6b719e678dd2e20406" @@ -5647,6 +5819,11 @@ lodash@^4.17.13, lodash@^4.17.14, lodash@^4.17.15: resolved "https://registry.yarnpkg.com/lodash/-/lodash-4.17.15.tgz#b447f6670a0455bbfeedd11392eff330ea097548" integrity sha512-8xOcRHvCjnocdS5cpwXQXVzmmh5e5+saE2QGoeQmbKmRS6J3VQppPOIt0MnmE+4xlZoumy0GPG0D0MVIQbNA1A== +lodash@^4.17.19: + version "4.17.19" + resolved "https://registry.yarnpkg.com/lodash/-/lodash-4.17.19.tgz#e48ddedbe30b3321783c5b4301fbd353bc1e4a4b" + integrity sha512-JNvd8XER9GQX0v2qJgsaN/mzFCNA5BRe/j8JN9d+tWyGLSodKQHKFicdwNYzWwI3wjRnaKPsGj1XkBjx/F96DQ== + log-symbols@3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/log-symbols/-/log-symbols-3.0.0.tgz#f3a08516a5dea893336a7dee14d18a1cfdab77c4" @@ -7091,7 +7268,7 @@ regex-not@^1.0.0, regex-not@^1.0.2: extend-shallow "^3.0.2" safe-regex "^1.1.0" -regexpp@^3.1.0: +regexpp@^3.0.0, regexpp@^3.1.0: version "3.1.0" resolved "https://registry.yarnpkg.com/regexpp/-/regexpp-3.1.0.tgz#206d0ad0a5648cffbdb8ae46438f3dc51c9f78e2" integrity sha512-ZOIzd8yVsQQA7j8GCSlPGXwg5PfmA1mrq0JP4nGhh54LaKN3xdai/vHUDu74pKwV8OxseMS65u2NImosQcSD0Q== @@ -8190,6 +8367,14 @@ timers-browserify@^2.0.4: dependencies: setimmediate "^1.0.4" +tiny-glob@^0.2.6: + version "0.2.6" + resolved "https://registry.yarnpkg.com/tiny-glob/-/tiny-glob-0.2.6.tgz#9e056e169d9788fe8a734dfa1ff02e9b92ed7eda" + integrity sha512-A7ewMqPu1B5PWwC3m7KVgAu96Ch5LA0w4SnEN/LbDREj/gAD0nPWboRbn8YoP9ISZXqeNAlMvKSKoEuhcfK3Pw== + dependencies: + globalyzer "^0.1.0" + globrex "^0.1.1" + tmp@0.2.1, tmp@^0.2.1: version "0.2.1" resolved "https://registry.yarnpkg.com/tmp/-/tmp-0.2.1.tgz#8457fc3037dcf4719c251367a1af6500ee1ccf14" @@ -8319,6 +8504,13 @@ tsutils@^2.29.0: dependencies: tslib "^1.8.1" +tsutils@^3.17.1: + version "3.17.1" + resolved "https://registry.yarnpkg.com/tsutils/-/tsutils-3.17.1.tgz#ed719917f11ca0dee586272b2ac49e015a2dd759" + integrity sha512-kzeQ5B8H3w60nFY2g8cJIuH7JDpsALXySGtwGJ0p2LSjLgay3NdIpqq5SoOBe46bKDW2iq25irHCr8wjomUS2g== + dependencies: + tslib "^1.8.1" + tty-browserify@0.0.0: version "0.0.0" resolved "https://registry.yarnpkg.com/tty-browserify/-/tty-browserify-0.0.0.tgz#a157ba402da24e9bf957f9aa69d524eed42901a6" @@ -8383,10 +8575,10 @@ typedarray@^0.0.6: resolved "https://registry.yarnpkg.com/typedarray/-/typedarray-0.0.6.tgz#867ac74e3864187b1d3d47d996a78ec5c8830777" integrity sha1-hnrHTjhkGHsdPUfZlqeOxciDB3c= -typescript@^3.9.5: - version "3.9.5" - resolved "https://registry.yarnpkg.com/typescript/-/typescript-3.9.5.tgz#586f0dba300cde8be52dd1ac4f7e1009c1b13f36" - integrity sha512-hSAifV3k+i6lEoCJ2k6R2Z/rp/H3+8sdmcn5NrS3/3kE7+RyZXm9aqvxWqjEXHAd8b0pShatpcdMTvEdvAJltQ== +typescript@^3.9.6: + version "3.9.6" + resolved "https://registry.yarnpkg.com/typescript/-/typescript-3.9.6.tgz#8f3e0198a34c3ae17091b35571d3afd31999365a" + integrity sha512-Pspx3oKAPJtjNwE92YS05HQoY7z2SFyOpHo9MqJor3BXAGNaPUs83CuVp9VISFkSjyRfiTpmKuAYGJB7S7hOxw== ua-parser-js@0.7.21, ua-parser-js@^0.7.21: version "0.7.21" From 94c50ddb06222cc48d705ae6bec17cb7ffcd1837 Mon Sep 17 00:00:00 2001 From: Amin Mahboubi Date: Thu, 16 Jul 2020 14:34:12 +0200 Subject: [PATCH 02/69] rename all files to ts --- src/{getstream.js => getstream.ts} | 0 src/lib/{batch_operations.js => batch_operations.ts} | 0 src/lib/{client.js => client.ts} | 0 src/lib/{collections.js => collections.ts} | 0 src/lib/{errors.js => errors.ts} | 0 src/lib/{feed.js => feed.ts} | 0 src/lib/{files.js => files.ts} | 0 src/lib/{images.js => images.ts} | 0 src/lib/{personalization.js => personalization.ts} | 0 src/lib/{reaction.js => reaction.ts} | 0 src/lib/{redirect_url.js => redirect_url.ts} | 0 src/lib/{signing.js => signing.ts} | 0 src/lib/{user.js => user.ts} | 0 src/lib/{utils.js => utils.ts} | 0 14 files changed, 0 insertions(+), 0 deletions(-) rename src/{getstream.js => getstream.ts} (100%) rename src/lib/{batch_operations.js => batch_operations.ts} (100%) rename src/lib/{client.js => client.ts} (100%) rename src/lib/{collections.js => collections.ts} (100%) rename src/lib/{errors.js => errors.ts} (100%) rename src/lib/{feed.js => feed.ts} (100%) rename src/lib/{files.js => files.ts} (100%) rename src/lib/{images.js => images.ts} (100%) rename src/lib/{personalization.js => personalization.ts} (100%) rename src/lib/{reaction.js => reaction.ts} (100%) rename src/lib/{redirect_url.js => redirect_url.ts} (100%) rename src/lib/{signing.js => signing.ts} (100%) rename src/lib/{user.js => user.ts} (100%) rename src/lib/{utils.js => utils.ts} (100%) diff --git a/src/getstream.js b/src/getstream.ts similarity index 100% rename from src/getstream.js rename to src/getstream.ts diff --git a/src/lib/batch_operations.js b/src/lib/batch_operations.ts similarity index 100% rename from src/lib/batch_operations.js rename to src/lib/batch_operations.ts diff --git a/src/lib/client.js b/src/lib/client.ts similarity index 100% rename from src/lib/client.js rename to src/lib/client.ts diff --git a/src/lib/collections.js b/src/lib/collections.ts similarity index 100% rename from src/lib/collections.js rename to src/lib/collections.ts diff --git a/src/lib/errors.js b/src/lib/errors.ts similarity index 100% rename from src/lib/errors.js rename to src/lib/errors.ts diff --git a/src/lib/feed.js b/src/lib/feed.ts similarity index 100% rename from src/lib/feed.js rename to src/lib/feed.ts diff --git a/src/lib/files.js b/src/lib/files.ts similarity index 100% rename from src/lib/files.js rename to src/lib/files.ts diff --git a/src/lib/images.js b/src/lib/images.ts similarity index 100% rename from src/lib/images.js rename to src/lib/images.ts diff --git a/src/lib/personalization.js b/src/lib/personalization.ts similarity index 100% rename from src/lib/personalization.js rename to src/lib/personalization.ts diff --git a/src/lib/reaction.js b/src/lib/reaction.ts similarity index 100% rename from src/lib/reaction.js rename to src/lib/reaction.ts diff --git a/src/lib/redirect_url.js b/src/lib/redirect_url.ts similarity index 100% rename from src/lib/redirect_url.js rename to src/lib/redirect_url.ts diff --git a/src/lib/signing.js b/src/lib/signing.ts similarity index 100% rename from src/lib/signing.js rename to src/lib/signing.ts diff --git a/src/lib/user.js b/src/lib/user.ts similarity index 100% rename from src/lib/user.js rename to src/lib/user.ts diff --git a/src/lib/utils.js b/src/lib/utils.ts similarity index 100% rename from src/lib/utils.js rename to src/lib/utils.ts From 31c18ff9f57ad85aa878018f18bac96e76943936 Mon Sep 17 00:00:00 2001 From: Amin Mahboubi Date: Tue, 21 Jul 2020 09:58:26 +0200 Subject: [PATCH 03/69] add dependency types --- package.json | 3 +++ yarn.lock | 46 +++++++++++++++++----------------------------- 2 files changed, 20 insertions(+), 29 deletions(-) diff --git a/package.json b/package.json index 5c2bc358..fd5f0fcc 100644 --- a/package.json +++ b/package.json @@ -65,7 +65,10 @@ "@babel/preset-env": "^7.10.4", "@babel/preset-typescript": "^7.10.4", "@babel/register": "^7.10.4", + "@types/jsonwebtoken": "^8.5.0", + "@types/jwt-decode": "^2.2.1", "@types/node": "^14.0.14", + "@types/qs": "^6.9.3", "@typescript-eslint/eslint-plugin": "^3.6.1", "@typescript-eslint/parser": "^3.6.1", "babel-eslint": "^10.1.0", diff --git a/yarn.lock b/yarn.lock index e88a4e66..682cf17e 100644 --- a/yarn.lock +++ b/yarn.lock @@ -1269,6 +1269,18 @@ resolved "https://registry.yarnpkg.com/@types/json5/-/json5-0.0.29.tgz#ee28707ae94e11d2b827bcbe5270bcea7f3e71ee" integrity sha1-7ihweulOEdK4J7y+UnC86n8+ce4= +"@types/jsonwebtoken@^8.5.0": + version "8.5.0" + resolved "https://registry.yarnpkg.com/@types/jsonwebtoken/-/jsonwebtoken-8.5.0.tgz#2531d5e300803aa63279b232c014acf780c981c5" + integrity sha512-9bVao7LvyorRGZCw0VmH/dr7Og+NdjYSsKAxB43OQoComFbBgsEpoR9JW6+qSq/ogwVBg8GI2MfAlk4SYI4OLg== + dependencies: + "@types/node" "*" + +"@types/jwt-decode@^2.2.1": + version "2.2.1" + resolved "https://registry.yarnpkg.com/@types/jwt-decode/-/jwt-decode-2.2.1.tgz#afdf5c527fcfccbd4009b5fd02d1e18241f2d2f2" + integrity sha512-aWw2YTtAdT7CskFyxEX2K21/zSDStuf/ikI3yBqmwpwJF0pS+/IX5DWv+1UFffZIbruP6cnT9/LAJV1gFwAT1A== + "@types/keyv@*": version "3.1.1" resolved "https://registry.yarnpkg.com/@types/keyv/-/keyv-3.1.1.tgz#e45a45324fca9dab716ab1230ee249c9fb52cfa7" @@ -1301,6 +1313,11 @@ resolved "https://registry.yarnpkg.com/@types/parsimmon/-/parsimmon-1.10.2.tgz#2ac8480e1230c1c212cb6a2fed001bc87201aed8" integrity sha512-WVugAiBoLsmay9IPrLJoMnmLTP0cWPbc4w5c5suTevyhaJW9TWGyPbkFraNUk5YULf8vQ5C/3NBEQcIs6XfTcg== +"@types/qs@^6.9.3": + version "6.9.3" + resolved "https://registry.yarnpkg.com/@types/qs/-/qs-6.9.3.tgz#b755a0934564a200d3efdf88546ec93c369abd03" + integrity sha512-7s9EQWupR1fTc2pSMtXRQ9w9gLOcrJn+h7HOXw4evxyvVqMi4f+q7d2tnFe3ng3SNHjtK+0EzGMGFUQX4/AQRA== + "@types/responselike@*", "@types/responselike@^1.0.0": version "1.0.0" resolved "https://registry.yarnpkg.com/@types/responselike/-/responselike-1.0.0.tgz#251f4fe7d154d2bad125abe1b429b23afd262e29" @@ -3633,17 +3650,6 @@ eslint-import-resolver-node@^0.3.3: debug "^2.6.9" resolve "^1.13.1" -eslint-import-resolver-typescript@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/eslint-import-resolver-typescript/-/eslint-import-resolver-typescript-2.0.0.tgz#e95f126cc12d3018b9cc11692b4dbfd3e17d3ea6" - integrity sha512-bT5Frpl8UWoHBtY25vKUOMoVIMlJQOMefHLyQ4Tz3MQpIZ2N6yYKEEIHMo38bszBNUuMBW6M3+5JNYxeiGFH4w== - dependencies: - debug "^4.1.1" - is-glob "^4.0.1" - resolve "^1.12.0" - tiny-glob "^0.2.6" - tsconfig-paths "^3.9.0" - eslint-module-utils@^2.6.0: version "2.6.0" resolved "https://registry.yarnpkg.com/eslint-module-utils/-/eslint-module-utils-2.6.0.tgz#579ebd094f56af7797d19c9866c9c9486629bfa6" @@ -4499,16 +4505,6 @@ globalthis@^1.0.1: dependencies: define-properties "^1.1.3" -globalyzer@^0.1.0: - version "0.1.4" - resolved "https://registry.yarnpkg.com/globalyzer/-/globalyzer-0.1.4.tgz#bc8e273afe1ac7c24eea8def5b802340c5cc534f" - integrity sha512-LeguVWaxgHN0MNbWC6YljNMzHkrCny9fzjmEUdnF1kQ7wATFD1RHFRqA1qxaX2tgxGENlcxjOflopBwj3YZiXA== - -globrex@^0.1.1: - version "0.1.2" - resolved "https://registry.yarnpkg.com/globrex/-/globrex-0.1.2.tgz#dd5d9ec826232730cd6793a5e33a9302985e6098" - integrity sha512-uHJgbwAMwNFf5mLst7IWLNg14x1CkeqglJb/K3doi4dw6q2IvAAmM/Y81kevy83wP+Sst+nutFTYOGg3d1lsxg== - got@^11.0.2, got@^11.1.4: version "11.3.0" resolved "https://registry.yarnpkg.com/got/-/got-11.3.0.tgz#25e8da8b0125b3b984613a6b719e678dd2e20406" @@ -8367,14 +8363,6 @@ timers-browserify@^2.0.4: dependencies: setimmediate "^1.0.4" -tiny-glob@^0.2.6: - version "0.2.6" - resolved "https://registry.yarnpkg.com/tiny-glob/-/tiny-glob-0.2.6.tgz#9e056e169d9788fe8a734dfa1ff02e9b92ed7eda" - integrity sha512-A7ewMqPu1B5PWwC3m7KVgAu96Ch5LA0w4SnEN/LbDREj/gAD0nPWboRbn8YoP9ISZXqeNAlMvKSKoEuhcfK3Pw== - dependencies: - globalyzer "^0.1.0" - globrex "^0.1.1" - tmp@0.2.1, tmp@^0.2.1: version "0.2.1" resolved "https://registry.yarnpkg.com/tmp/-/tmp-0.2.1.tgz#8457fc3037dcf4719c251367a1af6500ee1ccf14" From df52e13b2aeaeea6272ae8ed56603b68a597d781 Mon Sep 17 00:00:00 2001 From: Amin Mahboubi Date: Tue, 21 Jul 2020 10:08:48 +0200 Subject: [PATCH 04/69] update eslint rules --- .eslintignore | 3 ++- .eslintrc.js | 65 ++++++++++++++++++++++++--------------------------- 2 files changed, 32 insertions(+), 36 deletions(-) diff --git a/.eslintignore b/.eslintignore index bce3ae64..14cd43a9 100644 --- a/.eslintignore +++ b/.eslintignore @@ -5,5 +5,6 @@ test/integration/utils/kjur.js /bin/ /.git/ /docs/ -/types +/types/ + **/*.sh diff --git a/.eslintrc.js b/.eslintrc.js index f8da6d80..f3fe0a10 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -1,3 +1,25 @@ +const sharedRules = { + 'consistent-return': 0, + 'no-underscore-dangle': 0, + 'import/prefer-default-export': 0, + 'import/extensions': ['error', 'never', { json: 'always' }], + 'func-names': 0, + 'no-param-reassign': 0, + 'prefer-destructuring': ['error', { object: true, array: false }], + 'max-classes-per-file': 0, + 'no-plusplus': 0, + 'sonarjs/cognitive-complexity': 0, + 'sonarjs/no-collapsible-if': 0, + 'sonarjs/no-duplicate-string': 0, + 'sonarjs/no-identical-functions': 0, +}; + +const settings = { + 'import/resolver': { + node: { extensions: ['.js', '.ts'] }, + }, +}; + module.exports = { root: true, plugins: ['prettier', 'chai-friendly'], @@ -18,28 +40,8 @@ module.exports = { globals: { process: true, }, - settings: { - 'import/resolver': { - node: { - extensions: ['.js', '.ts'], - }, - }, - }, - rules: { - 'consistent-return': 0, - 'no-underscore-dangle': 0, - 'import/prefer-default-export': 0, - 'import/extensions': ['error', 'never', { json: 'always' }], - 'func-names': 0, - 'no-param-reassign': 0, - 'prefer-destructuring': ['error', { object: true, array: false }], - 'max-classes-per-file': 0, - 'no-plusplus': 0, - 'sonarjs/cognitive-complexity': 0, - 'sonarjs/no-collapsible-if': 0, - 'sonarjs/no-duplicate-string': 0, - 'sonarjs/no-identical-functions': 0, - }, + settings, + rules: sharedRules, overrides: [ { files: ['**/*.ts'], @@ -53,20 +55,13 @@ module.exports = { 'plugin:sonarjs/recommended', ], parser: '@typescript-eslint/parser', + settings, rules: { - 'consistent-return': 0, - 'no-underscore-dangle': 0, - 'import/prefer-default-export': 0, - 'import/extensions': ['error', 'never', { json: 'always' }], - 'func-names': 0, - 'no-param-reassign': 0, - 'prefer-destructuring': ['error', { object: true, array: false }], - 'max-classes-per-file': 0, - 'no-plusplus': 0, - 'sonarjs/cognitive-complexity': 0, - 'sonarjs/no-collapsible-if': 0, - 'sonarjs/no-duplicate-string': 0, - 'sonarjs/no-identical-functions': 0, + ...sharedRules, + camelcase: 0, + 'lines-between-class-members': 0, + '@typescript-eslint/explicit-module-boundary-types': 0, + 'no-useless-constructor': 0, }, }, ], From 01be40c80a9ee30cf1aacd26f809f1ada42ece5d Mon Sep 17 00:00:00 2001 From: Amin Mahboubi Date: Tue, 21 Jul 2020 11:16:25 +0200 Subject: [PATCH 05/69] add types for missing modules --- src/lib/modules.d.ts | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 src/lib/modules.d.ts diff --git a/src/lib/modules.d.ts b/src/lib/modules.d.ts new file mode 100644 index 00000000..5f0b109f --- /dev/null +++ b/src/lib/modules.d.ts @@ -0,0 +1,29 @@ +declare module 'faye' { + type Message = { + subscription?: string; + [key: string]: unknown; + }; + + type Subscription = { + cancel: () => void; + }; + + type Callback = (message: Message) => unknown; + + interface Middleware { + incoming: (message: Message, callback: Callback) => unknown; + outgoing: (message: Message, callback: Callback) => unknown; + } + + export class Client { + constructor(url: string, options: { timeout: number }); + + addExtension(extension: Middleware): void; + + subscribe(channel: string, callback: Callback): Subscription; + } +} + +declare module 'Base64' { + function atob(input: string): string; +} From 6199dd851da9034501ffadc1dfd5941ad4cf3da5 Mon Sep 17 00:00:00 2001 From: Amin Mahboubi Date: Tue, 21 Jul 2020 11:17:53 +0200 Subject: [PATCH 06/69] add baseUrl to tsconfig --- tsconfig.json | 1 + 1 file changed, 1 insertion(+) diff --git a/tsconfig.json b/tsconfig.json index 8bd05c16..e9627289 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,5 +1,6 @@ { "compilerOptions": { + "baseUrl": "src", "outDir": "types", "allowJs": true, "allowSyntheticDefaultImports": true, From 44b3275decf5642013c5743b6d3d4f43561668c3 Mon Sep 17 00:00:00 2001 From: Amin Mahboubi Date: Tue, 21 Jul 2020 12:27:01 +0200 Subject: [PATCH 07/69] run types cmd in CI --- .github/workflows/ci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1f4d9a6e..329545ea 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -46,5 +46,5 @@ jobs: if [ "$CLOUD_TESTS" == "yes" ]; then yarn run test-cloud; fi if [ "$CLOUD_TESTS" == "yes" ]; then yarn run test-integration-node; fi if [ "$RUN_LINTERS" == "yes" ]; then yarn run lint; fi - if [ "$RUN_LINTERS" == "yes" ]; then yarn run dtslint; fi + if [ "$RUN_LINTERS" == "yes" ]; then yarn run types; fi if [ "$BROWSER_TESTS" == "yes" ]; then yarn run test-browser; fi From 126e062ec0830765044618c6c656b71ce8b93d3a Mon Sep 17 00:00:00 2001 From: Amin Mahboubi Date: Tue, 21 Jul 2020 12:28:52 +0200 Subject: [PATCH 08/69] remove dtslint --- package.json | 2 - yarn.lock | 443 ++++----------------------------------------------- 2 files changed, 28 insertions(+), 417 deletions(-) diff --git a/package.json b/package.json index fd5f0fcc..e9c81065 100644 --- a/package.json +++ b/package.json @@ -15,7 +15,6 @@ "scripts": { "types": "tsc --outFile types/index --declaration true --declarationMap true --emitDeclarationOnly true", "build": "babel src --out-dir lib --extensions '.js,.ts'", - "dtslint": "dtslint types/getstream", "eslint": "eslint '**/*.{js,ts}' --max-warnings 0", "prettier": "prettier --list-different '**/*.{js,ts}'", "lint": "yarn run prettier && yarn run eslint", @@ -75,7 +74,6 @@ "babel-loader": "^8.1.0", "chai": "^4.2.0", "codecov": "^3.7.0", - "dtslint": "^3.6.12", "eslint": "^7.3.1", "eslint-config-airbnb-base": "^14.2.0", "eslint-config-prettier": "^6.11.0", diff --git a/yarn.lock b/yarn.lock index 682cf17e..a31c77ef 100644 --- a/yarn.lock +++ b/yarn.lock @@ -1154,48 +1154,6 @@ lodash "^4.17.19" to-fast-properties "^2.0.0" -"@definitelytyped/header-parser@0.0.34": - version "0.0.34" - resolved "https://registry.yarnpkg.com/@definitelytyped/header-parser/-/header-parser-0.0.34.tgz#892c83ae0cdbc52ee439dfc3ac34244903b8a5ee" - integrity sha512-/yTifMAhYKB8SFH3pSlAQmcBzrk7UyqpEz9/vJKaMKdzRpJrxmc1zWMP+hwJtJTVCjAK+Ul4m3i1GZQrTZfymw== - dependencies: - "@definitelytyped/typescript-versions" "^0.0.34" - "@types/parsimmon" "^1.10.1" - parsimmon "^1.13.0" - -"@definitelytyped/header-parser@latest": - version "0.0.40" - resolved "https://registry.yarnpkg.com/@definitelytyped/header-parser/-/header-parser-0.0.40.tgz#9b07f942f43a907b839840d4d63c3312bae16b28" - integrity sha512-XtlZMA3SoUcCLa8v3n9SzOqnrr6ZyiAtAV+CPcttvNAyd2l4sLcN72+3SHVHpH9z8HhTKaR6OC1PzzFoZXqNiA== - dependencies: - "@definitelytyped/typescript-versions" "^0.0.40" - "@types/parsimmon" "^1.10.1" - parsimmon "^1.13.0" - -"@definitelytyped/typescript-versions@^0.0.34": - version "0.0.34" - resolved "https://registry.yarnpkg.com/@definitelytyped/typescript-versions/-/typescript-versions-0.0.34.tgz#6167363d378670ad7ef9485b7cff7d198106dcdf" - integrity sha512-7IqWcbHKYbfY8Lt7AigXDa29cbz3gynzBHMjwMUCeLnex8D682M6OW8uBLouvVHCr+YENL58tQB3dn0Zos8mFQ== - -"@definitelytyped/typescript-versions@^0.0.40", "@definitelytyped/typescript-versions@latest": - version "0.0.40" - resolved "https://registry.yarnpkg.com/@definitelytyped/typescript-versions/-/typescript-versions-0.0.40.tgz#e7888b5bd0355777f78c76c50b13b9b1aa78b18e" - integrity sha512-bhgrKayF1LRHlWgvsMtH1sa/y3JzJhsEVZiZE3xdoWyv9NjZ76dpGvXTNix2dz5585KgQJLP+cKeIdZbwHnCUA== - -"@definitelytyped/utils@latest": - version "0.0.40" - resolved "https://registry.yarnpkg.com/@definitelytyped/utils/-/utils-0.0.40.tgz#83a0acb220fb8a84f0332467af26861797e5b039" - integrity sha512-XDPvPnw57xeN0Fho67EB+KAQNwzhp8xXS0SlhjPxrpAJSuAkLPlr3mz3OHMIt2HuNCBbBUvpnN+jsVTG6N39XQ== - dependencies: - "@definitelytyped/typescript-versions" "^0.0.40" - "@types/node" "^12.12.29" - charm "^1.0.2" - fs-extra "^8.1.0" - fstream "^1.0.12" - npm-registry-client "^8.6.0" - tar "^2.2.2" - tar-stream "1.6.2" - "@istanbuljs/load-nyc-config@^1.0.0": version "1.1.0" resolved "https://registry.yarnpkg.com/@istanbuljs/load-nyc-config/-/load-nyc-config-1.1.0.tgz#fd3db1d59ecf7cf121e80650bb86712f9b55eced" @@ -1293,11 +1251,6 @@ resolved "https://registry.yarnpkg.com/@types/node/-/node-14.0.13.tgz#ee1128e881b874c371374c1f72201893616417c9" integrity sha512-rouEWBImiRaSJsVA+ITTFM6ZxibuAlTuNOCyxVbwreu6k6+ujs7DfnU9o+PShFhET78pMBl3eH+AGSI5eOTkPA== -"@types/node@^12.12.29": - version "12.12.47" - resolved "https://registry.yarnpkg.com/@types/node/-/node-12.12.47.tgz#5007b8866a2f9150de82335ca7e24dd1d59bdfb5" - integrity sha512-yzBInQFhdY8kaZmqoL2+3U5dSTMrKaYcb561VU+lDzAYvqt+2lojvBEy+hmpSNuXnPTx7m9+04CzWYOUqWME2A== - "@types/node@^14.0.14": version "14.0.14" resolved "https://registry.yarnpkg.com/@types/node/-/node-14.0.14.tgz#24a0b5959f16ac141aeb0c5b3cd7a15b7c64cbce" @@ -1308,11 +1261,6 @@ resolved "https://registry.yarnpkg.com/@types/parse-json/-/parse-json-4.0.0.tgz#2f8bb441434d163b35fb8ffdccd7138927ffb8c0" integrity sha512-//oorEZjL6sbPcKUaCdIGlIUeH26mgzimjBB77G6XRgnDl/L5wOnpyBGRe/Mmf5CVW3PwEBE1NjiMZ/ssFh4wA== -"@types/parsimmon@^1.10.1": - version "1.10.2" - resolved "https://registry.yarnpkg.com/@types/parsimmon/-/parsimmon-1.10.2.tgz#2ac8480e1230c1c212cb6a2fed001bc87201aed8" - integrity sha512-WVugAiBoLsmay9IPrLJoMnmLTP0cWPbc4w5c5suTevyhaJW9TWGyPbkFraNUk5YULf8vQ5C/3NBEQcIs6XfTcg== - "@types/qs@^6.9.3": version "6.9.3" resolved "https://registry.yarnpkg.com/@types/qs/-/qs-6.9.3.tgz#b755a0934564a200d3efdf88546ec93c369abd03" @@ -1668,11 +1616,6 @@ ansi-colors@^3.0.0, ansi-colors@^3.2.1: resolved "https://registry.yarnpkg.com/ansi-colors/-/ansi-colors-3.2.4.tgz#e3a3da4bfbae6c86a9c285625de124a234026fbf" integrity sha512-hHUXGagefjN2iRrID63xckIvotOXOojhQKWIPUZ4mNUZ9nLZW+7FMNoE1lOkEhNWYsx/7ysGIuJYCiMAA9FnrA== -ansi-regex@^2.0.0: - version "2.1.1" - resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-2.1.1.tgz#c3b33ab5ee360d86e0e628f0468ae7ef27d654df" - integrity sha1-w7M6te42DYbg5ijwRorn7yfWVN8= - ansi-regex@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-3.0.0.tgz#ed0317c322064f79466c02966bddb605ab37d998" @@ -1688,11 +1631,6 @@ ansi-regex@^5.0.0: resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-5.0.0.tgz#388539f55179bf39339c81af30a654d69f87cb75" integrity sha512-bY6fj56OUQ0hU1KjFNDQuJFezqKdrAyFdIevADiqrWHwSlbmBNMHp5ak2f40Pm8JTFyM2mqxkG6ngkHO11f/lg== -ansi-styles@^2.2.1: - version "2.2.1" - resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-2.2.1.tgz#b432dd3358b634cf75e1e4664368240533c1ddbe" - integrity sha1-tDLdM1i2NM914eRmQ2gkBTPB3b4= - ansi-styles@^3.2.0, ansi-styles@^3.2.1: version "3.2.1" resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-3.2.1.tgz#41fbb20243e50b12be0f04b8dedbf07520ce841d" @@ -1731,7 +1669,7 @@ append-transform@^2.0.0: dependencies: default-require-extensions "^3.0.0" -aproba@^1.0.3, aproba@^1.1.1: +aproba@^1.1.1: version "1.2.0" resolved "https://registry.yarnpkg.com/aproba/-/aproba-1.2.0.tgz#6802e6264efd18c790a1b0d517f0f2627bf2c94a" integrity sha512-Y9J6ZjXtoYh8RnXVCMOU/ttDmk1aBjunq9vO0ta5x85WDQiQfUF9sIPBITdbiiIVcBo03Hi3jMxigBtsddlXRw== @@ -1782,14 +1720,6 @@ archy@^1.0.0: resolved "https://registry.yarnpkg.com/archy/-/archy-1.0.0.tgz#f9c8c13757cc1dd7bc379ac77b2c62a5c2868c40" integrity sha1-+cjBN1fMHde8N5rHeyxipcKGjEA= -are-we-there-yet@~1.1.2: - version "1.1.5" - resolved "https://registry.yarnpkg.com/are-we-there-yet/-/are-we-there-yet-1.1.5.tgz#4b35c2944f062a8bfcda66410760350fe9ddfc21" - integrity sha512-5hYdAkZlcG8tOLujVDTgCT+uPX0VnpAH28gWsLfzpXYm7wP6mp5Q/gYyR7YQ0cKVJcXJnl3j2kpBan13PtQf6w== - dependencies: - delegates "^1.0.0" - readable-stream "^2.0.6" - argparse@^1.0.7: version "1.0.10" resolved "https://registry.yarnpkg.com/argparse/-/argparse-1.0.10.tgz#bcd6791ea5ae09725e17e5ad988134cd40b3d911" @@ -1947,15 +1877,6 @@ axios@^0.19.2: dependencies: follow-redirects "1.5.10" -babel-code-frame@^6.22.0: - version "6.26.0" - resolved "https://registry.yarnpkg.com/babel-code-frame/-/babel-code-frame-6.26.0.tgz#63fd43f7dc1e3bb7ce35947db8fe369a3f58c74b" - integrity sha1-Y/1D99weO7fONZR9uP42mj9Yx0s= - dependencies: - chalk "^1.1.3" - esutils "^2.0.2" - js-tokens "^3.0.2" - babel-eslint@^10.1.0: version "10.1.0" resolved "https://registry.yarnpkg.com/babel-eslint/-/babel-eslint-10.1.0.tgz#6968e568a910b78fb3779cdd8b6ac2f479943232" @@ -2119,13 +2040,6 @@ blob@0.0.5: resolved "https://registry.yarnpkg.com/blob/-/blob-0.0.5.tgz#d680eeef25f8cd91ad533f5b01eed48e64caf683" integrity sha512-gaqbzQPqOoamawKg0LGVd7SzLgXS+JH61oWprSLH+P+abTczqJbhTR8CmJ2u9/bUYNmHTGJx/UEmn6doAvvuig== -block-stream@*: - version "0.0.9" - resolved "https://registry.yarnpkg.com/block-stream/-/block-stream-0.0.9.tgz#13ebfe778a03205cfe03751481ebb4b3300c126a" - integrity sha1-E+v+d4oDIFz+A3UUgeu0szAMEmo= - dependencies: - inherits "~2.0.0" - bluebird@^3.5.5, bluebird@^3.7.2: version "3.7.2" resolved "https://registry.yarnpkg.com/bluebird/-/bluebird-3.7.2.tgz#9f229c15be272454ffa973ace0dbee79a1b0c36f" @@ -2329,21 +2243,11 @@ buffer@^5.1.0, buffer@^5.2.1, buffer@^5.5.0: base64-js "^1.0.2" ieee754 "^1.1.4" -builtin-modules@^1.1.1: - version "1.1.1" - resolved "https://registry.yarnpkg.com/builtin-modules/-/builtin-modules-1.1.1.tgz#270f076c5a72c02f5b65a47df94c5fe3a278892f" - integrity sha1-Jw8HbFpywC9bZaR9+Uxf46J4iS8= - builtin-status-codes@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/builtin-status-codes/-/builtin-status-codes-3.0.0.tgz#85982878e21b98e1c66425e03d0174788f569ee8" integrity sha1-hZgoeOIbmOHGZCXgPQF0eI9Wnug= -builtins@^1.0.3: - version "1.0.3" - resolved "https://registry.yarnpkg.com/builtins/-/builtins-1.0.3.tgz#cb94faeb61c8696451db36534e1422f94f0aee88" - integrity sha1-y5T662HIaWRR2zZTThQi+U8K7og= - bytes@3.1.0: version "3.1.0" resolved "https://registry.yarnpkg.com/bytes/-/bytes-3.1.0.tgz#f6cf7933a360e0588fa9fde85651cdc7f805d1f6" @@ -2497,18 +2401,7 @@ chai@^4.2.0: pathval "^1.1.0" type-detect "^4.0.5" -chalk@^1.1.3: - version "1.1.3" - resolved "https://registry.yarnpkg.com/chalk/-/chalk-1.1.3.tgz#a8115c55e4a702fe4d150abd3872822a7e09fc98" - integrity sha1-qBFcVeSnAv5NFQq9OHKCKn4J/Jg= - dependencies: - 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" - -chalk@^2.0.0, chalk@^2.0.1, chalk@^2.1.0, chalk@^2.3.0, chalk@^2.4.2: +chalk@^2.0.0, chalk@^2.0.1, chalk@^2.1.0, chalk@^2.4.2: version "2.4.2" resolved "https://registry.yarnpkg.com/chalk/-/chalk-2.4.2.tgz#cd42541677a54333cf541a49108c1432b44c9424" integrity sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ== @@ -2543,13 +2436,6 @@ change-case@^4.1.1: snake-case "^3.0.3" tslib "^1.10.0" -charm@^1.0.2: - version "1.0.2" - resolved "https://registry.yarnpkg.com/charm/-/charm-1.0.2.tgz#8add367153a6d9a581331052c4090991da995e35" - integrity sha1-it02cVOm2aWBMxBSxAkJkdqZXjU= - dependencies: - inherits "^2.0.1" - check-error@^1.0.2: version "1.0.2" resolved "https://registry.yarnpkg.com/check-error/-/check-error-1.0.2.tgz#574d312edd88bb5dd8912e9286dd6c0aed4aac82" @@ -2690,11 +2576,6 @@ clone-response@1.0.2, clone-response@^1.0.2: dependencies: mimic-response "^1.0.0" -code-point-at@^1.0.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/code-point-at/-/code-point-at-1.1.0.tgz#0d070b4d043a5bea33a2f1a40e2edb3d9a4ccf77" - integrity sha1-DQcLTQQ6W+ozovGkDi7bPZpMz3c= - codecov@^3.7.0: version "3.7.0" resolved "https://registry.yarnpkg.com/codecov/-/codecov-3.7.0.tgz#4a09939cde24447a43f36d068e8b4e0188dc3f27" @@ -2750,12 +2631,7 @@ combined-stream@^1.0.6, combined-stream@^1.0.8, combined-stream@~1.0.6: dependencies: delayed-stream "~1.0.0" -command-exists@^1.2.8: - version "1.2.9" - resolved "https://registry.yarnpkg.com/command-exists/-/command-exists-1.2.9.tgz#c50725af3808c8ab0260fd60b01fbfa25b954f69" - integrity sha512-LTQ/SGc+s0Xc0Fu5WaKnR0YiygZkm9eKFvyS+fRsU7/ZWFF8ykFM6Pc9aCVf1+xasOOZpO3BAVgVrKvsqKHV7w== - -commander@^2.12.1, commander@^2.20.0, commander@~2.20.3: +commander@^2.20.0, commander@~2.20.3: version "2.20.3" resolved "https://registry.yarnpkg.com/commander/-/commander-2.20.3.tgz#fd485e84c03eb4881c20722ba48035e8531aeb33" integrity sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ== @@ -2817,7 +2693,7 @@ concat-map@0.0.1: resolved "https://registry.yarnpkg.com/concat-map/-/concat-map-0.0.1.tgz#d8a96bd77fd68df7793a73036a3ba0d5405d477b" integrity sha1-2Klr13/Wjfd5OnMDajug1UBdR3s= -concat-stream@^1.5.0, concat-stream@^1.5.2: +concat-stream@^1.5.0: version "1.6.2" resolved "https://registry.yarnpkg.com/concat-stream/-/concat-stream-1.6.2.tgz#904bdf194cd3122fc675c77fc4ac3d4ff0fd1a34" integrity sha512-27HBghJxjiZtIk3Ycvn/4kbJk/1uZuJFfuPEns6LaEvpvG1f0hTea8lilrouyo9mVc2GWdcEZ8OLoGmSADlrCw== @@ -2855,11 +2731,6 @@ console-browserify@^1.1.0: resolved "https://registry.yarnpkg.com/console-browserify/-/console-browserify-1.2.0.tgz#67063cef57ceb6cf4993a2ab3a55840ae8c49336" integrity sha512-ZMkYO/LkF17QvCPqM0gxw8yUzigAOZOSWSHg91FH6orS7vcEj5dVZTidN2fQ14yBSdg97RqhSNwLUXInd52OTA== -console-control-strings@^1.0.0, console-control-strings@~1.1.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/console-control-strings/-/console-control-strings-1.1.0.tgz#3d7cf4464db6446ea644bf4b39507f9851008e8e" - integrity sha1-PXz0Rk22RG6mRL9LOVB/mFEAjo4= - constant-case@^3.0.3: version "3.0.3" resolved "https://registry.yarnpkg.com/constant-case/-/constant-case-3.0.3.tgz#ac910a99caf3926ac5112f352e3af599d8c5fc0a" @@ -3248,11 +3119,6 @@ delayed-stream@~1.0.0: resolved "https://registry.yarnpkg.com/delayed-stream/-/delayed-stream-1.0.0.tgz#df3ae199acadfb7d440aaae0b29e2272b24ec619" integrity sha1-3zrhmayt+31ECqrgsp4icrJOxhk= -delegates@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/delegates/-/delegates-1.0.0.tgz#84c6e159b81904fdca59a0ef44cd870d31250f9a" - integrity sha1-hMbhWbgZBP3KWaDvRM2HDTElD5o= - depd@~1.1.2: version "1.1.2" resolved "https://registry.yarnpkg.com/depd/-/depd-1.1.2.tgz#9bcd52e14c097763e749b274c4346ed2e560b5a9" @@ -3300,11 +3166,6 @@ diff@4.0.2: resolved "https://registry.yarnpkg.com/diff/-/diff-4.0.2.tgz#60f3aecb89d5fae520c11aa19efc2bb982aade7d" integrity sha512-58lmxKSA4BNyLz+HHMUzlOEpg09FV+ev6ZMe3vJihgdxzgcwZ8VoEEPmALCZG9LmqfVoNMMKpttIYTVG6uDY7A== -diff@^3.2.0: - version "3.5.0" - resolved "https://registry.yarnpkg.com/diff/-/diff-3.5.0.tgz#800c0dd1e0a8bfbc95835c202ad220fe317e5a12" - integrity sha512-A46qtFgd+g7pDZinpnwiRJtxbC1hpgf0uzP3iG89scHk0AUC7A1TGxf5OiiOUv/JMZR8GOt8hL900hV0bOy5xA== - diffie-hellman@^5.0.0: version "5.0.3" resolved "https://registry.yarnpkg.com/diffie-hellman/-/diffie-hellman-5.0.3.tgz#40e8ee98f55a2149607146921c63e1ae5f3d2875" @@ -3370,33 +3231,6 @@ download@^7.1.0: p-event "^2.1.0" pify "^3.0.0" -dts-critic@latest: - version "3.2.7" - resolved "https://registry.yarnpkg.com/dts-critic/-/dts-critic-3.2.7.tgz#2f15a950f29541b821432742af0cc60cd52a3394" - integrity sha512-b0oUT92CJ/ZPAqvEJ5XzATqMVbLcZEhO00GQByBoJHQ8zhFDW/zVcJ2TtJkkB+VKGWKeAV7hhmjn1Oyot0jz8w== - dependencies: - "@definitelytyped/header-parser" "0.0.34" - command-exists "^1.2.8" - rimraf "^3.0.2" - semver "^6.2.0" - tmp "^0.2.1" - yargs "^15.3.1" - -dtslint@^3.6.12: - version "3.6.12" - resolved "https://registry.yarnpkg.com/dtslint/-/dtslint-3.6.12.tgz#cd6f6fb915227bb7ef5eaa031f660b147339d97a" - integrity sha512-fNqUqLcKu6up8rT7bb6rnfUCPDYTUButrHEsp4uENlsYiQJETaB+cM9eltYcUhiHtBoULEZrnl081yRvNUPcGA== - dependencies: - "@definitelytyped/header-parser" latest - "@definitelytyped/typescript-versions" latest - "@definitelytyped/utils" latest - dts-critic latest - fs-extra "^6.0.1" - json-stable-stringify "^1.0.1" - strip-json-comments "^2.0.1" - tslint "5.14.0" - yargs "^15.1.0" - duplexer3@^0.1.4: version "0.1.4" resolved "https://registry.yarnpkg.com/duplexer3/-/duplexer3-0.1.4.tgz#ee01dd1cac0ed3cbc7fdbea37dc0a8f1ce002ce2" @@ -4254,15 +4088,6 @@ fs-constants@^1.0.0: resolved "https://registry.yarnpkg.com/fs-constants/-/fs-constants-1.0.0.tgz#6be0de9be998ce16af8afc24497b9ee9b7ccd9ad" integrity sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow== -fs-extra@^6.0.1: - version "6.0.1" - resolved "https://registry.yarnpkg.com/fs-extra/-/fs-extra-6.0.1.tgz#8abc128f7946e310135ddc93b98bddb410e7a34b" - integrity sha512-GnyIkKhhzXZUWFCaJzvyDLEEgDkPfb4/TPvJCJVuS8MWZgoSsErf++QpiAlDnKFcqhRlm+tIOcencCjyJE6ZCA== - dependencies: - graceful-fs "^4.1.2" - jsonfile "^4.0.0" - universalify "^0.1.0" - fs-extra@^8.1.0: version "8.1.0" resolved "https://registry.yarnpkg.com/fs-extra/-/fs-extra-8.1.0.tgz#49d43c45a88cd9677668cb7be1b46efdb8d2e1c0" @@ -4305,16 +4130,6 @@ fsevents@~2.1.2: resolved "https://registry.yarnpkg.com/fsevents/-/fsevents-2.1.3.tgz#fb738703ae8d2f9fe900c33836ddebee8b97f23e" integrity sha512-Auw9a4AxqWpa9GUfj370BMPzzyncfBABW8Mab7BGWBYDj4Isgq+cDKtx0i6u9jcX9pQDnswsaaOTgTmA5pEjuQ== -fstream@^1.0.12: - version "1.0.12" - resolved "https://registry.yarnpkg.com/fstream/-/fstream-1.0.12.tgz#4e8ba8ee2d48be4f7d0de505455548eae5932045" - integrity sha512-WvJ193OHa0GHPEL+AycEJgxvBEwyfRkN1vhjca23OaPVMCaLCXTd5qAu82AjTcgP1UJmytkOKb63Ypde7raDIg== - dependencies: - graceful-fs "^4.1.2" - inherits "~2.0.0" - mkdirp ">=0.5 0" - rimraf "2" - function-bind@^1.1.1: version "1.1.1" resolved "https://registry.yarnpkg.com/function-bind/-/function-bind-1.1.1.tgz#a56899d3ea3c9bab874bb9773b7c5ede92f4895d" @@ -4325,20 +4140,6 @@ functional-red-black-tree@^1.0.1: resolved "https://registry.yarnpkg.com/functional-red-black-tree/-/functional-red-black-tree-1.0.1.tgz#1b0ab3bd553b2a0d6399d29c0e3ea0b252078327" integrity sha1-GwqzvVU7Kg1jmdKcDj6gslIHgyc= -gauge@~2.7.3: - version "2.7.4" - resolved "https://registry.yarnpkg.com/gauge/-/gauge-2.7.4.tgz#2c03405c7538c39d7eb37b317022e325fb018bf7" - integrity sha1-LANAXHU4w51+s3sxcCLjJfsBi/c= - dependencies: - 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" - gensync@^1.0.0-beta.1: version "1.0.0-beta.1" resolved "https://registry.yarnpkg.com/gensync/-/gensync-1.0.0-beta.1.tgz#58f4361ff987e5ff6e1e7a210827aa371eaac269" @@ -4425,7 +4226,7 @@ glob-parent@^5.0.0, glob-parent@~5.1.0: dependencies: is-glob "^4.0.1" -glob@7.1.6, glob@^7.0.0, glob@^7.1.1, glob@^7.1.2, glob@^7.1.3, glob@^7.1.4, glob@^7.1.6: +glob@7.1.6, glob@^7.0.0, glob@^7.1.2, glob@^7.1.3, glob@^7.1.4, glob@^7.1.6: version "7.1.6" resolved "https://registry.yarnpkg.com/glob/-/glob-7.1.6.tgz#141f33b81a7c2492e125594307480c46679278a6" integrity sha512-LwaxwyZ72Lk7vZINtNNrywX0ZuLyStrdDtabefZKAY5ZGJhVtgdznluResxNmPitE0SAO+O26sWTHeKSI2wMBA== @@ -4579,13 +4380,6 @@ har-validator@~5.1.3: ajv "^6.5.5" har-schema "^2.0.0" -has-ansi@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/has-ansi/-/has-ansi-2.0.0.tgz#34f5049ce1ecdf2b0649af3ef24e45ed35416d91" - integrity sha1-NPUEnOHs3ysGSa8+8k5F7TVBbZE= - dependencies: - ansi-regex "^2.0.0" - has-binary2@~1.0.2: version "1.0.3" resolved "https://registry.yarnpkg.com/has-binary2/-/has-binary2-1.0.3.tgz#7776ac627f3ea77250cfc332dab7ddf5e4f5d11d" @@ -4625,11 +4419,6 @@ has-to-string-tag-x@^1.2.0: dependencies: has-symbol-support-x "^1.4.1" -has-unicode@^2.0.0: - version "2.0.1" - resolved "https://registry.yarnpkg.com/has-unicode/-/has-unicode-2.0.1.tgz#e0e6fe6a28cf51138855e086d1691e771de2a8b9" - integrity sha1-4Ob+aijPUROIVeCG0Wkedx3iqLk= - has-value@^0.3.1: version "0.3.1" resolved "https://registry.yarnpkg.com/has-value/-/has-value-0.3.1.tgz#7b1f58bada62ca827ec0a2078025654845995e1f" @@ -4722,7 +4511,7 @@ homedir-polyfill@^1.0.1: dependencies: parse-passwd "^1.0.0" -hosted-git-info@^2.1.4, hosted-git-info@^2.7.1: +hosted-git-info@^2.1.4: version "2.8.8" resolved "https://registry.yarnpkg.com/hosted-git-info/-/hosted-git-info-2.8.8.tgz#7539bd4bc1e0e0a895815a2e0262420b12858488" integrity sha512-f/wzC2QaWBs7t9IYqB4T3sR1xviIViXJRJTWBlx2Gf3g0Xi5vI7Yy4koXQ1c9OYDGHN9sBy1DQ2AB8fqZBWhUg== @@ -4900,7 +4689,7 @@ inflight@^1.0.4: once "^1.3.0" wrappy "1" -inherits@2, inherits@^2.0.1, inherits@^2.0.3, inherits@^2.0.4, inherits@~2.0.0, inherits@~2.0.1, inherits@~2.0.3: +inherits@2, inherits@^2.0.1, inherits@^2.0.3, inherits@^2.0.4, inherits@~2.0.1, inherits@~2.0.3: version "2.0.4" resolved "https://registry.yarnpkg.com/inherits/-/inherits-2.0.4.tgz#0fa2c64f932917c3433a0ded55363aae37416b7c" integrity sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ== @@ -5052,13 +4841,6 @@ is-extglob@^2.1.0, is-extglob@^2.1.1: resolved "https://registry.yarnpkg.com/is-extglob/-/is-extglob-2.1.1.tgz#a88c02535791f02ed37c76a1b9ea9773c833f8c2" integrity sha1-qIwCU1eR8C7TfHahueqXc8gz+MI= -is-fullwidth-code-point@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/is-fullwidth-code-point/-/is-fullwidth-code-point-1.0.0.tgz#ef9e31386f031a7f0d643af82fde50c457ef00cb" - integrity sha1-754xOG8DGn8NZDr4L95QxFfvAMs= - dependencies: - number-is-nan "^1.0.0" - is-fullwidth-code-point@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz#a3b30a5c4f199183167aaab93beefae3ddfb654f" @@ -5317,11 +5099,6 @@ iterate-value@^1.0.0: resolved "https://registry.yarnpkg.com/js-tokens/-/js-tokens-4.0.0.tgz#19203fb59991df98e3a287050d4647cdeaf32499" integrity sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ== -js-tokens@^3.0.2: - version "3.0.2" - resolved "https://registry.yarnpkg.com/js-tokens/-/js-tokens-3.0.2.tgz#9866df395102130e38f7f996bceb65443209c25b" - integrity sha1-mGbfOVECEw449/mWvOtlRDIJwls= - js-yaml@3.13.1: version "3.13.1" resolved "https://registry.yarnpkg.com/js-yaml/-/js-yaml-3.13.1.tgz#aff151b30bfdfa8e49e05da22e7415e9dfa37847" @@ -5330,7 +5107,7 @@ js-yaml@3.13.1: argparse "^1.0.7" esprima "^4.0.0" -js-yaml@^3.13.1, js-yaml@^3.7.0: +js-yaml@^3.13.1: version "3.14.0" resolved "https://registry.yarnpkg.com/js-yaml/-/js-yaml-3.14.0.tgz#a7a34170f26a21bb162424d8adacb4113a69e482" integrity sha512-/4IbIeHcD9VMHFqDR/gQ7EdZdLimOvW2DdcxFjdyyZ9NsbS+ccrXqVWDtab/lRl5AlUqmpBx8EhPaWR+OtY17A== @@ -5415,13 +5192,6 @@ json-stable-stringify-without-jsonify@^1.0.1: resolved "https://registry.yarnpkg.com/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz#9db7b59496ad3f3cfef30a75142d2d930ad72651" integrity sha1-nbe1lJatPzz+8wp1FC0tkwrXJlE= -json-stable-stringify@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/json-stable-stringify/-/json-stable-stringify-1.0.1.tgz#9a759d39c5f2ff503fd5300646ed445f88c4f9af" - integrity sha1-mnWdOcXy/1A/1TAGRu1EX4jE+a8= - dependencies: - jsonify "~0.0.0" - json-stringify-safe@^5.0.1, json-stringify-safe@~5.0.1: version "5.0.1" resolved "https://registry.yarnpkg.com/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz#1296a2d58fd45f19a0f6ce01d65701e2c735b6eb" @@ -5448,11 +5218,6 @@ jsonfile@^4.0.0: optionalDependencies: graceful-fs "^4.1.6" -jsonify@~0.0.0: - version "0.0.0" - resolved "https://registry.yarnpkg.com/jsonify/-/jsonify-0.0.0.tgz#2c74b6ee41d93ca51b7b5aaee8f503631d252a73" - integrity sha1-LHS27kHZPKUbe1qu6PUDYx0lKnM= - jsonwebtoken@^8.5.1: version "8.5.1" resolved "https://registry.yarnpkg.com/jsonwebtoken/-/jsonwebtoken-8.5.1.tgz#00e71e0b8df54c2121a1f26137df2280673bcc0d" @@ -6111,7 +5876,7 @@ mkdirp-classic@^0.5.2: resolved "https://registry.yarnpkg.com/mkdirp-classic/-/mkdirp-classic-0.5.3.tgz#fa10c9115cc6d8865be221ba47ee9bed78601113" integrity sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A== -"mkdirp@>=0.5 0", mkdirp@^0.5.1, mkdirp@^0.5.3: +mkdirp@^0.5.1, mkdirp@^0.5.3: version "0.5.5" resolved "https://registry.yarnpkg.com/mkdirp/-/mkdirp-0.5.5.tgz#d91cefd62d1436ca0f41620e251288d420099def" integrity sha512-NKmAlESf6jMGym1++R0Ra7wvhV+wFW63FaSOFPwRahvea0gMUcGUhVeAg/0BC0wiv9ih5NYPB1Wn1UEI1/L+xQ== @@ -6285,7 +6050,7 @@ node-releases@^1.1.53: resolved "https://registry.yarnpkg.com/node-releases/-/node-releases-1.1.58.tgz#8ee20eef30fa60e52755fcc0942def5a734fe935" integrity sha512-NxBudgVKiRh/2aPWMgPR7bPTX0VPmGx5QBwCtdHitnqFE5/O8DeBXuIMH1nwNnw/aMo6AjOrpsHzfY3UbUJ7yg== -normalize-package-data@^2.3.2, "normalize-package-data@~1.0.1 || ^2.0.0": +normalize-package-data@^2.3.2: version "2.5.0" resolved "https://registry.yarnpkg.com/normalize-package-data/-/normalize-package-data-2.5.0.tgz#e66db1838b200c1dfc233225d12cb36520e234a8" integrity sha512-/5CMN3T0R4XTj4DcGaexo+roZSdSFW/0AOOTROrjxzCG1wrWXEsGbRKevjlIL+ZDE4sZlJr5ED4YW0yqmkK+eA== @@ -6329,35 +6094,6 @@ npm-conf@^1.1.0: config-chain "^1.1.11" pify "^3.0.0" -"npm-package-arg@^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0": - version "6.1.1" - resolved "https://registry.yarnpkg.com/npm-package-arg/-/npm-package-arg-6.1.1.tgz#02168cb0a49a2b75bf988a28698de7b529df5cb7" - integrity sha512-qBpssaL3IOZWi5vEKUKW0cO7kzLeT+EQO9W8RsLOZf76KF9E/K9+wH0C7t06HXPpaH8WH5xF1MExLuCwbTqRUg== - dependencies: - hosted-git-info "^2.7.1" - osenv "^0.1.5" - semver "^5.6.0" - validate-npm-package-name "^3.0.0" - -npm-registry-client@^8.6.0: - version "8.6.0" - resolved "https://registry.yarnpkg.com/npm-registry-client/-/npm-registry-client-8.6.0.tgz#7f1529f91450732e89f8518e0f21459deea3e4c4" - integrity sha512-Qs6P6nnopig+Y8gbzpeN/dkt+n7IyVd8f45NTMotGk6Qo7GfBmzwYx6jRLoOOgKiMnaQfYxsuyQlD8Mc3guBhg== - dependencies: - concat-stream "^1.5.2" - graceful-fs "^4.1.6" - normalize-package-data "~1.0.1 || ^2.0.0" - npm-package-arg "^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0" - once "^1.3.3" - request "^2.74.0" - retry "^0.10.0" - safe-buffer "^5.1.1" - semver "2 >=2.2.1 || 3.x || 4 || 5" - slide "^1.1.3" - ssri "^5.2.4" - optionalDependencies: - npmlog "2 || ^3.1.0 || ^4.0.0" - npm-run-path@^2.0.0: version "2.0.2" resolved "https://registry.yarnpkg.com/npm-run-path/-/npm-run-path-2.0.2.tgz#35a9232dfa35d7067b4cb2ddf2357b1871536c5f" @@ -6365,16 +6101,6 @@ npm-run-path@^2.0.0: dependencies: path-key "^2.0.0" -"npmlog@2 || ^3.1.0 || ^4.0.0": - version "4.1.2" - resolved "https://registry.yarnpkg.com/npmlog/-/npmlog-4.1.2.tgz#08a7f2a8bf734604779a9efa4ad5cc717abb954b" - integrity sha512-2uUqazuKlTaSI/dC8AzicUck7+IrEaOnN/e0jd3Xtt1KcGpwx30v50mL7oPyr/h9bL3E4aZccVwpwP+5W9Vjkg== - dependencies: - are-we-there-yet "~1.1.2" - console-control-strings "~1.1.0" - gauge "~2.7.3" - set-blocking "~2.0.0" - null-loader@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/null-loader/-/null-loader-4.0.0.tgz#8e491b253cd87341d82c0e84b66980d806dfbd04" @@ -6383,11 +6109,6 @@ null-loader@^4.0.0: loader-utils "^2.0.0" schema-utils "^2.6.5" -number-is-nan@^1.0.0: - version "1.0.1" - resolved "https://registry.yarnpkg.com/number-is-nan/-/number-is-nan-1.0.1.tgz#097b602b53422a522c1afb8790318336941a011d" - integrity sha1-CXtgK1NCKlIsGvuHkDGDNpQaAR0= - nyc@^15.1.0: version "15.1.0" resolved "https://registry.yarnpkg.com/nyc/-/nyc-15.1.0.tgz#1335dae12ddc87b6e249d5a1994ca4bdaea75f02" @@ -6513,7 +6234,7 @@ on-finished@~2.3.0: dependencies: ee-first "1.1.1" -once@^1.3.0, once@^1.3.1, once@^1.3.3, once@^1.4.0: +once@^1.3.0, once@^1.3.1, once@^1.4.0: version "1.4.0" resolved "https://registry.yarnpkg.com/once/-/once-1.4.0.tgz#583b1aa775961d4b113ac17d9c50baef9dd76bd1" integrity sha1-WDsap3WWHUsROsF9nFC6753Xa9E= @@ -6549,24 +6270,6 @@ os-filter-obj@^2.0.0: dependencies: arch "^2.1.0" -os-homedir@^1.0.0: - version "1.0.2" - resolved "https://registry.yarnpkg.com/os-homedir/-/os-homedir-1.0.2.tgz#ffbc4988336e0e833de0c168c7ef152121aa7fb3" - integrity sha1-/7xJiDNuDoM94MFox+8VISGqf7M= - -os-tmpdir@^1.0.0: - version "1.0.2" - resolved "https://registry.yarnpkg.com/os-tmpdir/-/os-tmpdir-1.0.2.tgz#bbe67406c79aa85c5cfec766fe5734555dfa1274" - integrity sha1-u+Z0BseaqFxc/sdm/lc0VV36EnQ= - -osenv@^0.1.5: - version "0.1.5" - resolved "https://registry.yarnpkg.com/osenv/-/osenv-0.1.5.tgz#85cdfafaeb28e8677f416e287592b5f3f49ea410" - integrity sha512-0CWcCECdMVc2Rw3U5w9ZjqX6ga6ubk1xDVKxtBQPK7wis/0F2r9T6k4ydGYhecl7YUBxBVxhL5oisPsNxAPe2g== - dependencies: - os-homedir "^1.0.0" - os-tmpdir "^1.0.0" - p-cancelable@^0.4.0: version "0.4.1" resolved "https://registry.yarnpkg.com/p-cancelable/-/p-cancelable-0.4.1.tgz#35f363d67d52081c8d9585e37bcceb7e0bbcb2a0" @@ -6745,11 +6448,6 @@ parseurl@~1.3.3: resolved "https://registry.yarnpkg.com/parseurl/-/parseurl-1.3.3.tgz#9da19e7bee8d12dff0513ed5b76957793bc2e8d4" integrity sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ== -parsimmon@^1.13.0: - version "1.13.0" - resolved "https://registry.yarnpkg.com/parsimmon/-/parsimmon-1.13.0.tgz#6e4ef3dbd45ed6ea6808be600ac4b9c8a44228cf" - integrity sha512-5UIrOCW+gjbILkjKPgTgmq8LKf8TT3Iy7kN2VD7OtQ81facKn8B4gG1X94jWqXYZsxG2KbJhrv/Yq/5H6BQn7A== - pascal-case@^3.1.1: version "3.1.1" resolved "https://registry.yarnpkg.com/pascal-case/-/pascal-case-3.1.1.tgz#5ac1975133ed619281e88920973d2cd1f279de5f" @@ -7186,7 +6884,7 @@ read-pkg@^2.0.0: normalize-package-data "^2.3.2" path-type "^2.0.0" -"readable-stream@1 || 2", readable-stream@^2.0.0, readable-stream@^2.0.1, readable-stream@^2.0.2, readable-stream@^2.0.5, readable-stream@^2.0.6, readable-stream@^2.1.5, readable-stream@^2.2.2, readable-stream@^2.3.0, readable-stream@^2.3.3, readable-stream@^2.3.5, readable-stream@^2.3.6, readable-stream@^2.3.7, readable-stream@~2.3.6: +"readable-stream@1 || 2", readable-stream@^2.0.0, readable-stream@^2.0.1, readable-stream@^2.0.2, readable-stream@^2.0.5, readable-stream@^2.1.5, readable-stream@^2.2.2, readable-stream@^2.3.0, readable-stream@^2.3.3, readable-stream@^2.3.5, readable-stream@^2.3.6, readable-stream@^2.3.7, readable-stream@~2.3.6: version "2.3.7" resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-2.3.7.tgz#1eca1cf711aef814c04f62252a36a62f6cb23b57" integrity sha512-Ebho8K4jIbHAxnuxi7o42OrZgF/ZTNcsZj6nRKyUmkhLFq8CHItp/fy6hQZuZmP/n3yZ9VBUbp4zz/mX8hmYPw== @@ -7315,7 +7013,7 @@ repeat-string@^1.6.1: resolved "https://registry.yarnpkg.com/repeat-string/-/repeat-string-1.6.1.tgz#8dcae470e1c88abc2d600fff4a776286da75e637" integrity sha1-jcrkcOHIirwtYA//Sndihtp15jc= -request@^2.74.0, request@^2.88.2: +request@^2.88.2: version "2.88.2" resolved "https://registry.yarnpkg.com/request/-/request-2.88.2.tgz#d73c918731cb5a87da047e207234146f664d12b3" integrity sha512-MsvtOrfG9ZcrOwAW+Qi+F6HbD0CWXEh9ou77uOb7FM2WPhwT7smM833PzanhJLsgXjN89Ir6V2PczXNnMpwKhw== @@ -7436,11 +7134,6 @@ ret@~0.1.10: resolved "https://registry.yarnpkg.com/ret/-/ret-0.1.15.tgz#b8a4825d5bdb1fc3f6f53c2bc33f81388681c7bc" integrity sha512-TTlYpa+OL+vMMNG24xSlQGEJ3B/RzEfUlLct7b5G/ytav+wPrplCpVMFuwzXbkecJrb6IYo1iFb0S9v37754mg== -retry@^0.10.0: - version "0.10.1" - resolved "https://registry.yarnpkg.com/retry/-/retry-0.10.1.tgz#e76388d217992c252750241d3d3956fed98d8ff4" - integrity sha1-52OI0heZLCUnUCQdPTlW/tmNj/Q= - rfdc@^1.1.4: version "1.1.4" resolved "https://registry.yarnpkg.com/rfdc/-/rfdc-1.1.4.tgz#ba72cc1367a0ccd9cf81a870b3b58bd3ad07f8c2" @@ -7451,13 +7144,6 @@ rgb2hex@^0.2.0: resolved "https://registry.yarnpkg.com/rgb2hex/-/rgb2hex-0.2.0.tgz#801b4887127181d1e691f610df2cecdb77330265" integrity sha512-cHdNTwmTMPu/TpP1bJfdApd6MbD+Kzi4GNnM6h35mdFChhQPSi9cAI8J7DMn5kQDKX8NuBaQXAyo360Oa7tOEA== -rimraf@2, rimraf@^2.5.4, rimraf@^2.6.3: - version "2.7.1" - resolved "https://registry.yarnpkg.com/rimraf/-/rimraf-2.7.1.tgz#35797f13a7fdadc566142c29d4f07ccad483e3ec" - integrity sha512-uWjbaKIK3T1OSVptzX7Nl6PvQ3qAGtKEtVRjRuazjfL3Bx5eI409VZSqgND+4UNnmzLVdPj9FqFJNPqBZFve4w== - dependencies: - glob "^7.1.3" - rimraf@2.6.3: version "2.6.3" resolved "https://registry.yarnpkg.com/rimraf/-/rimraf-2.6.3.tgz#b2d104fe0d8fb27cf9e0a1cda8262dd3833c6cab" @@ -7465,6 +7151,13 @@ rimraf@2.6.3: dependencies: glob "^7.1.3" +rimraf@^2.5.4, rimraf@^2.6.3: + version "2.7.1" + resolved "https://registry.yarnpkg.com/rimraf/-/rimraf-2.7.1.tgz#35797f13a7fdadc566142c29d4f07ccad483e3ec" + integrity sha512-uWjbaKIK3T1OSVptzX7Nl6PvQ3qAGtKEtVRjRuazjfL3Bx5eI409VZSqgND+4UNnmzLVdPj9FqFJNPqBZFve4w== + dependencies: + glob "^7.1.3" + rimraf@^3.0.0, rimraf@^3.0.2: version "3.0.2" resolved "https://registry.yarnpkg.com/rimraf/-/rimraf-3.0.2.tgz#f1a5402ba6220ad52cc1282bac1ae3aa49fd061a" @@ -7576,7 +7269,7 @@ semver-truncate@^1.1.2: dependencies: semver "^5.3.0" -"semver@2 >=2.2.1 || 3.x || 4 || 5", "semver@2 || 3 || 4 || 5", semver@^5.3.0, semver@^5.4.1, semver@^5.5.0, semver@^5.5.1, semver@^5.6.0, semver@^5.7.0: +"semver@2 || 3 || 4 || 5", semver@^5.3.0, semver@^5.4.1, semver@^5.5.0, semver@^5.5.1, semver@^5.6.0, semver@^5.7.0: version "5.7.1" resolved "https://registry.yarnpkg.com/semver/-/semver-5.7.1.tgz#a954f931aeba508d307bbf069eff0c01c96116f7" integrity sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ== @@ -7586,7 +7279,7 @@ semver@7.0.0: resolved "https://registry.yarnpkg.com/semver/-/semver-7.0.0.tgz#5f3ca35761e47e05b206c6daff2cf814f0316b8e" integrity sha512-+GB6zVA9LWh6zovYQLALHwv5rb2PHGlJi3lfiqIHxR0uuwCgefcOJc59v9fv1w8GbStwxuuqqAjI9NMAOOgq1A== -semver@^6.0.0, semver@^6.2.0, semver@^6.3.0: +semver@^6.0.0, semver@^6.3.0: version "6.3.0" resolved "https://registry.yarnpkg.com/semver/-/semver-6.3.0.tgz#ee0a64c8af5e8ceea67687b133761e1becbd1d3d" integrity sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw== @@ -7634,7 +7327,7 @@ serialize-javascript@^3.1.0: dependencies: randombytes "^2.1.0" -set-blocking@^2.0.0, set-blocking@~2.0.0: +set-blocking@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/set-blocking/-/set-blocking-2.0.0.tgz#045f9782d011ae9a6803ddd382b24392b3d890f7" integrity sha1-BF+XgtARrppoA93TgrJDkrPYkPc= @@ -7722,11 +7415,6 @@ slice-ansi@^2.1.0: astral-regex "^1.0.0" is-fullwidth-code-point "^2.0.0" -slide@^1.1.3: - version "1.1.6" - resolved "https://registry.yarnpkg.com/slide/-/slide-1.1.6.tgz#56eb027d65b4d2dce6cb2e2d32c4d4afc9e1d707" - integrity sha1-VusCfWW00tzmyy4tMsTUr8nh1wc= - snake-case@^3.0.3: version "3.0.3" resolved "https://registry.yarnpkg.com/snake-case/-/snake-case-3.0.3.tgz#c598b822ab443fcbb145ae8a82c5e43526d5bbee" @@ -7955,13 +7643,6 @@ sshpk@^1.7.0: safer-buffer "^2.0.2" tweetnacl "~0.14.0" -ssri@^5.2.4: - version "5.3.0" - resolved "https://registry.yarnpkg.com/ssri/-/ssri-5.3.0.tgz#ba3872c9c6d33a0704a7d71ff045e5ec48999d06" - integrity sha512-XRSIPqLij52MtgoQavH/x/dU1qVKtWUAAZeOHsR9c2Ddi4XerFy3mc1alf+dLJKl9EUIm/Ht+EowFkTUOA6GAQ== - dependencies: - safe-buffer "^5.1.1" - ssri@^6.0.1: version "6.0.1" resolved "https://registry.yarnpkg.com/ssri/-/ssri-6.0.1.tgz#2a3c41b28dd45b62b63676ecb74001265ae9edd8" @@ -8035,15 +7716,6 @@ strict-uri-encode@^1.0.0: resolved "https://registry.yarnpkg.com/strict-uri-encode/-/strict-uri-encode-1.1.0.tgz#279b225df1d582b1f54e65addd4352e18faa0713" integrity sha1-J5siXfHVgrH1TmWt3UNS4Y+qBxM= -string-width@^1.0.1: - version "1.0.2" - resolved "https://registry.yarnpkg.com/string-width/-/string-width-1.0.2.tgz#118bdf5b8cdc51a2a7e70d211e07e2b0b9b107d3" - integrity sha1-EYvfW4zcUaKn5w0hHgfisLmxB9M= - dependencies: - code-point-at "^1.0.0" - is-fullwidth-code-point "^1.0.0" - strip-ansi "^3.0.0" - "string-width@^1.0.2 || 2": version "2.1.1" resolved "https://registry.yarnpkg.com/string-width/-/string-width-2.1.1.tgz#ab93f27a8dc13d28cac815c462143a6d9012ae9e" @@ -8108,13 +7780,6 @@ stringify-object-es5@^2.5.0: is-plain-obj "^1.0.0" is-regexp "^1.0.0" -strip-ansi@^3.0.0, strip-ansi@^3.0.1: - version "3.0.1" - resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-3.0.1.tgz#6a385fb8853d952d5ff05d0e8aaf94278dc63dcf" - integrity sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8= - dependencies: - ansi-regex "^2.0.0" - strip-ansi@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-4.0.0.tgz#a8479022eb1ac368a871389b635262c505ee368f" @@ -8163,11 +7828,6 @@ strip-json-comments@3.0.1: resolved "https://registry.yarnpkg.com/strip-json-comments/-/strip-json-comments-3.0.1.tgz#85713975a91fb87bf1b305cca77395e40d2a64a7" integrity sha512-VTyMAUfdm047mwKl+u79WIdrZxtFtn+nBxHeb844XBQ9uMNTuTHdx2hc5RiAJYqwTj3wc/xe5HLSdJSkJ+WfZw== -strip-json-comments@^2.0.1: - version "2.0.1" - resolved "https://registry.yarnpkg.com/strip-json-comments/-/strip-json-comments-2.0.1.tgz#3c531942e908c2697c0ec344858c286c7ca0a60a" - integrity sha1-PFMZQukIwml8DsNEhYwobHygpgo= - strip-json-comments@^3.1.0: version "3.1.0" resolved "https://registry.yarnpkg.com/strip-json-comments/-/strip-json-comments-3.1.0.tgz#7638d31422129ecf4457440009fba03f9f9ac180" @@ -8192,11 +7852,6 @@ supports-color@7.1.0, supports-color@^7.1.0: dependencies: has-flag "^4.0.0" -supports-color@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-2.0.0.tgz#535d045ce6b6363fa40117084629995e9df324c7" - integrity sha1-U10EXOa2Nj+kARcIRimZXp3zJMc= - supports-color@^5.3.0: version "5.5.0" resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-5.5.0.tgz#e2e69a44ac8772f78a1ec0b35b689df6530efc8f" @@ -8241,7 +7896,7 @@ tar-fs@^2.0.0: pump "^3.0.0" tar-stream "^2.0.0" -tar-stream@1.6.2, tar-stream@^1.5.2: +tar-stream@^1.5.2: version "1.6.2" resolved "https://registry.yarnpkg.com/tar-stream/-/tar-stream-1.6.2.tgz#8ea55dab37972253d9a9af90fdcd559ae435c555" integrity sha512-rzS0heiNf8Xn7/mpdSVVSMAWAoy9bfb1WOTYC78Z0UQKeKa/CWS8FOq0lKGNa8DWKAn9gxjCvMLYc5PGXYlK2A== @@ -8265,15 +7920,6 @@ tar-stream@^2.0.0, tar-stream@^2.1.2: inherits "^2.0.3" readable-stream "^3.1.1" -tar@^2.2.2: - version "2.2.2" - resolved "https://registry.yarnpkg.com/tar/-/tar-2.2.2.tgz#0ca8848562c7299b8b446ff6a4d60cdbb23edc40" - integrity sha512-FCEhQ/4rE1zYv9rYXJw/msRqsnmlje5jHP6huWeBZ704jUTy02c5AZyWujpMR1ax6mVw9NyJMfuK2CMDWVIfgA== - dependencies: - block-stream "*" - fstream "^1.0.12" - inherits "2" - teeny-request@6.0.1: version "6.0.1" resolved "https://registry.yarnpkg.com/teeny-request/-/teeny-request-6.0.1.tgz#9b1f512cef152945827ba7e34f62523a4ce2c5b0" @@ -8363,7 +8009,7 @@ timers-browserify@^2.0.4: dependencies: setimmediate "^1.0.4" -tmp@0.2.1, tmp@^0.2.1: +tmp@0.2.1: version "0.2.1" resolved "https://registry.yarnpkg.com/tmp/-/tmp-0.2.1.tgz#8457fc3037dcf4719c251367a1af6500ee1ccf14" integrity sha512-76SUhtfqR2Ijn+xllcI5P1oyannHNHByD80W1q447gU3mp9G9PSpGdWmjUOHRDPiHYacIk66W7ubDTuPF3BEtQ== @@ -8461,37 +8107,11 @@ tsconfig-paths@^3.9.0: minimist "^1.2.0" strip-bom "^3.0.0" -tslib@^1.10.0, tslib@^1.8.0, tslib@^1.8.1, tslib@^1.9.0: +tslib@^1.10.0, tslib@^1.8.1, tslib@^1.9.0: version "1.13.0" resolved "https://registry.yarnpkg.com/tslib/-/tslib-1.13.0.tgz#c881e13cc7015894ed914862d276436fa9a47043" integrity sha512-i/6DQjL8Xf3be4K/E6Wgpekn5Qasl1usyw++dAA35Ue5orEn65VIxOA+YvNNl9HV3qv70T7CNwjODHZrLwvd1Q== -tslint@5.14.0: - version "5.14.0" - resolved "https://registry.yarnpkg.com/tslint/-/tslint-5.14.0.tgz#be62637135ac244fc9b37ed6ea5252c9eba1616e" - integrity sha512-IUla/ieHVnB8Le7LdQFRGlVJid2T/gaJe5VkjzRVSRR6pA2ODYrnfR1hmxi+5+au9l50jBwpbBL34txgv4NnTQ== - dependencies: - babel-code-frame "^6.22.0" - builtin-modules "^1.1.1" - chalk "^2.3.0" - commander "^2.12.1" - diff "^3.2.0" - glob "^7.1.1" - js-yaml "^3.7.0" - minimatch "^3.0.4" - mkdirp "^0.5.1" - resolve "^1.3.2" - semver "^5.3.0" - tslib "^1.8.0" - tsutils "^2.29.0" - -tsutils@^2.29.0: - version "2.29.0" - resolved "https://registry.yarnpkg.com/tsutils/-/tsutils-2.29.0.tgz#32b488501467acbedd4b85498673a0812aca0b99" - integrity sha512-g5JVHCIJwzfISaXpXE1qvNalca5Jwob6FjI4AoPlqMusJ6ftFE7IkkFoMhVLRgK+4Kx3gkzb8UZK5t5yTTvEmA== - dependencies: - tslib "^1.8.1" - tsutils@^3.17.1: version "3.17.1" resolved "https://registry.yarnpkg.com/tsutils/-/tsutils-3.17.1.tgz#ed719917f11ca0dee586272b2ac49e015a2dd759" @@ -8793,13 +8413,6 @@ validate-npm-package-license@^3.0.1: spdx-correct "^3.0.0" spdx-expression-parse "^3.0.0" -validate-npm-package-name@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/validate-npm-package-name/-/validate-npm-package-name-3.0.0.tgz#5fa912d81eb7d0c74afc140de7317f0ca7df437e" - integrity sha1-X6kS2B630MdK/BQN5zF/DKffQ34= - dependencies: - builtins "^1.0.3" - verror@1.10.0: version "1.10.0" resolved "https://registry.yarnpkg.com/verror/-/verror-1.10.0.tgz#3a105ca17053af55d6e270c1f8288682e18da400" @@ -8982,7 +8595,7 @@ which@^1.2.1, which@^1.2.14, which@^1.2.9, which@^1.3.1: dependencies: isexe "^2.0.0" -wide-align@1.1.3, wide-align@^1.1.0: +wide-align@1.1.3: version "1.1.3" resolved "https://registry.yarnpkg.com/wide-align/-/wide-align-1.1.3.tgz#ae074e6bdc0c14a431e804e624549c633b000457" integrity sha512-QGkOQc8XL6Bt5PwnsExKBPuMKBxnGxWWW3fU55Xt4feHozMUhdUMaBCk290qpm/wG5u/RSKzwdAC4i51YigihA== @@ -9134,7 +8747,7 @@ yargs@13.3.2, yargs@^13.3.0, yargs@^13.3.2: y18n "^4.0.0" yargs-parser "^13.1.2" -yargs@^15.0.2, yargs@^15.1.0, yargs@^15.3.1: +yargs@^15.0.2, yargs@^15.3.1: version "15.3.1" resolved "https://registry.yarnpkg.com/yargs/-/yargs-15.3.1.tgz#9505b472763963e54afe60148ad27a330818e98b" integrity sha512-92O1HWEjw27sBfgmXiixJWT5hRBp2eobqXicLtPBIDBhYB+1HpwZlXmbW2luivBJHBzki+7VyCLRtAkScbTBQA== From bb3c5faca098773a50d37f84cd982d846bca18df Mon Sep 17 00:00:00 2001 From: Amin Mahboubi Date: Tue, 21 Jul 2020 12:29:31 +0200 Subject: [PATCH 09/69] remove manual types --- types/getstream/index.d.ts | 382 ------------------------------ types/getstream/testsGetstream.ts | 40 ---- types/getstream/tsconfig.json | 19 -- types/getstream/tslint.json | 7 - 4 files changed, 448 deletions(-) delete mode 100644 types/getstream/index.d.ts delete mode 100644 types/getstream/testsGetstream.ts delete mode 100644 types/getstream/tsconfig.json delete mode 100644 types/getstream/tslint.json diff --git a/types/getstream/index.d.ts b/types/getstream/index.d.ts deleted file mode 100644 index c3a50aad..00000000 --- a/types/getstream/index.d.ts +++ /dev/null @@ -1,382 +0,0 @@ -/// -// TypeScript Version: 3.5 -export as namespace stream; - -export interface APIResponse { - duration: string; - [customFieldKey: string]: any; -} - -/** - * Create StreamClient - */ -export function connect(apiKey: string, apiSecret: string | null, appId: string, options?: object): stream.Client; - -export class CollectionEntry { - constructor(store: Collections, collection: string, id: string, data: object); - - // Get the entry ref string - ref(): string; - - // Get the entry from the Collection - get(): Promise; - - // Add the entry to the Collection - add(): Promise; - - // Update the entry in the object storage - update(): Promise; - - // Delete the entry from the collection - delete(): Promise; -} - -export class Collections { - /** Construct Collections. */ - constructor(client: StreamClient, token: string); - - // Build the URL for a collection or collection item - buildURL(collection: string, itemId?: string): string; - - // Instantiate a collection entry object - entry(collection: string, itemId?: string, itemData?: object): CollectionEntry; - - // Get a collection entry - get(collection: string, itemId: string): Promise; - - // Add a single entry to a collection - add(collection: string, itemId: string, itemData?: object): Promise; - - // Update a single collection entry - update(collection: string, entryId: string, data?: object): Promise; - - // Delete a single collection entry - delete(collection: string, entryId: string): Promise; - - // Upsert one or more items within a collection. - upsert(collectionName: string, data: object | object[]): Promise; - - // Select all objects with ids from the collection. - select(collectionName: string, ids: object | object[]): Promise; - - // Remove all objects by id from the collection. - deleteMany(collectionName: string, ids: object | object[]): Promise; -} - -export class Personalization { - /** Construct Personalization. */ - constructor(client: StreamClient); - - // Get personalized activities for this feed. - get(resource: string, options?: object): Promise; - - // Post data to personalization endpoint. - post(resource: string, options?: object, data?: object): Promise; - - // Delete metadata or activities - delete(resource: string, options?: object): Promise; -} - -export interface FileUploadAPIResponse extends APIResponse { - file: string; -} - -export interface ImageProcessOptions { - w?: number | string; - h?: number | string; - resize?: string | 'clip' | 'crop' | 'scale' | 'fill'; - crop?: string | 'top' | 'bottom' | 'left' | 'right' | 'center'; -} - -export type onUploadProgress = (progressEvent: ProgressEvent) => void; - -export class StreamImageStore { - constructor(client: StreamClient, token: string); - - upload( - uri: string | Buffer | File, - name?: string, - contentType?: string, - onUploadProgress?: onUploadProgress, - ): Promise; - - process(uri: string, options: ImageProcessOptions): Promise; - - thumbnail( - uri: string, - w: number | string, - h: number | string, - options?: ImageProcessOptions, - ): Promise; - - delete(uri: string): Promise<{}>; -} - -export class StreamFileStore { - constructor(client: StreamClient, token: string); - - upload( - uri: string | Buffer | File, - name?: string, - contentType?: string, - onUploadProgress?: onUploadProgress, - ): Promise; - - delete(uri: string): Promise<{}>; -} - -export class Feed { - /** Construct Feed. */ - constructor(client: StreamClient, feedSlug: string, userId: string, token: string); - - // Add activity - addActivity(activity: Activity): Promise; - - // Remove activity - removeActivity(activityId: string | object): Promise; - - // Add activities - addActivities(activities: Activity[]): Promise; - - // Follow feed - follow(targetSlug: string, targetUserId: string, options?: object): Promise; - - // Unfollow feed - unfollow(targetSlug: string, targetUserId: string, options?: object): Promise; - - // List followed feeds - following(options: object): Promise; - - // List followers - followers(options: object): Promise; - - // Get feed - get(options: object): Promise; - - // Activity details - getActivityDetail(activityId: string, options?: object): Promise; - - // Subscriptions - getFayeClient(timeout?: number): object; // would like to return `Faye.Client` here, but they haven't release any ts def files yet - subscribe(callback: GenericCallback): Promise; - unsubscribe(): void; - - // Updates an activity's "to" fields - updateActivityToTargets( - foreignId: string, - time: string, - newTargets: string[], - addedTargets: string[], - removedTargets: string[], - ): Promise; -} - -export class Reaction { - /** Construct Reaction. */ - constructor(client: StreamClient); - - add(kind: string, activity: string | Activity, data?: object, targetFeeds?: string[]): Promise; - - addChild(kind: string, reaction: string | Reaction, data?: object, targetFeeds?: string[]): Promise; - - get(id: string): Promise; - - filter(conditions: object): Promise; - - update(id: string, data: object, targetFeeds?: string[]): Promise; - - delete(id: string): Promise; -} - -export class User { - /** Construct User. */ - constructor(client: StreamClient, userId: string); - - ref(): string; - - delete(): Promise; - - get(options: object): Promise; - - create(data: object): Promise; - - update(data: object): Promise; - - getOrCreate(options: object): Promise; - - profile(): Promise; -} - -export class StreamClient { - /** Construct StreamClient */ - constructor(apiKey: string, apiSecret?: string, appId?: string, options?: object); - - apiKey: string; - appId?: string; - apiSecret?: string; - userToken?: string; - userId?: string; - currentUser?: User; - - // Event subscriptions - on(event: string, callback: (args: any[]) => void): void; - off(key: string): void; - - // Get user agent - userAgent(): string; - - // Get feed tokens - getReadOnlyToken(feedSlug: string, userId: string): string; - getReadWriteToken(feedSlug: string, userId: string): string; - - // Create user token - createUserToken(userId: string, extraData?: object): string; - - // Create feed - feed(feedSlug: string, userId: string | User): Feed; - - // Update activity - updateActivity(activity: object): Promise; - - // Retrieve activities by ID or foreign ID and time - getActivities(params: object): Promise; - - // Partially update activity - activityPartialUpdate(data: object): Promise; - - // Partially update multiple activities - activitiesPartialUpdate(changes: object): Promise; - - // Update activities - updateActivities(activities: object[]): Promise; - - // Add activity to many feeds - /** - * addToMany. - * Available in node environments with batchOperations enabled. - */ - addToMany(activity: Activity, feeds: string[]): Promise; - - // Collections sub-component - collections: Collections; - personalization: Personalization; - images: StreamImageStore; - files: StreamFileStore; - reactions: Reaction; - - // Instantiate a StreamUser class for the given user ID - user(userId: string): User; - - // Follow many feeds - /** - * followMany. - * Available in node environments with batchOperations enabled - */ - followMany(follows: object[], activityCopyLimit?: number): Promise; - - // Unfollow many feeds - /** - * unfollowMany. - * Available in node environments with batchOperations enabled - */ - unfollowMany(unfollows: object[]): Promise; - - /** - * og. - * Retrieve open graph information of urls - */ - og(url: string): Promise; -} - -// Export the OGResource -export interface OGResource { - url?: string; - secure_url?: string; - type?: string; -} - -// Export the OGAudio -export interface OGAudio extends OGResource { - audio?: string; -} - -// Export the OGImage -export interface OGImage extends OGResource { - image?: string; - width?: number; - height?: number; - alt?: string; -} - -// Export the OGVideo -export interface OGVideo extends OGResource { - video?: string; - width?: number; - height?: number; -} - -// Export the OGResponse -export interface OGResponse extends APIResponse { - title?: string; - type?: string; - url?: string; - site?: string; - site_name?: string; - description?: string; - favicon?: string; - determiner?: string; - locale?: string; - audios?: OGAudio[]; - images?: OGImage[]; - videos?: OGVideo[]; -} - -// Export the Stream Client -export { StreamClient as Client }; - -// Export the Stream errors -export namespace errors { - class MissingSchemaError { - /** - * Construct MissingSchemaError. - * Not typically instantiated by app developers. - */ - } - - class FeedError { - /** - * Construct FeedError. - * Not typically instantiated by app developers. - */ - } - class SiteError { - /** - * Construct SiteError. - * Not typically instantiated by app developers. - */ - } -} - -export interface Activity { - actor: string | User; - verb: string; - object: string; - time?: string; - to?: string[]; - foreign_id?: string; - [customFieldKey: string]: any; - - // reserved words - activity_id?: never; - activity?: never; - analytics?: never; - extra_context?: never; - id?: never; - is_read?: never; - is_seen?: never; - origin?: never; - score?: never; - site_id?: never; -} - -export type GenericCallback = (data: T) => void; diff --git a/types/getstream/testsGetstream.ts b/types/getstream/testsGetstream.ts deleted file mode 100644 index 6473d90a..00000000 --- a/types/getstream/testsGetstream.ts +++ /dev/null @@ -1,40 +0,0 @@ -new stream.Client('key', undefined, 'apiSecret'); - -// prettier-ignore -stream.connect('abc', 'def', 'ghi'); // $ExpectType StreamClient - -// prettier-ignore -const client = stream.connect('abc', 'def', 'ghi'); -client.feed('feedSlug', 'user'); // $ExpectType Feed -client.og('https://getstream.io'); // $ExpectType Promise -client.images.upload('http://foo.bar/img.jpg', 'img.jpg', 'image/jpeg'); // $ExpectType Promise -// prettier-ignore -client.images.process('http://foo.bar/img.jpg', { crop: 'bottom', resize: 'clip', h: 50, w: 50 }); // $ExpectType Promise -// prettier-ignore -client.images.thumbnail('http://foo.bar/img.jpg', 50, 50, { crop: 'bottom', resize: 'fill' }); // $ExpectType Promise -client.images.delete('http://foo.bar/img.jpg'); // $ExpectType Promise -client.files.upload('http://foo.bar/txt.txt', 'txt.txt', 'text/plain'); // $ExpectType Promise -client.files.delete('http://foo.bar/txt.txt'); // $ExpectType Promise - -let feed = client.feed('feedSlug', 'user'); -feed.follow('feedSlug', 'user'); // $ExpectType Promise -feed.follow('feedSlug', 'user', { activity_copy_limit: 10 }); // $ExpectType Promise - -feed.unfollow('feedSlug', 'user'); // $ExpectType Promise -feed.unfollow('feedSlug', 'user', { keep_history: true }); // $ExpectType Promise - -let collections = client.collections; // $ExpectType Collections -collections.buildURL('events', 'login-134'); // $ExpectType string -collections.entry('events', 'login-134', { user: 'john', source: 'website' }); // $ExpectType CollectionEntry -collections.get('events', 'login-134'); // $ExpectType Promise -collections.add('events', 'login-123', { user: 'john' }); // $ExpectType Promise -collections.update('events', 'login-2', { user: 'jo' }); // $ExpectType Promise -collections.delete('events', 'login-134'); // $ExpectType Promise -collections.upsert('events', { id: 'login-1', user: 'jo' }); // $ExpectType Promise -collections.upsert('events', { id: 'login-1', source: 'cart' }); // $ExpectType Promise -collections.select('events', ['login-1', 'login-123']); // $ExpectType Promise -collections.deleteMany('events', ['login-2', 'login-234']); // $ExpectType Promise - -new stream.errors.MissingSchemaError(); // $ExpectType MissingSchemaError -new stream.errors.FeedError(); // $ExpectType FeedError -new stream.errors.SiteError(); // $ExpectType SiteError diff --git a/types/getstream/tsconfig.json b/types/getstream/tsconfig.json deleted file mode 100644 index 21b933e6..00000000 --- a/types/getstream/tsconfig.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "compileOnSave": false, - "compilerOptions": { - "forceConsistentCasingInFileNames": true, - "lib": ["DOM", "ES6"], - "module": "commonjs", - "noEmit": true, - "noImplicitAny": true, - "noImplicitThis": true, - "removeComments": true, - "preserveConstEnums": true, - "strictFunctionTypes": true, - "strictNullChecks": true, - "sourceMap": true, - "baseUrl": "../", - "types": [], - "paths": { "getstream": ["getstream/"] } - } -} diff --git a/types/getstream/tslint.json b/types/getstream/tslint.json deleted file mode 100644 index d53f2d6d..00000000 --- a/types/getstream/tslint.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "extends": "dtslint/dtslint.json", - "strictFunctionTypes": true, - "rules": { - "indent": [true, "spaces"] - } -} From 35e6fdbaaabfba575f57f5f2ad5211013ef1c554 Mon Sep 17 00:00:00 2001 From: Amin Mahboubi Date: Tue, 21 Jul 2020 12:29:49 +0200 Subject: [PATCH 10/69] fix package types path --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index e9c81065..44c3da44 100644 --- a/package.json +++ b/package.json @@ -7,7 +7,7 @@ "description": "The official low-level GetStream.io client for Node.js and the browser.", "main": "./lib/getstream.js", "module": "./lib/getstream.js", - "types": "./types/getstream/index.d.ts", + "types": "./types/index.d.ts", "homepage": "https://getstream.io/docs/?language=js", "email": "support@getstream.io", "license": "BSD-3-Clause", From ab465d1a6c23c109c1850e6bd5ad747c5d56df16 Mon Sep 17 00:00:00 2001 From: Amin Mahboubi Date: Tue, 21 Jul 2020 12:38:11 +0200 Subject: [PATCH 11/69] WIP/lib conversion to typescript --- src/getstream.ts | 12 +- src/lib/batch_operations.ts | 15 +- src/lib/client.ts | 388 ++++++++++++++++++++++++++---------- src/lib/collections.ts | 93 ++++++--- src/lib/errors.ts | 13 +- src/lib/feed.ts | 136 ++++++++----- src/lib/files.ts | 18 +- src/lib/images.ts | 37 +++- src/lib/personalization.ts | 26 ++- src/lib/reaction.ts | 175 ++++++++++++---- src/lib/redirect_url.ts | 15 +- src/lib/signing.ts | 52 ++--- src/lib/user.ts | 42 ++-- src/lib/utils.ts | 40 ++-- 14 files changed, 757 insertions(+), 305 deletions(-) diff --git a/src/getstream.ts b/src/getstream.ts index df68d9ae..e5f24f3b 100644 --- a/src/getstream.ts +++ b/src/getstream.ts @@ -3,11 +3,11 @@ * @author Thierry Schellenbach * BSD License */ -import Client from './lib/client'; +import StreamClient, { ClientOptions } from './lib/client'; import errors from './lib/errors'; import signing from './lib/signing'; -function connect(apiKey, apiSecret, appId, options) { +function connect(apiKey: string, apiSecret: string | null, appId?: string, options?: ClientOptions): StreamClient { /** * Create StreamClient * @method connect @@ -27,7 +27,7 @@ function connect(apiKey, apiSecret, appId, options) { * "https://thierry:pass@gestream.io/?app=1" */ if (process && process.env && process.env.STREAM_URL && !apiKey) { - const parts = /https:\/\/(\w+):(\w+)@([\w-]*).*\?app_id=(\d+)/.exec(process.env.STREAM_URL); + const parts = /https:\/\/(\w+):(\w+)@([\w-]*).*\?app_id=(\d+)/.exec(process.env.STREAM_URL) || []; apiKey = parts[1]; apiSecret = parts[2]; const location = parts[3]; @@ -41,10 +41,10 @@ function connect(apiKey, apiSecret, appId, options) { } } - return new Client(apiKey, apiSecret, appId, options); + return new StreamClient(apiKey, apiSecret, appId, options); } -export { connect, errors, signing, Client }; +export { connect, errors, signing, StreamClient as Client }; /* deprecated default export */ -export default { connect, errors, signing, Client }; +export default { connect, errors, signing, Client: StreamClient }; diff --git a/src/lib/batch_operations.ts b/src/lib/batch_operations.ts index 57e86669..0f8465df 100644 --- a/src/lib/batch_operations.ts +++ b/src/lib/batch_operations.ts @@ -1,6 +1,7 @@ +import StreamClient, { APIResponse, FollowRelation } from './client'; import utils from './utils'; -function addToMany(activity, feeds) { +function addToMany(this: StreamClient, activity: T, feeds: string[]): Promise { /** * Add one activity to many feeds * @method addToMany @@ -12,7 +13,7 @@ function addToMany(activity, feeds) { */ this._throwMissingApiSecret(); - return this.post({ + return this.post({ url: 'feed/add_to_many/', body: { activity: utils.replaceStreamObjects(activity), @@ -22,7 +23,7 @@ function addToMany(activity, feeds) { }); } -function followMany(follows, activityCopyLimit) { +function followMany(this: StreamClient, follows: FollowRelation[], activityCopyLimit?: number): Promise { /** * Follow multiple feeds with one API call * @method followMany @@ -34,10 +35,10 @@ function followMany(follows, activityCopyLimit) { */ this._throwMissingApiSecret(); - const qs = {}; + const qs: { activity_copy_limit?: number } = {}; if (typeof activityCopyLimit === 'number') qs.activity_copy_limit = activityCopyLimit; - return this.post({ + return this.post({ url: 'follow_many/', body: follows, qs, @@ -45,7 +46,7 @@ function followMany(follows, activityCopyLimit) { }); } -function unfollowMany(unfollows) { +function unfollowMany(this: StreamClient, unfollows: FollowRelation[]): Promise { /** * Unfollow multiple feeds with one API call * @method unfollowMany @@ -56,7 +57,7 @@ function unfollowMany(unfollows) { */ this._throwMissingApiSecret(); - return this.post({ + return this.post({ url: 'unfollow_many/', body: unfollows, signature: this.getOrCreateToken(), diff --git a/src/lib/client.ts b/src/lib/client.ts index 00d8f4a0..ca438d56 100644 --- a/src/lib/client.ts +++ b/src/lib/client.ts @@ -1,7 +1,7 @@ -import axios from 'axios'; +import * as axios from 'axios'; import http from 'http'; import https from 'https'; -import Faye from 'faye'; +import * as Faye from 'faye'; import jwtDecode from 'jwt-decode'; import Personalization from './personalization'; @@ -18,12 +18,173 @@ import errors from './errors'; import utils from './utils'; import pkg from '../../package.json'; +export type APIResponse = { + duration?: string; + [key: string]: unknown; +}; + +export type FileUploadAPIResponse = APIResponse & { + file: string; +}; + +export type OnUploadProgress = (progressEvent: ProgressEvent) => void; + +type ActivityPartialChanges = { + id?: string; + foreignID?: string; + time?: string | Date; + set?: Record; + unset?: string[]; +}; + +type BaseActivity = { + id: string; + actor: string; + verb: string; + object: string; + time: string | Date; + foreign_id: string; + to?: string[]; +}; + +export type Activity> = BaseActivity & T; + +type GetActivitiesAPIResponse = APIResponse & { results: Activity[] }; + +type PartialUpdateActivityAPIResponse = APIResponse & { activities: Activity[] }; + +export type FollowRelation = { + source: string; + target: string; +}; + +export type ClientOptions = { + location?: string | undefined; + expireTokens?: boolean; + version?: string; + group?: string; + keepAlive?: boolean; + timeout?: number; + browser?: boolean; + fayeUrl?: string; + protocol?: string; + local?: boolean; + urlOverride?: { [key: string]: string }; +}; + +export type EnrichOptions = { + enrich?: boolean; + withOwnReactions?: boolean; + withOwnChildren?: boolean; + ownReactions?: boolean; + withReactionCounts?: boolean; + withRecentReactions?: boolean; + recentReactionsLimit?: number; +}; + +type OGResource = { + url?: string; + secure_url?: string; + type?: string; +}; + +type OGAudio = OGResource & { + audio?: string; +}; + +type OGImage = OGResource & { + image?: string; + width?: number; + height?: number; + alt?: string; +}; + +type OGVideo = OGResource & { + video?: string; + width?: number; + height?: number; +}; + +type OGAPIResponse = APIResponse & { + title?: string; + type?: string; + url?: string; + site?: string; + site_name?: string; + description?: string; + favicon?: string; + determiner?: string; + locale?: string; + audios?: OGAudio[]; + images?: OGImage[]; + videos?: OGVideo[]; +}; + +type AxiosConfig = { + signature: string; + url: string; + serviceName?: string; + body?: unknown; + qs?: { [key: string]: unknown }; + headers?: { [key: string]: string }; + axiosOptions?: axios.AxiosRequestConfig; +}; + +type HandlerCallback = (...args: unknown[]) => unknown; + /** * Client to connect to Stream api * @class StreamClient */ -class StreamClient { - constructor(apiKey, apiSecretOrToken, appId, options = {}) { +class StreamClient { + baseUrl: string; + baseAnalyticsUrl: string; + apiKey: string; + appId: string | undefined; + usingApiSecret: boolean; + apiSecret: string | null; + userToken: string | null; + enrichByDefault: boolean; + options: ClientOptions; + userId: undefined | string; + authPayload: undefined | unknown; + version: string; + fayeUrl: string; + group: string; + expireTokens: boolean; + location: string; + fayeClient: Faye.Client | null; + browser: boolean; + node: boolean; + nodeOptions: undefined | { httpAgent: http.Agent; httpsAgent: https.Agent }; + + request: axios.AxiosInstance; + subscriptions: { + [key: string]: { + userId: string; + token: string; + fayeSubscription: Faye.Subscription; + }; + }; + handlers: { [key: string]: HandlerCallback }; + + currentUser: StreamUser | undefined; + personalization: Personalization; + collections: Collections; + files: StreamFileStore; + images: StreamImageStore; + reactions: StreamReaction; + + private _personalizationToken: string | undefined; + private _collectionsToken: string | undefined; + private _getOrCreateToken: string | undefined; + + addToMany?: (this: StreamClient, activity: T, feeds: string[]) => Promise; + followMany?: (this: StreamClient, follows: FollowRelation[], activityCopyLimit?: number) => Promise; + unfollowMany?: (this: StreamClient, unfollows: FollowRelation[]) => Promise; + createRedirectUrl?: (this: StreamClient, targetUrl: string, userId: string, events: unknown[]) => string; + + constructor(apiKey: string, apiSecretOrToken: string | null, appId?: string, options: ClientOptions = {}) { /** * Initialize a client * @method initialize @@ -49,7 +210,7 @@ class StreamClient { this.enrichByDefault = !this.usingApiSecret; if (this.userToken != null) { - const jwtBody = jwtDecode(this.userToken); + const jwtBody: { user_id?: string } = jwtDecode(this.userToken); if (!jwtBody.user_id) { throw new TypeError('user_id is missing in user token'); } @@ -69,16 +230,11 @@ class StreamClient { this.subscriptions = {}; this.expireTokens = this.options.expireTokens ? this.options.expireTokens : false; // which data center to use - this.location = this.options.location; + this.location = this.options.location as string; this.baseUrl = this.getBaseUrl(); - if (typeof process !== 'undefined' && process.env.LOCAL_FAYE) { - this.fayeUrl = 'http://localhost:9999/faye/'; - } - - if (typeof process !== 'undefined' && process.env.STREAM_ANALYTICS_BASE_URL) { - this.baseAnalyticsUrl = process.env.STREAM_ANALYTICS_BASE_URL; - } + if (process?.env?.LOCAL_FAYE) this.fayeUrl = 'http://localhost:9999/faye/'; + if (process?.env?.STREAM_ANALYTICS_BASE_URL) this.baseAnalyticsUrl = process.env.STREAM_ANALYTICS_BASE_URL; this.handlers = {}; this.browser = typeof this.options.browser !== 'undefined' ? this.options.browser : typeof window !== 'undefined'; @@ -92,7 +248,7 @@ class StreamClient { }; } - this.request = axios.create({ + this.request = axios.default.create({ timeout: this.options.timeout || 10 * 1000, // 10 seconds withCredentials: false, // making sure cookies are not sent ...(this.nodeOptions || {}), @@ -109,9 +265,17 @@ class StreamClient { this.files = new StreamFileStore(this, this.getOrCreateToken()); this.images = new StreamImageStore(this, this.getOrCreateToken()); this.reactions = new StreamReaction(this, this.getOrCreateToken()); + + // If we are in a node environment and batchOperations/createRedirectUrl is available add the methods to the prototype of StreamClient + if (BatchOperations && createRedirectUrl) { + this.addToMany = BatchOperations.addToMany; + this.followMany = BatchOperations.followMany; + this.unfollowMany = BatchOperations.unfollowMany; + this.createRedirectUrl = createRedirectUrl; + } } - _throwMissingApiSecret() { + _throwMissingApiSecret(): void | never { if (!this.usingApiSecret) { throw new errors.SiteError( 'This method can only be used server-side using your API Secret, use client = stream.connect(key, secret);', @@ -119,12 +283,12 @@ class StreamClient { } } - getPersonalizationToken() { + getPersonalizationToken(): string { if (this._personalizationToken) return this._personalizationToken; this._throwMissingApiSecret(); - this._personalizationToken = signing.JWTScopeToken(this.apiSecret, 'personalization', '*', { + this._personalizationToken = signing.JWTScopeToken(this.apiSecret as string, 'personalization', '*', { userId: '*', feedId: '*', expireTokens: this.expireTokens, @@ -132,37 +296,36 @@ class StreamClient { return this._personalizationToken; } - getCollectionsToken() { + getCollectionsToken(): string { if (this._collectionsToken) return this._collectionsToken; this._throwMissingApiSecret(); - this._collectionsToken = signing.JWTScopeToken(this.apiSecret, 'collections', '*', { + this._collectionsToken = signing.JWTScopeToken(this.apiSecret as string, 'collections', '*', { feedId: '*', expireTokens: this.expireTokens, }); return this._collectionsToken; } - getAnalyticsToken() { + getAnalyticsToken(): string { this._throwMissingApiSecret(); - return signing.JWTScopeToken(this.apiSecret, 'analytics', '*', { + return signing.JWTScopeToken(this.apiSecret as string, 'analytics', '*', { userId: '*', expireTokens: this.expireTokens, }); } - getBaseUrl(serviceName) { + getBaseUrl(serviceName?: string): string { if (!serviceName) serviceName = 'api'; if (this.options.urlOverride && this.options.urlOverride[serviceName]) return this.options.urlOverride[serviceName]; const urlEnvironmentKey = serviceName === 'api' ? 'STREAM_BASE_URL' : `STREAM_${serviceName.toUpperCase()}_URL`; - if (typeof process !== 'undefined' && process.env[urlEnvironmentKey]) return process.env[urlEnvironmentKey]; + if (process?.env?.[urlEnvironmentKey]) return process.env[urlEnvironmentKey] as string; - if ((typeof process !== 'undefined' && process.env.LOCAL) || this.options.local) - return `http://localhost:8000/${serviceName}/`; + if (process?.env?.LOCAL || this.options.local) return `http://localhost:8000/${serviceName}/`; if (this.location) { const protocol = this.options.protocol || 'https'; @@ -174,7 +337,7 @@ class StreamClient { return this.baseUrl; } - on(event, callback) { + on(event: string, callback: HandlerCallback): void { /** * Support for global event callbacks * This is useful for generic error and loading handling @@ -189,7 +352,7 @@ class StreamClient { this.handlers[event] = callback; } - off(key) { + off(key?: string): void { /** * Remove one or more event handlers * @method off @@ -206,7 +369,7 @@ class StreamClient { } } - send(key, ...args) { + send(key: string, ...args: unknown[]): void { /** * Call the given handler with the arguments * @method send @@ -216,7 +379,7 @@ class StreamClient { if (this.handlers[key]) this.handlers[key].apply(this, args); } - userAgent() { + userAgent(): string { /** * Get the current user agent * @method userAgent @@ -226,7 +389,7 @@ class StreamClient { return `stream-javascript-client-${this.node ? 'node' : 'browser'}-${pkg.version}`; } - getReadOnlyToken(feedSlug, userId) { + getReadOnlyToken(feedSlug: string, userId: string): string { /** * Returns a token that allows only read operations * @@ -241,13 +404,13 @@ class StreamClient { utils.validateFeedSlug(feedSlug); utils.validateUserId(userId); - return signing.JWTScopeToken(this.apiSecret, '*', 'read', { + return signing.JWTScopeToken(this.apiSecret as string, '*', 'read', { feedId: `${feedSlug}${userId}`, expireTokens: this.expireTokens, }); } - getReadWriteToken(feedSlug, userId) { + getReadWriteToken(feedSlug: string, userId: string): string { /** * Returns a token that allows read and write operations * @@ -262,13 +425,13 @@ class StreamClient { utils.validateFeedSlug(feedSlug); utils.validateUserId(userId); - return signing.JWTScopeToken(this.apiSecret, '*', '*', { + return signing.JWTScopeToken(this.apiSecret as string, '*', '*', { feedId: `${feedSlug}${userId}`, expireTokens: this.expireTokens, }); } - feed(feedSlug, userId = this.userId, token) { + feed(feedSlug: string, userId?: string | StreamUser, token?: string): StreamFeed { /** * Returns a feed object for the given feed id and token * @method feed @@ -284,16 +447,16 @@ class StreamClient { if (token === undefined) { if (this.usingApiSecret) { - token = signing.JWTScopeToken(this.apiSecret, '*', '*', { feedId: `${feedSlug}${userId}` }); + token = signing.JWTScopeToken(this.apiSecret as string, '*', '*', { feedId: `${feedSlug}${userId}` }); } else { - token = this.userToken; + token = this.userToken as string; } } - return new StreamFeed(this, feedSlug, userId, token); + return new StreamFeed(this, feedSlug, userId || (this.userId as string), token); } - enrichUrl(relativeUrl, serviceName) { + enrichUrl(relativeUrl: string, serviceName?: string): string { /** * Combines the base url with version and the relative url * @method enrichUrl @@ -304,9 +467,15 @@ class StreamClient { return `${this.getBaseUrl(serviceName)}${this.version}/${relativeUrl}`; } - replaceReactionOptions = (options = {}) => { + replaceReactionOptions = (options: { + reactions?: Record; + withOwnReactions?: boolean; + withRecentReactions?: boolean; + withReactionCounts?: boolean; + withOwnChildren?: boolean; + }): void => { // Shortcut options for reaction enrichment - if (options.reactions) { + if (options?.reactions) { if (options.reactions.own != null) { options.withOwnReactions = options.reactions.own; } @@ -323,7 +492,15 @@ class StreamClient { } }; - shouldUseEnrichEndpoint(options = {}) { + shouldUseEnrichEndpoint( + options: { + enrich?: boolean; + ownReactions?: boolean; + withRecentReactions?: boolean; + withReactionCounts?: boolean; + withOwnChildren?: boolean; + } = {}, + ): boolean { if (options.enrich) { const result = options.enrich; delete options.enrich; @@ -339,7 +516,7 @@ class StreamClient { ); } - enrichKwargs({ method, ...kwargs }) { + enrichKwargs({ method, signature, ...kwargs }: AxiosConfig & { method: axios.Method }): axios.AxiosRequestConfig { /** * Adds the API key and the signature * @method enrichKwargs @@ -347,7 +524,6 @@ class StreamClient { * @param {object} kwargs * @private */ - const signature = kwargs.signature || this.signature; const isJWT = signing.isJWTSignature(signature); return { @@ -369,7 +545,7 @@ class StreamClient { }; } - getFayeAuthorization() { + getFayeAuthorization(): Faye.Middleware { /** * Get the authorization middleware to use Faye with getstream.io * @method getFayeAuthorization @@ -378,8 +554,8 @@ class StreamClient { * @return {object} Faye authorization middleware */ return { - incoming: (message, callback) => callback(message), - outgoing: (message, callback) => { + incoming: (message: Faye.Message, callback: Faye.Callback) => callback(message), + outgoing: (message: Faye.Message, callback: Faye.Callback) => { if (message.subscription && this.subscriptions[message.subscription]) { const subscription = this.subscriptions[message.subscription]; @@ -395,7 +571,7 @@ class StreamClient { }; } - getFayeClient(timeout = 10) { + getFayeClient(timeout = 10): Faye.Client { /** * Returns this client's current Faye client * @method getFayeClient @@ -412,7 +588,7 @@ class StreamClient { return this.fayeClient; } - handleResponse = (response) => { + handleResponse = (response: axios.AxiosResponse): T => { if (/^2/.test(`${response.status}`)) { this.send('response', null, response, response.data); return response.data; @@ -425,7 +601,7 @@ class StreamClient { ); }; - doAxiosRequest = async (method, options) => { + doAxiosRequest = async (method: axios.Method, options: AxiosConfig): Promise => { this.send('request', method, options); try { @@ -437,9 +613,15 @@ class StreamClient { } }; - upload(url, uri, name, contentType, onUploadProgress) { + upload( + url: string, + uri: string | File | NodeJS.ReadStream, + name?: string, + contentType?: string, + onUploadProgress?: OnUploadProgress, + ): Promise { const fd = utils.addFileToFormData(uri, name, contentType); - return this.doAxiosRequest('POST', { + return this.doAxiosRequest('POST', { url, body: fd, headers: fd.getHeaders ? fd.getHeaders() : {}, // node vs browser @@ -447,13 +629,12 @@ class StreamClient { axiosOptions: { timeout: 0, maxContentLength: Infinity, - maxBodyLength: Infinity, onUploadProgress, }, }); } - get(kwargs) { + get(kwargs: AxiosConfig): Promise { /** * Shorthand function for get request * @method get @@ -465,7 +646,7 @@ class StreamClient { return this.doAxiosRequest('GET', kwargs); } - post(kwargs) { + post(kwargs: AxiosConfig): Promise { /** * Shorthand function for post request * @method post @@ -477,7 +658,7 @@ class StreamClient { return this.doAxiosRequest('POST', kwargs); } - delete(kwargs) { + delete(kwargs: AxiosConfig): Promise { /** * Shorthand function for delete request * @method delete @@ -489,7 +670,7 @@ class StreamClient { return this.doAxiosRequest('DELETE', kwargs); } - put(kwargs) { + put(kwargs: AxiosConfig): Promise { /** * Shorthand function for put request * @method put @@ -505,15 +686,15 @@ class StreamClient { * @param {string} userId * @param {object} extraData */ - createUserToken(userId, extraData = {}) { + createUserToken(userId: string, extraData = {}): string { this._throwMissingApiSecret(); - return signing.JWTUserSessionToken(this.apiSecret, userId, extraData, { + return signing.JWTUserSessionToken(this.apiSecret as string, userId, extraData, { noTimestamp: !this.expireTokens, }); } - updateActivities(activities) { + updateActivities(activities: Activity[]): Promise { /** * Updates all supplied activities on the getstream-io api * @since 3.1.0 @@ -526,19 +707,19 @@ class StreamClient { throw new TypeError('The activities argument should be an Array'); } - const authToken = signing.JWTScopeToken(this.apiSecret, 'activities', '*', { + const authToken = signing.JWTScopeToken(this.apiSecret as string, 'activities', '*', { feedId: '*', expireTokens: this.expireTokens, }); - return this.post({ + return this.post({ url: 'activities/', body: { activities }, signature: authToken, }); } - updateActivity(activity) { + updateActivity(activity: Activity): Promise { /** * Updates one activity on the getstream-io api * @since 3.1.0 @@ -547,27 +728,38 @@ class StreamClient { */ this._throwMissingApiSecret(); - return this.updateActivities([activity]); + return this.updateActivities([activity]); } - getActivities({ ids, foreignIDTimes, ...params }) { + getActivities({ + ids, + foreignIDTimes, + ...params + }: EnrichOptions & { + ids?: string[]; + foreignIDTimes?: { foreignID: string; time: string | Date }[]; + + reactions?: Record; + }): Promise> { /** * Retrieve activities by ID or foreign ID and time * @since 3.19.0 * @param {object} params object containing either the list of activity IDs as {ids: ['...', ...]} or foreign IDs and time as {foreignIDTimes: [{foreignID: ..., time: ...}, ...]} * @return {Promise} */ + const extraParams: { ids?: string; foreign_ids?: string; timestamps?: string } = {}; + if (ids) { if (!(ids instanceof Array)) { throw new TypeError('The ids argument should be an Array'); } - params.ids = ids.join(','); + extraParams.ids = ids.join(','); } else if (foreignIDTimes) { if (!(foreignIDTimes instanceof Array)) { throw new TypeError('The foreignIDTimes argument should be an Array'); } - const foreignIDs = []; - const timestamps = []; + const foreignIDs: string[] = []; + const timestamps: (string | Date)[] = []; foreignIDTimes.forEach((fidTime) => { if (!(fidTime instanceof Object)) { throw new TypeError('foreignIDTimes elements should be Objects'); @@ -576,15 +768,15 @@ class StreamClient { timestamps.push(fidTime.time); }); - params.foreign_ids = foreignIDs.join(','); - params.timestamps = timestamps.join(','); + extraParams.foreign_ids = foreignIDs.join(','); + extraParams.timestamps = timestamps.join(','); } else { throw new TypeError('Missing ids or foreignIDTimes params'); } - let token = this.userToken; + let token = this.userToken as string; if (this.usingApiSecret) { - token = signing.JWTScopeToken(this.apiSecret, 'activities', '*', { + token = signing.JWTScopeToken(this.apiSecret as string, 'activities', '*', { feedId: '*', expireTokens: this.expireTokens, }); @@ -593,41 +785,43 @@ class StreamClient { this.replaceReactionOptions(params); const path = this.shouldUseEnrichEndpoint(params) ? 'enrich/activities/' : 'activities/'; - return this.get({ + return this.get>({ url: path, - qs: params, + qs: { ...params, ...extraParams }, signature: token, }); } - getOrCreateToken() { + getOrCreateToken(): string { if (!this._getOrCreateToken) { this._getOrCreateToken = this.usingApiSecret - ? signing.JWTScopeToken(this.apiSecret, '*', '*', { feedId: '*' }) - : this.userToken; + ? signing.JWTScopeToken(this.apiSecret as string, '*', '*', { feedId: '*' }) + : (this.userToken as string); } return this._getOrCreateToken; } - user(userId) { - return new StreamUser(this, userId, this.getOrCreateToken()); + user(userId: string): StreamUser { + return new StreamUser(this, userId, this.getOrCreateToken()); } - async setUser(data) { + async setUser(data: U): Promise> { if (this.usingApiSecret) { throw new errors.SiteError('This method can only be used client-side using a user token'); } const body = { ...data }; - delete body.id; + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + delete body?.id; - const user = await this.currentUser.getOrCreate(body); + const user = await (this.currentUser as StreamUser).getOrCreate(body); this.currentUser = user; return user; } - og(url) { - return this.get({ + og(url: string): Promise { + return this.get({ url: 'og/', qs: { url }, signature: this.getOrCreateToken(), @@ -642,7 +836,7 @@ class StreamClient { }); } - async activityPartialUpdate(data) { + async activityPartialUpdate(data: ActivityPartialChanges): Promise> { /** * Update a single activity with partial operations. * @since 3.20.0 @@ -675,13 +869,13 @@ class StreamClient { * ] * }) */ - const response = await this.activitiesPartialUpdate([data]); + const response = await this.activitiesPartialUpdate([data]); const activity = response.activities[0]; delete response.activities; return { ...activity, ...response }; } - activitiesPartialUpdate(changes) { + activitiesPartialUpdate(changes: ActivityPartialChanges[]): Promise> { /** * Update multiple activities with partial operations. * @since v3.20.0 @@ -739,7 +933,7 @@ class StreamClient { if (!(changes instanceof Array)) { throw new TypeError('changes should be an Array'); } - changes.forEach(function (item) { + changes.forEach(function (item: ActivityPartialChanges & { foreign_id?: string }) { if (!(item instanceof Object)) { throw new TypeError(`changeset should be and Object`); } @@ -757,15 +951,15 @@ class StreamClient { } }); - let authToken = this.userToken; + let authToken = this.userToken as string; if (this.usingApiSecret) { - authToken = signing.JWTScopeToken(this.apiSecret, 'activities', '*', { + authToken = signing.JWTScopeToken(this.apiSecret as string, 'activities', '*', { feedId: '*', expireTokens: this.expireTokens, }); } - return this.post({ + return this.post>({ url: 'activity/', body: { changes, @@ -775,18 +969,4 @@ class StreamClient { } } -// If we are in a node environment and batchOperations is available add the methods to the prototype of StreamClient -if (BatchOperations) { - Object.keys(BatchOperations).forEach((key) => { - if (Object.prototype.hasOwnProperty.call(BatchOperations, key)) { - StreamClient.prototype[key] = BatchOperations[key]; - } - }); -} - -// If we are in a node environment and redirectUrl is available add the methods to the prototype of StreamClient -if (createRedirectUrl) { - StreamClient.prototype.createRedirectUrl = createRedirectUrl; -} - export default StreamClient; diff --git a/src/lib/collections.ts b/src/lib/collections.ts index 4a090817..fdab8fad 100644 --- a/src/lib/collections.ts +++ b/src/lib/collections.ts @@ -1,18 +1,52 @@ +import StreamClient, { APIResponse } from './client'; import errors from './errors'; -class CollectionEntry { - constructor(store, collection, id, data) { +type CollectionResponse = { + collection: string; + id: string; + data: T; + foregin_id: string; + created_at: Date; + updated_at: Date; + user_id?: string; +}; + +type CollectionAPIResponse = APIResponse & CollectionResponse; + +type SelectCollectionAPIResponse = APIResponse & { + response: { + data: CollectionResponse[]; + }; +}; + +type UpsertCollectionAPIResponse = APIResponse & { + data: { + [key: string]: { + id: string; + data: T; + }[]; + }; +}; + +class CollectionEntry { + id: string; + collection: string; + store: Collections; + data: T | null; + full: unknown; + + constructor(store: Collections, collection: string, id: string, data: T) { this.collection = collection; this.store = store; this.id = id; this.data = data; } - ref() { + ref(): string { return `SO:${this.collection}:${this.id}`; } - async get() { + async get(): Promise> { /** * get item from collection and sync data * @method get @@ -20,13 +54,13 @@ class CollectionEntry { * @return {Promise} Promise object * @example collection.get("0c7db91c-67f9-11e8-bcd9-fe00a9219401") */ - const response = await this.store.get(this.collection, this.id); + const response = await this.store.get(this.collection, this.id); this.data = response.data; this.full = response; return response; } - async add() { + async add(): Promise> { /** * Add item to collection * @method add @@ -34,13 +68,13 @@ class CollectionEntry { * @return {Promise} Promise object * @example collection.add("cheese101", {"name": "cheese burger","toppings": "cheese"}) */ - const response = await this.store.add(this.collection, this.id, this.data); + const response = await this.store.add(this.collection, this.id, this.data as T); this.data = response.data; this.full = response; return response; } - async update() { + async update(): Promise> { /** * Update item in the object storage * @method update @@ -49,13 +83,13 @@ class CollectionEntry { * @example store.update("0c7db91c-67f9-11e8-bcd9-fe00a9219401", {"name": "cheese burger","toppings": "cheese"}) * @example store.update("cheese101", {"name": "cheese burger","toppings": "cheese"}) */ - const response = await this.store.update(this.collection, this.id, this.data); + const response = await this.store.update(this.collection, this.id, this.data as T); this.data = response.data; this.full = response; return response; } - async delete() { + async delete(): Promise { /** * Delete item from collection * @method delete @@ -71,6 +105,9 @@ class CollectionEntry { } export default class Collections { + client: StreamClient; + token: string; + /** * Initialize a feed object * @method constructor @@ -78,21 +115,21 @@ export default class Collections { * @param {StreamCloudClient} client Stream client this collection is constructed from * @param {string} token JWT token */ - constructor(client, token) { + constructor(client: StreamClient, token: string) { this.client = client; this.token = token; } - buildURL = (collection, itemId) => { + buildURL = (collection: string, itemId?: string): string => { const url = `collections/${collection}/`; return itemId === undefined ? url : `${url}${itemId}/`; }; - entry(collection, itemId, itemData) { - return new CollectionEntry(this, collection, itemId, itemData); + entry(collection: string, itemId: string, itemData: T): CollectionEntry { + return new CollectionEntry(this, collection, itemId, itemData); } - async get(collection, itemId) { + async get(collection: string, itemId: string): Promise> { /** * get item from collection * @method get @@ -102,7 +139,7 @@ export default class Collections { * @return {Promise} Promise object * @example collection.get("food", "0c7db91c-67f9-11e8-bcd9-fe00a9219401") */ - const response = await this.client.get({ + const response = await this.client.get>({ url: this.buildURL(collection, itemId), signature: this.token, }); @@ -112,7 +149,7 @@ export default class Collections { return entry; } - async add(collection, itemId, itemData) { + async add(collection: string, itemId: string, itemData: T): Promise> { /** * Add item to collection * @method add @@ -123,7 +160,7 @@ export default class Collections { * @return {Promise} Promise object * @example collection.add("food", "cheese101", {"name": "cheese burger","toppings": "cheese"}) */ - const response = await this.client.post({ + const response = await this.client.post>({ url: this.buildURL(collection), body: { id: itemId === null ? undefined : itemId, @@ -137,7 +174,7 @@ export default class Collections { return entry; } - async update(collection, entryId, data) { + async update(collection: string, entryId: string, data: T): Promise> { /** * Update entry in the collection * @method update @@ -149,7 +186,7 @@ export default class Collections { * @example store.update("0c7db91c-67f9-11e8-bcd9-fe00a9219401", {"name": "cheese burger","toppings": "cheese"}) * @example store.update("food", "cheese101", {"name": "cheese burger","toppings": "cheese"}) */ - const response = await this.client.put({ + const response = await this.client.put>({ url: this.buildURL(collection, entryId), body: { data }, signature: this.token, @@ -160,7 +197,7 @@ export default class Collections { return entry; } - delete(collection, entryId) { + delete(collection: string, entryId: string): Promise { /** * Delete entry from collection * @method delete @@ -169,13 +206,13 @@ export default class Collections { * @return {Promise} Promise object * @example collection.delete("food", "cheese101") */ - return this.client.delete({ + return this.client.delete({ url: this.buildURL(collection, entryId), signature: this.token, }); } - upsert(collection, data) { + upsert(collection: string, data: T | T[]): Promise> { /** * Upsert one or more items within a collection. * @@ -190,7 +227,7 @@ export default class Collections { if (!Array.isArray(data)) data = [data]; - return this.client.post({ + return this.client.post>({ url: 'collections/', serviceName: 'api', body: { data: { [collection]: data } }, @@ -198,7 +235,7 @@ export default class Collections { }); } - select(collection, ids) { + select(collection: string, ids: string | string[]): Promise> { /** * Select all objects with ids from the collection. * @@ -213,7 +250,7 @@ export default class Collections { if (!Array.isArray(ids)) ids = [ids]; - return this.client.get({ + return this.client.get>({ url: 'collections/', serviceName: 'api', qs: { foreign_ids: ids.map((id) => `${collection}:${id}`).join(',') }, @@ -221,7 +258,7 @@ export default class Collections { }); } - deleteMany(collection, ids) { + deleteMany(collection: string, ids: string | string[]): Promise { /** * Remove all objects by id from the collection. * @@ -241,7 +278,7 @@ export default class Collections { ids: ids.map((id) => id.toString()).join(','), }; - return this.client.delete({ + return this.client.delete({ url: 'collections/', serviceName: 'api', qs: params, diff --git a/src/lib/errors.ts b/src/lib/errors.ts index 462c4f91..f3b40692 100644 --- a/src/lib/errors.ts +++ b/src/lib/errors.ts @@ -1,3 +1,5 @@ +import * as axios from 'axios'; + const canCapture = typeof Error.captureStackTrace === 'function'; const canStack = !!new Error().stack; @@ -8,13 +10,15 @@ const canStack = !!new Error().stack; * @param {string} [msg] Error message */ class ErrorAbstract extends Error { - constructor(msg) { + message: string; + + constructor(msg: string) { super(msg); this.message = msg; if (canCapture) { - Error.captureStackTrace(this, constructor); + Error.captureStackTrace(this, ErrorAbstract.constructor); } else if (canStack) { this.stack = new Error().stack; } else { @@ -64,7 +68,10 @@ class MissingSchemaError extends ErrorAbstract {} * @param {object} response */ class StreamApiError extends ErrorAbstract { - constructor(msg, data, response) { + error: unknown; + response: axios.AxiosResponse; + + constructor(msg: string, data: unknown, response: axios.AxiosResponse) { super(msg); this.error = data; diff --git a/src/lib/feed.ts b/src/lib/feed.ts index c11f651a..10ccc067 100644 --- a/src/lib/feed.ts +++ b/src/lib/feed.ts @@ -1,14 +1,43 @@ +import * as Faye from 'faye'; +import StreamClient, { APIResponse, Activity, EnrichOptions } from './client'; import StreamUser from './user'; import errors from './errors'; import utils from './utils'; +type FeedOptions = { + id_lt?: string; + id_lte?: string; + id_gt?: string; + id_gte?: string; + limit?: number; + offset?: number; + ranking?: string; +}; + +type GetFollowOptions = { + limit?: number; + offset?: number; + filter?: string[]; +}; + /** * Manage api calls for specific feeds * The feed object contains convenience functions such add activity, remove activity etc * @class StreamFeed */ export default class StreamFeed { - constructor(client, feedSlug, userId, token) { + client: StreamClient; + token: string; + id: string; + slug: string; + userId: string; + feedUrl: string; + feedTogether: string; + signature: string; + notificationChannel: string; + enrichByDefault: boolean; + + constructor(client: StreamClient, feedSlug: string, userId: string, token: string) { /** * Initialize a feed object * @method constructor @@ -51,7 +80,7 @@ export default class StreamFeed { this.enrichByDefault = false; } - addActivity(activity) { + addActivity(activity: T): Promise> { /** * Adds the given activity to the feed * @method addActivity @@ -65,14 +94,14 @@ export default class StreamFeed { activity.actor = this.client.currentUser.ref(); } - return this.client.post({ + return this.client.post>({ url: `feed/${this.feedUrl}/`, body: activity, signature: this.signature, }); } - removeActivity(activityId) { + removeActivity(activityId: string | { foreignId: string }): Promise { /** * Removes the activity by activityId * @method removeActivity @@ -84,14 +113,14 @@ export default class StreamFeed { * @example * feed.removeActivity({'foreignId': foreignId}); */ - return this.client.delete({ - url: `feed/${this.feedUrl}/${activityId.foreignId || activityId}/`, - qs: activityId.foreignId ? { foreign_id: '1' } : {}, + return this.client.delete({ + url: `feed/${this.feedUrl}/${(activityId as { foreignId: string }).foreignId || activityId}/`, + qs: (activityId as { foreignId: string }).foreignId ? { foreign_id: '1' } : {}, signature: this.signature, }); } - addActivities(activities) { + addActivities(activities: T[]): Promise { /** * Adds the given activities to the feed * @method addActivities @@ -99,14 +128,18 @@ export default class StreamFeed { * @param {Array} activities Array of activities to add * @return {Promise} XHR request object */ - return this.client.post({ + return this.client.post({ url: `feed/${this.feedUrl}/`, body: { activities: utils.replaceStreamObjects(activities) }, signature: this.signature, }); } - follow(targetSlug, targetUserId, options = {}) { + follow( + targetSlug: string, + targetUserId: string | { id: string }, + options: { limit?: number } = {}, + ): Promise { /** * Follows the given target feed * @method follow @@ -114,7 +147,7 @@ export default class StreamFeed { * @param {string} targetSlug Slug of the target feed * @param {string} targetUserId User identifier of the target feed * @param {object} options Additional options - * @param {number} options.activityCopyLimit Limit the amount of activities copied over on follow + * @param {number} options.limit Limit the amount of activities copied over on follow * @return {Promise} Promise object * @example feed.follow('user', '1'); * @example feed.follow('user', '1'); @@ -124,9 +157,9 @@ export default class StreamFeed { targetUserId = targetUserId.id; } utils.validateFeedSlug(targetSlug); - utils.validateUserId(targetUserId); + utils.validateUserId(targetUserId as string); - const body = { target: `${targetSlug}:${targetUserId}` }; + const body: { target: string; activity_copy_limit?: number } = { target: `${targetSlug}:${targetUserId}` }; if (typeof options.limit === 'number') body.activity_copy_limit = options.limit; return this.client.post({ @@ -136,7 +169,7 @@ export default class StreamFeed { }); } - unfollow(targetSlug, targetUserId, options = {}) { + unfollow(targetSlug: string, targetUserId: string, options: { keepHistory?: boolean } = {}): Promise { /** * Unfollow the given feed * @method unfollow @@ -149,7 +182,7 @@ export default class StreamFeed { * @return {object} XHR request object * @example feed.unfollow('user', '2'); */ - const qs = {}; + const qs: { keep_history?: string } = {}; if (typeof options.keepHistory === 'boolean' && options.keepHistory) qs.keep_history = '1'; utils.validateFeedSlug(targetSlug); @@ -162,7 +195,7 @@ export default class StreamFeed { }); } - following(options = {}) { + following(options: GetFollowOptions = {}): Promise { /** * List which feeds this feed is following * @method following @@ -172,18 +205,17 @@ export default class StreamFeed { * @return {Promise} Promise object * @example feed.following({limit:10, filter: ['user:1', 'user:2']}); */ - if (options.filter) { - options.filter = options.filter.join(','); - } + const extraOptions: { filter?: string } = {}; + if (options.filter) extraOptions.filter = options.filter.join(','); - return this.client.get({ + return this.client.get({ url: `feed/${this.feedUrl}/following/`, - qs: options, + qs: { ...options, ...extraOptions }, signature: this.signature, }); } - followers(options = {}) { + followers(options: GetFollowOptions = {}): Promise { /** * List the followers of this feed * @method followers @@ -194,18 +226,19 @@ export default class StreamFeed { * @example * feed.followers({limit:10, filter: ['user:1', 'user:2']}); */ - if (options.filter) { - options.filter = options.filter.join(','); - } + const extraOptions: { filter?: string } = {}; + if (options.filter) extraOptions.filter = options.filter.join(','); - return this.client.get({ + return this.client.get({ url: `feed/${this.feedUrl}/followers/`, - qs: options, + qs: { ...options, ...extraOptions }, signature: this.signature, }); } - get(options = {}) { + get( + options: EnrichOptions & FeedOptions & { mark_read?: boolean | string[]; mark_seen?: boolean | string[] } = {}, + ): Promise { /** * Reads the feed * @method get @@ -216,26 +249,28 @@ export default class StreamFeed { * @example feed.get({limit: 10, mark_seen: true}) */ - if (options.mark_read && options.mark_read.join) { - options.mark_read = options.mark_read.join(','); + const extraOptions: { mark_read?: boolean | string; mark_seen?: boolean | string } = {}; + + if (options.mark_read && (options.mark_read as string[]).join) { + extraOptions.mark_read = (options.mark_read as string[]).join(','); } - if (options.mark_seen && options.mark_seen.join) { - options.mark_seen = options.mark_seen.join(','); + if (options.mark_seen && (options.mark_seen as string[]).join) { + extraOptions.mark_seen = (options.mark_seen as string[]).join(','); } this.client.replaceReactionOptions(options); const path = this.client.shouldUseEnrichEndpoint(options) ? 'enrich/feed/' : 'feed/'; - return this.client.get({ + return this.client.get({ url: `${path}${this.feedUrl}/`, - qs: options, + qs: { ...options, ...extraOptions }, signature: this.signature, }); } - getActivityDetail(activityId, options) { + getActivityDetail(activityId: string, options: EnrichOptions): Promise { /** * Retrieves one activity from a feed and adds enrichment * @method getActivityDetail @@ -251,7 +286,7 @@ export default class StreamFeed { return this.get({ id_lte: activityId, id_gte: activityId, limit: 1, ...(options || {}) }); } - getFayeClient() { + getFayeClient(): Faye.Client { /** * Returns the current faye client object * @method getFayeClient @@ -262,7 +297,7 @@ export default class StreamFeed { return this.client.getFayeClient(); } - subscribe(callback) { + subscribe(callback: Faye.Callback): Faye.Subscription { /** * Subscribes to any changes in the feed, return a promise * @method subscribe @@ -290,7 +325,7 @@ export default class StreamFeed { return subscription; } - unsubscribe() { + unsubscribe(): void { /** * Cancel updates created via feed.subscribe() * @return void @@ -302,7 +337,13 @@ export default class StreamFeed { } } - updateActivityToTargets(foreignId, time, newTargets, addedTargets, removedTargets) { + updateActivityToTargets( + foreignId: string, + time: string, + newTargets?: string[], + addedTargets?: string[], + removedTargets?: string[], + ): Promise { /** * Updates an activity's "to" fields * @since 3.10.0 @@ -313,11 +354,8 @@ export default class StreamFeed { * @param {array} removedTargets Remove these targets from the activity */ - if (!foreignId) { - throw new Error('Missing `foreign_id` parameter!'); - } else if (!time) { - throw new Error('Missing `time` parameter!'); - } + if (!foreignId) throw new Error('Missing `foreign_id` parameter!'); + if (!time) throw new Error('Missing `time` parameter!'); if (!newTargets && !addedTargets && !removedTargets) { throw new Error( @@ -340,12 +378,18 @@ export default class StreamFeed { }); } - const body = { foreign_id: foreignId, time }; + const body: { + foreign_id: string; + time: string; + new_targets?: string[]; + added_targets?: string[]; + removed_targets?: string[]; + } = { foreign_id: foreignId, time }; if (newTargets) body.new_targets = newTargets; if (addedTargets) body.added_targets = addedTargets; if (removedTargets) body.removed_targets = removedTargets; - return this.client.post({ + return this.client.post({ url: `feed_targets/${this.feedUrl}/activity_to_targets/`, signature: this.signature, body, diff --git a/src/lib/files.ts b/src/lib/files.ts index cd5d5025..f8d41d46 100644 --- a/src/lib/files.ts +++ b/src/lib/files.ts @@ -1,12 +1,22 @@ +import StreamClient, { APIResponse, FileUploadAPIResponse, OnUploadProgress } from './client'; + export default class StreamFileStore { - constructor(client, token) { + client: StreamClient; + token: string; + + constructor(client: StreamClient, token: string) { this.client = client; this.token = token; } // React Native does not auto-detect MIME type, you need to pass that via contentType // param. If you don't then Android will refuse to perform the upload - upload(uri, name, contentType, onUploadProgress) { + upload( + uri: string | File | NodeJS.ReadStream, + name?: string, + contentType?: string, + onUploadProgress?: OnUploadProgress, + ): Promise { /** * upload a File instance or a readable stream of data * @param {File|Buffer|string} uri - File object or Buffer or URI @@ -18,8 +28,8 @@ export default class StreamFileStore { return this.client.upload('files/', uri, name, contentType, onUploadProgress); } - delete(uri) { - return this.client.delete({ + delete(uri: string): Promise { + return this.client.delete({ url: `files/`, qs: { url: uri }, signature: this.token, diff --git a/src/lib/images.ts b/src/lib/images.ts index 75f93311..853ef9c7 100644 --- a/src/lib/images.ts +++ b/src/lib/images.ts @@ -1,12 +1,30 @@ +import StreamClient, { APIResponse, FileUploadAPIResponse, OnUploadProgress } from './client'; + +export type ImageProcessOptions = { + w?: number | string; + h?: number | string; + resize?: string | 'clip' | 'crop' | 'scale' | 'fill'; + crop?: string | 'top' | 'bottom' | 'left' | 'right' | 'center'; +}; + export default class StreamImageStore { - constructor(client, token) { + client: StreamClient; + + token: string; + + constructor(client: StreamClient, token: string) { this.client = client; this.token = token; } // React Native does not auto-detect MIME type, you need to pass that via contentType // param. If you don't then Android will refuse to perform the upload - upload(uri, name, contentType, onUploadProgress) { + upload( + uri: string | File | NodeJS.ReadStream, + name?: string, + contentType?: string, + onUploadProgress?: OnUploadProgress, + ): Promise { /** * upload an Image File instance or a readable stream of data * @param {File|Buffer|string} uri - File object or Buffer or URI @@ -18,28 +36,33 @@ export default class StreamImageStore { return this.client.upload('images/', uri, name, contentType, onUploadProgress); } - delete(uri) { - return this.client.delete({ + delete(uri: string): Promise { + return this.client.delete({ url: `images/`, qs: { url: uri }, signature: this.token, }); } - process(uri, options) { + process(uri: string, options: ImageProcessOptions): Promise { const params = Object.assign(options, { url: uri }); if (Array.isArray(params.crop)) { params.crop = params.crop.join(','); } - return this.client.get({ + return this.client.get({ url: `images/`, qs: params, signature: this.token, }); } - thumbnail(uri, w, h, { crop, resize } = { crop: 'center', resize: 'clip' }) { + thumbnail( + uri: string, + w: number | string, + h: number | string, + { crop, resize } = { crop: 'center', resize: 'clip' }, + ): Promise { return this.process(uri, { w, h, crop, resize }); } } diff --git a/src/lib/personalization.ts b/src/lib/personalization.ts index c20562da..ece48911 100644 --- a/src/lib/personalization.ts +++ b/src/lib/personalization.ts @@ -1,3 +1,5 @@ +import StreamClient, { APIResponse } from './client'; + /** * Manage api calls for personalization * The collection object contains convenience functions such as get, post, delete @@ -5,7 +7,9 @@ */ export default class Personalization { - constructor(client) { + client: StreamClient; + + constructor(client: StreamClient) { /** * Initialize the Personalization class * @@ -16,18 +20,18 @@ export default class Personalization { this.client = client; } - get(resource, options = {}) { + get(resource: string, options: { token?: string } & { [key: string]: string } = {}): Promise { /** * Get personalized activities for this feed * * @method get * @memberof Personalization.prototype - * @param {object} resource - personalized resource endpoint i.e "follow_recommendations" + * @param {string} resource - personalized resource endpoint i.e "follow_recommendations" * @param {object} options Additional options * @return {Promise} Promise object. Personalized feed * @example client.personalization.get('follow_recommendations', {foo: 'bar', baz: 'qux'}) */ - return this.client.get({ + return this.client.get({ url: `${resource}/`, serviceName: 'personalization', qs: options, @@ -35,19 +39,23 @@ export default class Personalization { }); } - post(resource, options = {}, data = {}) { + post( + resource: string, + options: { [key: string]: string } = {}, + data: { [key: string]: unknown } = {}, + ): Promise { /** * Post data to personalization endpoint * * @method post * @memberof Personalization.prototype - * @param {object} resource - personalized resource endpoint i.e "follow_recommendations" + * @param {string} resource - personalized resource endpoint i.e "follow_recommendations" * @param {object} options - Additional options * @param {object} data - Data to send in the payload * @return {Promise} Promise object. Data that was posted if successful, or an error. * @example client.personalization.post('follow_recommendations', {foo: 'bar', baz: 'qux'}) */ - return this.client.post({ + return this.client.post({ url: `${resource}/`, serviceName: 'personalization', qs: options, @@ -56,7 +64,7 @@ export default class Personalization { }); } - delete(resource, options = {}) { + delete(resource: string, options: { [key: string]: string } = {}): Promise { /** * Delete metadata or activities * @@ -67,7 +75,7 @@ export default class Personalization { * @return {Promise} Promise object. Data that was deleted if successful, or an error. * @example client.personalization.delete('follow_recommendations', {foo: 'bar', baz: 'qux'}) */ - return this.client.delete({ + return this.client.delete({ url: `${resource}/`, serviceName: 'personalization', qs: options, diff --git a/src/lib/reaction.ts b/src/lib/reaction.ts index bf98ed4d..ac5f1c71 100644 --- a/src/lib/reaction.ts +++ b/src/lib/reaction.ts @@ -1,7 +1,66 @@ +import StreamClient, { APIResponse } from './client'; +import StreamFeed from './feed'; import errors from './errors'; +type Activity> = T & { + id: string; +}; + +type Reaction> = T & { + id: string; +}; + +type TargetFeeds = (string | StreamFeed)[]; + +type TargetFeed = string | StreamFeed; + +type TargetFeedsExtraData = { + [key: string]: unknown; +}; + +type ReactionBody = { + id?: string; + activity_id?: string | { id: string }; + parent?: string | { id: string }; + kind?: string; + data?: T | Record; + target_feeds?: TargetFeeds; + user_id?: string; + target_feeds_extra_data?: TargetFeedsExtraData; +}; + +type ReactionAPIResponse = APIResponse & { + id: string; + kind: string; + activity_id: string; + user_id: string; + data: T; + created_at: Date; + updated_at: Date; + user?: unknown; + latest_children?: { + [key: string]: unknown; + }; + children_counts?: { + [key: string]: number; + }; +}; + +type ChildReactionAPIResponse = ReactionAPIResponse & { + parent: string; +}; + +type ReactionFilterAPIResponse = APIResponse & { + results: ReactionAPIResponse[] | ChildReactionAPIResponse[]; + activity: A; + next: string; +}; + export default class StreamReaction { - constructor(client, token) { + client: StreamClient; + token: string; + + constructor(client: StreamClient, token: string) { /** * Initialize a reaction object * @method constructor @@ -12,14 +71,13 @@ export default class StreamReaction { */ this.client = client; this.token = token; - this.signature = token; } - buildURL = (...args) => { + buildURL = (...args: string[]): string => { return `${['reaction', ...args].join('/')}/`; }; - all(options = {}) { + all(options = {}): Promise { /** * get all reactions * @method all @@ -31,16 +89,26 @@ export default class StreamReaction { */ return this.client.get({ url: this.buildURL(), - signature: this.signature, + signature: this.token, qs: options, }); } - _convertTargetFeeds = (targetFeeds = []) => { - return targetFeeds.map((elem) => (typeof elem === 'string' ? elem : elem.id)); + _convertTargetFeeds = (targetFeeds: TargetFeeds = []): string[] => { + return targetFeeds.map((elem: TargetFeed) => (typeof elem === 'string' ? elem : (elem as StreamFeed).id)); }; - add(kind, activity, data = {}, { id, targetFeeds = [], userId, targetFeedsExtraData } = {}) { + add( + kind: string, + activity: string | Activity, + data: T, + { + id, + targetFeeds = [], + userId, + targetFeedsExtraData, + }: { id?: string; targetFeeds?: TargetFeeds; userId?: string; targetFeedsExtraData?: TargetFeedsExtraData } = {}, + ): Promise> { /** * add reaction * @method add @@ -53,25 +121,38 @@ export default class StreamReaction { * @example reactions.add("like", "0c7db91c-67f9-11e8-bcd9-fe00a9219401") * @example reactions.add("comment", "0c7db91c-67f9-11e8-bcd9-fe00a9219401", {"text": "love it!"},) */ - const body = { + const body: ReactionBody = { id, - activity_id: activity instanceof Object ? activity.id : activity, + activity_id: activity instanceof Object ? (activity as Activity).id : activity, kind, - data, + data: data || {}, target_feeds: this._convertTargetFeeds(targetFeeds), user_id: userId, }; if (targetFeedsExtraData != null) { body.target_feeds_extra_data = targetFeedsExtraData; } - return this.client.post({ + return this.client.post>({ url: this.buildURL(), body, - signature: this.signature, + signature: this.token, }); } - addChild(kind, reaction, data = {}, { targetFeeds = [], userId, targetFeedsExtraData } = {}) { + addChild( + kind: string, + reaction: string | Reaction, + data = {}, + { + targetFeeds = [], + userId, + targetFeedsExtraData, + }: { + targetFeeds?: TargetFeeds; + userId?: string; + targetFeedsExtraData?: TargetFeedsExtraData; + } = {}, + ): Promise> { /** * add reaction * @method add @@ -84,8 +165,8 @@ export default class StreamReaction { * @example reactions.add("like", "0c7db91c-67f9-11e8-bcd9-fe00a9219401") * @example reactions.add("comment", "0c7db91c-67f9-11e8-bcd9-fe00a9219401", {"text": "love it!"},) */ - const body = { - parent: reaction instanceof Object ? reaction.id : reaction, + const body: ReactionBody = { + parent: reaction instanceof Object ? (reaction as Reaction).id : reaction, kind, data, target_feeds: this._convertTargetFeeds(targetFeeds), @@ -94,14 +175,14 @@ export default class StreamReaction { if (targetFeedsExtraData != null) { body.target_feeds_extra_data = targetFeedsExtraData; } - return this.client.post({ + return this.client.post>({ url: this.buildURL(), body, - signature: this.signature, + signature: this.token, }); } - get(id) { + get(id: string): Promise | ChildReactionAPIResponse> { /** * get reaction * @method add @@ -110,13 +191,24 @@ export default class StreamReaction { * @return {Promise} Promise object * @example reactions.get("67b3e3b5-b201-4697-96ac-482eb14f88ec") */ - return this.client.get({ + return this.client.get | ChildReactionAPIResponse>({ url: this.buildURL(id), - signature: this.signature, + signature: this.token, }); } - filter(conditions) { + filter(conditions: { + kind?: string; + user_id?: string; + activity_id?: string; + reaction_id?: string; + id_lt?: string; + id_lte?: string; + id_gt?: string; + id_gte?: string; + limit?: number; + with_activity_data?: boolean; + }): Promise> { /** * retrieve reactions by activity_id, user_id or reaction_id (to paginate children reactions), pagination can be done using id_lt, id_lte, id_gt and id_gte parameters * id_lt and id_lte return reactions order by creation descending starting from the reaction with the ID provided, when id_lte is used @@ -124,12 +216,12 @@ export default class StreamReaction { * id_gt and id_gte return reactions order by creation ascending (oldest to newest) starting from the reaction with the ID provided, when id_gte is used * the reaction with ID equal to the value provided is included. * results are limited to 25 at most and are ordered newest to oldest by default. - * @method lookup + * @method filter * @memberof StreamReaction.prototype - * @param {object} conditions Reaction Id {activity_id|user_id|foreign_id:string, kind:string, next:string, previous:string, limit:integer} + * @param {object} conditions Reaction Id {activity_id|user_id|reaction_id:string, kind:string, limit:integer} * @return {Promise} Promise object - * @example reactions.lookup({activity_id: "0c7db91c-67f9-11e8-bcd9-fe00a9219401", kind:"like"}) - * @example reactions.lookup({user_id: "john", kinds:"like"}) + * @example reactions.filter({activity_id: "0c7db91c-67f9-11e8-bcd9-fe00a9219401", kind:"like"}) + * @example reactions.filter({user_id: "john", kinds:"like"}) */ const { user_id: userId, activity_id: activityId, reaction_id: reactionId, ...qs } = conditions; @@ -146,16 +238,25 @@ export default class StreamReaction { const lookupType = (userId && 'user_id') || (activityId && 'activity_id') || (reactionId && 'reaction_id'); const value = userId || activityId || reactionId; - const url = conditions.kind ? this.buildURL(lookupType, value, conditions.kind) : this.buildURL(lookupType, value); + const url = conditions.kind + ? this.buildURL(lookupType as string, value as string, conditions.kind) + : this.buildURL(lookupType as string, value as string); - return this.client.get({ + return this.client.get>({ url, - qs, - signature: this.signature, + qs: qs as { [key: string]: unknown }, + signature: this.token, }); } - update(id, data, { targetFeeds = [], targetFeedsExtraData } = {}) { + update( + id: string, + data: T, + { + targetFeeds = [], + targetFeedsExtraData, + }: { targetFeeds?: string[] | StreamFeed[]; targetFeedsExtraData?: TargetFeedsExtraData } = {}, + ): Promise | ChildReactionAPIResponse> { /** * update reaction * @method add @@ -167,21 +268,21 @@ export default class StreamReaction { * @example reactions.update("67b3e3b5-b201-4697-96ac-482eb14f88ec", "0c7db91c-67f9-11e8-bcd9-fe00a9219401", "like") * @example reactions.update("67b3e3b5-b201-4697-96ac-482eb14f88ec", "0c7db91c-67f9-11e8-bcd9-fe00a9219401", "comment", {"text": "love it!"},) */ - const body = { + const body: ReactionBody = { data, target_feeds: this._convertTargetFeeds(targetFeeds), }; if (targetFeedsExtraData != null) { body.target_feeds_extra_data = targetFeedsExtraData; } - return this.client.put({ + return this.client.put | ChildReactionAPIResponse>({ url: this.buildURL(id), body, - signature: this.signature, + signature: this.token, }); } - delete(id) { + delete(id: string): Promise { /** * delete reaction * @method delete @@ -190,9 +291,9 @@ export default class StreamReaction { * @return {Promise} Promise object * @example reactions.delete("67b3e3b5-b201-4697-96ac-482eb14f88ec") */ - return this.client.delete({ + return this.client.delete({ url: this.buildURL(id), - signature: this.signature, + signature: this.token, }); } } diff --git a/src/lib/redirect_url.ts b/src/lib/redirect_url.ts index 772230f2..dc87387a 100644 --- a/src/lib/redirect_url.ts +++ b/src/lib/redirect_url.ts @@ -1,11 +1,18 @@ import Url from 'url'; import qs from 'qs'; +import StreamClient from './client'; import errors from './errors'; import utils from './utils'; import signing from './signing'; -export default function createRedirectUrl(targetUrl, userId, events) { +// TODO: userId is skipped here +export default function createRedirectUrl( + this: StreamClient, + targetUrl: string, + userId: string, + events: unknown[], +): string { /** * Creates a redirect url for tracking the given events in the context of * an email using Stream's analytics platform. Learn more at @@ -19,11 +26,11 @@ export default function createRedirectUrl(targetUrl, userId, events) { */ const uri = Url.parse(targetUrl); - if (!(uri.host || (uri.hostname && uri.port)) && !uri.isUnix) { + if (!(uri.host || (uri.hostname && uri.port))) { throw new errors.MissingSchemaError(`Invalid URI: "${Url.format(uri)}"`); } - const authToken = signing.JWTScopeToken(this.apiSecret, 'redirect_and_track', '*', { + const authToken = signing.JWTScopeToken(this.apiSecret as string, 'redirect_and_track', '*', { userId: '*', expireTokens: this.expireTokens, }); @@ -36,7 +43,7 @@ export default function createRedirectUrl(targetUrl, userId, events) { events: JSON.stringify(events), }; - const qString = utils.rfc3986(qs.stringify(kwargs, null, null, {})); + const qString = utils.rfc3986(qs.stringify(kwargs)); return `${analyticsUrl}?${qString}`; } diff --git a/src/lib/signing.ts b/src/lib/signing.ts index 87314357..ac2e86fe 100644 --- a/src/lib/signing.ts +++ b/src/lib/signing.ts @@ -1,18 +1,18 @@ -import jwt from 'jsonwebtoken'; +import * as jwt from 'jsonwebtoken'; import Base64 from 'Base64'; const JWS_REGEX = /^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/; -function safeJsonParse(thing) { +function safeJsonParse(thing: unknown): unknown { if (typeof thing === 'object') return thing; try { - return JSON.parse(thing); + return JSON.parse(thing as string); } catch (e) { return undefined; } } -function padString(string) { +function padString(string: string): string { const segmentLength = 4; const diff = string.length % segmentLength; if (!diff) return string; @@ -23,13 +23,13 @@ function padString(string) { return string; } -function toBase64(base64UrlString) { +function toBase64(base64UrlString: string): string { return padString(base64UrlString) .replace(/\-/g, '+') // eslint-disable-line no-useless-escape .replace(/_/g, '/'); } -function decodeBase64Url(base64UrlString) { +function decodeBase64Url(base64UrlString: string) { try { return Base64.atob(toBase64(base64UrlString)); } catch (e) { @@ -40,12 +40,17 @@ function decodeBase64Url(base64UrlString) { } } -function headerFromJWS(jwsSig) { +function headerFromJWS(jwsSig: string): unknown { const encodedHeader = jwsSig.split('.', 1)[0]; return safeJsonParse(decodeBase64Url(encodedHeader)); } -function JWTScopeToken(apiSecret, resource, action, opts) { +function JWTScopeToken( + apiSecret: string, + resource: string, + action: string, + options: { feedId?: string; userId?: string; expireTokens?: boolean } = {}, +) { /** * Creates the JWT token for feedId, resource and action using the apiSecret * @method JWTScopeToken @@ -59,25 +64,20 @@ function JWTScopeToken(apiSecret, resource, action, opts) { * @param {string} [options.userId] - JWT payload user identifier * @return {string} JWT Token */ - const options = opts || {}; const noTimestamp = options.expireTokens ? !options.expireTokens : true; - const payload = { resource, action }; + const payload: { resource: string; action: string; feed_id?: string; user_id?: string } = { resource, action }; + if (options.feedId) payload.feed_id = options.feedId; + if (options.userId) payload.user_id = options.userId; - if (options.feedId) { - payload.feed_id = options.feedId; - } - - if (options.userId) { - payload.user_id = options.userId; - } - - return jwt.sign(payload, apiSecret, { - algorithm: 'HS256', - noTimestamp, - }); + return jwt.sign(payload, apiSecret, { algorithm: 'HS256', noTimestamp }); } -function JWTUserSessionToken(apiSecret, userId, extraData = {}, jwtOptions = {}) { +function JWTUserSessionToken( + apiSecret: string, + userId: string, + extraData: { [key: string]: unknown } = {}, + jwtOptions: jwt.SignOptions = {}, +): string { /** * Creates the JWT token that can be used for a UserSession * @method JWTUserSessionToken @@ -85,7 +85,7 @@ function JWTUserSessionToken(apiSecret, userId, extraData = {}, jwtOptions = {}) * @private * @param {string} apiSecret - API Secret key * @param {string} userId - The user_id key in the JWT payload - * @param {string} [extraData] - Extra that should be part of the JWT token + * @param {object} [extraData] - Extra that should be part of the JWT token * @param {object} [jwtOptions] - Options that can be past to jwt.sign * @return {string} JWT Token */ @@ -95,11 +95,11 @@ function JWTUserSessionToken(apiSecret, userId, extraData = {}, jwtOptions = {}) const payload = { user_id: userId, ...extraData }; - const opts = { algorithm: 'HS256', noTimestamp: true, ...jwtOptions }; + const opts: jwt.SignOptions = { algorithm: 'HS256', noTimestamp: true, ...jwtOptions }; return jwt.sign(payload, apiSecret, opts); } -function isJWTSignature(signature) { +function isJWTSignature(signature: string | null): boolean { /** * check if token is a valid JWT token * @method isJWTSignature diff --git a/src/lib/user.ts b/src/lib/user.ts index 3cd7d212..01a99f0d 100644 --- a/src/lib/user.ts +++ b/src/lib/user.ts @@ -1,5 +1,23 @@ -export default class StreamUser { - constructor(client, userId, userAuthToken) { +import StreamClient, { APIResponse } from './client'; + +type UserAPIResponse = APIResponse & { + id: string; + data: T; + created_at: Date; + updated_at: Date; + followers_count?: number; + following_count?: number; +}; + +export default class StreamUser { + client: StreamClient; + token: string; + id: string; + data: undefined | T; + full: undefined | UserAPIResponse; + private url: string; + + constructor(client: StreamClient, userId: string, userAuthToken: string) { /** * Initialize a user session object * @method constructor @@ -17,19 +35,19 @@ export default class StreamUser { this.url = `user/${this.id}/`; } - ref() { + ref(): string { return `SU:${this.id}`; } - delete() { + delete(): Promise { return this.client.delete({ url: this.url, signature: this.token, }); } - async get(options) { - const response = await this.client.get({ + async get(options: { with_follow_counts?: boolean }): Promise> { + const response = await this.client.get>({ url: this.url, signature: this.token, qs: options, @@ -41,8 +59,8 @@ export default class StreamUser { return this; } - async create(data, options) { - const response = await this.client.post({ + async create(data: T, options: { get_or_create?: boolean }): Promise> { + const response = await this.client.post>({ url: 'user/', body: { id: this.id, @@ -58,8 +76,8 @@ export default class StreamUser { return this; } - async update(data) { - const response = await this.client.put({ + async update(data?: { [key: string]: unknown }): Promise> { + const response = await this.client.put>({ url: this.url, body: { data: data || this.data || {}, @@ -73,11 +91,11 @@ export default class StreamUser { return this; } - getOrCreate(data) { + getOrCreate(data: T): Promise> { return this.create(data, { get_or_create: true }); } - profile() { + profile(): Promise> { return this.get({ with_follow_counts: true }); } } diff --git a/src/lib/utils.ts b/src/lib/utils.ts index af4059d9..356a4a30 100644 --- a/src/lib/utils.ts +++ b/src/lib/utils.ts @@ -5,7 +5,7 @@ import errors from './errors'; const validFeedSlugRe = /^[\w]+$/; const validUserIdRe = /^[\w-]+$/; -function validateFeedSlug(feedSlug) { +function validateFeedSlug(feedSlug: string): string { /* * Validate that the feedSlug matches \w */ @@ -16,7 +16,7 @@ function validateFeedSlug(feedSlug) { return feedSlug; } -function validateUserId(userId) { +function validateUserId(userId: string): string { /* * Validate the userId matches \w */ @@ -27,15 +27,15 @@ function validateUserId(userId) { return userId; } -function rfc3986(str) { +function rfc3986(str: string): string { return str.replace(/[!'()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`); } -function isReadableStream(obj) { - return obj && typeof obj === 'object' && typeof obj._read === 'function' && typeof obj._readableState === 'object'; +function isReadableStream(obj: NodeJS.ReadStream): obj is NodeJS.ReadStream { + return obj !== null && typeof obj === 'object' && typeof (obj as NodeJS.ReadStream)._read === 'function'; } -function validateFeedId(feedId) { +function validateFeedId(feedId: string): string { /* * Validate that the feedId matches the spec user:1 */ @@ -50,14 +50,17 @@ function validateFeedId(feedId) { return feedId; } -function addFileToFormData(uri, name, contentType) { +function addFileToFormData(uri: string | File | NodeJS.ReadStream, name?: string, contentType?: string): FormData { const data = new FormData(); - let fileField; - if (isReadableStream(uri) || (uri && uri.toString && uri.toString() === '[object File]')) { - fileField = uri; + let fileField: File | NodeJS.ReadStream | { uri: string; name: string; type?: string }; + + if (isReadableStream(uri as NodeJS.ReadStream)) { + fileField = uri as NodeJS.ReadStream; + } else if (uri && uri.toString && uri.toString() === '[object File]') { + fileField = uri as File; } else { - fileField = { uri, name: name || uri.split('/').reverse()[0] }; + fileField = { uri: uri as string, name: name || (uri as string).split('/').reverse()[0] }; if (contentType != null) fileField.type = contentType; } @@ -65,15 +68,28 @@ function addFileToFormData(uri, name, contentType) { return data; } -function replaceStreamObjects(obj) { +function replaceStreamObjects(obj: T): V { + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore if (Array.isArray(obj)) return obj.map((v) => replaceStreamObjects(v)); + + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore if (Object.prototype.toString.call(obj) !== '[object Object]') return obj; + + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore if (typeof obj.ref === 'function') return obj.ref(); const cloned = {}; Object.keys(obj).forEach((k) => { + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore cloned[k] = replaceStreamObjects(obj[k]); }); + + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore return cloned; } From acda0fdf517130151e283a19b61813d9062eebd7 Mon Sep 17 00:00:00 2001 From: Amin Mahboubi Date: Tue, 21 Jul 2020 12:38:34 +0200 Subject: [PATCH 12/69] tests/fix client unit test missing param --- test/unit/common/client_test.js | 1 - 1 file changed, 1 deletion(-) diff --git a/test/unit/common/client_test.js b/test/unit/common/client_test.js index 5e140455..6f01846f 100644 --- a/test/unit/common/client_test.js +++ b/test/unit/common/client_test.js @@ -352,7 +352,6 @@ describe('[UNIT] Stream Client (Common)', function () { axiosOptions: { timeout: 0, maxContentLength: Infinity, - maxBodyLength: Infinity, onUploadProgress, }, }), From 42fdf114df2973f873a5698441a9eda07de4c8db Mon Sep 17 00:00:00 2001 From: Amin Mahboubi Date: Tue, 21 Jul 2020 12:40:05 +0200 Subject: [PATCH 13/69] run CI on push --- .github/workflows/ci.yml | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 329545ea..eacca9be 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,9 +1,6 @@ name: build -on: - push: - branches: - - 'master' - pull_request: + +on: [push] jobs: build: From 4ff71ca9bbd4f878144f77409f1be780b874fffb Mon Sep 17 00:00:00 2001 From: Amin Mahboubi Date: Tue, 21 Jul 2020 13:14:20 +0200 Subject: [PATCH 14/69] remove allowJs from tsconfig --- tsconfig.json | 1 - 1 file changed, 1 deletion(-) diff --git a/tsconfig.json b/tsconfig.json index e9627289..cd52724f 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -2,7 +2,6 @@ "compilerOptions": { "baseUrl": "src", "outDir": "types", - "allowJs": true, "allowSyntheticDefaultImports": true, "esModuleInterop": true, "resolveJsonModule": true, From 16ee252c86fd4841c6d1962919bb29fea4e9dfc4 Mon Sep 17 00:00:00 2001 From: Amin Mahboubi Date: Tue, 21 Jul 2020 17:09:35 +0200 Subject: [PATCH 15/69] fix errros default export --- src/lib/errors.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/lib/errors.ts b/src/lib/errors.ts index f3b40692..ffddcc98 100644 --- a/src/lib/errors.ts +++ b/src/lib/errors.ts @@ -35,7 +35,7 @@ class ErrorAbstract extends Error { * @memberof Stream.errors * @param {String} [msg] - An error message that will probably end up in a log. */ -class FeedError extends ErrorAbstract {} +export class FeedError extends ErrorAbstract {} /** * SiteError @@ -45,7 +45,7 @@ class FeedError extends ErrorAbstract {} * @memberof Stream.errors * @param {string} [msg] An error message that will probably end up in a log. */ -class SiteError extends ErrorAbstract {} +export class SiteError extends ErrorAbstract {} /** * MissingSchemaError @@ -55,7 +55,7 @@ class SiteError extends ErrorAbstract {} * @memberof Stream.errors * @param {string} msg */ -class MissingSchemaError extends ErrorAbstract {} +export class MissingSchemaError extends ErrorAbstract {} /** * StreamApiError @@ -67,7 +67,7 @@ class MissingSchemaError extends ErrorAbstract {} * @param {object} data * @param {object} response */ -class StreamApiError extends ErrorAbstract { +export class StreamApiError extends ErrorAbstract { error: unknown; response: axios.AxiosResponse; From 22d58a6f6af987b1b1b1b24eb75a162420f6d7df Mon Sep 17 00:00:00 2001 From: Amin Mahboubi Date: Tue, 21 Jul 2020 17:49:19 +0200 Subject: [PATCH 16/69] Merge branch 'master' into feature/typescript --- package.json | 2 +- yarn.lock | 15 +++++---------- 2 files changed, 6 insertions(+), 11 deletions(-) diff --git a/package.json b/package.json index 57b187af..7f86cf76 100644 --- a/package.json +++ b/package.json @@ -73,7 +73,7 @@ "babel-eslint": "^10.1.0", "babel-loader": "^8.1.0", "chai": "^4.2.0", - "codecov": "^3.7.0", + "codecov": "^3.7.1", "eslint": "^7.3.1", "eslint-config-airbnb-base": "^14.2.0", "eslint-config-prettier": "^6.11.0", diff --git a/yarn.lock b/yarn.lock index ca90199e..804f88a2 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2576,10 +2576,10 @@ clone-response@1.0.2, clone-response@^1.0.2: dependencies: mimic-response "^1.0.0" -codecov@^3.7.0: - version "3.7.0" - resolved "https://registry.yarnpkg.com/codecov/-/codecov-3.7.0.tgz#4a09939cde24447a43f36d068e8b4e0188dc3f27" - integrity sha512-uIixKofG099NbUDyzRk1HdGtaG8O+PBUAg3wfmjwXw2+ek+PZp+puRvbTohqrVfuudaezivJHFgTtSC3M8MXww== +codecov@^3.7.1: + version "3.7.1" + resolved "https://registry.yarnpkg.com/codecov/-/codecov-3.7.1.tgz#434cb8d55f18ef01672e5739d3d266696bebc202" + integrity sha512-JHWxyPTkMLLJn9SmKJnwAnvY09kg2Os2+Ux+GG7LwZ9g8gzDDISpIN5wAsH1UBaafA/yGcd3KofMaorE8qd6Lw== dependencies: argv "0.0.2" ignore-walk "3.0.3" @@ -5575,12 +5575,7 @@ lodash.zip@^4.2.0: resolved "https://registry.yarnpkg.com/lodash.zip/-/lodash.zip-4.2.0.tgz#ec6662e4896408ed4ab6c542a3990b72cc080020" integrity sha1-7GZi5IlkCO1KtsVCo5kLcswIACA= -lodash@^4.17.13, lodash@^4.17.14, lodash@^4.17.15: - version "4.17.19" - resolved "https://registry.yarnpkg.com/lodash/-/lodash-4.17.19.tgz#e48ddedbe30b3321783c5b4301fbd353bc1e4a4b" - integrity sha512-JNvd8XER9GQX0v2qJgsaN/mzFCNA5BRe/j8JN9d+tWyGLSodKQHKFicdwNYzWwI3wjRnaKPsGj1XkBjx/F96DQ== - -lodash@^4.17.19: +lodash@^4.17.13, lodash@^4.17.14, lodash@^4.17.15, lodash@^4.17.19: version "4.17.19" resolved "https://registry.yarnpkg.com/lodash/-/lodash-4.17.19.tgz#e48ddedbe30b3321783c5b4301fbd353bc1e4a4b" integrity sha512-JNvd8XER9GQX0v2qJgsaN/mzFCNA5BRe/j8JN9d+tWyGLSodKQHKFicdwNYzWwI3wjRnaKPsGj1XkBjx/F96DQ== From 91ee38296495f1605cb8fe846d20e3a1333c0cc4 Mon Sep 17 00:00:00 2001 From: Amin Mahboubi Date: Wed, 22 Jul 2020 12:05:45 +0200 Subject: [PATCH 17/69] disable eslint/ban-ts-comment --- .eslintrc.js | 1 + src/lib/utils.ts | 16 ++++++---------- 2 files changed, 7 insertions(+), 10 deletions(-) diff --git a/.eslintrc.js b/.eslintrc.js index f3fe0a10..0a286051 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -61,6 +61,7 @@ module.exports = { camelcase: 0, 'lines-between-class-members': 0, '@typescript-eslint/explicit-module-boundary-types': 0, + '@typescript-eslint/ban-ts-comment': 0, 'no-useless-constructor': 0, }, }, diff --git a/src/lib/utils.ts b/src/lib/utils.ts index 356a4a30..94f51760 100644 --- a/src/lib/utils.ts +++ b/src/lib/utils.ts @@ -68,28 +68,24 @@ function addFileToFormData(uri: string | File | NodeJS.ReadStream, name?: string return data; } +// TODO: refactor and add proper types function replaceStreamObjects(obj: T): V { - // eslint-disable-next-line @typescript-eslint/ban-ts-comment - // @ts-ignore + // @ts-expect-error if (Array.isArray(obj)) return obj.map((v) => replaceStreamObjects(v)); - // eslint-disable-next-line @typescript-eslint/ban-ts-comment - // @ts-ignore + // @ts-expect-error if (Object.prototype.toString.call(obj) !== '[object Object]') return obj; - // eslint-disable-next-line @typescript-eslint/ban-ts-comment - // @ts-ignore + // @ts-expect-error if (typeof obj.ref === 'function') return obj.ref(); const cloned = {}; Object.keys(obj).forEach((k) => { - // eslint-disable-next-line @typescript-eslint/ban-ts-comment - // @ts-ignore + // @ts-expect-error cloned[k] = replaceStreamObjects(obj[k]); }); - // eslint-disable-next-line @typescript-eslint/ban-ts-comment - // @ts-ignore + // @ts-expect-error return cloned; } From 11159d415ca833461372de1f5029358e67b63909 Mon Sep 17 00:00:00 2001 From: Amin Mahboubi Date: Wed, 22 Jul 2020 13:36:46 +0200 Subject: [PATCH 18/69] typescript/use global generics --- src/getstream.ts | 21 +++++++++-- src/lib/batch_operations.ts | 2 +- src/lib/client.ts | 72 ++++++++++++++++++++++--------------- src/lib/collections.ts | 69 ++++++++++++++++++----------------- src/lib/feed.ts | 26 ++++++++++---- src/lib/personalization.ts | 2 +- src/lib/reaction.ts | 68 ++++++++++++++++------------------- src/lib/user.ts | 28 +++++++-------- 8 files changed, 163 insertions(+), 125 deletions(-) diff --git a/src/getstream.ts b/src/getstream.ts index e5f24f3b..a95a2dc0 100644 --- a/src/getstream.ts +++ b/src/getstream.ts @@ -7,7 +7,19 @@ import StreamClient, { ClientOptions } from './lib/client'; import errors from './lib/errors'; import signing from './lib/signing'; -function connect(apiKey: string, apiSecret: string | null, appId?: string, options?: ClientOptions): StreamClient { +function connect< + UserType = unknown, + CollectionType = unknown, + ActivityType = unknown, + ReactionType = unknown, + ChildReactionType = unknown, + PersonalizationType = unknown +>( + apiKey: string, + apiSecret: string | null, + appId?: string, + options?: ClientOptions, +): StreamClient { /** * Create StreamClient * @method connect @@ -41,7 +53,12 @@ function connect(apiKey: string, apiSecret: string | null, appId?: string, optio } } - return new StreamClient(apiKey, apiSecret, appId, options); + return new StreamClient( + apiKey, + apiSecret, + appId, + options, + ); } export { connect, errors, signing, StreamClient as Client }; diff --git a/src/lib/batch_operations.ts b/src/lib/batch_operations.ts index 0f8465df..73d04885 100644 --- a/src/lib/batch_operations.ts +++ b/src/lib/batch_operations.ts @@ -1,7 +1,7 @@ import StreamClient, { APIResponse, FollowRelation } from './client'; import utils from './utils'; -function addToMany(this: StreamClient, activity: T, feeds: string[]): Promise { +function addToMany(this: StreamClient, activity: ActivityType, feeds: string[]): Promise { /** * Add one activity to many feeds * @method addToMany diff --git a/src/lib/client.ts b/src/lib/client.ts index ca438d56..d4baddd2 100644 --- a/src/lib/client.ts +++ b/src/lib/client.ts @@ -47,7 +47,7 @@ type BaseActivity = { to?: string[]; }; -export type Activity> = BaseActivity & T; +export type Activity> = BaseActivity & ActivityType; type GetActivitiesAPIResponse = APIResponse & { results: Activity[] }; @@ -136,7 +136,14 @@ type HandlerCallback = (...args: unknown[]) => unknown; * Client to connect to Stream api * @class StreamClient */ -class StreamClient { +class StreamClient< + UserType = unknown, + CollectionType = unknown, + ActivityType = unknown, + ReactionType = unknown, + ChildReactionType = unknown, + PersonalizationType = unknown +> { baseUrl: string; baseAnalyticsUrl: string; apiKey: string; @@ -168,18 +175,18 @@ class StreamClient { }; handlers: { [key: string]: HandlerCallback }; - currentUser: StreamUser | undefined; - personalization: Personalization; - collections: Collections; + currentUser: StreamUser | undefined; + personalization: Personalization; + collections: Collections; files: StreamFileStore; images: StreamImageStore; - reactions: StreamReaction; + reactions: StreamReaction; private _personalizationToken: string | undefined; private _collectionsToken: string | undefined; private _getOrCreateToken: string | undefined; - addToMany?: (this: StreamClient, activity: T, feeds: string[]) => Promise; + addToMany?: (this: StreamClient, activity: ActivityType, feeds: string[]) => Promise; followMany?: (this: StreamClient, follows: FollowRelation[], activityCopyLimit?: number) => Promise; unfollowMany?: (this: StreamClient, unfollows: FollowRelation[]) => Promise; createRedirectUrl?: (this: StreamClient, targetUrl: string, userId: string, events: unknown[]) => string; @@ -254,17 +261,17 @@ class StreamClient { ...(this.nodeOptions || {}), }); - this.personalization = new Personalization(this); + this.personalization = new Personalization(this); if (this.browser && this.usingApiSecret) { throw new errors.FeedError( 'You are publicly sharing your App Secret. Do not expose the App Secret in browsers, "native" mobile apps, or other non-trusted environments.', ); } - this.collections = new Collections(this, this.getOrCreateToken()); + this.collections = new Collections(this, this.getOrCreateToken()); this.files = new StreamFileStore(this, this.getOrCreateToken()); this.images = new StreamImageStore(this, this.getOrCreateToken()); - this.reactions = new StreamReaction(this, this.getOrCreateToken()); + this.reactions = new StreamReaction(this, this.getOrCreateToken()); // If we are in a node environment and batchOperations/createRedirectUrl is available add the methods to the prototype of StreamClient if (BatchOperations && createRedirectUrl) { @@ -431,7 +438,11 @@ class StreamClient { }); } - feed(feedSlug: string, userId?: string | StreamUser, token?: string): StreamFeed { + feed( + feedSlug: string, + userId?: string | StreamUser, + token?: string, + ): StreamFeed { /** * Returns a feed object for the given feed id and token * @method feed @@ -453,7 +464,12 @@ class StreamClient { } } - return new StreamFeed(this, feedSlug, userId || (this.userId as string), token); + return new StreamFeed( + this, + feedSlug, + userId || (this.userId as string), + token, + ); } enrichUrl(relativeUrl: string, serviceName?: string): string { @@ -694,7 +710,7 @@ class StreamClient { }); } - updateActivities(activities: Activity[]): Promise { + updateActivities(activities: Activity[]): Promise { /** * Updates all supplied activities on the getstream-io api * @since 3.1.0 @@ -719,7 +735,7 @@ class StreamClient { }); } - updateActivity(activity: Activity): Promise { + updateActivity(activity: Activity): Promise { /** * Updates one activity on the getstream-io api * @since 3.1.0 @@ -728,19 +744,18 @@ class StreamClient { */ this._throwMissingApiSecret(); - return this.updateActivities([activity]); + return this.updateActivities([activity]); } - getActivities({ + getActivities({ ids, foreignIDTimes, ...params }: EnrichOptions & { ids?: string[]; foreignIDTimes?: { foreignID: string; time: string | Date }[]; - reactions?: Record; - }): Promise> { + }): Promise> { /** * Retrieve activities by ID or foreign ID and time * @since 3.19.0 @@ -785,7 +800,7 @@ class StreamClient { this.replaceReactionOptions(params); const path = this.shouldUseEnrichEndpoint(params) ? 'enrich/activities/' : 'activities/'; - return this.get>({ + return this.get>({ url: path, qs: { ...params, ...extraParams }, signature: token, @@ -801,21 +816,20 @@ class StreamClient { return this._getOrCreateToken; } - user(userId: string): StreamUser { - return new StreamUser(this, userId, this.getOrCreateToken()); + user(userId: string): StreamUser { + return new StreamUser(this, userId, this.getOrCreateToken()); } - async setUser(data: U): Promise> { + async setUser(data: UserType): Promise> { if (this.usingApiSecret) { throw new errors.SiteError('This method can only be used client-side using a user token'); } const body = { ...data }; - // eslint-disable-next-line @typescript-eslint/ban-ts-comment - // @ts-ignore + // @ts-expect-error delete body?.id; - const user = await (this.currentUser as StreamUser).getOrCreate(body); + const user = await (this.currentUser as StreamUser).getOrCreate(body); this.currentUser = user; return user; } @@ -836,7 +850,7 @@ class StreamClient { }); } - async activityPartialUpdate(data: ActivityPartialChanges): Promise> { + async activityPartialUpdate(data: ActivityPartialChanges): Promise> { /** * Update a single activity with partial operations. * @since 3.20.0 @@ -869,13 +883,13 @@ class StreamClient { * ] * }) */ - const response = await this.activitiesPartialUpdate([data]); + const response = await this.activitiesPartialUpdate([data]); const activity = response.activities[0]; delete response.activities; return { ...activity, ...response }; } - activitiesPartialUpdate(changes: ActivityPartialChanges[]): Promise> { + activitiesPartialUpdate(changes: ActivityPartialChanges[]): Promise> { /** * Update multiple activities with partial operations. * @since v3.20.0 @@ -959,7 +973,7 @@ class StreamClient { }); } - return this.post>({ + return this.post>({ url: 'activity/', body: { changes, diff --git a/src/lib/collections.ts b/src/lib/collections.ts index fdab8fad..00ebf8d6 100644 --- a/src/lib/collections.ts +++ b/src/lib/collections.ts @@ -1,41 +1,41 @@ import StreamClient, { APIResponse } from './client'; import errors from './errors'; -type CollectionResponse = { +type CollectionResponse = { collection: string; id: string; - data: T; + data: CollectionType; foregin_id: string; created_at: Date; updated_at: Date; user_id?: string; }; -type CollectionAPIResponse = APIResponse & CollectionResponse; +type CollectionAPIResponse = APIResponse & CollectionResponse; -type SelectCollectionAPIResponse = APIResponse & { +type SelectCollectionAPIResponse = APIResponse & { response: { - data: CollectionResponse[]; + data: CollectionResponse[]; }; }; -type UpsertCollectionAPIResponse = APIResponse & { +type UpsertCollectionAPIResponse = APIResponse & { data: { [key: string]: { id: string; - data: T; + data: CollectionType; }[]; }; }; -class CollectionEntry { +class CollectionEntry { id: string; collection: string; - store: Collections; - data: T | null; + store: Collections; + data: CollectionType | null; full: unknown; - constructor(store: Collections, collection: string, id: string, data: T) { + constructor(store: Collections, collection: string, id: string, data: CollectionType) { this.collection = collection; this.store = store; this.id = id; @@ -46,7 +46,7 @@ class CollectionEntry { return `SO:${this.collection}:${this.id}`; } - async get(): Promise> { + async get(): Promise> { /** * get item from collection and sync data * @method get @@ -54,13 +54,13 @@ class CollectionEntry { * @return {Promise} Promise object * @example collection.get("0c7db91c-67f9-11e8-bcd9-fe00a9219401") */ - const response = await this.store.get(this.collection, this.id); + const response = await this.store.get(this.collection, this.id); this.data = response.data; this.full = response; return response; } - async add(): Promise> { + async add(): Promise> { /** * Add item to collection * @method add @@ -68,13 +68,13 @@ class CollectionEntry { * @return {Promise} Promise object * @example collection.add("cheese101", {"name": "cheese burger","toppings": "cheese"}) */ - const response = await this.store.add(this.collection, this.id, this.data as T); + const response = await this.store.add(this.collection, this.id, this.data as CollectionType); this.data = response.data; this.full = response; return response; } - async update(): Promise> { + async update(): Promise> { /** * Update item in the object storage * @method update @@ -83,7 +83,7 @@ class CollectionEntry { * @example store.update("0c7db91c-67f9-11e8-bcd9-fe00a9219401", {"name": "cheese burger","toppings": "cheese"}) * @example store.update("cheese101", {"name": "cheese burger","toppings": "cheese"}) */ - const response = await this.store.update(this.collection, this.id, this.data as T); + const response = await this.store.update(this.collection, this.id, this.data as CollectionType); this.data = response.data; this.full = response; return response; @@ -104,7 +104,7 @@ class CollectionEntry { } } -export default class Collections { +export default class Collections { client: StreamClient; token: string; @@ -125,11 +125,11 @@ export default class Collections { return itemId === undefined ? url : `${url}${itemId}/`; }; - entry(collection: string, itemId: string, itemData: T): CollectionEntry { - return new CollectionEntry(this, collection, itemId, itemData); + entry(collection: string, itemId: string, itemData: CollectionType): CollectionEntry { + return new CollectionEntry(this, collection, itemId, itemData); } - async get(collection: string, itemId: string): Promise> { + async get(collection: string, itemId: string): Promise> { /** * get item from collection * @method get @@ -139,17 +139,17 @@ export default class Collections { * @return {Promise} Promise object * @example collection.get("food", "0c7db91c-67f9-11e8-bcd9-fe00a9219401") */ - const response = await this.client.get>({ + const response = await this.client.get>({ url: this.buildURL(collection, itemId), signature: this.token, }); - const entry = this.client.collections.entry(response.collection, response.id, response.data); + const entry = this.entry(response.collection, response.id, response.data); entry.full = response; return entry; } - async add(collection: string, itemId: string, itemData: T): Promise> { + async add(collection: string, itemId: string, itemData: CollectionType): Promise> { /** * Add item to collection * @method add @@ -160,7 +160,7 @@ export default class Collections { * @return {Promise} Promise object * @example collection.add("food", "cheese101", {"name": "cheese burger","toppings": "cheese"}) */ - const response = await this.client.post>({ + const response = await this.client.post>({ url: this.buildURL(collection), body: { id: itemId === null ? undefined : itemId, @@ -169,12 +169,12 @@ export default class Collections { signature: this.token, }); - const entry = this.client.collections.entry(response.collection, response.id, response.data); + const entry = this.entry(response.collection, response.id, response.data); entry.full = response; return entry; } - async update(collection: string, entryId: string, data: T): Promise> { + async update(collection: string, entryId: string, data: CollectionType): Promise> { /** * Update entry in the collection * @method update @@ -186,13 +186,13 @@ export default class Collections { * @example store.update("0c7db91c-67f9-11e8-bcd9-fe00a9219401", {"name": "cheese burger","toppings": "cheese"}) * @example store.update("food", "cheese101", {"name": "cheese burger","toppings": "cheese"}) */ - const response = await this.client.put>({ + const response = await this.client.put>({ url: this.buildURL(collection, entryId), body: { data }, signature: this.token, }); - const entry = this.client.collections.entry(response.collection, response.id, response.data); + const entry = this.entry(response.collection, response.id, response.data); entry.full = response; return entry; } @@ -212,7 +212,10 @@ export default class Collections { }); } - upsert(collection: string, data: T | T[]): Promise> { + upsert( + collection: string, + data: CollectionType | CollectionType[], + ): Promise> { /** * Upsert one or more items within a collection. * @@ -227,7 +230,7 @@ export default class Collections { if (!Array.isArray(data)) data = [data]; - return this.client.post>({ + return this.client.post>({ url: 'collections/', serviceName: 'api', body: { data: { [collection]: data } }, @@ -235,7 +238,7 @@ export default class Collections { }); } - select(collection: string, ids: string | string[]): Promise> { + select(collection: string, ids: string | string[]): Promise> { /** * Select all objects with ids from the collection. * @@ -250,7 +253,7 @@ export default class Collections { if (!Array.isArray(ids)) ids = [ids]; - return this.client.get>({ + return this.client.get>({ url: 'collections/', serviceName: 'api', qs: { foreign_ids: ids.map((id) => `${collection}:${id}`).join(',') }, diff --git a/src/lib/feed.ts b/src/lib/feed.ts index 10ccc067..59b285a0 100644 --- a/src/lib/feed.ts +++ b/src/lib/feed.ts @@ -20,12 +20,27 @@ type GetFollowOptions = { filter?: string[]; }; +type NewActivity = { + actor: string; + verb: string; + object: string | unknown; + to?: string[]; + target?: string; + time?: string; + foreign_id?: string; +}; + /** * Manage api calls for specific feeds * The feed object contains convenience functions such add activity, remove activity etc * @class StreamFeed */ -export default class StreamFeed { +export default class StreamFeed< + ActivityType = unknown, + UserType = unknown, + ReactionType = unknown, + ChildReactionType = unknown +> { client: StreamClient; token: string; id: string; @@ -35,7 +50,6 @@ export default class StreamFeed { feedTogether: string; signature: string; notificationChannel: string; - enrichByDefault: boolean; constructor(client: StreamClient, feedSlug: string, userId: string, token: string) { /** @@ -76,11 +90,9 @@ export default class StreamFeed { // faye setup this.notificationChannel = `site-${this.client.appId}-feed-${this.feedTogether}`; - - this.enrichByDefault = false; } - addActivity(activity: T): Promise> { + addActivity(activity: NewActivity & ActivityType): Promise> { /** * Adds the given activity to the feed * @method addActivity @@ -94,7 +106,7 @@ export default class StreamFeed { activity.actor = this.client.currentUser.ref(); } - return this.client.post>({ + return this.client.post>({ url: `feed/${this.feedUrl}/`, body: activity, signature: this.signature, @@ -120,7 +132,7 @@ export default class StreamFeed { }); } - addActivities(activities: T[]): Promise { + addActivities(activities: (NewActivity & ActivityType)[]): Promise { /** * Adds the given activities to the feed * @method addActivities diff --git a/src/lib/personalization.ts b/src/lib/personalization.ts index ece48911..7535a210 100644 --- a/src/lib/personalization.ts +++ b/src/lib/personalization.ts @@ -6,7 +6,7 @@ import StreamClient, { APIResponse } from './client'; * @class Personalization */ -export default class Personalization { +export default class Personalization { client: StreamClient; constructor(client: StreamClient) { diff --git a/src/lib/reaction.ts b/src/lib/reaction.ts index ac5f1c71..05ed32d2 100644 --- a/src/lib/reaction.ts +++ b/src/lib/reaction.ts @@ -2,14 +2,6 @@ import StreamClient, { APIResponse } from './client'; import StreamFeed from './feed'; import errors from './errors'; -type Activity> = T & { - id: string; -}; - -type Reaction> = T & { - id: string; -}; - type TargetFeeds = (string | StreamFeed)[]; type TargetFeed = string | StreamFeed; @@ -29,12 +21,12 @@ type ReactionBody = { target_feeds_extra_data?: TargetFeedsExtraData; }; -type ReactionAPIResponse = APIResponse & { +type ReactionAPIResponse = APIResponse & { id: string; kind: string; activity_id: string; user_id: string; - data: T; + data: ReactionType; created_at: Date; updated_at: Date; user?: unknown; @@ -46,17 +38,17 @@ type ReactionAPIResponse = APIResponse & { }; }; -type ChildReactionAPIResponse = ReactionAPIResponse & { +type ChildReactionAPIResponse = ReactionAPIResponse & { parent: string; }; -type ReactionFilterAPIResponse = APIResponse & { - results: ReactionAPIResponse[] | ChildReactionAPIResponse[]; - activity: A; +type ReactionFilterAPIResponse = APIResponse & { + results: ReactionAPIResponse[] | ChildReactionAPIResponse[]; + activity: ActivityType; next: string; }; -export default class StreamReaction { +export default class StreamReaction { client: StreamClient; token: string; @@ -98,17 +90,17 @@ export default class StreamReaction { return targetFeeds.map((elem: TargetFeed) => (typeof elem === 'string' ? elem : (elem as StreamFeed).id)); }; - add( + add( kind: string, - activity: string | Activity, - data: T, + activity: string | { id: string }, + data: ReactionType, { id, targetFeeds = [], userId, targetFeedsExtraData, }: { id?: string; targetFeeds?: TargetFeeds; userId?: string; targetFeedsExtraData?: TargetFeedsExtraData } = {}, - ): Promise> { + ): Promise> { /** * add reaction * @method add @@ -121,9 +113,9 @@ export default class StreamReaction { * @example reactions.add("like", "0c7db91c-67f9-11e8-bcd9-fe00a9219401") * @example reactions.add("comment", "0c7db91c-67f9-11e8-bcd9-fe00a9219401", {"text": "love it!"},) */ - const body: ReactionBody = { + const body: ReactionBody = { id, - activity_id: activity instanceof Object ? (activity as Activity).id : activity, + activity_id: activity instanceof Object ? (activity as { id: string }).id : activity, kind, data: data || {}, target_feeds: this._convertTargetFeeds(targetFeeds), @@ -132,16 +124,16 @@ export default class StreamReaction { if (targetFeedsExtraData != null) { body.target_feeds_extra_data = targetFeedsExtraData; } - return this.client.post>({ + return this.client.post>({ url: this.buildURL(), body, signature: this.token, }); } - addChild( + addChild( kind: string, - reaction: string | Reaction, + reaction: string | { id: string }, data = {}, { targetFeeds = [], @@ -152,7 +144,7 @@ export default class StreamReaction { userId?: string; targetFeedsExtraData?: TargetFeedsExtraData; } = {}, - ): Promise> { + ): Promise> { /** * add reaction * @method add @@ -165,8 +157,8 @@ export default class StreamReaction { * @example reactions.add("like", "0c7db91c-67f9-11e8-bcd9-fe00a9219401") * @example reactions.add("comment", "0c7db91c-67f9-11e8-bcd9-fe00a9219401", {"text": "love it!"},) */ - const body: ReactionBody = { - parent: reaction instanceof Object ? (reaction as Reaction).id : reaction, + const body: ReactionBody = { + parent: reaction instanceof Object ? (reaction as { id: string }).id : reaction, kind, data, target_feeds: this._convertTargetFeeds(targetFeeds), @@ -175,14 +167,14 @@ export default class StreamReaction { if (targetFeedsExtraData != null) { body.target_feeds_extra_data = targetFeedsExtraData; } - return this.client.post>({ + return this.client.post>({ url: this.buildURL(), body, signature: this.token, }); } - get(id: string): Promise | ChildReactionAPIResponse> { + get(id: string): Promise | ChildReactionAPIResponse> { /** * get reaction * @method add @@ -191,13 +183,13 @@ export default class StreamReaction { * @return {Promise} Promise object * @example reactions.get("67b3e3b5-b201-4697-96ac-482eb14f88ec") */ - return this.client.get | ChildReactionAPIResponse>({ + return this.client.get | ChildReactionAPIResponse>({ url: this.buildURL(id), signature: this.token, }); } - filter(conditions: { + filter(conditions: { kind?: string; user_id?: string; activity_id?: string; @@ -208,7 +200,7 @@ export default class StreamReaction { id_gte?: string; limit?: number; with_activity_data?: boolean; - }): Promise> { + }): Promise> { /** * retrieve reactions by activity_id, user_id or reaction_id (to paginate children reactions), pagination can be done using id_lt, id_lte, id_gt and id_gte parameters * id_lt and id_lte return reactions order by creation descending starting from the reaction with the ID provided, when id_lte is used @@ -242,21 +234,21 @@ export default class StreamReaction { ? this.buildURL(lookupType as string, value as string, conditions.kind) : this.buildURL(lookupType as string, value as string); - return this.client.get>({ + return this.client.get>({ url, qs: qs as { [key: string]: unknown }, signature: this.token, }); } - update( + update( id: string, - data: T, + data: ReactionType | ChildReactionType, { targetFeeds = [], targetFeedsExtraData, }: { targetFeeds?: string[] | StreamFeed[]; targetFeedsExtraData?: TargetFeedsExtraData } = {}, - ): Promise | ChildReactionAPIResponse> { + ): Promise | ChildReactionAPIResponse> { /** * update reaction * @method add @@ -268,14 +260,14 @@ export default class StreamReaction { * @example reactions.update("67b3e3b5-b201-4697-96ac-482eb14f88ec", "0c7db91c-67f9-11e8-bcd9-fe00a9219401", "like") * @example reactions.update("67b3e3b5-b201-4697-96ac-482eb14f88ec", "0c7db91c-67f9-11e8-bcd9-fe00a9219401", "comment", {"text": "love it!"},) */ - const body: ReactionBody = { + const body: ReactionBody = { data, target_feeds: this._convertTargetFeeds(targetFeeds), }; if (targetFeedsExtraData != null) { body.target_feeds_extra_data = targetFeedsExtraData; } - return this.client.put | ChildReactionAPIResponse>({ + return this.client.put | ChildReactionAPIResponse>({ url: this.buildURL(id), body, signature: this.token, diff --git a/src/lib/user.ts b/src/lib/user.ts index 01a99f0d..8d116a85 100644 --- a/src/lib/user.ts +++ b/src/lib/user.ts @@ -1,20 +1,20 @@ import StreamClient, { APIResponse } from './client'; -type UserAPIResponse = APIResponse & { +type UserAPIResponse = APIResponse & { id: string; - data: T; + data: UserType; created_at: Date; updated_at: Date; followers_count?: number; following_count?: number; }; -export default class StreamUser { +export default class StreamUser { client: StreamClient; token: string; id: string; - data: undefined | T; - full: undefined | UserAPIResponse; + data: undefined | UserType; + full: undefined | UserAPIResponse; private url: string; constructor(client: StreamClient, userId: string, userAuthToken: string) { @@ -40,14 +40,14 @@ export default class StreamUser { } delete(): Promise { - return this.client.delete({ + return this.client.delete({ url: this.url, signature: this.token, }); } - async get(options: { with_follow_counts?: boolean }): Promise> { - const response = await this.client.get>({ + async get(options: { with_follow_counts?: boolean }): Promise> { + const response = await this.client.get>({ url: this.url, signature: this.token, qs: options, @@ -59,8 +59,8 @@ export default class StreamUser { return this; } - async create(data: T, options: { get_or_create?: boolean }): Promise> { - const response = await this.client.post>({ + async create(data: UserType, options: { get_or_create?: boolean }): Promise> { + const response = await this.client.post>({ url: 'user/', body: { id: this.id, @@ -76,8 +76,8 @@ export default class StreamUser { return this; } - async update(data?: { [key: string]: unknown }): Promise> { - const response = await this.client.put>({ + async update(data?: { [key: string]: unknown }): Promise> { + const response = await this.client.put>({ url: this.url, body: { data: data || this.data || {}, @@ -91,11 +91,11 @@ export default class StreamUser { return this; } - getOrCreate(data: T): Promise> { + getOrCreate(data: UserType): Promise> { return this.create(data, { get_or_create: true }); } - profile(): Promise> { + profile(): Promise> { return this.get({ with_follow_counts: true }); } } From d3481fa4534fe508aa6bfa63f07491d9e542d70e Mon Sep 17 00:00:00 2001 From: Amin Mahboubi Date: Wed, 22 Jul 2020 14:00:16 +0200 Subject: [PATCH 19/69] change webpack entry file to ts file --- webpack.config.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/webpack.config.js b/webpack.config.js index f658935f..3c69e88c 100644 --- a/webpack.config.js +++ b/webpack.config.js @@ -2,7 +2,7 @@ const path = require('path'); const UglifyJsPlugin = require('uglifyjs-webpack-plugin'); module.exports = (env, argv = []) => ({ - entry: ['./src/getstream.js'], + entry: ['./src/getstream.ts'], mode: 'production', From 892bdae3b398c8a4d065d7e2114c6ecf7c31597a Mon Sep 17 00:00:00 2001 From: Amin Mahboubi Date: Wed, 22 Jul 2020 16:35:16 +0200 Subject: [PATCH 20/69] fix types output file wrong base url --- package.json | 10 +++++----- src/lib/client.ts | 5 ++++- tsconfig.json | 11 +++++++---- 3 files changed, 16 insertions(+), 10 deletions(-) diff --git a/package.json b/package.json index 7f86cf76..925d064f 100644 --- a/package.json +++ b/package.json @@ -7,14 +7,15 @@ "description": "The official low-level GetStream.io client for Node.js and the browser.", "main": "./lib/getstream.js", "module": "./lib/getstream.js", - "types": "./types/index.d.ts", + "types": "./lib/index.d.ts", "homepage": "https://getstream.io/docs/?language=js", "email": "support@getstream.io", "license": "BSD-3-Clause", "version": "5.0.2", "scripts": { - "types": "tsc --outFile types/index --declaration true --declarationMap true --emitDeclarationOnly true", - "build": "babel src --out-dir lib --extensions '.js,.ts'", + "transpile": "rm -rf lib && babel src --out-dir lib --extensions '.js,.ts'", + "types": "tsc --outFile lib/index --declaration true --declarationMap true --emitDeclarationOnly true", + "build": "yarn transpile && yarn types", "eslint": "eslint '**/*.{js,ts}' --max-warnings 0", "prettier": "prettier --list-different '**/*.{js,ts}'", "lint": "yarn run prettier && yarn run eslint", @@ -119,8 +120,7 @@ }, "files": [ "dist", - "lib", - "types" + "lib" ], "engines": { "node": "10 || 12 || >=14" diff --git a/src/lib/client.ts b/src/lib/client.ts index d4baddd2..7d68ca6d 100644 --- a/src/lib/client.ts +++ b/src/lib/client.ts @@ -16,7 +16,10 @@ import createRedirectUrl from './redirect_url'; import signing from './signing'; import errors from './errors'; import utils from './utils'; -import pkg from '../../package.json'; + +// no import since typescript json loader shifts the final output structure +// eslint-disable-next-line @typescript-eslint/no-var-requires +const pkg = require('../../package.json'); export type APIResponse = { duration?: string; diff --git a/tsconfig.json b/tsconfig.json index cd52724f..53a1052e 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,16 +1,19 @@ { "compilerOptions": { + "rootDir": "src", "baseUrl": "src", - "outDir": "types", + "declaration": true, + "declarationMap": true, + "module": "commonjs", + "moduleResolution": "node", "allowSyntheticDefaultImports": true, "esModuleInterop": true, - "resolveJsonModule": true, "noImplicitAny": true, "strictNullChecks": true, "strict": true, "lib": ["DOM", "ES6"], "target": "ES5" }, - "include": ["src/**/*"], - "exclude": ["node_modules", "test", "lib", "dist", "types"] + "include": ["src"], + "exclude": ["node_modules", "test", "lib", "dist"] } From e3e3fed61fd0d97e0a401be29222f70155d69984 Mon Sep 17 00:00:00 2001 From: Amin Mahboubi Date: Wed, 22 Jul 2020 16:53:31 +0200 Subject: [PATCH 21/69] simplify yarn types cmd --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 925d064f..8b525c1f 100644 --- a/package.json +++ b/package.json @@ -14,7 +14,7 @@ "version": "5.0.2", "scripts": { "transpile": "rm -rf lib && babel src --out-dir lib --extensions '.js,.ts'", - "types": "tsc --outFile lib/index --declaration true --declarationMap true --emitDeclarationOnly true", + "types": "tsc --outFile lib/index --emitDeclarationOnly", "build": "yarn transpile && yarn types", "eslint": "eslint '**/*.{js,ts}' --max-warnings 0", "prettier": "prettier --list-different '**/*.{js,ts}'", From bf7e4515180cab7233bc258c176048bdbb2fc626 Mon Sep 17 00:00:00 2001 From: Amin Mahboubi Date: Thu, 23 Jul 2020 08:52:34 +0200 Subject: [PATCH 22/69] fix unfollow relation type --- src/lib/batch_operations.ts | 4 ++-- src/lib/client.ts | 12 ++++++++++-- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/src/lib/batch_operations.ts b/src/lib/batch_operations.ts index 73d04885..36b5215d 100644 --- a/src/lib/batch_operations.ts +++ b/src/lib/batch_operations.ts @@ -1,4 +1,4 @@ -import StreamClient, { APIResponse, FollowRelation } from './client'; +import StreamClient, { APIResponse, FollowRelation, UnfollowRelation } from './client'; import utils from './utils'; function addToMany(this: StreamClient, activity: ActivityType, feeds: string[]): Promise { @@ -46,7 +46,7 @@ function followMany(this: StreamClient, follows: FollowRelation[], activityCopyL }); } -function unfollowMany(this: StreamClient, unfollows: FollowRelation[]): Promise { +function unfollowMany(this: StreamClient, unfollows: UnfollowRelation[]): Promise { /** * Unfollow multiple feeds with one API call * @method unfollowMany diff --git a/src/lib/client.ts b/src/lib/client.ts index 7d68ca6d..3245dc02 100644 --- a/src/lib/client.ts +++ b/src/lib/client.ts @@ -56,11 +56,19 @@ type GetActivitiesAPIResponse = APIResponse & { results: Activity[] }; type PartialUpdateActivityAPIResponse = APIResponse & { activities: Activity[] }; -export type FollowRelation = { +type BaseFollowRelation = { source: string; target: string; }; +export type FollowRelation = BaseFollowRelation & { + activity_copy_limit?: number; +}; + +export type UnfollowRelation = BaseFollowRelation & { + keep_history?: boolean; +}; + export type ClientOptions = { location?: string | undefined; expireTokens?: boolean; @@ -191,7 +199,7 @@ class StreamClient< addToMany?: (this: StreamClient, activity: ActivityType, feeds: string[]) => Promise; followMany?: (this: StreamClient, follows: FollowRelation[], activityCopyLimit?: number) => Promise; - unfollowMany?: (this: StreamClient, unfollows: FollowRelation[]) => Promise; + unfollowMany?: (this: StreamClient, unfollows: UnfollowRelation[]) => Promise; createRedirectUrl?: (this: StreamClient, targetUrl: string, userId: string, events: unknown[]) => string; constructor(apiKey: string, apiSecretOrToken: string | null, appId?: string, options: ClientOptions = {}) { From 7cb467bceb4fff3e4bb8c43aa125e7a12b05e3e6 Mon Sep 17 00:00:00 2001 From: Amin Mahboubi Date: Thu, 23 Jul 2020 08:52:50 +0200 Subject: [PATCH 23/69] fix new collection entry missing types --- src/lib/collections.ts | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/lib/collections.ts b/src/lib/collections.ts index 00ebf8d6..8afe60cc 100644 --- a/src/lib/collections.ts +++ b/src/lib/collections.ts @@ -1,13 +1,19 @@ import StreamClient, { APIResponse } from './client'; import errors from './errors'; -type CollectionResponse = { +type BaseCollection = { collection: string; id: string; data: CollectionType; +}; + +type CollectionResponse = BaseCollection & { foregin_id: string; created_at: Date; updated_at: Date; +}; + +type NewCollectionEntry = BaseCollection & { user_id?: string; }; @@ -214,7 +220,7 @@ export default class Collections { upsert( collection: string, - data: CollectionType | CollectionType[], + data: NewCollectionEntry | NewCollectionEntry[], ): Promise> { /** * Upsert one or more items within a collection. From c0cdeaf2d1c0fca2eb145a80de93a1c84284ea5c Mon Sep 17 00:00:00 2001 From: Amin Mahboubi Date: Thu, 23 Jul 2020 10:27:59 +0200 Subject: [PATCH 24/69] WIP/basic feed response types --- src/lib/client.ts | 18 ++------ src/lib/feed.ts | 109 +++++++++++++++++++++++++++++++++++++++++++--- 2 files changed, 107 insertions(+), 20 deletions(-) diff --git a/src/lib/client.ts b/src/lib/client.ts index 3245dc02..8b615c57 100644 --- a/src/lib/client.ts +++ b/src/lib/client.ts @@ -7,7 +7,7 @@ import jwtDecode from 'jwt-decode'; import Personalization from './personalization'; import BatchOperations from './batch_operations'; import Collections from './collections'; -import StreamFeed from './feed'; +import StreamFeed, { Activity } from './feed'; import StreamFileStore from './files'; import StreamImageStore from './images'; import StreamReaction from './reaction'; @@ -40,21 +40,9 @@ type ActivityPartialChanges = { unset?: string[]; }; -type BaseActivity = { - id: string; - actor: string; - verb: string; - object: string; - time: string | Date; - foreign_id: string; - to?: string[]; -}; - -export type Activity> = BaseActivity & ActivityType; - -type GetActivitiesAPIResponse = APIResponse & { results: Activity[] }; +type GetActivitiesAPIResponse = APIResponse & { results: Activity[] }; -type PartialUpdateActivityAPIResponse = APIResponse & { activities: Activity[] }; +type PartialUpdateActivityAPIResponse = APIResponse & { activities: Activity[] }; type BaseFollowRelation = { source: string; diff --git a/src/lib/feed.ts b/src/lib/feed.ts index 59b285a0..b78f29e9 100644 --- a/src/lib/feed.ts +++ b/src/lib/feed.ts @@ -1,5 +1,5 @@ import * as Faye from 'faye'; -import StreamClient, { APIResponse, Activity, EnrichOptions } from './client'; +import StreamClient, { APIResponse, EnrichOptions } from './client'; import StreamUser from './user'; import errors from './errors'; import utils from './utils'; @@ -30,6 +30,97 @@ type NewActivity = { foreign_id?: string; }; +type BaseActivity = { + id: string; + actor: string; + verb: string; + object: string; + time: string | Date; + foreign_id: string; + to?: string[]; +}; + +export type Activity = BaseActivity & ActivityType; + +type BaseReaction = { + id: string; + user_id: string; + activity_id: string; + kind: string; + created_at: Date; + updated_at: Date; + user?: UserType; +}; + +type ChildReaction = BaseReaction & { + parent: string; + data?: ChildReactionType; +}; + +type ChildReactions = Record[]>; + +type Reaction = BaseReaction & { + data?: ReactionType; + latest_children?: ChildReactions; + own_children?: ChildReactions; + children_counts?: Record; +}; + +type Reactions = Record< + string, + Reaction[] +>; + +type EnrichedActivity = Activity & { + actor: UserType | string; + object: string | ActivityType; + + // ranked feeds + score?: number; + analytics?: Record; + + // enriched reactions + reaction_counts?: Record; + latest_reactions?: Reactions; + latest_reactions_extra?: Record; + own_reactions?: Reactions[]; + own_reactions_extra?: Record; + + // Reactions posted to feed + reaction?: Reaction; + activity_id?: string; + origin?: string; + + // TODO: unknown! + // site_id?: string; + // target?: string; + // is_read?: unknown; + // is_seen?: unknown; + // extra_context?: unknown; +}; + +type GroupedActivity = { + id: string; + verb: string; + group: string; + activity_count: number; + actor_count: number; + is_read: boolean; + is_seen: boolean; + updated_at: Date; + created_at: Date; + + // TODO: unknown + activities: Activity[] | EnrichedActivity[]; +}; + +type FeedAPIResponse = APIResponse & { + results: + | Activity[] + | EnrichedActivity[] + | GroupedActivity; + next: string; +}; /** * Manage api calls for specific feeds * The feed object contains convenience functions such add activity, remove activity etc @@ -250,7 +341,7 @@ export default class StreamFeed< get( options: EnrichOptions & FeedOptions & { mark_read?: boolean | string[]; mark_seen?: boolean | string[] } = {}, - ): Promise { + ): Promise> { /** * Reads the feed * @method get @@ -275,14 +366,17 @@ export default class StreamFeed< const path = this.client.shouldUseEnrichEndpoint(options) ? 'enrich/feed/' : 'feed/'; - return this.client.get({ + return this.client.get>({ url: `${path}${this.feedUrl}/`, qs: { ...options, ...extraOptions }, signature: this.signature, }); } - getActivityDetail(activityId: string, options: EnrichOptions): Promise { + getActivityDetail( + activityId: string, + options: EnrichOptions, + ): Promise> { /** * Retrieves one activity from a feed and adds enrichment * @method getActivityDetail @@ -295,7 +389,12 @@ export default class StreamFeed< * @example feed.getActivityDetail(activityId, {withReactionCounts: true}) * @example feed.getActivityDetail(activityId, {withOwnReactions: true, withReactionCounts: true}) */ - return this.get({ id_lte: activityId, id_gte: activityId, limit: 1, ...(options || {}) }); + return this.get({ + id_lte: activityId, + id_gte: activityId, + limit: 1, + ...(options || {}), + }); } getFayeClient(): Faye.Client { From 1c975cb01a5401f6d74f02cd623e9991507ce87e Mon Sep 17 00:00:00 2001 From: Amin Mahboubi Date: Thu, 23 Jul 2020 10:30:33 +0200 Subject: [PATCH 25/69] move follow relation types to batch file --- src/lib/batch_operations.ts | 15 +++++++++++++- src/lib/client.ts | 39 +++++++++++++------------------------ 2 files changed, 27 insertions(+), 27 deletions(-) diff --git a/src/lib/batch_operations.ts b/src/lib/batch_operations.ts index 36b5215d..b0cc3842 100644 --- a/src/lib/batch_operations.ts +++ b/src/lib/batch_operations.ts @@ -1,6 +1,19 @@ -import StreamClient, { APIResponse, FollowRelation, UnfollowRelation } from './client'; +import StreamClient, { APIResponse } from './client'; import utils from './utils'; +type BaseFollowRelation = { + source: string; + target: string; +}; + +export type FollowRelation = BaseFollowRelation & { + activity_copy_limit?: number; +}; + +export type UnfollowRelation = BaseFollowRelation & { + keep_history?: boolean; +}; + function addToMany(this: StreamClient, activity: ActivityType, feeds: string[]): Promise { /** * Add one activity to many feeds diff --git a/src/lib/client.ts b/src/lib/client.ts index 8b615c57..3206bbd5 100644 --- a/src/lib/client.ts +++ b/src/lib/client.ts @@ -5,7 +5,7 @@ import * as Faye from 'faye'; import jwtDecode from 'jwt-decode'; import Personalization from './personalization'; -import BatchOperations from './batch_operations'; +import BatchOperations, { FollowRelation, UnfollowRelation } from './batch_operations'; import Collections from './collections'; import StreamFeed, { Activity } from './feed'; import StreamFileStore from './files'; @@ -32,31 +32,6 @@ export type FileUploadAPIResponse = APIResponse & { export type OnUploadProgress = (progressEvent: ProgressEvent) => void; -type ActivityPartialChanges = { - id?: string; - foreignID?: string; - time?: string | Date; - set?: Record; - unset?: string[]; -}; - -type GetActivitiesAPIResponse = APIResponse & { results: Activity[] }; - -type PartialUpdateActivityAPIResponse = APIResponse & { activities: Activity[] }; - -type BaseFollowRelation = { - source: string; - target: string; -}; - -export type FollowRelation = BaseFollowRelation & { - activity_copy_limit?: number; -}; - -export type UnfollowRelation = BaseFollowRelation & { - keep_history?: boolean; -}; - export type ClientOptions = { location?: string | undefined; expireTokens?: boolean; @@ -131,6 +106,18 @@ type AxiosConfig = { type HandlerCallback = (...args: unknown[]) => unknown; +type ActivityPartialChanges = { + id?: string; + foreignID?: string; + time?: string | Date; + set?: Record; + unset?: string[]; +}; + +type GetActivitiesAPIResponse = APIResponse & { results: Activity[] }; + +type PartialUpdateActivityAPIResponse = APIResponse & { activities: Activity[] }; + /** * Client to connect to Stream api * @class StreamClient From 6d73648cfcc77fc6d85b3ecd3d5d27d391c5c287 Mon Sep 17 00:00:00 2001 From: Amin Mahboubi Date: Thu, 23 Jul 2020 10:57:38 +0200 Subject: [PATCH 26/69] exclude js files from transpile cmd --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 8b525c1f..7285d303 100644 --- a/package.json +++ b/package.json @@ -13,7 +13,7 @@ "license": "BSD-3-Clause", "version": "5.0.2", "scripts": { - "transpile": "rm -rf lib && babel src --out-dir lib --extensions '.js,.ts'", + "transpile": "rm -rf lib && babel src --out-dir lib --extensions '.ts'", "types": "tsc --outFile lib/index --emitDeclarationOnly", "build": "yarn transpile && yarn types", "eslint": "eslint '**/*.{js,ts}' --max-warnings 0", From 65e205436fbf53f2fb675bca7ab4cadf6f3b58f0 Mon Sep 17 00:00:00 2001 From: Amin Mahboubi Date: Thu, 23 Jul 2020 15:30:14 +0200 Subject: [PATCH 27/69] cleanup some types --- src/lib/client.ts | 37 ++++++++----------------------------- src/lib/feed.ts | 12 +++++++++++- src/lib/personalization.ts | 8 ++++---- src/lib/reaction.ts | 12 +++--------- src/lib/signing.ts | 2 +- src/lib/user.ts | 2 +- 6 files changed, 28 insertions(+), 45 deletions(-) diff --git a/src/lib/client.ts b/src/lib/client.ts index 3206bbd5..6c6d993a 100644 --- a/src/lib/client.ts +++ b/src/lib/client.ts @@ -7,7 +7,7 @@ import jwtDecode from 'jwt-decode'; import Personalization from './personalization'; import BatchOperations, { FollowRelation, UnfollowRelation } from './batch_operations'; import Collections from './collections'; -import StreamFeed, { Activity } from './feed'; +import StreamFeed, { Activity, EnrichOptions } from './feed'; import StreamFileStore from './files'; import StreamImageStore from './images'; import StreamReaction from './reaction'; @@ -21,14 +21,9 @@ import utils from './utils'; // eslint-disable-next-line @typescript-eslint/no-var-requires const pkg = require('../../package.json'); -export type APIResponse = { - duration?: string; - [key: string]: unknown; -}; +export type APIResponse = Record & { duration?: string }; -export type FileUploadAPIResponse = APIResponse & { - file: string; -}; +export type FileUploadAPIResponse = APIResponse & { file: string }; export type OnUploadProgress = (progressEvent: ProgressEvent) => void; @@ -43,17 +38,7 @@ export type ClientOptions = { fayeUrl?: string; protocol?: string; local?: boolean; - urlOverride?: { [key: string]: string }; -}; - -export type EnrichOptions = { - enrich?: boolean; - withOwnReactions?: boolean; - withOwnChildren?: boolean; - ownReactions?: boolean; - withReactionCounts?: boolean; - withRecentReactions?: boolean; - recentReactionsLimit?: number; + urlOverride?: Record; }; type OGResource = { @@ -99,8 +84,8 @@ type AxiosConfig = { url: string; serviceName?: string; body?: unknown; - qs?: { [key: string]: unknown }; - headers?: { [key: string]: string }; + qs?: Record; + headers?: Record; axiosOptions?: axios.AxiosRequestConfig; }; @@ -152,14 +137,8 @@ class StreamClient< nodeOptions: undefined | { httpAgent: http.Agent; httpsAgent: https.Agent }; request: axios.AxiosInstance; - subscriptions: { - [key: string]: { - userId: string; - token: string; - fayeSubscription: Faye.Subscription; - }; - }; - handlers: { [key: string]: HandlerCallback }; + subscriptions: Record; + handlers: Record; currentUser: StreamUser | undefined; personalization: Personalization; diff --git a/src/lib/feed.ts b/src/lib/feed.ts index b78f29e9..51ed9855 100644 --- a/src/lib/feed.ts +++ b/src/lib/feed.ts @@ -1,9 +1,19 @@ import * as Faye from 'faye'; -import StreamClient, { APIResponse, EnrichOptions } from './client'; +import StreamClient, { APIResponse } from './client'; import StreamUser from './user'; import errors from './errors'; import utils from './utils'; +export type EnrichOptions = { + enrich?: boolean; + withOwnReactions?: boolean; + withOwnChildren?: boolean; + ownReactions?: boolean; + withReactionCounts?: boolean; + withRecentReactions?: boolean; + recentReactionsLimit?: number; +}; + type FeedOptions = { id_lt?: string; id_lte?: string; diff --git a/src/lib/personalization.ts b/src/lib/personalization.ts index 7535a210..776b33db 100644 --- a/src/lib/personalization.ts +++ b/src/lib/personalization.ts @@ -20,7 +20,7 @@ export default class Personalization { this.client = client; } - get(resource: string, options: { token?: string } & { [key: string]: string } = {}): Promise { + get(resource: string, options: Record & { token?: string } = {}): Promise { /** * Get personalized activities for this feed * @@ -41,8 +41,8 @@ export default class Personalization { post( resource: string, - options: { [key: string]: string } = {}, - data: { [key: string]: unknown } = {}, + options: Record = {}, + data: Record = {}, ): Promise { /** * Post data to personalization endpoint @@ -64,7 +64,7 @@ export default class Personalization { }); } - delete(resource: string, options: { [key: string]: string } = {}): Promise { + delete(resource: string, options: Record = {}): Promise { /** * Delete metadata or activities * diff --git a/src/lib/reaction.ts b/src/lib/reaction.ts index 05ed32d2..0e3c084e 100644 --- a/src/lib/reaction.ts +++ b/src/lib/reaction.ts @@ -6,9 +6,7 @@ type TargetFeeds = (string | StreamFeed)[]; type TargetFeed = string | StreamFeed; -type TargetFeedsExtraData = { - [key: string]: unknown; -}; +type TargetFeedsExtraData = Record; type ReactionBody = { id?: string; @@ -30,12 +28,8 @@ type ReactionAPIResponse = APIResponse & { created_at: Date; updated_at: Date; user?: unknown; - latest_children?: { - [key: string]: unknown; - }; - children_counts?: { - [key: string]: number; - }; + latest_children?: Record; + children_counts?: Record; }; type ChildReactionAPIResponse = ReactionAPIResponse & { diff --git a/src/lib/signing.ts b/src/lib/signing.ts index ac2e86fe..5f4d0dde 100644 --- a/src/lib/signing.ts +++ b/src/lib/signing.ts @@ -75,7 +75,7 @@ function JWTScopeToken( function JWTUserSessionToken( apiSecret: string, userId: string, - extraData: { [key: string]: unknown } = {}, + extraData: Record = {}, jwtOptions: jwt.SignOptions = {}, ): string { /** diff --git a/src/lib/user.ts b/src/lib/user.ts index 8d116a85..446b4c16 100644 --- a/src/lib/user.ts +++ b/src/lib/user.ts @@ -76,7 +76,7 @@ export default class StreamUser { return this; } - async update(data?: { [key: string]: unknown }): Promise> { + async update(data?: Record): Promise> { const response = await this.client.put>({ url: this.url, body: { From 058c0d7b6775ab1d64a29e31a5a667cd6051c26e Mon Sep 17 00:00:00 2001 From: Amin Mahboubi Date: Thu, 23 Jul 2020 15:34:42 +0200 Subject: [PATCH 28/69] remove types from eslintingore --- .eslintignore | 2 -- 1 file changed, 2 deletions(-) diff --git a/.eslintignore b/.eslintignore index 14cd43a9..8ceb4255 100644 --- a/.eslintignore +++ b/.eslintignore @@ -5,6 +5,4 @@ test/integration/utils/kjur.js /bin/ /.git/ /docs/ -/types/ - **/*.sh From eff9771b7a7bc4d06bd1e337d487cadf8c9c14f5 Mon Sep 17 00:00:00 2001 From: Amin Mahboubi Date: Fri, 24 Jul 2020 10:05:25 +0200 Subject: [PATCH 29/69] generalize reaction types --- src/lib/reaction.ts | 60 ++++++++++++++++++++++++++------------------- 1 file changed, 35 insertions(+), 25 deletions(-) diff --git a/src/lib/reaction.ts b/src/lib/reaction.ts index 0e3c084e..a3ab6a62 100644 --- a/src/lib/reaction.ts +++ b/src/lib/reaction.ts @@ -9,40 +9,50 @@ type TargetFeed = string | StreamFeed; type TargetFeedsExtraData = Record; type ReactionBody = { - id?: string; - activity_id?: string | { id: string }; - parent?: string | { id: string }; - kind?: string; + id?: string; // api will generate an id if it's missing + kind?: string; // required only for add/addChile, not update + user_id?: string; // optional when using client tokens + activity_id?: string; // only required for reactions + parent?: string; // only required for child reactions data?: T | Record; - target_feeds?: TargetFeeds; - user_id?: string; + target_feeds?: string[]; target_feeds_extra_data?: TargetFeedsExtraData; }; -type ReactionAPIResponse = APIResponse & { +export type Reaction = { id: string; kind: string; activity_id: string; user_id: string; - data: ReactionType; + data: T; created_at: Date; updated_at: Date; - user?: unknown; - latest_children?: Record; - children_counts?: Record; + target_feeds?: string[]; + target_feeds_extra_data?: TargetFeedsExtraData; + parent: string; }; -type ChildReactionAPIResponse = ReactionAPIResponse & { - parent: string; +type ReactionAPIResponse = APIResponse & Reaction; + +export type EnrichedReaction = Reaction & { + children_counts: Record; + latest_children: Record; + own_children?: Record; + user?: UserType; }; -type ReactionFilterAPIResponse = APIResponse & { - results: ReactionAPIResponse[] | ChildReactionAPIResponse[]; - activity: ActivityType; +type EnrichedReactionAPIResponse = APIResponse & + EnrichedReaction; + +type ReactionFilterAPIResponse = APIResponse & { + activity?: ActivityType; next: string; + results: + | ReactionAPIResponse[] + | EnrichedReactionAPIResponse[]; }; -export default class StreamReaction { +export default class StreamReaction { client: StreamClient; token: string; @@ -138,7 +148,7 @@ export default class StreamReaction> { + ): Promise> { /** * add reaction * @method add @@ -161,14 +171,14 @@ export default class StreamReaction>({ + return this.client.post>({ url: this.buildURL(), body, signature: this.token, }); } - get(id: string): Promise | ChildReactionAPIResponse> { + get(id: string): Promise> { /** * get reaction * @method add @@ -177,7 +187,7 @@ export default class StreamReaction | ChildReactionAPIResponse>({ + return this.client.get>({ url: this.buildURL(id), signature: this.token, }); @@ -194,7 +204,7 @@ export default class StreamReaction> { + }): Promise> { /** * retrieve reactions by activity_id, user_id or reaction_id (to paginate children reactions), pagination can be done using id_lt, id_lte, id_gt and id_gte parameters * id_lt and id_lte return reactions order by creation descending starting from the reaction with the ID provided, when id_lte is used @@ -228,7 +238,7 @@ export default class StreamReaction>({ + return this.client.get>({ url, qs: qs as { [key: string]: unknown }, signature: this.token, @@ -242,7 +252,7 @@ export default class StreamReaction | ChildReactionAPIResponse> { + ): Promise> { /** * update reaction * @method add @@ -261,7 +271,7 @@ export default class StreamReaction | ChildReactionAPIResponse>({ + return this.client.put>({ url: this.buildURL(id), body, signature: this.token, From 9162cd41a3a332033b88d5bbe98c13088efd409c Mon Sep 17 00:00:00 2001 From: Amin Mahboubi Date: Fri, 24 Jul 2020 10:05:59 +0200 Subject: [PATCH 30/69] add Personalization api response types --- src/lib/personalization.ts | 24 ++++++++++++++++++------ 1 file changed, 18 insertions(+), 6 deletions(-) diff --git a/src/lib/personalization.ts b/src/lib/personalization.ts index 776b33db..0312ab0d 100644 --- a/src/lib/personalization.ts +++ b/src/lib/personalization.ts @@ -6,6 +6,15 @@ import StreamClient, { APIResponse } from './client'; * @class Personalization */ +type BasePersonalizationAPIResponse = APIResponse & { + app_id: string; + results: unknown[]; + next: string; + offset?: number; + limit?: number; + version?: string; +}; + export default class Personalization { client: StreamClient; @@ -20,7 +29,10 @@ export default class Personalization { this.client = client; } - get(resource: string, options: Record & { token?: string } = {}): Promise { + get( + resource: string, + options: Record & { token?: string } = {}, + ): Promise { /** * Get personalized activities for this feed * @@ -31,7 +43,7 @@ export default class Personalization { * @return {Promise} Promise object. Personalized feed * @example client.personalization.get('follow_recommendations', {foo: 'bar', baz: 'qux'}) */ - return this.client.get({ + return this.client.get({ url: `${resource}/`, serviceName: 'personalization', qs: options, @@ -43,7 +55,7 @@ export default class Personalization { resource: string, options: Record = {}, data: Record = {}, - ): Promise { + ): Promise { /** * Post data to personalization endpoint * @@ -55,7 +67,7 @@ export default class Personalization { * @return {Promise} Promise object. Data that was posted if successful, or an error. * @example client.personalization.post('follow_recommendations', {foo: 'bar', baz: 'qux'}) */ - return this.client.post({ + return this.client.post({ url: `${resource}/`, serviceName: 'personalization', qs: options, @@ -64,7 +76,7 @@ export default class Personalization { }); } - delete(resource: string, options: Record = {}): Promise { + delete(resource: string, options: Record = {}): Promise { /** * Delete metadata or activities * @@ -75,7 +87,7 @@ export default class Personalization { * @return {Promise} Promise object. Data that was deleted if successful, or an error. * @example client.personalization.delete('follow_recommendations', {foo: 'bar', baz: 'qux'}) */ - return this.client.delete({ + return this.client.delete({ url: `${resource}/`, serviceName: 'personalization', qs: options, From 9905bf5fd7617857e7003d24631cd50efd9c29c8 Mon Sep 17 00:00:00 2001 From: Amin Mahboubi Date: Fri, 24 Jul 2020 13:48:13 +0200 Subject: [PATCH 31/69] remove default types from connect fn --- src/getstream.ts | 13 +++---------- 1 file changed, 3 insertions(+), 10 deletions(-) diff --git a/src/getstream.ts b/src/getstream.ts index a95a2dc0..c7d573c5 100644 --- a/src/getstream.ts +++ b/src/getstream.ts @@ -7,19 +7,12 @@ import StreamClient, { ClientOptions } from './lib/client'; import errors from './lib/errors'; import signing from './lib/signing'; -function connect< - UserType = unknown, - CollectionType = unknown, - ActivityType = unknown, - ReactionType = unknown, - ChildReactionType = unknown, - PersonalizationType = unknown ->( +function connect( apiKey: string, apiSecret: string | null, appId?: string, options?: ClientOptions, -): StreamClient { +): StreamClient { /** * Create StreamClient * @method connect @@ -53,7 +46,7 @@ function connect< } } - return new StreamClient( + return new StreamClient( apiKey, apiSecret, appId, From b6214d781bef4386b7a1aac7a89939b463f4870f Mon Sep 17 00:00:00 2001 From: Amin Mahboubi Date: Fri, 24 Jul 2020 13:48:43 +0200 Subject: [PATCH 32/69] deprecate reactions.all fn --- src/lib/reaction.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/lib/reaction.ts b/src/lib/reaction.ts index a3ab6a62..d086401c 100644 --- a/src/lib/reaction.ts +++ b/src/lib/reaction.ts @@ -73,7 +73,8 @@ export default class StreamReaction { + // DEPRECATED + all(options = {}) { /** * get all reactions * @method all @@ -83,6 +84,7 @@ export default class StreamReaction Date: Fri, 24 Jul 2020 13:49:59 +0200 Subject: [PATCH 33/69] improve and cleanup more types --- src/lib/client.ts | 78 ++++++++------ src/lib/collections.ts | 4 +- src/lib/feed.ts | 226 +++++++++++++++++++++++++---------------- src/lib/modules.d.ts | 1 + src/lib/reaction.ts | 2 +- src/lib/user.ts | 4 +- 6 files changed, 192 insertions(+), 123 deletions(-) diff --git a/src/lib/client.ts b/src/lib/client.ts index 6c6d993a..b1d3f649 100644 --- a/src/lib/client.ts +++ b/src/lib/client.ts @@ -5,9 +5,7 @@ import * as Faye from 'faye'; import jwtDecode from 'jwt-decode'; import Personalization from './personalization'; -import BatchOperations, { FollowRelation, UnfollowRelation } from './batch_operations'; import Collections from './collections'; -import StreamFeed, { Activity, EnrichOptions } from './feed'; import StreamFileStore from './files'; import StreamImageStore from './images'; import StreamReaction from './reaction'; @@ -16,6 +14,15 @@ import createRedirectUrl from './redirect_url'; import signing from './signing'; import errors from './errors'; import utils from './utils'; +import BatchOperations, { FollowRelation, UnfollowRelation } from './batch_operations'; +import StreamFeed, { + UpdateActivity, + Activity, + EnrichOptions, + PersonalizationFeedAPIResponse, + GetActivitiesAPIResponse, + GetFeedOptions, +} from './feed'; // no import since typescript json loader shifts the final output structure // eslint-disable-next-line @typescript-eslint/no-var-requires @@ -28,7 +35,7 @@ export type FileUploadAPIResponse = APIResponse & { file: string }; export type OnUploadProgress = (progressEvent: ProgressEvent) => void; export type ClientOptions = { - location?: string | undefined; + location?: string; expireTokens?: boolean; version?: string; group?: string; @@ -94,23 +101,19 @@ type HandlerCallback = (...args: unknown[]) => unknown; type ActivityPartialChanges = { id?: string; foreignID?: string; - time?: string | Date; + time?: Date; set?: Record; unset?: string[]; }; -type GetActivitiesAPIResponse = APIResponse & { results: Activity[] }; - -type PartialUpdateActivityAPIResponse = APIResponse & { activities: Activity[] }; - /** * Client to connect to Stream api * @class StreamClient */ class StreamClient< UserType = unknown, - CollectionType = unknown, ActivityType = unknown, + CollectionType = unknown, ReactionType = unknown, ChildReactionType = unknown, PersonalizationType = unknown @@ -118,14 +121,14 @@ class StreamClient< baseUrl: string; baseAnalyticsUrl: string; apiKey: string; - appId: string | undefined; + appId?: string; usingApiSecret: boolean; apiSecret: string | null; userToken: string | null; enrichByDefault: boolean; options: ClientOptions; - userId: undefined | string; - authPayload: undefined | unknown; + userId?: string; + authPayload?: unknown; version: string; fayeUrl: string; group: string; @@ -134,22 +137,22 @@ class StreamClient< fayeClient: Faye.Client | null; browser: boolean; node: boolean; - nodeOptions: undefined | { httpAgent: http.Agent; httpsAgent: https.Agent }; + nodeOptions?: { httpAgent: http.Agent; httpsAgent: https.Agent }; request: axios.AxiosInstance; subscriptions: Record; handlers: Record; - currentUser: StreamUser | undefined; + currentUser?: StreamUser; personalization: Personalization; collections: Collections; files: StreamFileStore; images: StreamImageStore; - reactions: StreamReaction; + reactions: StreamReaction; - private _personalizationToken: string | undefined; - private _collectionsToken: string | undefined; - private _getOrCreateToken: string | undefined; + private _personalizationToken?: string; + private _collectionsToken?: string; + private _getOrCreateToken?: string; addToMany?: (this: StreamClient, activity: ActivityType, feeds: string[]) => Promise; followMany?: (this: StreamClient, follows: FollowRelation[], activityCopyLimit?: number) => Promise; @@ -236,7 +239,10 @@ class StreamClient< this.collections = new Collections(this, this.getOrCreateToken()); this.files = new StreamFileStore(this, this.getOrCreateToken()); this.images = new StreamImageStore(this, this.getOrCreateToken()); - this.reactions = new StreamReaction(this, this.getOrCreateToken()); + this.reactions = new StreamReaction( + this, + this.getOrCreateToken(), + ); // If we are in a node environment and batchOperations/createRedirectUrl is available add the methods to the prototype of StreamClient if (BatchOperations && createRedirectUrl) { @@ -407,7 +413,7 @@ class StreamClient< feedSlug: string, userId?: string | StreamUser, token?: string, - ): StreamFeed { + ): StreamFeed { /** * Returns a feed object for the given feed id and token * @method feed @@ -429,7 +435,7 @@ class StreamClient< } } - return new StreamFeed( + return new StreamFeed( this, feedSlug, userId || (this.userId as string), @@ -675,7 +681,7 @@ class StreamClient< }); } - updateActivities(activities: Activity[]): Promise { + updateActivities(activities: UpdateActivity[]): Promise { /** * Updates all supplied activities on the getstream-io api * @since 3.1.0 @@ -693,14 +699,14 @@ class StreamClient< expireTokens: this.expireTokens, }); - return this.post({ + return this.post({ url: 'activities/', body: { activities }, signature: authToken, }); } - updateActivity(activity: Activity): Promise { + updateActivity(activity: UpdateActivity): Promise { /** * Updates one activity on the getstream-io api * @since 3.1.0 @@ -718,9 +724,9 @@ class StreamClient< ...params }: EnrichOptions & { ids?: string[]; - foreignIDTimes?: { foreignID: string; time: string | Date }[]; + foreignIDTimes?: { foreignID: string; time: Date }[]; reactions?: Record; - }): Promise> { + }): Promise> { /** * Retrieve activities by ID or foreign ID and time * @since 3.19.0 @@ -739,7 +745,7 @@ class StreamClient< throw new TypeError('The foreignIDTimes argument should be an Array'); } const foreignIDs: string[] = []; - const timestamps: (string | Date)[] = []; + const timestamps: Date[] = []; foreignIDTimes.forEach((fidTime) => { if (!(fidTime instanceof Object)) { throw new TypeError('foreignIDTimes elements should be Objects'); @@ -765,7 +771,7 @@ class StreamClient< this.replaceReactionOptions(params); const path = this.shouldUseEnrichEndpoint(params) ? 'enrich/activities/' : 'activities/'; - return this.get>({ + return this.get>({ url: path, qs: { ...params, ...extraParams }, signature: token, @@ -807,8 +813,12 @@ class StreamClient< }); } - personalizedFeed(options = {}) { - return this.get({ + personalizedFeed( + options: GetFeedOptions = {}, + ): Promise> { + return this.get< + PersonalizationFeedAPIResponse + >({ url: 'enrich/personalization/feed/', qs: options, signature: this.getOrCreateToken(), @@ -854,13 +864,15 @@ class StreamClient< return { ...activity, ...response }; } - activitiesPartialUpdate(changes: ActivityPartialChanges[]): Promise> { + activitiesPartialUpdate( + changes: ActivityPartialChanges[], + ): Promise[] }> { /** * Update multiple activities with partial operations. * @since v3.20.0 * @param {array} changes array containing the changesets to be applied. Every changeset contains the activity identifier which is either the ID or the pair of of foreign ID and time of the activity. The operations to issue can be set:{...} and unset:[...]. * @return {Promise} - * @xample + * @example * client.activitiesPartialUpdate([ * { * id: "4b39fda2-d6e2-42c9-9abf-5301ef071b12", @@ -938,7 +950,7 @@ class StreamClient< }); } - return this.post>({ + return this.post[] }>({ url: 'activity/', body: { changes, diff --git a/src/lib/collections.ts b/src/lib/collections.ts index 8afe60cc..64dfb40f 100644 --- a/src/lib/collections.ts +++ b/src/lib/collections.ts @@ -7,7 +7,7 @@ type BaseCollection = { data: CollectionType; }; -type CollectionResponse = BaseCollection & { +export type CollectionResponse = BaseCollection & { foregin_id: string; created_at: Date; updated_at: Date; @@ -39,7 +39,7 @@ class CollectionEntry { collection: string; store: Collections; data: CollectionType | null; - full: unknown; + full?: unknown; constructor(store: Collections, collection: string, id: string, data: CollectionType) { this.collection = collection; diff --git a/src/lib/feed.ts b/src/lib/feed.ts index 51ed9855..495589d0 100644 --- a/src/lib/feed.ts +++ b/src/lib/feed.ts @@ -3,25 +3,39 @@ import StreamClient, { APIResponse } from './client'; import StreamUser from './user'; import errors from './errors'; import utils from './utils'; +import { EnrichedReaction } from './reaction'; +import { CollectionResponse } from './collections'; export type EnrichOptions = { enrich?: boolean; withOwnReactions?: boolean; withOwnChildren?: boolean; - ownReactions?: boolean; + ownReactions?: boolean; // best not to use it, will removed by clinet.replaceReactionOptions() withReactionCounts?: boolean; withRecentReactions?: boolean; recentReactionsLimit?: number; + reactionKindsFilter?: string; // TODO: add support for array sample: kind,kind,kind }; -type FeedOptions = { +type FeedPaginationOptions = { id_lt?: string; id_lte?: string; id_gt?: string; id_gte?: string; limit?: number; +}; + +type RankedFeedOptions = { offset?: number; ranking?: string; + session?: string; +}; + +export type GetFeedOptions = FeedPaginationOptions & EnrichOptions & RankedFeedOptions; + +type NotificationFeedOptions = { + mark_read?: boolean | 'current' | string[]; + mark_seen?: boolean | 'current' | string[]; }; type GetFollowOptions = { @@ -30,115 +44,157 @@ type GetFollowOptions = { filter?: string[]; }; -type NewActivity = { +type GetFollowAPIResponse = APIResponse & { + results: { feed_id: string; target_id: string; created_at: Date; updated_at: Date }[]; +}; + +type BaseActivity = ActivityType & { actor: string; verb: string; object: string | unknown; to?: string[]; target?: string; - time?: string; - foreign_id?: string; }; -type BaseActivity = { - id: string; - actor: string; - verb: string; - object: string; - time: string | Date; - foreign_id: string; - to?: string[]; -}; +type NewActivity = BaseActivity & { time?: string; foreign_id?: string }; -export type Activity = BaseActivity & ActivityType; +export type UpdateActivity = BaseActivity & { time: string; foreign_id: string }; -type BaseReaction = { +export type Activity = BaseActivity & { id: string; - user_id: string; - activity_id: string; - kind: string; - created_at: Date; - updated_at: Date; - user?: UserType; -}; - -type ChildReaction = BaseReaction & { - parent: string; - data?: ChildReactionType; -}; - -type ChildReactions = Record[]>; + time: Date; + foreign_id: string; + origin?: string; + extra_context?: Record; -type Reaction = BaseReaction & { - data?: ReactionType; - latest_children?: ChildReactions; - own_children?: ChildReactions; - children_counts?: Record; + // ranked feeds + score?: number; + analytics?: Record; }; -type Reactions = Record< +type ReactionsRecords = Record< string, - Reaction[] + EnrichedReaction[] >; -type EnrichedActivity = Activity & { +type EnrichedActivity = Activity< + ActivityType +> & { actor: UserType | string; - object: string | ActivityType; - - // ranked feeds - score?: number; - analytics?: Record; + object: + | string + | unknown + | EnrichedActivity + | EnrichedReaction + | CollectionResponse; // enriched reactions reaction_counts?: Record; - latest_reactions?: Reactions; + latest_reactions?: ReactionsRecords; + own_reactions?: ReactionsRecords[]; latest_reactions_extra?: Record; - own_reactions?: Reactions[]; own_reactions_extra?: Record; + // Reaction posted to feed + reaction?: EnrichedReaction; +}; - // Reactions posted to feed - reaction?: Reaction; - activity_id?: string; - origin?: string; +type FlatActivity = Activity; - // TODO: unknown! - // site_id?: string; - // target?: string; - // is_read?: unknown; - // is_seen?: unknown; - // extra_context?: unknown; -}; +type FlatActivityEnriched = EnrichedActivity< + UserType, + ActivityType, + CollectionType, + ReactionType, + ChildReactionType +>; -type GroupedActivity = { +type BaseAggregatedActivity = { id: string; verb: string; group: string; activity_count: number; actor_count: number; - is_read: boolean; - is_seen: boolean; updated_at: Date; created_at: Date; + score?: number; +}; - // TODO: unknown - activities: Activity[] | EnrichedActivity[]; +type AggregatedActivity = BaseAggregatedActivity & { + activities: Activity[]; }; -type FeedAPIResponse = APIResponse & { +type AggregatedActivityEnriched< + UserType, + ActivityType, + CollectionType, + ReactionType, + ChildReactionType +> = BaseAggregatedActivity & { + activities: EnrichedActivity; +}; + +type BaseNotificationActivity = { is_read: boolean; is_seen: boolean }; +type NotificationActivity = AggregatedActivity & BaseNotificationActivity; + +type NotificationActivityEnriched< + UserType, + ActivityType, + CollectionType, + ReactionType, + ChildReactionType +> = BaseNotificationActivity & + AggregatedActivityEnriched; + +type FeedAPIResponse = APIResponse & { + next: string; results: - | Activity[] - | EnrichedActivity[] - | GroupedActivity; + | FlatActivity[] + | FlatActivityEnriched[] + | AggregatedActivity[] + | AggregatedActivityEnriched[] + | NotificationActivity[] + | NotificationActivityEnriched[]; + + // Notification Feed only + unread?: number; + unseen?: number; +}; + +export type PersonalizationFeedAPIResponse< + UserType, + ActivityType, + CollectionType, + ReactionType, + ChildReactionType +> = APIResponse & { next: string; + limit: number; + offset: number; + version: string; + results: FlatActivityEnriched[]; +}; + +export type GetActivitiesAPIResponse< + UserType, + ActivityType, + CollectionType, + ReactionType, + ChildReactionType +> = APIResponse & { + results: + | FlatActivity[] + | FlatActivityEnriched[]; }; + /** * Manage api calls for specific feeds * The feed object contains convenience functions such add activity, remove activity etc * @class StreamFeed */ export default class StreamFeed< - ActivityType = unknown, UserType = unknown, + ActivityType = unknown, + CollectionType = unknown, ReactionType = unknown, ChildReactionType = unknown > { @@ -193,7 +249,7 @@ export default class StreamFeed< this.notificationChannel = `site-${this.client.appId}-feed-${this.feedTogether}`; } - addActivity(activity: NewActivity & ActivityType): Promise> { + addActivity(activity: NewActivity): Promise> { /** * Adds the given activity to the feed * @method addActivity @@ -214,7 +270,7 @@ export default class StreamFeed< }); } - removeActivity(activityId: string | { foreignId: string }): Promise { + removeActivity(activityId: string | { foreignId: string }): Promise { /** * Removes the activity by activityId * @method removeActivity @@ -226,14 +282,14 @@ export default class StreamFeed< * @example * feed.removeActivity({'foreignId': foreignId}); */ - return this.client.delete({ + return this.client.delete({ url: `feed/${this.feedUrl}/${(activityId as { foreignId: string }).foreignId || activityId}/`, qs: (activityId as { foreignId: string }).foreignId ? { foreign_id: '1' } : {}, signature: this.signature, }); } - addActivities(activities: (NewActivity & ActivityType)[]): Promise { + addActivities(activities: NewActivity[]): Promise[]> { /** * Adds the given activities to the feed * @method addActivities @@ -241,7 +297,7 @@ export default class StreamFeed< * @param {Array} activities Array of activities to add * @return {Promise} XHR request object */ - return this.client.post({ + return this.client.post[]>({ url: `feed/${this.feedUrl}/`, body: { activities: utils.replaceStreamObjects(activities) }, signature: this.signature, @@ -252,7 +308,7 @@ export default class StreamFeed< targetSlug: string, targetUserId: string | { id: string }, options: { limit?: number } = {}, - ): Promise { + ): Promise { /** * Follows the given target feed * @method follow @@ -275,14 +331,14 @@ export default class StreamFeed< const body: { target: string; activity_copy_limit?: number } = { target: `${targetSlug}:${targetUserId}` }; if (typeof options.limit === 'number') body.activity_copy_limit = options.limit; - return this.client.post({ + return this.client.post({ url: `feed/${this.feedUrl}/following/`, body, signature: this.signature, }); } - unfollow(targetSlug: string, targetUserId: string, options: { keepHistory?: boolean } = {}): Promise { + unfollow(targetSlug: string, targetUserId: string, options: { keepHistory?: boolean } = {}): Promise { /** * Unfollow the given feed * @method unfollow @@ -301,14 +357,14 @@ export default class StreamFeed< utils.validateFeedSlug(targetSlug); utils.validateUserId(targetUserId); const targetFeedId = `${targetSlug}:${targetUserId}`; - return this.client.delete({ + return this.client.delete({ url: `feed/${this.feedUrl}/following/${targetFeedId}/`, qs, signature: this.signature, }); } - following(options: GetFollowOptions = {}): Promise { + following(options: GetFollowOptions = {}): Promise { /** * List which feeds this feed is following * @method following @@ -321,14 +377,14 @@ export default class StreamFeed< const extraOptions: { filter?: string } = {}; if (options.filter) extraOptions.filter = options.filter.join(','); - return this.client.get({ + return this.client.get({ url: `feed/${this.feedUrl}/following/`, qs: { ...options, ...extraOptions }, signature: this.signature, }); } - followers(options: GetFollowOptions = {}): Promise { + followers(options: GetFollowOptions = {}): Promise { /** * List the followers of this feed * @method followers @@ -342,7 +398,7 @@ export default class StreamFeed< const extraOptions: { filter?: string } = {}; if (options.filter) extraOptions.filter = options.filter.join(','); - return this.client.get({ + return this.client.get({ url: `feed/${this.feedUrl}/followers/`, qs: { ...options, ...extraOptions }, signature: this.signature, @@ -350,8 +406,8 @@ export default class StreamFeed< } get( - options: EnrichOptions & FeedOptions & { mark_read?: boolean | string[]; mark_seen?: boolean | string[] } = {}, - ): Promise> { + options: GetFeedOptions & NotificationFeedOptions = {}, + ): Promise> { /** * Reads the feed * @method get @@ -376,7 +432,7 @@ export default class StreamFeed< const path = this.client.shouldUseEnrichEndpoint(options) ? 'enrich/feed/' : 'feed/'; - return this.client.get>({ + return this.client.get>({ url: `${path}${this.feedUrl}/`, qs: { ...options, ...extraOptions }, signature: this.signature, @@ -386,7 +442,7 @@ export default class StreamFeed< getActivityDetail( activityId: string, options: EnrichOptions, - ): Promise> { + ): Promise> { /** * Retrieves one activity from a feed and adds enrichment * @method getActivityDetail @@ -464,7 +520,7 @@ export default class StreamFeed< newTargets?: string[], addedTargets?: string[], removedTargets?: string[], - ): Promise { + ): Promise & { added?: string[]; removed?: string[] }> { /** * Updates an activity's "to" fields * @since 3.10.0 @@ -510,7 +566,7 @@ export default class StreamFeed< if (addedTargets) body.added_targets = addedTargets; if (removedTargets) body.removed_targets = removedTargets; - return this.client.post({ + return this.client.post & { added?: string[]; removed?: string[] }>({ url: `feed_targets/${this.feedUrl}/activity_to_targets/`, signature: this.signature, body, diff --git a/src/lib/modules.d.ts b/src/lib/modules.d.ts index 5f0b109f..dd50e6f7 100644 --- a/src/lib/modules.d.ts +++ b/src/lib/modules.d.ts @@ -1,6 +1,7 @@ declare module 'faye' { type Message = { subscription?: string; + // TODO: generalize [key: string]: unknown; }; diff --git a/src/lib/reaction.ts b/src/lib/reaction.ts index d086401c..e7c4d74b 100644 --- a/src/lib/reaction.ts +++ b/src/lib/reaction.ts @@ -52,7 +52,7 @@ type ReactionFilterAPIResponse[]; }; -export default class StreamReaction { +export default class StreamReaction { client: StreamClient; token: string; diff --git a/src/lib/user.ts b/src/lib/user.ts index 446b4c16..5956ce1f 100644 --- a/src/lib/user.ts +++ b/src/lib/user.ts @@ -13,8 +13,8 @@ export default class StreamUser { client: StreamClient; token: string; id: string; - data: undefined | UserType; - full: undefined | UserAPIResponse; + data?: UserType; + full?: UserAPIResponse; private url: string; constructor(client: StreamClient, userId: string, userAuthToken: string) { From e51213593d7b93008ce2e70ae5c9b31edfd313ae Mon Sep 17 00:00:00 2001 From: Amin Mahboubi Date: Fri, 24 Jul 2020 14:25:31 +0200 Subject: [PATCH 34/69] flatten the src folder --- package.json | 8 ++++---- src/{lib => }/batch_operations.ts | 0 src/{lib => }/client.ts | 2 +- src/{lib => }/collections.ts | 0 src/{lib => }/errors.ts | 0 src/{lib => }/feed.ts | 0 src/{lib => }/files.ts | 0 src/{lib => }/images.ts | 0 src/{getstream.ts => index.ts} | 6 +++--- src/{lib => }/modules.d.ts | 0 src/{lib => }/personalization.ts | 0 src/{lib => }/reaction.ts | 0 src/{lib => }/redirect_url.ts | 0 src/{lib => }/signing.ts | 0 src/{lib => }/user.ts | 0 src/{lib => }/utils.ts | 0 test/integration/browser/client_test.js | 2 +- test/integration/cloud/utils.js | 2 +- test/integration/common/client_test.js | 2 +- test/integration/common/faye_test.js | 4 ++-- test/integration/node/client_test.js | 4 ++-- test/integration/utils/hooks.js | 2 +- test/unit/browser/client_test.js | 4 ++-- test/unit/browser/utils_test.js | 2 +- test/unit/common/client_test.js | 4 ++-- test/unit/common/feed_test.js | 4 ++-- test/unit/common/jwt_test.js | 2 +- test/unit/common/utils_test.js | 4 ++-- test/unit/node/client_test.js | 6 +++--- test/unit/node/collections_test.js | 4 ++-- test/unit/node/heroku_test.js | 2 +- test/unit/node/personalization_test.js | 4 ++-- test/unit/node/redirect_test.js | 4 ++-- test/unit/node/token_test.js | 2 +- test/unit/node/utils_test.js | 2 +- test/unit/utils/hooks.js | 2 +- webpack.config.js | 2 +- 37 files changed, 40 insertions(+), 40 deletions(-) rename src/{lib => }/batch_operations.ts (100%) rename src/{lib => }/client.ts (99%) rename src/{lib => }/collections.ts (100%) rename src/{lib => }/errors.ts (100%) rename src/{lib => }/feed.ts (100%) rename src/{lib => }/files.ts (100%) rename src/{lib => }/images.ts (100%) rename src/{getstream.ts => index.ts} (93%) rename src/{lib => }/modules.d.ts (100%) rename src/{lib => }/personalization.ts (100%) rename src/{lib => }/reaction.ts (100%) rename src/{lib => }/redirect_url.ts (100%) rename src/{lib => }/signing.ts (100%) rename src/{lib => }/user.ts (100%) rename src/{lib => }/utils.ts (100%) diff --git a/package.json b/package.json index 7285d303..296e715f 100644 --- a/package.json +++ b/package.json @@ -5,8 +5,8 @@ }, "name": "getstream", "description": "The official low-level GetStream.io client for Node.js and the browser.", - "main": "./lib/getstream.js", - "module": "./lib/getstream.js", + "main": "./lib/index.js", + "module": "./lib/index.js", "types": "./lib/index.d.ts", "homepage": "https://getstream.io/docs/?language=js", "email": "support@getstream.io", @@ -41,7 +41,7 @@ "browser": { "crypto": false, "jsonwebtoken": false, - "./lib/lib/batch_operations.js": false, + "./lib/batch_operations.js": false, "qs": false, "url": false, "http": false, @@ -50,7 +50,7 @@ "react-native": { "crypto": false, "jsonwebtoken": false, - "./lib/lib/batch_operations.js": false, + "./lib/batch_operations.js": false, "qs": false, "url": false }, diff --git a/src/lib/batch_operations.ts b/src/batch_operations.ts similarity index 100% rename from src/lib/batch_operations.ts rename to src/batch_operations.ts diff --git a/src/lib/client.ts b/src/client.ts similarity index 99% rename from src/lib/client.ts rename to src/client.ts index b1d3f649..97be879c 100644 --- a/src/lib/client.ts +++ b/src/client.ts @@ -26,7 +26,7 @@ import StreamFeed, { // no import since typescript json loader shifts the final output structure // eslint-disable-next-line @typescript-eslint/no-var-requires -const pkg = require('../../package.json'); +const pkg = require('../package.json'); export type APIResponse = Record & { duration?: string }; diff --git a/src/lib/collections.ts b/src/collections.ts similarity index 100% rename from src/lib/collections.ts rename to src/collections.ts diff --git a/src/lib/errors.ts b/src/errors.ts similarity index 100% rename from src/lib/errors.ts rename to src/errors.ts diff --git a/src/lib/feed.ts b/src/feed.ts similarity index 100% rename from src/lib/feed.ts rename to src/feed.ts diff --git a/src/lib/files.ts b/src/files.ts similarity index 100% rename from src/lib/files.ts rename to src/files.ts diff --git a/src/lib/images.ts b/src/images.ts similarity index 100% rename from src/lib/images.ts rename to src/images.ts diff --git a/src/getstream.ts b/src/index.ts similarity index 93% rename from src/getstream.ts rename to src/index.ts index c7d573c5..f8ce3617 100644 --- a/src/getstream.ts +++ b/src/index.ts @@ -3,9 +3,9 @@ * @author Thierry Schellenbach * BSD License */ -import StreamClient, { ClientOptions } from './lib/client'; -import errors from './lib/errors'; -import signing from './lib/signing'; +import StreamClient, { ClientOptions } from './client'; +import errors from './errors'; +import signing from './signing'; function connect( apiKey: string, diff --git a/src/lib/modules.d.ts b/src/modules.d.ts similarity index 100% rename from src/lib/modules.d.ts rename to src/modules.d.ts diff --git a/src/lib/personalization.ts b/src/personalization.ts similarity index 100% rename from src/lib/personalization.ts rename to src/personalization.ts diff --git a/src/lib/reaction.ts b/src/reaction.ts similarity index 100% rename from src/lib/reaction.ts rename to src/reaction.ts diff --git a/src/lib/redirect_url.ts b/src/redirect_url.ts similarity index 100% rename from src/lib/redirect_url.ts rename to src/redirect_url.ts diff --git a/src/lib/signing.ts b/src/signing.ts similarity index 100% rename from src/lib/signing.ts rename to src/signing.ts diff --git a/src/lib/user.ts b/src/user.ts similarity index 100% rename from src/lib/user.ts rename to src/user.ts diff --git a/src/lib/utils.ts b/src/utils.ts similarity index 100% rename from src/lib/utils.ts rename to src/utils.ts diff --git a/test/integration/browser/client_test.js b/test/integration/browser/client_test.js index b0af0c70..c2320d70 100644 --- a/test/integration/browser/client_test.js +++ b/test/integration/browser/client_test.js @@ -1,6 +1,6 @@ import expect from 'expect.js'; -import errors from '../../../src/lib/errors'; +import errors from '../../../src/errors'; import { init, beforeEachFn } from '../utils/hooks'; function mockedFile(size = 1024, name = 'file.txt', mimeType = 'plain/txt') { diff --git a/test/integration/cloud/utils.js b/test/integration/cloud/utils.js index 036323c1..0f6639bf 100644 --- a/test/integration/cloud/utils.js +++ b/test/integration/cloud/utils.js @@ -1,6 +1,6 @@ import chai, { expect } from 'chai'; -import { connect, errors } from '../../../src/getstream'; +import { connect, errors } from '../../../src'; import config from '../utils/config'; import { randUserId } from '../utils/hooks'; diff --git a/test/integration/common/client_test.js b/test/integration/common/client_test.js index 10302d34..904adf20 100644 --- a/test/integration/common/client_test.js +++ b/test/integration/common/client_test.js @@ -1,6 +1,6 @@ import expect from 'expect.js'; -import errors from '../../../src/lib/errors'; +import errors from '../../../src/errors'; import config from '../utils/config'; import { init, beforeEachFn } from '../utils/hooks'; diff --git a/test/integration/common/faye_test.js b/test/integration/common/faye_test.js index f250684c..fa1d80f6 100644 --- a/test/integration/common/faye_test.js +++ b/test/integration/common/faye_test.js @@ -1,7 +1,7 @@ import expect from 'expect.js'; -import { connect } from '../../../src/getstream'; -import errors from '../../../src/lib/errors'; +import { connect } from '../../../src'; +import errors from '../../../src/errors'; import { init, beforeEachFn } from '../utils/hooks'; describe('[INTEGRATION] Stream client (Faye)', function () { diff --git a/test/integration/node/client_test.js b/test/integration/node/client_test.js index 166d70f8..9ed7ceff 100644 --- a/test/integration/node/client_test.js +++ b/test/integration/node/client_test.js @@ -1,7 +1,7 @@ import expect from 'expect.js'; -import { connect } from '../../../src/getstream'; -import errors from '../../../src/lib/errors'; +import { connect } from '../../../src'; +import errors from '../../../src/errors'; import { init, beforeEachFn } from '../utils/hooks'; diff --git a/test/integration/utils/hooks.js b/test/integration/utils/hooks.js index 74c8a3cd..6656a1e7 100644 --- a/test/integration/utils/hooks.js +++ b/test/integration/utils/hooks.js @@ -1,4 +1,4 @@ -const stream = require('../../../src/getstream').default; +const stream = require('../../../src').default; const config = require('./config'); // this function can only be run in browser context diff --git a/test/unit/browser/client_test.js b/test/unit/browser/client_test.js index 8d6f2a80..dbb6d6b2 100644 --- a/test/unit/browser/client_test.js +++ b/test/unit/browser/client_test.js @@ -1,8 +1,8 @@ import expect from 'expect.js'; import pkg from '../../../package.json'; -import StreamFeed from '../../../src/lib/feed'; -import { connect, errors } from '../../../src/getstream'; +import StreamFeed from '../../../src/feed'; +import { connect, errors } from '../../../src'; import { init, beforeEachFn } from '../utils/hooks'; describe('[UNIT] Stream Client (browser)', function () { diff --git a/test/unit/browser/utils_test.js b/test/unit/browser/utils_test.js index 3c694fb0..72e8ddd1 100644 --- a/test/unit/browser/utils_test.js +++ b/test/unit/browser/utils_test.js @@ -1,7 +1,7 @@ import FormData from 'form-data'; import expect from 'expect.js'; -import utils from '../../../src/lib/utils'; +import utils from '../../../src/utils'; import { init } from '../utils/hooks'; function mockedFile(size = 1024, name = 'mockfile.txt', mimeType = 'plain/txt') { diff --git a/test/unit/common/client_test.js b/test/unit/common/client_test.js index 6f01846f..fae5515a 100644 --- a/test/unit/common/client_test.js +++ b/test/unit/common/client_test.js @@ -1,8 +1,8 @@ import expect from 'expect.js'; import td from 'testdouble'; -import utils from '../../../src/lib/utils'; -import errors from '../../../src/lib/errors'; +import utils from '../../../src/utils'; +import errors from '../../../src/errors'; import config from '../utils/config'; import { init, beforeEachFn } from '../utils/hooks'; diff --git a/test/unit/common/feed_test.js b/test/unit/common/feed_test.js index cff2c2e9..1afca98b 100644 --- a/test/unit/common/feed_test.js +++ b/test/unit/common/feed_test.js @@ -1,8 +1,8 @@ import expect from 'expect.js'; import td from 'testdouble'; -import StreamFeed from '../../../src/lib/feed'; -import errors from '../../../src/lib/errors'; +import StreamFeed from '../../../src/feed'; +import errors from '../../../src/errors'; import { init, beforeEachFn } from '../utils/hooks'; describe('[UNIT] Stream Feed (Common)', function () { diff --git a/test/unit/common/jwt_test.js b/test/unit/common/jwt_test.js index b6037d57..8346fee4 100644 --- a/test/unit/common/jwt_test.js +++ b/test/unit/common/jwt_test.js @@ -1,6 +1,6 @@ import expect from 'expect.js'; -import signing from '../../../src/lib/signing'; +import signing from '../../../src/signing'; describe('[UNIT] Json web token validation', function () { const validSignature = diff --git a/test/unit/common/utils_test.js b/test/unit/common/utils_test.js index 787204f0..43a3624d 100644 --- a/test/unit/common/utils_test.js +++ b/test/unit/common/utils_test.js @@ -1,7 +1,7 @@ import expect from 'expect.js'; -import errors from '../../../src/lib/errors'; -import utils from '../../../src/lib/utils'; +import errors from '../../../src/errors'; +import utils from '../../../src/utils'; import { init } from '../utils/hooks'; describe('[UNIT] Utility functions', function () { diff --git a/test/unit/node/client_test.js b/test/unit/node/client_test.js index a2d88047..483fcf1a 100644 --- a/test/unit/node/client_test.js +++ b/test/unit/node/client_test.js @@ -3,9 +3,9 @@ import td from 'testdouble'; import jwtDecode from 'jwt-decode'; import pkg from '../../../package.json'; -import { connect } from '../../../src/getstream'; -import StreamClient from '../../../src/lib/client'; -import StreamFeed from '../../../src/lib/feed'; +import { connect } from '../../../src'; +import StreamClient from '../../../src/client'; +import StreamFeed from '../../../src/feed'; import { beforeEachFn } from '../utils/hooks'; describe('[UNIT] Stream Client instantiation (Node)', function () { diff --git a/test/unit/node/collections_test.js b/test/unit/node/collections_test.js index 9200e102..4e3b29e4 100644 --- a/test/unit/node/collections_test.js +++ b/test/unit/node/collections_test.js @@ -1,8 +1,8 @@ import expect from 'expect.js'; import td from 'testdouble'; -import StreamClient from '../../../src/lib/client'; -import errors from '../../../src/lib/errors'; +import StreamClient from '../../../src/client'; +import errors from '../../../src/errors'; import { beforeEachFn } from '../utils/hooks'; describe('[UNIT] Stream Collections (node)', function () { diff --git a/test/unit/node/heroku_test.js b/test/unit/node/heroku_test.js index bde82410..57fbf582 100644 --- a/test/unit/node/heroku_test.js +++ b/test/unit/node/heroku_test.js @@ -1,6 +1,6 @@ import expect from 'expect.js'; -import { connect } from '../../../src/getstream'; +import { connect } from '../../../src'; import { init, beforeEachFn } from '../utils/hooks'; describe('[UNIT] Stream client (Heroku)', function () { diff --git a/test/unit/node/personalization_test.js b/test/unit/node/personalization_test.js index 0199a90d..a74afd32 100644 --- a/test/unit/node/personalization_test.js +++ b/test/unit/node/personalization_test.js @@ -1,8 +1,8 @@ import expect from 'expect.js'; import td from 'testdouble'; -import StreamClient from '../../../src/lib/client'; -import errors from '../../../src/lib/errors'; +import StreamClient from '../../../src/client'; +import errors from '../../../src/errors'; import { beforeEachFn } from '../utils/hooks'; describe('[UNIT] Stream Personalization (node)', function () { diff --git a/test/unit/node/redirect_test.js b/test/unit/node/redirect_test.js index bb019253..a94e1d6e 100644 --- a/test/unit/node/redirect_test.js +++ b/test/unit/node/redirect_test.js @@ -4,8 +4,8 @@ import url from 'url'; import qs from 'qs'; import request from 'request'; -import StreamClient from '../../../src/lib/client'; -import errors from '../../../src/lib/errors'; +import StreamClient from '../../../src/client'; +import errors from '../../../src/errors'; import config from '../utils/config'; describe("[UNIT] Redirect URL's", function () { diff --git a/test/unit/node/token_test.js b/test/unit/node/token_test.js index 119885cb..7b628362 100644 --- a/test/unit/node/token_test.js +++ b/test/unit/node/token_test.js @@ -1,6 +1,6 @@ import expect from 'expect.js'; -import signing from '../../../src/lib/signing'; +import signing from '../../../src/signing'; import { beforeEachFn } from '../utils/hooks'; describe('[UNIT] Creating tokens', function () { diff --git a/test/unit/node/utils_test.js b/test/unit/node/utils_test.js index be1ef9f8..e3fc165e 100644 --- a/test/unit/node/utils_test.js +++ b/test/unit/node/utils_test.js @@ -2,7 +2,7 @@ import FormData from 'form-data'; import expect from 'expect.js'; import fs from 'fs'; -import utils from '../../../src/lib/utils'; +import utils from '../../../src/utils'; import { init } from '../utils/hooks'; describe('[UNIT] Utility functions (node)', function () { diff --git a/test/unit/utils/hooks.js b/test/unit/utils/hooks.js index 7fae8449..3a8c169b 100644 --- a/test/unit/utils/hooks.js +++ b/test/unit/utils/hooks.js @@ -1,5 +1,5 @@ const td = require('testdouble'); -const StreamClient = require('../../../src/lib/client').default; +const StreamClient = require('../../../src/client').default; const config = require('./config'); function init() { diff --git a/webpack.config.js b/webpack.config.js index 3c69e88c..2c16ab94 100644 --- a/webpack.config.js +++ b/webpack.config.js @@ -2,7 +2,7 @@ const path = require('path'); const UglifyJsPlugin = require('uglifyjs-webpack-plugin'); module.exports = (env, argv = []) => ({ - entry: ['./src/getstream.ts'], + entry: ['./src/index.ts'], mode: 'production', From d5c06fe8e66a8ffcd4fd0acd7d18ccd5a9aecabd Mon Sep 17 00:00:00 2001 From: Amin Mahboubi Date: Fri, 24 Jul 2020 15:02:02 +0200 Subject: [PATCH 35/69] fix PersonalizationAPIResponse type --- src/lib/personalization.ts | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/src/lib/personalization.ts b/src/lib/personalization.ts index 0312ab0d..5e8bba31 100644 --- a/src/lib/personalization.ts +++ b/src/lib/personalization.ts @@ -6,9 +6,9 @@ import StreamClient, { APIResponse } from './client'; * @class Personalization */ -type BasePersonalizationAPIResponse = APIResponse & { +type PersonalizationAPIResponse = APIResponse & { app_id: string; - results: unknown[]; + results: PersonalizationType[]; next: string; offset?: number; limit?: number; @@ -32,7 +32,7 @@ export default class Personalization { get( resource: string, options: Record & { token?: string } = {}, - ): Promise { + ): Promise> { /** * Get personalized activities for this feed * @@ -43,7 +43,7 @@ export default class Personalization { * @return {Promise} Promise object. Personalized feed * @example client.personalization.get('follow_recommendations', {foo: 'bar', baz: 'qux'}) */ - return this.client.get({ + return this.client.get>({ url: `${resource}/`, serviceName: 'personalization', qs: options, @@ -55,7 +55,7 @@ export default class Personalization { resource: string, options: Record = {}, data: Record = {}, - ): Promise { + ): Promise> { /** * Post data to personalization endpoint * @@ -67,7 +67,7 @@ export default class Personalization { * @return {Promise} Promise object. Data that was posted if successful, or an error. * @example client.personalization.post('follow_recommendations', {foo: 'bar', baz: 'qux'}) */ - return this.client.post({ + return this.client.post>({ url: `${resource}/`, serviceName: 'personalization', qs: options, @@ -76,7 +76,10 @@ export default class Personalization { }); } - delete(resource: string, options: Record = {}): Promise { + delete( + resource: string, + options: Record = {}, + ): Promise> { /** * Delete metadata or activities * @@ -87,7 +90,7 @@ export default class Personalization { * @return {Promise} Promise object. Data that was deleted if successful, or an error. * @example client.personalization.delete('follow_recommendations', {foo: 'bar', baz: 'qux'}) */ - return this.client.delete({ + return this.client.delete>({ url: `${resource}/`, serviceName: 'personalization', qs: options, From bd425ba307c3e22804642c12808d30d267abc87b Mon Sep 17 00:00:00 2001 From: Amin Mahboubi Date: Mon, 27 Jul 2020 11:05:53 +0200 Subject: [PATCH 36/69] set ts default outDir --- tsconfig.json | 1 + 1 file changed, 1 insertion(+) diff --git a/tsconfig.json b/tsconfig.json index 53a1052e..bee777d0 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -2,6 +2,7 @@ "compilerOptions": { "rootDir": "src", "baseUrl": "src", + "outDir": "lib", "declaration": true, "declarationMap": true, "module": "commonjs", From f8133ec3e6687c06af641b367d53cec023049fab Mon Sep 17 00:00:00 2001 From: Amin Mahboubi Date: Mon, 27 Jul 2020 12:10:27 +0200 Subject: [PATCH 37/69] remove errors default export --- src/client.ts | 2 +- src/collections.ts | 2 +- src/errors.ts | 7 ------- src/feed.ts | 2 +- src/index.ts | 2 +- src/reaction.ts | 2 +- src/redirect_url.ts | 2 +- src/utils.ts | 2 +- test/integration/browser/client_test.js | 2 +- test/integration/common/client_test.js | 2 +- test/integration/common/faye_test.js | 2 +- test/integration/node/client_test.js | 2 +- test/unit/common/client_test.js | 2 +- test/unit/common/feed_test.js | 2 +- test/unit/common/utils_test.js | 2 +- test/unit/node/collections_test.js | 2 +- test/unit/node/personalization_test.js | 2 +- test/unit/node/redirect_test.js | 2 +- 18 files changed, 17 insertions(+), 24 deletions(-) diff --git a/src/client.ts b/src/client.ts index 97be879c..9e7f104a 100644 --- a/src/client.ts +++ b/src/client.ts @@ -12,7 +12,7 @@ import StreamReaction from './reaction'; import StreamUser from './user'; import createRedirectUrl from './redirect_url'; import signing from './signing'; -import errors from './errors'; +import * as errors from './errors'; import utils from './utils'; import BatchOperations, { FollowRelation, UnfollowRelation } from './batch_operations'; import StreamFeed, { diff --git a/src/collections.ts b/src/collections.ts index 64dfb40f..8cbbcee4 100644 --- a/src/collections.ts +++ b/src/collections.ts @@ -1,5 +1,5 @@ import StreamClient, { APIResponse } from './client'; -import errors from './errors'; +import * as errors from './errors'; type BaseCollection = { collection: string; diff --git a/src/errors.ts b/src/errors.ts index ffddcc98..8f8639a3 100644 --- a/src/errors.ts +++ b/src/errors.ts @@ -78,10 +78,3 @@ export class StreamApiError extends ErrorAbstract { this.response = response; } } - -export default { - FeedError, - SiteError, - MissingSchemaError, - StreamApiError, -}; diff --git a/src/feed.ts b/src/feed.ts index 495589d0..2c02bc63 100644 --- a/src/feed.ts +++ b/src/feed.ts @@ -1,7 +1,7 @@ import * as Faye from 'faye'; import StreamClient, { APIResponse } from './client'; import StreamUser from './user'; -import errors from './errors'; +import * as errors from './errors'; import utils from './utils'; import { EnrichedReaction } from './reaction'; import { CollectionResponse } from './collections'; diff --git a/src/index.ts b/src/index.ts index f8ce3617..2c3ad089 100644 --- a/src/index.ts +++ b/src/index.ts @@ -4,7 +4,7 @@ * BSD License */ import StreamClient, { ClientOptions } from './client'; -import errors from './errors'; +import * as errors from './errors'; import signing from './signing'; function connect( diff --git a/src/reaction.ts b/src/reaction.ts index e7c4d74b..7efba3cd 100644 --- a/src/reaction.ts +++ b/src/reaction.ts @@ -1,6 +1,6 @@ import StreamClient, { APIResponse } from './client'; import StreamFeed from './feed'; -import errors from './errors'; +import * as errors from './errors'; type TargetFeeds = (string | StreamFeed)[]; diff --git a/src/redirect_url.ts b/src/redirect_url.ts index dc87387a..f99f2a1e 100644 --- a/src/redirect_url.ts +++ b/src/redirect_url.ts @@ -2,7 +2,7 @@ import Url from 'url'; import qs from 'qs'; import StreamClient from './client'; -import errors from './errors'; +import * as errors from './errors'; import utils from './utils'; import signing from './signing'; diff --git a/src/utils.ts b/src/utils.ts index 94f51760..e5169f99 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -1,6 +1,6 @@ import FormData from 'form-data'; -import errors from './errors'; +import * as errors from './errors'; const validFeedSlugRe = /^[\w]+$/; const validUserIdRe = /^[\w-]+$/; diff --git a/test/integration/browser/client_test.js b/test/integration/browser/client_test.js index c2320d70..1400f8db 100644 --- a/test/integration/browser/client_test.js +++ b/test/integration/browser/client_test.js @@ -1,6 +1,6 @@ import expect from 'expect.js'; -import errors from '../../../src/errors'; +import * as errors from '../../../src/errors'; import { init, beforeEachFn } from '../utils/hooks'; function mockedFile(size = 1024, name = 'file.txt', mimeType = 'plain/txt') { diff --git a/test/integration/common/client_test.js b/test/integration/common/client_test.js index 904adf20..b7ca19c9 100644 --- a/test/integration/common/client_test.js +++ b/test/integration/common/client_test.js @@ -1,6 +1,6 @@ import expect from 'expect.js'; -import errors from '../../../src/errors'; +import * as errors from '../../../src/errors'; import config from '../utils/config'; import { init, beforeEachFn } from '../utils/hooks'; diff --git a/test/integration/common/faye_test.js b/test/integration/common/faye_test.js index fa1d80f6..d2a76fa9 100644 --- a/test/integration/common/faye_test.js +++ b/test/integration/common/faye_test.js @@ -1,7 +1,7 @@ import expect from 'expect.js'; import { connect } from '../../../src'; -import errors from '../../../src/errors'; +import * as errors from '../../../src/errors'; import { init, beforeEachFn } from '../utils/hooks'; describe('[INTEGRATION] Stream client (Faye)', function () { diff --git a/test/integration/node/client_test.js b/test/integration/node/client_test.js index 9ed7ceff..bb9afefe 100644 --- a/test/integration/node/client_test.js +++ b/test/integration/node/client_test.js @@ -1,7 +1,7 @@ import expect from 'expect.js'; import { connect } from '../../../src'; -import errors from '../../../src/errors'; +import * as errors from '../../../src/errors'; import { init, beforeEachFn } from '../utils/hooks'; diff --git a/test/unit/common/client_test.js b/test/unit/common/client_test.js index fae5515a..5e16ae47 100644 --- a/test/unit/common/client_test.js +++ b/test/unit/common/client_test.js @@ -2,7 +2,7 @@ import expect from 'expect.js'; import td from 'testdouble'; import utils from '../../../src/utils'; -import errors from '../../../src/errors'; +import * as errors from '../../../src/errors'; import config from '../utils/config'; import { init, beforeEachFn } from '../utils/hooks'; diff --git a/test/unit/common/feed_test.js b/test/unit/common/feed_test.js index 1afca98b..2faa314e 100644 --- a/test/unit/common/feed_test.js +++ b/test/unit/common/feed_test.js @@ -2,7 +2,7 @@ import expect from 'expect.js'; import td from 'testdouble'; import StreamFeed from '../../../src/feed'; -import errors from '../../../src/errors'; +import * as errors from '../../../src/errors'; import { init, beforeEachFn } from '../utils/hooks'; describe('[UNIT] Stream Feed (Common)', function () { diff --git a/test/unit/common/utils_test.js b/test/unit/common/utils_test.js index 43a3624d..e9aab3b7 100644 --- a/test/unit/common/utils_test.js +++ b/test/unit/common/utils_test.js @@ -1,6 +1,6 @@ import expect from 'expect.js'; -import errors from '../../../src/errors'; +import * as errors from '../../../src/errors'; import utils from '../../../src/utils'; import { init } from '../utils/hooks'; diff --git a/test/unit/node/collections_test.js b/test/unit/node/collections_test.js index 4e3b29e4..5b7775ed 100644 --- a/test/unit/node/collections_test.js +++ b/test/unit/node/collections_test.js @@ -2,7 +2,7 @@ import expect from 'expect.js'; import td from 'testdouble'; import StreamClient from '../../../src/client'; -import errors from '../../../src/errors'; +import * as errors from '../../../src/errors'; import { beforeEachFn } from '../utils/hooks'; describe('[UNIT] Stream Collections (node)', function () { diff --git a/test/unit/node/personalization_test.js b/test/unit/node/personalization_test.js index a74afd32..ad0c7341 100644 --- a/test/unit/node/personalization_test.js +++ b/test/unit/node/personalization_test.js @@ -2,7 +2,7 @@ import expect from 'expect.js'; import td from 'testdouble'; import StreamClient from '../../../src/client'; -import errors from '../../../src/errors'; +import * as errors from '../../../src/errors'; import { beforeEachFn } from '../utils/hooks'; describe('[UNIT] Stream Personalization (node)', function () { diff --git a/test/unit/node/redirect_test.js b/test/unit/node/redirect_test.js index a94e1d6e..72c7454b 100644 --- a/test/unit/node/redirect_test.js +++ b/test/unit/node/redirect_test.js @@ -5,7 +5,7 @@ import qs from 'qs'; import request from 'request'; import StreamClient from '../../../src/client'; -import errors from '../../../src/errors'; +import * as errors from '../../../src/errors'; import config from '../utils/config'; describe("[UNIT] Redirect URL's", function () { From 5246da203266ed9066ccd44fbea9414b6f8cc4b1 Mon Sep 17 00:00:00 2001 From: Amin Mahboubi Date: Tue, 28 Jul 2020 17:52:54 +0200 Subject: [PATCH 38/69] refactor connect into its own file --- src/connect.ts | 50 ++++++++++++++++++++++++++++++++++++++++++++++++++ src/index.ts | 50 ++------------------------------------------------ 2 files changed, 52 insertions(+), 48 deletions(-) create mode 100644 src/connect.ts diff --git a/src/connect.ts b/src/connect.ts new file mode 100644 index 00000000..95699b1c --- /dev/null +++ b/src/connect.ts @@ -0,0 +1,50 @@ +import StreamClient, { ClientOptions } from './client'; + +function connect( + apiKey: string, + apiSecret: string | null, + appId?: string, + options?: ClientOptions, +) { + /** + * Create StreamClient + * @method connect + * @param {string} apiKey API key + * @param {string} [apiSecret] API secret (only use this on the server) + * @param {string} [appId] Application identifier + * @param {object} [options] Additional options + * @param {string} [options.location] Datacenter location + * @return {StreamClient} StreamClient + * @example Basic usage + * stream.connect(apiKey, apiSecret); + * @example or if you want to be able to subscribe and listen + * stream.connect(apiKey, apiSecret, appId); + * @example or on Heroku + * stream.connect(streamURL); + * @example where streamURL looks like + * "https://thierry:pass@gestream.io/?app=1" + */ + if (process && process.env && process.env.STREAM_URL && !apiKey) { + const parts = /https:\/\/(\w+):(\w+)@([\w-]*).*\?app_id=(\d+)/.exec(process.env.STREAM_URL) || []; + apiKey = parts[1]; + apiSecret = parts[2]; + const location = parts[3]; + appId = parts[4]; + if (options === undefined) { + options = {}; + } + + if (location !== 'getstream' && location !== 'stream-io-api') { + options.location = location; + } + } + + return new StreamClient( + apiKey, + apiSecret, + appId, + options, + ); +} + +export { connect }; diff --git a/src/index.ts b/src/index.ts index 2c3ad089..5cd8b1b2 100644 --- a/src/index.ts +++ b/src/index.ts @@ -3,56 +3,10 @@ * @author Thierry Schellenbach * BSD License */ -import StreamClient, { ClientOptions } from './client'; +import StreamClient from './client'; import * as errors from './errors'; import signing from './signing'; - -function connect( - apiKey: string, - apiSecret: string | null, - appId?: string, - options?: ClientOptions, -): StreamClient { - /** - * Create StreamClient - * @method connect - * @param {string} apiKey API key - * @param {string} [apiSecret] API secret (only use this on the server) - * @param {string} [appId] Application identifier - * @param {object} [options] Additional options - * @param {string} [options.location] Datacenter location - * @return {StreamClient} StreamClient - * @example Basic usage - * stream.connect(apiKey, apiSecret); - * @example or if you want to be able to subscribe and listen - * stream.connect(apiKey, apiSecret, appId); - * @example or on Heroku - * stream.connect(streamURL); - * @example where streamURL looks like - * "https://thierry:pass@gestream.io/?app=1" - */ - if (process && process.env && process.env.STREAM_URL && !apiKey) { - const parts = /https:\/\/(\w+):(\w+)@([\w-]*).*\?app_id=(\d+)/.exec(process.env.STREAM_URL) || []; - apiKey = parts[1]; - apiSecret = parts[2]; - const location = parts[3]; - appId = parts[4]; - if (options === undefined) { - options = {}; - } - - if (location !== 'getstream' && location !== 'stream-io-api') { - options.location = location; - } - } - - return new StreamClient( - apiKey, - apiSecret, - appId, - options, - ); -} +import { connect } from './connect'; export { connect, errors, signing, StreamClient as Client }; From c259ee048e09e1c31505e171a977e9de63e1e42a Mon Sep 17 00:00:00 2001 From: Amin Mahboubi Date: Tue, 28 Jul 2020 22:52:45 +0200 Subject: [PATCH 39/69] remove some explicit return types --- src/batch_operations.ts | 6 ++-- src/client.ts | 72 +++++++++++++++++++---------------------- src/collections.ts | 35 +++++++++----------- src/feed.ts | 35 ++++++++------------ src/files.ts | 8 ++--- src/images.ts | 12 +++---- src/personalization.ts | 16 ++------- src/reaction.ts | 18 +++++------ src/redirect_url.ts | 7 +--- src/signing.ts | 12 +++---- src/user.ts | 16 ++++----- src/utils.ts | 10 +++--- 12 files changed, 108 insertions(+), 139 deletions(-) diff --git a/src/batch_operations.ts b/src/batch_operations.ts index b0cc3842..c613338f 100644 --- a/src/batch_operations.ts +++ b/src/batch_operations.ts @@ -14,7 +14,7 @@ export type UnfollowRelation = BaseFollowRelation & { keep_history?: boolean; }; -function addToMany(this: StreamClient, activity: ActivityType, feeds: string[]): Promise { +function addToMany(this: StreamClient, activity: ActivityType, feeds: string[]) { /** * Add one activity to many feeds * @method addToMany @@ -36,7 +36,7 @@ function addToMany(this: StreamClient, activity: ActivityType, fee }); } -function followMany(this: StreamClient, follows: FollowRelation[], activityCopyLimit?: number): Promise { +function followMany(this: StreamClient, follows: FollowRelation[], activityCopyLimit?: number) { /** * Follow multiple feeds with one API call * @method followMany @@ -59,7 +59,7 @@ function followMany(this: StreamClient, follows: FollowRelation[], activityCopyL }); } -function unfollowMany(this: StreamClient, unfollows: UnfollowRelation[]): Promise { +function unfollowMany(this: StreamClient, unfollows: UnfollowRelation[]) { /** * Unfollow multiple feeds with one API call * @method unfollowMany diff --git a/src/client.ts b/src/client.ts index 9e7f104a..4af6aea6 100644 --- a/src/client.ts +++ b/src/client.ts @@ -28,7 +28,7 @@ import StreamFeed, { // eslint-disable-next-line @typescript-eslint/no-var-requires const pkg = require('../package.json'); -export type APIResponse = Record & { duration?: string }; +export type APIResponse = { duration?: string }; export type FileUploadAPIResponse = APIResponse & { file: string }; @@ -253,7 +253,7 @@ class StreamClient< } } - _throwMissingApiSecret(): void | never { + _throwMissingApiSecret() { if (!this.usingApiSecret) { throw new errors.SiteError( 'This method can only be used server-side using your API Secret, use client = stream.connect(key, secret);', @@ -261,7 +261,7 @@ class StreamClient< } } - getPersonalizationToken(): string { + getPersonalizationToken() { if (this._personalizationToken) return this._personalizationToken; this._throwMissingApiSecret(); @@ -274,7 +274,7 @@ class StreamClient< return this._personalizationToken; } - getCollectionsToken(): string { + getCollectionsToken() { if (this._collectionsToken) return this._collectionsToken; this._throwMissingApiSecret(); @@ -286,7 +286,7 @@ class StreamClient< return this._collectionsToken; } - getAnalyticsToken(): string { + getAnalyticsToken() { this._throwMissingApiSecret(); return signing.JWTScopeToken(this.apiSecret as string, 'analytics', '*', { @@ -295,7 +295,7 @@ class StreamClient< }); } - getBaseUrl(serviceName?: string): string { + getBaseUrl(serviceName?: string) { if (!serviceName) serviceName = 'api'; if (this.options.urlOverride && this.options.urlOverride[serviceName]) return this.options.urlOverride[serviceName]; @@ -315,7 +315,7 @@ class StreamClient< return this.baseUrl; } - on(event: string, callback: HandlerCallback): void { + on(event: string, callback: HandlerCallback) { /** * Support for global event callbacks * This is useful for generic error and loading handling @@ -330,7 +330,7 @@ class StreamClient< this.handlers[event] = callback; } - off(key?: string): void { + off(key?: string) { /** * Remove one or more event handlers * @method off @@ -347,7 +347,7 @@ class StreamClient< } } - send(key: string, ...args: unknown[]): void { + send(key: string, ...args: unknown[]) { /** * Call the given handler with the arguments * @method send @@ -357,7 +357,7 @@ class StreamClient< if (this.handlers[key]) this.handlers[key].apply(this, args); } - userAgent(): string { + userAgent() { /** * Get the current user agent * @method userAgent @@ -367,7 +367,7 @@ class StreamClient< return `stream-javascript-client-${this.node ? 'node' : 'browser'}-${pkg.version}`; } - getReadOnlyToken(feedSlug: string, userId: string): string { + getReadOnlyToken(feedSlug: string, userId: string) { /** * Returns a token that allows only read operations * @@ -388,7 +388,7 @@ class StreamClient< }); } - getReadWriteToken(feedSlug: string, userId: string): string { + getReadWriteToken(feedSlug: string, userId: string) { /** * Returns a token that allows read and write operations * @@ -443,7 +443,7 @@ class StreamClient< ); } - enrichUrl(relativeUrl: string, serviceName?: string): string { + enrichUrl(relativeUrl: string, serviceName?: string) { /** * Combines the base url with version and the relative url * @method enrichUrl @@ -460,7 +460,7 @@ class StreamClient< withRecentReactions?: boolean; withReactionCounts?: boolean; withOwnChildren?: boolean; - }): void => { + }) => { // Shortcut options for reaction enrichment if (options?.reactions) { if (options.reactions.own != null) { @@ -487,7 +487,7 @@ class StreamClient< withReactionCounts?: boolean; withOwnChildren?: boolean; } = {}, - ): boolean { + ) { if (options.enrich) { const result = options.enrich; delete options.enrich; @@ -558,7 +558,7 @@ class StreamClient< }; } - getFayeClient(timeout = 10): Faye.Client { + getFayeClient(timeout = 10) { /** * Returns this client's current Faye client * @method getFayeClient @@ -606,7 +606,7 @@ class StreamClient< name?: string, contentType?: string, onUploadProgress?: OnUploadProgress, - ): Promise { + ) { const fd = utils.addFileToFormData(uri, name, contentType); return this.doAxiosRequest('POST', { url, @@ -621,7 +621,7 @@ class StreamClient< }); } - get(kwargs: AxiosConfig): Promise { + get(kwargs: AxiosConfig) { /** * Shorthand function for get request * @method get @@ -630,10 +630,10 @@ class StreamClient< * @param {object} kwargs * @return {Promise} Promise object */ - return this.doAxiosRequest('GET', kwargs); + return this.doAxiosRequest('GET', kwargs); } - post(kwargs: AxiosConfig): Promise { + post(kwargs: AxiosConfig) { /** * Shorthand function for post request * @method post @@ -642,10 +642,10 @@ class StreamClient< * @param {object} kwargs * @return {Promise} Promise object */ - return this.doAxiosRequest('POST', kwargs); + return this.doAxiosRequest('POST', kwargs); } - delete(kwargs: AxiosConfig): Promise { + delete(kwargs: AxiosConfig) { /** * Shorthand function for delete request * @method delete @@ -654,10 +654,10 @@ class StreamClient< * @param {object} kwargs * @return {Promise} Promise object */ - return this.doAxiosRequest('DELETE', kwargs); + return this.doAxiosRequest('DELETE', kwargs); } - put(kwargs: AxiosConfig): Promise { + put(kwargs: AxiosConfig) { /** * Shorthand function for put request * @method put @@ -666,14 +666,14 @@ class StreamClient< * @param {object} kwargs * @return {Promise} Promise object */ - return this.doAxiosRequest('PUT', kwargs); + return this.doAxiosRequest('PUT', kwargs); } /** * @param {string} userId * @param {object} extraData */ - createUserToken(userId: string, extraData = {}): string { + createUserToken(userId: string, extraData = {}) { this._throwMissingApiSecret(); return signing.JWTUserSessionToken(this.apiSecret as string, userId, extraData, { @@ -681,7 +681,7 @@ class StreamClient< }); } - updateActivities(activities: UpdateActivity[]): Promise { + updateActivities(activities: UpdateActivity[]) { /** * Updates all supplied activities on the getstream-io api * @since 3.1.0 @@ -706,7 +706,7 @@ class StreamClient< }); } - updateActivity(activity: UpdateActivity): Promise { + updateActivity(activity: UpdateActivity) { /** * Updates one activity on the getstream-io api * @since 3.1.0 @@ -726,7 +726,7 @@ class StreamClient< ids?: string[]; foreignIDTimes?: { foreignID: string; time: Date }[]; reactions?: Record; - }): Promise> { + }) { /** * Retrieve activities by ID or foreign ID and time * @since 3.19.0 @@ -778,7 +778,7 @@ class StreamClient< }); } - getOrCreateToken(): string { + getOrCreateToken() { if (!this._getOrCreateToken) { this._getOrCreateToken = this.usingApiSecret ? signing.JWTScopeToken(this.apiSecret as string, '*', '*', { feedId: '*' }) @@ -791,7 +791,7 @@ class StreamClient< return new StreamUser(this, userId, this.getOrCreateToken()); } - async setUser(data: UserType): Promise> { + async setUser(data: UserType) { if (this.usingApiSecret) { throw new errors.SiteError('This method can only be used client-side using a user token'); } @@ -805,7 +805,7 @@ class StreamClient< return user; } - og(url: string): Promise { + og(url: string) { return this.get({ url: 'og/', qs: { url }, @@ -813,9 +813,7 @@ class StreamClient< }); } - personalizedFeed( - options: GetFeedOptions = {}, - ): Promise> { + personalizedFeed(options: GetFeedOptions = {}) { return this.get< PersonalizationFeedAPIResponse >({ @@ -864,9 +862,7 @@ class StreamClient< return { ...activity, ...response }; } - activitiesPartialUpdate( - changes: ActivityPartialChanges[], - ): Promise[] }> { + activitiesPartialUpdate(changes: ActivityPartialChanges[]) { /** * Update multiple activities with partial operations. * @since v3.20.0 diff --git a/src/collections.ts b/src/collections.ts index 8cbbcee4..3a92c1f9 100644 --- a/src/collections.ts +++ b/src/collections.ts @@ -48,11 +48,11 @@ class CollectionEntry { this.data = data; } - ref(): string { + ref() { return `SO:${this.collection}:${this.id}`; } - async get(): Promise> { + async get() { /** * get item from collection and sync data * @method get @@ -66,7 +66,7 @@ class CollectionEntry { return response; } - async add(): Promise> { + async add() { /** * Add item to collection * @method add @@ -80,7 +80,7 @@ class CollectionEntry { return response; } - async update(): Promise> { + async update() { /** * Update item in the object storage * @method update @@ -95,7 +95,7 @@ class CollectionEntry { return response; } - async delete(): Promise { + async delete() { /** * Delete item from collection * @method delete @@ -126,16 +126,16 @@ export default class Collections { this.token = token; } - buildURL = (collection: string, itemId?: string): string => { + buildURL = (collection: string, itemId?: string) => { const url = `collections/${collection}/`; return itemId === undefined ? url : `${url}${itemId}/`; }; - entry(collection: string, itemId: string, itemData: CollectionType): CollectionEntry { + entry(collection: string, itemId: string, itemData: CollectionType) { return new CollectionEntry(this, collection, itemId, itemData); } - async get(collection: string, itemId: string): Promise> { + async get(collection: string, itemId: string) { /** * get item from collection * @method get @@ -155,7 +155,7 @@ export default class Collections { return entry; } - async add(collection: string, itemId: string, itemData: CollectionType): Promise> { + async add(collection: string, itemId: string, itemData: CollectionType) { /** * Add item to collection * @method add @@ -180,7 +180,7 @@ export default class Collections { return entry; } - async update(collection: string, entryId: string, data: CollectionType): Promise> { + async update(collection: string, entryId: string, data: CollectionType) { /** * Update entry in the collection * @method update @@ -203,7 +203,7 @@ export default class Collections { return entry; } - delete(collection: string, entryId: string): Promise { + delete(collection: string, entryId: string) { /** * Delete entry from collection * @method delete @@ -212,16 +212,13 @@ export default class Collections { * @return {Promise} Promise object * @example collection.delete("food", "cheese101") */ - return this.client.delete({ + return this.client.delete({ url: this.buildURL(collection, entryId), signature: this.token, }); } - upsert( - collection: string, - data: NewCollectionEntry | NewCollectionEntry[], - ): Promise> { + upsert(collection: string, data: NewCollectionEntry | NewCollectionEntry[]) { /** * Upsert one or more items within a collection. * @@ -244,7 +241,7 @@ export default class Collections { }); } - select(collection: string, ids: string | string[]): Promise> { + select(collection: string, ids: string | string[]) { /** * Select all objects with ids from the collection. * @@ -267,7 +264,7 @@ export default class Collections { }); } - deleteMany(collection: string, ids: string | string[]): Promise { + deleteMany(collection: string, ids: string | string[]) { /** * Remove all objects by id from the collection. * @@ -287,7 +284,7 @@ export default class Collections { ids: ids.map((id) => id.toString()).join(','), }; - return this.client.delete({ + return this.client.delete({ url: 'collections/', serviceName: 'api', qs: params, diff --git a/src/feed.ts b/src/feed.ts index 2c02bc63..7bd4227d 100644 --- a/src/feed.ts +++ b/src/feed.ts @@ -249,7 +249,7 @@ export default class StreamFeed< this.notificationChannel = `site-${this.client.appId}-feed-${this.feedTogether}`; } - addActivity(activity: NewActivity): Promise> { + addActivity(activity: NewActivity) { /** * Adds the given activity to the feed * @method addActivity @@ -270,7 +270,7 @@ export default class StreamFeed< }); } - removeActivity(activityId: string | { foreignId: string }): Promise { + removeActivity(activityId: string | { foreignId: string }) { /** * Removes the activity by activityId * @method removeActivity @@ -289,7 +289,7 @@ export default class StreamFeed< }); } - addActivities(activities: NewActivity[]): Promise[]> { + addActivities(activities: NewActivity[]) { /** * Adds the given activities to the feed * @method addActivities @@ -304,11 +304,7 @@ export default class StreamFeed< }); } - follow( - targetSlug: string, - targetUserId: string | { id: string }, - options: { limit?: number } = {}, - ): Promise { + follow(targetSlug: string, targetUserId: string | { id: string }, options: { limit?: number } = {}) { /** * Follows the given target feed * @method follow @@ -338,7 +334,7 @@ export default class StreamFeed< }); } - unfollow(targetSlug: string, targetUserId: string, options: { keepHistory?: boolean } = {}): Promise { + unfollow(targetSlug: string, targetUserId: string, options: { keepHistory?: boolean } = {}) { /** * Unfollow the given feed * @method unfollow @@ -364,7 +360,7 @@ export default class StreamFeed< }); } - following(options: GetFollowOptions = {}): Promise { + following(options: GetFollowOptions = {}) { /** * List which feeds this feed is following * @method following @@ -384,7 +380,7 @@ export default class StreamFeed< }); } - followers(options: GetFollowOptions = {}): Promise { + followers(options: GetFollowOptions = {}) { /** * List the followers of this feed * @method followers @@ -405,9 +401,7 @@ export default class StreamFeed< }); } - get( - options: GetFeedOptions & NotificationFeedOptions = {}, - ): Promise> { + get(options: GetFeedOptions & NotificationFeedOptions = {}) { /** * Reads the feed * @method get @@ -439,10 +433,7 @@ export default class StreamFeed< }); } - getActivityDetail( - activityId: string, - options: EnrichOptions, - ): Promise> { + getActivityDetail(activityId: string, options: EnrichOptions) { /** * Retrieves one activity from a feed and adds enrichment * @method getActivityDetail @@ -463,7 +454,7 @@ export default class StreamFeed< }); } - getFayeClient(): Faye.Client { + getFayeClient() { /** * Returns the current faye client object * @method getFayeClient @@ -474,7 +465,7 @@ export default class StreamFeed< return this.client.getFayeClient(); } - subscribe(callback: Faye.Callback): Faye.Subscription { + subscribe(callback: Faye.Callback) { /** * Subscribes to any changes in the feed, return a promise * @method subscribe @@ -502,7 +493,7 @@ export default class StreamFeed< return subscription; } - unsubscribe(): void { + unsubscribe() { /** * Cancel updates created via feed.subscribe() * @return void @@ -520,7 +511,7 @@ export default class StreamFeed< newTargets?: string[], addedTargets?: string[], removedTargets?: string[], - ): Promise & { added?: string[]; removed?: string[] }> { + ) { /** * Updates an activity's "to" fields * @since 3.10.0 diff --git a/src/files.ts b/src/files.ts index f8d41d46..43df7b99 100644 --- a/src/files.ts +++ b/src/files.ts @@ -1,4 +1,4 @@ -import StreamClient, { APIResponse, FileUploadAPIResponse, OnUploadProgress } from './client'; +import StreamClient, { OnUploadProgress } from './client'; export default class StreamFileStore { client: StreamClient; @@ -16,7 +16,7 @@ export default class StreamFileStore { name?: string, contentType?: string, onUploadProgress?: OnUploadProgress, - ): Promise { + ) { /** * upload a File instance or a readable stream of data * @param {File|Buffer|string} uri - File object or Buffer or URI @@ -28,8 +28,8 @@ export default class StreamFileStore { return this.client.upload('files/', uri, name, contentType, onUploadProgress); } - delete(uri: string): Promise { - return this.client.delete({ + delete(uri: string) { + return this.client.delete({ url: `files/`, qs: { url: uri }, signature: this.token, diff --git a/src/images.ts b/src/images.ts index 853ef9c7..07ab5913 100644 --- a/src/images.ts +++ b/src/images.ts @@ -1,4 +1,4 @@ -import StreamClient, { APIResponse, FileUploadAPIResponse, OnUploadProgress } from './client'; +import StreamClient, { FileUploadAPIResponse, OnUploadProgress } from './client'; export type ImageProcessOptions = { w?: number | string; @@ -24,7 +24,7 @@ export default class StreamImageStore { name?: string, contentType?: string, onUploadProgress?: OnUploadProgress, - ): Promise { + ) { /** * upload an Image File instance or a readable stream of data * @param {File|Buffer|string} uri - File object or Buffer or URI @@ -36,15 +36,15 @@ export default class StreamImageStore { return this.client.upload('images/', uri, name, contentType, onUploadProgress); } - delete(uri: string): Promise { - return this.client.delete({ + delete(uri: string) { + return this.client.delete({ url: `images/`, qs: { url: uri }, signature: this.token, }); } - process(uri: string, options: ImageProcessOptions): Promise { + process(uri: string, options: ImageProcessOptions) { const params = Object.assign(options, { url: uri }); if (Array.isArray(params.crop)) { params.crop = params.crop.join(','); @@ -62,7 +62,7 @@ export default class StreamImageStore { w: number | string, h: number | string, { crop, resize } = { crop: 'center', resize: 'clip' }, - ): Promise { + ) { return this.process(uri, { w, h, crop, resize }); } } diff --git a/src/personalization.ts b/src/personalization.ts index 5e8bba31..300556f5 100644 --- a/src/personalization.ts +++ b/src/personalization.ts @@ -29,10 +29,7 @@ export default class Personalization { this.client = client; } - get( - resource: string, - options: Record & { token?: string } = {}, - ): Promise> { + get(resource: string, options: Record & { token?: string } = {}) { /** * Get personalized activities for this feed * @@ -51,11 +48,7 @@ export default class Personalization { }); } - post( - resource: string, - options: Record = {}, - data: Record = {}, - ): Promise> { + post(resource: string, options: Record = {}, data: Record = {}) { /** * Post data to personalization endpoint * @@ -76,10 +69,7 @@ export default class Personalization { }); } - delete( - resource: string, - options: Record = {}, - ): Promise> { + delete(resource: string, options: Record = {}) { /** * Delete metadata or activities * diff --git a/src/reaction.ts b/src/reaction.ts index 7efba3cd..e6f1ba26 100644 --- a/src/reaction.ts +++ b/src/reaction.ts @@ -69,7 +69,7 @@ export default class StreamReaction { + buildURL = (...args: string[]) => { return `${['reaction', ...args].join('/')}/`; }; @@ -92,7 +92,7 @@ export default class StreamReaction { + _convertTargetFeeds = (targetFeeds: TargetFeeds = []) => { return targetFeeds.map((elem: TargetFeed) => (typeof elem === 'string' ? elem : (elem as StreamFeed).id)); }; @@ -106,7 +106,7 @@ export default class StreamReaction> { + ) { /** * add reaction * @method add @@ -150,7 +150,7 @@ export default class StreamReaction> { + ) { /** * add reaction * @method add @@ -180,7 +180,7 @@ export default class StreamReaction> { + get(id: string) { /** * get reaction * @method add @@ -206,7 +206,7 @@ export default class StreamReaction> { + }) { /** * retrieve reactions by activity_id, user_id or reaction_id (to paginate children reactions), pagination can be done using id_lt, id_lte, id_gt and id_gte parameters * id_lt and id_lte return reactions order by creation descending starting from the reaction with the ID provided, when id_lte is used @@ -254,7 +254,7 @@ export default class StreamReaction> { + ) { /** * update reaction * @method add @@ -280,7 +280,7 @@ export default class StreamReaction { + delete(id: string) { /** * delete reaction * @method delete @@ -289,7 +289,7 @@ export default class StreamReaction({ + return this.client.delete({ url: this.buildURL(id), signature: this.token, }); diff --git a/src/redirect_url.ts b/src/redirect_url.ts index f99f2a1e..b4740c42 100644 --- a/src/redirect_url.ts +++ b/src/redirect_url.ts @@ -7,12 +7,7 @@ import utils from './utils'; import signing from './signing'; // TODO: userId is skipped here -export default function createRedirectUrl( - this: StreamClient, - targetUrl: string, - userId: string, - events: unknown[], -): string { +export default function createRedirectUrl(this: StreamClient, targetUrl: string, userId: string, events: unknown[]) { /** * Creates a redirect url for tracking the given events in the context of * an email using Stream's analytics platform. Learn more at diff --git a/src/signing.ts b/src/signing.ts index 5f4d0dde..72b34fbe 100644 --- a/src/signing.ts +++ b/src/signing.ts @@ -3,7 +3,7 @@ import Base64 from 'Base64'; const JWS_REGEX = /^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/; -function safeJsonParse(thing: unknown): unknown { +function safeJsonParse(thing: T | string): T | undefined { if (typeof thing === 'object') return thing; try { return JSON.parse(thing as string); @@ -12,7 +12,7 @@ function safeJsonParse(thing: unknown): unknown { } } -function padString(string: string): string { +function padString(string: string) { const segmentLength = 4; const diff = string.length % segmentLength; if (!diff) return string; @@ -23,7 +23,7 @@ function padString(string: string): string { return string; } -function toBase64(base64UrlString: string): string { +function toBase64(base64UrlString: string) { return padString(base64UrlString) .replace(/\-/g, '+') // eslint-disable-line no-useless-escape .replace(/_/g, '/'); @@ -40,7 +40,7 @@ function decodeBase64Url(base64UrlString: string) { } } -function headerFromJWS(jwsSig: string): unknown { +function headerFromJWS(jwsSig: string) { const encodedHeader = jwsSig.split('.', 1)[0]; return safeJsonParse(decodeBase64Url(encodedHeader)); } @@ -77,7 +77,7 @@ function JWTUserSessionToken( userId: string, extraData: Record = {}, jwtOptions: jwt.SignOptions = {}, -): string { +) { /** * Creates the JWT token that can be used for a UserSession * @method JWTUserSessionToken @@ -99,7 +99,7 @@ function JWTUserSessionToken( return jwt.sign(payload, apiSecret, opts); } -function isJWTSignature(signature: string | null): boolean { +function isJWTSignature(signature: string | null) { /** * check if token is a valid JWT token * @method isJWTSignature diff --git a/src/user.ts b/src/user.ts index 5956ce1f..34c95298 100644 --- a/src/user.ts +++ b/src/user.ts @@ -35,18 +35,18 @@ export default class StreamUser { this.url = `user/${this.id}/`; } - ref(): string { + ref() { return `SU:${this.id}`; } - delete(): Promise { - return this.client.delete({ + delete() { + return this.client.delete({ url: this.url, signature: this.token, }); } - async get(options: { with_follow_counts?: boolean }): Promise> { + async get(options: { with_follow_counts?: boolean }) { const response = await this.client.get>({ url: this.url, signature: this.token, @@ -59,7 +59,7 @@ export default class StreamUser { return this; } - async create(data: UserType, options: { get_or_create?: boolean }): Promise> { + async create(data: UserType, options: { get_or_create?: boolean }) { const response = await this.client.post>({ url: 'user/', body: { @@ -76,7 +76,7 @@ export default class StreamUser { return this; } - async update(data?: Record): Promise> { + async update(data?: Partial) { const response = await this.client.put>({ url: this.url, body: { @@ -91,11 +91,11 @@ export default class StreamUser { return this; } - getOrCreate(data: UserType): Promise> { + getOrCreate(data: UserType) { return this.create(data, { get_or_create: true }); } - profile(): Promise> { + profile() { return this.get({ with_follow_counts: true }); } } diff --git a/src/utils.ts b/src/utils.ts index e5169f99..6495fc98 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -5,7 +5,7 @@ import * as errors from './errors'; const validFeedSlugRe = /^[\w]+$/; const validUserIdRe = /^[\w-]+$/; -function validateFeedSlug(feedSlug: string): string { +function validateFeedSlug(feedSlug: string) { /* * Validate that the feedSlug matches \w */ @@ -16,7 +16,7 @@ function validateFeedSlug(feedSlug: string): string { return feedSlug; } -function validateUserId(userId: string): string { +function validateUserId(userId: string) { /* * Validate the userId matches \w */ @@ -27,7 +27,7 @@ function validateUserId(userId: string): string { return userId; } -function rfc3986(str: string): string { +function rfc3986(str: string) { return str.replace(/[!'()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`); } @@ -35,7 +35,7 @@ function isReadableStream(obj: NodeJS.ReadStream): obj is NodeJS.ReadStream { return obj !== null && typeof obj === 'object' && typeof (obj as NodeJS.ReadStream)._read === 'function'; } -function validateFeedId(feedId: string): string { +function validateFeedId(feedId: string) { /* * Validate that the feedId matches the spec user:1 */ @@ -50,7 +50,7 @@ function validateFeedId(feedId: string): string { return feedId; } -function addFileToFormData(uri: string | File | NodeJS.ReadStream, name?: string, contentType?: string): FormData { +function addFileToFormData(uri: string | File | NodeJS.ReadStream, name?: string, contentType?: string) { const data = new FormData(); let fileField: File | NodeJS.ReadStream | { uri: string; name: string; type?: string }; From 6f9f65582366e8e5072b12c6112601c5b0760568 Mon Sep 17 00:00:00 2001 From: Amin Mahboubi Date: Tue, 28 Jul 2020 22:54:43 +0200 Subject: [PATCH 40/69] rename moduls.d.ts to .ts file to get included in emitted types --- src/{modules.d.ts => modules_types.ts} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename src/{modules.d.ts => modules_types.ts} (100%) diff --git a/src/modules.d.ts b/src/modules_types.ts similarity index 100% rename from src/modules.d.ts rename to src/modules_types.ts From 762318076283941bcb616d1b2ac591e6da6d18e8 Mon Sep 17 00:00:00 2001 From: Amin Mahboubi Date: Wed, 29 Jul 2020 10:37:58 +0200 Subject: [PATCH 41/69] export internal types at root level --- src/client.ts | 10 ++++------ src/collections.ts | 8 ++++---- src/connect.ts | 4 +--- src/feed.ts | 32 ++++++++++++++++---------------- src/index.ts | 13 +++++++++++++ src/personalization.ts | 2 +- src/reaction.ts | 12 ++++++------ src/user.ts | 2 +- 8 files changed, 46 insertions(+), 37 deletions(-) diff --git a/src/client.ts b/src/client.ts index 4af6aea6..a2a8e511 100644 --- a/src/client.ts +++ b/src/client.ts @@ -71,7 +71,7 @@ type OGVideo = OGResource & { height?: number; }; -type OGAPIResponse = APIResponse & { +export type OGAPIResponse = APIResponse & { title?: string; type?: string; url?: string; @@ -96,9 +96,9 @@ type AxiosConfig = { axiosOptions?: axios.AxiosRequestConfig; }; -type HandlerCallback = (...args: unknown[]) => unknown; +export type HandlerCallback = (...args: unknown[]) => unknown; -type ActivityPartialChanges = { +export type ActivityPartialChanges = { id?: string; foreignID?: string; time?: Date; @@ -110,7 +110,7 @@ type ActivityPartialChanges = { * Client to connect to Stream api * @class StreamClient */ -class StreamClient< +export default class StreamClient< UserType = unknown, ActivityType = unknown, CollectionType = unknown, @@ -955,5 +955,3 @@ class StreamClient< }); } } - -export default StreamClient; diff --git a/src/collections.ts b/src/collections.ts index 3a92c1f9..361d74a7 100644 --- a/src/collections.ts +++ b/src/collections.ts @@ -13,19 +13,19 @@ export type CollectionResponse = BaseCollection updated_at: Date; }; -type NewCollectionEntry = BaseCollection & { +export type NewCollectionEntry = BaseCollection & { user_id?: string; }; -type CollectionAPIResponse = APIResponse & CollectionResponse; +export type CollectionAPIResponse = APIResponse & CollectionResponse; -type SelectCollectionAPIResponse = APIResponse & { +export type SelectCollectionAPIResponse = APIResponse & { response: { data: CollectionResponse[]; }; }; -type UpsertCollectionAPIResponse = APIResponse & { +export type UpsertCollectionAPIResponse = APIResponse & { data: { [key: string]: { id: string; diff --git a/src/connect.ts b/src/connect.ts index 95699b1c..c7979e80 100644 --- a/src/connect.ts +++ b/src/connect.ts @@ -1,6 +1,6 @@ import StreamClient, { ClientOptions } from './client'; -function connect( +export function connect( apiKey: string, apiSecret: string | null, appId?: string, @@ -46,5 +46,3 @@ function connect = ActivityType & { target?: string; }; -type NewActivity = BaseActivity & { time?: string; foreign_id?: string }; +export type NewActivity = BaseActivity & { time?: string; foreign_id?: string }; export type UpdateActivity = BaseActivity & { time: string; foreign_id: string }; @@ -72,12 +72,12 @@ export type Activity = BaseActivity & { analytics?: Record; }; -type ReactionsRecords = Record< +export type ReactionsRecords = Record< string, EnrichedReaction[] >; -type EnrichedActivity = Activity< +export type EnrichedActivity = Activity< ActivityType > & { actor: UserType | string; @@ -98,15 +98,15 @@ type EnrichedActivity; }; -type FlatActivity = Activity; +export type FlatActivity = Activity; -type FlatActivityEnriched = EnrichedActivity< +export type FlatActivityEnriched< UserType, ActivityType, CollectionType, ReactionType, ChildReactionType ->; +> = EnrichedActivity; type BaseAggregatedActivity = { id: string; @@ -119,11 +119,11 @@ type BaseAggregatedActivity = { score?: number; }; -type AggregatedActivity = BaseAggregatedActivity & { +export type AggregatedActivity = BaseAggregatedActivity & { activities: Activity[]; }; -type AggregatedActivityEnriched< +export type AggregatedActivityEnriched< UserType, ActivityType, CollectionType, @@ -134,9 +134,9 @@ type AggregatedActivityEnriched< }; type BaseNotificationActivity = { is_read: boolean; is_seen: boolean }; -type NotificationActivity = AggregatedActivity & BaseNotificationActivity; +export type NotificationActivity = AggregatedActivity & BaseNotificationActivity; -type NotificationActivityEnriched< +export type NotificationActivityEnriched< UserType, ActivityType, CollectionType, @@ -145,7 +145,7 @@ type NotificationActivityEnriched< > = BaseNotificationActivity & AggregatedActivityEnriched; -type FeedAPIResponse = APIResponse & { +export type FeedAPIResponse = APIResponse & { next: string; results: | FlatActivity[] diff --git a/src/index.ts b/src/index.ts index 5cd8b1b2..c1820904 100644 --- a/src/index.ts +++ b/src/index.ts @@ -12,3 +12,16 @@ export { connect, errors, signing, StreamClient as Client }; /* deprecated default export */ export default { connect, errors, signing, Client: StreamClient }; + +/* + * typescript does not export the default exports here + * useful for exposing exported internal types + */ +export * from './client'; +export * from './collections'; +export * from './feed'; +export * from './files'; +export * from './images'; +export * from './personalization'; +export * from './reaction'; +export * from './user'; diff --git a/src/personalization.ts b/src/personalization.ts index 300556f5..5f5d5ad8 100644 --- a/src/personalization.ts +++ b/src/personalization.ts @@ -6,7 +6,7 @@ import StreamClient, { APIResponse } from './client'; * @class Personalization */ -type PersonalizationAPIResponse = APIResponse & { +export type PersonalizationAPIResponse = APIResponse & { app_id: string; results: PersonalizationType[]; next: string; diff --git a/src/reaction.ts b/src/reaction.ts index e6f1ba26..5b4330ac 100644 --- a/src/reaction.ts +++ b/src/reaction.ts @@ -2,11 +2,11 @@ import StreamClient, { APIResponse } from './client'; import StreamFeed from './feed'; import * as errors from './errors'; -type TargetFeeds = (string | StreamFeed)[]; +export type TargetFeeds = (string | StreamFeed)[]; -type TargetFeed = string | StreamFeed; +export type TargetFeed = string | StreamFeed; -type TargetFeedsExtraData = Record; +export type TargetFeedsExtraData = Record; type ReactionBody = { id?: string; // api will generate an id if it's missing @@ -32,7 +32,7 @@ export type Reaction = { parent: string; }; -type ReactionAPIResponse = APIResponse & Reaction; +export type ReactionAPIResponse = APIResponse & Reaction; export type EnrichedReaction = Reaction & { children_counts: Record; @@ -41,10 +41,10 @@ export type EnrichedReaction = Reacti user?: UserType; }; -type EnrichedReactionAPIResponse = APIResponse & +export type EnrichedReactionAPIResponse = APIResponse & EnrichedReaction; -type ReactionFilterAPIResponse = APIResponse & { +export type ReactionFilterAPIResponse = APIResponse & { activity?: ActivityType; next: string; results: diff --git a/src/user.ts b/src/user.ts index 34c95298..c879f517 100644 --- a/src/user.ts +++ b/src/user.ts @@ -1,6 +1,6 @@ import StreamClient, { APIResponse } from './client'; -type UserAPIResponse = APIResponse & { +export type UserAPIResponse = APIResponse & { id: string; data: UserType; created_at: Date; From b70d4fcd290ac1538dba4d9231c4c2b2397eaa61 Mon Sep 17 00:00:00 2001 From: Amin Mahboubi Date: Wed, 29 Jul 2020 10:39:56 +0200 Subject: [PATCH 42/69] ditch single .d.ts file in favor of one .d.ts file per each .ts file --- package.json | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/package.json b/package.json index 296e715f..10b25ca6 100644 --- a/package.json +++ b/package.json @@ -13,9 +13,9 @@ "license": "BSD-3-Clause", "version": "5.0.2", "scripts": { - "transpile": "rm -rf lib && babel src --out-dir lib --extensions '.ts'", - "types": "tsc --outFile lib/index --emitDeclarationOnly", - "build": "yarn transpile && yarn types", + "transpile": "babel src --out-dir lib --extensions '.ts'", + "types": "tsc --emitDeclarationOnly", + "build": "rm -rf lib && yarn transpile && yarn types", "eslint": "eslint '**/*.{js,ts}' --max-warnings 0", "prettier": "prettier --list-different '**/*.{js,ts}'", "lint": "yarn run prettier && yarn run eslint", From 48363d91c5399ee91f6ec0779b7915bc473a7445 Mon Sep 17 00:00:00 2001 From: Amin Mahboubi Date: Wed, 29 Jul 2020 10:40:57 +0200 Subject: [PATCH 43/69] bundle src folder for better ts source map --- package.json | 1 + 1 file changed, 1 insertion(+) diff --git a/package.json b/package.json index 10b25ca6..47154eae 100644 --- a/package.json +++ b/package.json @@ -119,6 +119,7 @@ "url": "git://github.com/GetStream/stream-js.git" }, "files": [ + "src", "dist", "lib" ], From 464c03513e107f7305072ea8e1f5560e5442a643 Mon Sep 17 00:00:00 2001 From: Amin Mahboubi Date: Wed, 29 Jul 2020 14:00:01 +0200 Subject: [PATCH 44/69] default UnknownType --- src/client.ts | 14 ++++++++------ src/connect.ts | 16 +++++++++------- 2 files changed, 17 insertions(+), 13 deletions(-) diff --git a/src/client.ts b/src/client.ts index a2a8e511..db4f6ca6 100644 --- a/src/client.ts +++ b/src/client.ts @@ -28,6 +28,8 @@ import StreamFeed, { // eslint-disable-next-line @typescript-eslint/no-var-requires const pkg = require('../package.json'); +export type UnknownType = Record; + export type APIResponse = { duration?: string }; export type FileUploadAPIResponse = APIResponse & { file: string }; @@ -111,12 +113,12 @@ export type ActivityPartialChanges = { * @class StreamClient */ export default class StreamClient< - UserType = unknown, - ActivityType = unknown, - CollectionType = unknown, - ReactionType = unknown, - ChildReactionType = unknown, - PersonalizationType = unknown + UserType extends UnknownType = UnknownType, + ActivityType extends UnknownType = UnknownType, + CollectionType extends UnknownType = UnknownType, + ReactionType extends UnknownType = UnknownType, + ChildReactionType extends UnknownType = UnknownType, + PersonalizationType extends UnknownType = UnknownType > { baseUrl: string; baseAnalyticsUrl: string; diff --git a/src/connect.ts b/src/connect.ts index c7979e80..38ed753a 100644 --- a/src/connect.ts +++ b/src/connect.ts @@ -1,11 +1,13 @@ -import StreamClient, { ClientOptions } from './client'; +import StreamClient, { UnknownType, ClientOptions } from './client'; -export function connect( - apiKey: string, - apiSecret: string | null, - appId?: string, - options?: ClientOptions, -) { +export function connect< + UserType extends UnknownType = UnknownType, + ActivityType extends UnknownType = UnknownType, + CollectionType extends UnknownType = UnknownType, + ReactionType extends UnknownType = UnknownType, + ChildReactionType extends UnknownType = UnknownType, + PersonalizationType extends UnknownType = UnknownType +>(apiKey: string, apiSecret: string | null, appId?: string, options?: ClientOptions) { /** * Create StreamClient * @method connect From 2f5199ece80b66c7281982f73e3bec7e03dde970 Mon Sep 17 00:00:00 2001 From: Amin Mahboubi Date: Wed, 29 Jul 2020 14:01:11 +0200 Subject: [PATCH 45/69] remove unused @ts-expect-error --- src/client.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/client.ts b/src/client.ts index db4f6ca6..191088ff 100644 --- a/src/client.ts +++ b/src/client.ts @@ -799,8 +799,7 @@ export default class StreamClient< } const body = { ...data }; - // @ts-expect-error - delete body?.id; + delete body.id; const user = await (this.currentUser as StreamUser).getOrCreate(body); this.currentUser = user; From c8a0727ffb35e1103a129be8f71e52709fd7ca5b Mon Sep 17 00:00:00 2001 From: Amin Mahboubi Date: Wed, 29 Jul 2020 14:43:10 +0200 Subject: [PATCH 46/69] change faye subscription return type to Promise --- src/client.ts | 5 ++++- src/feed.ts | 2 +- src/modules_types.ts | 2 +- 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/src/client.ts b/src/client.ts index 191088ff..b3c4a38a 100644 --- a/src/client.ts +++ b/src/client.ts @@ -142,7 +142,10 @@ export default class StreamClient< nodeOptions?: { httpAgent: http.Agent; httpsAgent: https.Agent }; request: axios.AxiosInstance; - subscriptions: Record; + subscriptions: Record< + string, + { userId: string; token: string; fayeSubscription: Faye.Subscription | Promise } + >; handlers: Record; currentUser?: StreamUser; diff --git a/src/feed.ts b/src/feed.ts index 17b2b6c4..05a9c67b 100644 --- a/src/feed.ts +++ b/src/feed.ts @@ -501,7 +501,7 @@ export default class StreamFeed< const streamSubscription = this.client.subscriptions[`/${this.notificationChannel}`]; if (streamSubscription) { delete this.client.subscriptions[`/${this.notificationChannel}`]; - streamSubscription.fayeSubscription.cancel(); + (streamSubscription.fayeSubscription as Faye.Subscription).cancel(); } } diff --git a/src/modules_types.ts b/src/modules_types.ts index dd50e6f7..06d6308f 100644 --- a/src/modules_types.ts +++ b/src/modules_types.ts @@ -21,7 +21,7 @@ declare module 'faye' { addExtension(extension: Middleware): void; - subscribe(channel: string, callback: Callback): Subscription; + subscribe(channel: string, callback: Callback): Promise; } } From 4c4e359724858cb85f266591a1c7b849850ffdab Mon Sep 17 00:00:00 2001 From: Amin Mahboubi Date: Wed, 29 Jul 2020 15:07:12 +0200 Subject: [PATCH 47/69] update outdated jsdocs --- src/batch_operations.ts | 16 +++++----- src/client.ts | 65 ++++++++++++++++++++------------------ src/collections.ts | 42 +++++++++++++------------ src/connect.ts | 8 +++-- src/feed.ts | 69 +++++++++++++++++++++-------------------- src/files.ts | 4 +-- src/images.ts | 4 +-- src/personalization.ts | 6 ++-- src/reaction.ts | 45 ++++++++++++++++----------- src/signing.ts | 1 + src/user.ts | 2 +- 11 files changed, 143 insertions(+), 119 deletions(-) diff --git a/src/batch_operations.ts b/src/batch_operations.ts index c613338f..287f75b6 100644 --- a/src/batch_operations.ts +++ b/src/batch_operations.ts @@ -20,9 +20,9 @@ function addToMany(this: StreamClient, activity: ActivityType, fee * @method addToMany * @memberof StreamClient.prototype * @since 2.3.0 - * @param {object} activity The activity to add - * @param {Array} feeds Array of objects describing the feeds to add to - * @return {Promise} Promise object + * @param {ActivityType} activity The activity to add + * @param {string[]} feeds Array of feed id in form of `${feedSlug}:${feedId}` + * @return {Promise} */ this._throwMissingApiSecret(); @@ -42,9 +42,9 @@ function followMany(this: StreamClient, follows: FollowRelation[], activityCopyL * @method followMany * @memberof StreamClient.prototype * @since 2.3.0 - * @param {Array} follows The follow relations to create - * @param {number} [activityCopyLimit] How many activities should be copied from the target feed - * @return {Promise} Promise object + * @param {FollowRelation[]} follows The follow relations to create: [{ source: string; target: string }] + * @param {number} [activityCopyLimit] How many activities should be copied from the target feed + * @return {Promise} */ this._throwMissingApiSecret(); @@ -65,8 +65,8 @@ function unfollowMany(this: StreamClient, unfollows: UnfollowRelation[]) { * @method unfollowMany * @memberof StreamClient.prototype * @since 3.15.0 - * @param {Array} unfollows The follow relations to remove - * @return {Promise} Promise object + * @param {UnfollowRelation[]} unfollows The follow relations to remove: [{ source: string; target: string }] + * @return {Promise} */ this._throwMissingApiSecret(); diff --git a/src/client.ts b/src/client.ts index b3c4a38a..4fcbc464 100644 --- a/src/client.ts +++ b/src/client.ts @@ -172,9 +172,12 @@ export default class StreamClient< * @param {string} apiKey - the api key * @param {string} [apiSecret] - the api secret * @param {string} [appId] - id of the app - * @param {object} [options] - additional options + * @param {ClientOptions} [options] - additional options * @param {string} [options.location] - which data center to use * @param {boolean} [options.expireTokens=false] - whether to use a JWT timestamp field (i.e. iat) + * @param {string} [options.version] - advanced usage, custom api version + * @param {boolean} [options.keepAlive] - axios keepAlive, default to true + * @param {number} [options.timeout] - axios timeout in Ms, default to 10s * @example initialize is not directly called by via stream.connect, ie: * stream.connect(apiKey, apiSecret) * @example secret is optional and only used in server side mode @@ -381,8 +384,7 @@ export default class StreamClient< * @param {string} feedSlug - The feed slug to get a read only token for * @param {string} userId - The user identifier * @return {string} token - * @example - * client.getReadOnlyToken('user', '1'); + * @example client.getReadOnlyToken('user', '1'); */ utils.validateFeedSlug(feedSlug); utils.validateUserId(userId); @@ -402,8 +404,7 @@ export default class StreamClient< * @param {string} feedSlug - The feed slug to get a read only token for * @param {string} userId - The user identifier * @return {string} token - * @example - * client.getReadWriteToken('user', '1'); + * @example client.getReadWriteToken('user', '1'); */ utils.validateFeedSlug(feedSlug); utils.validateUserId(userId); @@ -424,11 +425,10 @@ export default class StreamClient< * @method feed * @memberof StreamClient.prototype * @param {string} feedSlug - The feed slug - * @param {string} userId - The user identifier - * @param {string} [token] - The token (DEPRECATED), used for internal testing + * @param {string} [userId] - The user identifier + * @param {string} [token] - The token * @return {StreamFeed} - * @example - * client.feed('user', '1'); + * @example client.feed('user', '1'); */ if (userId instanceof StreamUser) userId = userId.id; @@ -455,6 +455,8 @@ export default class StreamClient< * @memberof StreamClient.prototype * @private * @param {string} relativeUrl + * @param {string} [serviceName] + * @return {string} */ return `${this.getBaseUrl(serviceName)}${this.version}/${relativeUrl}`; } @@ -512,9 +514,10 @@ export default class StreamClient< /** * Adds the API key and the signature * @method enrichKwargs - * @memberof StreamClient.prototype - * @param {object} kwargs * @private + * @memberof StreamClient.prototype + * @param {AxiosConfig} kwargs + * @return {axios.AxiosRequestConfig} */ const isJWT = signing.isJWTSignature(signature); @@ -543,7 +546,7 @@ export default class StreamClient< * @method getFayeAuthorization * @memberof StreamClient.prototype * @private - * @return {object} Faye authorization middleware + * @return {Faye.Middleware} Faye authorization middleware */ return { incoming: (message: Faye.Message, callback: Faye.Callback) => callback(message), @@ -569,7 +572,8 @@ export default class StreamClient< * @method getFayeClient * @memberof StreamClient.prototype * @private - * @return {object} Faye client + * @param {number} timeout + * @return {Faye.Client} Faye client */ if (this.fayeClient === null) { this.fayeClient = new Faye.Client(this.fayeUrl, { timeout }); @@ -632,7 +636,7 @@ export default class StreamClient< * @method get * @memberof StreamClient.prototype * @private - * @param {object} kwargs + * @param {AxiosConfig} kwargs * @return {Promise} Promise object */ return this.doAxiosRequest('GET', kwargs); @@ -644,7 +648,7 @@ export default class StreamClient< * @method post * @memberof StreamClient.prototype * @private - * @param {object} kwargs + * @param {AxiosConfig} kwargs * @return {Promise} Promise object */ return this.doAxiosRequest('POST', kwargs); @@ -656,7 +660,7 @@ export default class StreamClient< * @method delete * @memberof StreamClient.prototype * @private - * @param {object} kwargs + * @param {AxiosConfig} kwargs * @return {Promise} Promise object */ return this.doAxiosRequest('DELETE', kwargs); @@ -668,17 +672,18 @@ export default class StreamClient< * @method put * @memberof StreamClient.prototype * @private - * @param {object} kwargs + * @param {AxiosConfig} kwargs * @return {Promise} Promise object */ return this.doAxiosRequest('PUT', kwargs); } - /** - * @param {string} userId - * @param {object} extraData - */ createUserToken(userId: string, extraData = {}) { + /** + * @param {string} userId + * @param {object} extraData + * @return {string} + */ this._throwMissingApiSecret(); return signing.JWTUserSessionToken(this.apiSecret as string, userId, extraData, { @@ -690,8 +695,8 @@ export default class StreamClient< /** * Updates all supplied activities on the getstream-io api * @since 3.1.0 - * @param {array} activities list of activities to update - * @return {Promise} + * @param {UpdateActivity[]} activities list of activities to update + * @return {Promise} */ this._throwMissingApiSecret(); @@ -715,8 +720,8 @@ export default class StreamClient< /** * Updates one activity on the getstream-io api * @since 3.1.0 - * @param {object} activity The activity to update - * @return {Promise} + * @param {UpdateActivity} activity The activity to update + * @return {Promise} */ this._throwMissingApiSecret(); @@ -736,7 +741,7 @@ export default class StreamClient< * Retrieve activities by ID or foreign ID and time * @since 3.19.0 * @param {object} params object containing either the list of activity IDs as {ids: ['...', ...]} or foreign IDs and time as {foreignIDTimes: [{foreignID: ..., time: ...}, ...]} - * @return {Promise} + * @return {Promise} */ const extraParams: { ids?: string; foreign_ids?: string; timestamps?: string } = {}; @@ -831,8 +836,8 @@ export default class StreamClient< /** * Update a single activity with partial operations. * @since 3.20.0 - * @param {object} data object containing either the ID or the foreign ID and time of the activity and the operations to issue as set:{...} and unset:[...]. - * @return {Promise} + * @param {ActivityPartialChanges} data object containing either the ID or the foreign ID and time of the activity and the operations to issue as set:{...} and unset:[...]. + * @return {Promise>} * @example * client.activityPartialUpdate({ * id: "54a60c1e-4ee3-494b-a1e3-50c06acb5ed4", @@ -870,8 +875,8 @@ export default class StreamClient< /** * Update multiple activities with partial operations. * @since v3.20.0 - * @param {array} changes array containing the changesets to be applied. Every changeset contains the activity identifier which is either the ID or the pair of of foreign ID and time of the activity. The operations to issue can be set:{...} and unset:[...]. - * @return {Promise} + * @param {ActivityPartialChanges[]} changes array containing the changesets to be applied. Every changeset contains the activity identifier which is either the ID or the pair of of foreign ID and time of the activity. The operations to issue can be set:{...} and unset:[...]. + * @return {Promise<{ activities: Activity[] }>} * @example * client.activitiesPartialUpdate([ * { diff --git a/src/collections.ts b/src/collections.ts index 361d74a7..fb82418a 100644 --- a/src/collections.ts +++ b/src/collections.ts @@ -57,7 +57,7 @@ class CollectionEntry { * get item from collection and sync data * @method get * @memberof CollectionEntry.prototype - * @return {Promise} Promise object + * @return {Promise>} * @example collection.get("0c7db91c-67f9-11e8-bcd9-fe00a9219401") */ const response = await this.store.get(this.collection, this.id); @@ -71,7 +71,7 @@ class CollectionEntry { * Add item to collection * @method add * @memberof CollectionEntry.prototype - * @return {Promise} Promise object + * @return {Promise>} * @example collection.add("cheese101", {"name": "cheese burger","toppings": "cheese"}) */ const response = await this.store.add(this.collection, this.id, this.data as CollectionType); @@ -85,7 +85,7 @@ class CollectionEntry { * Update item in the object storage * @method update * @memberof CollectionEntry.prototype - * @return {Promise} Promise object + * @return {Promise>} * @example store.update("0c7db91c-67f9-11e8-bcd9-fe00a9219401", {"name": "cheese burger","toppings": "cheese"}) * @example store.update("cheese101", {"name": "cheese burger","toppings": "cheese"}) */ @@ -100,7 +100,7 @@ class CollectionEntry { * Delete item from collection * @method delete * @memberof CollectionEntry.prototype - * @return {Promise} Promise object + * @return {Promise} * @example collection.delete("cheese101") */ const response = await this.store.delete(this.collection, this.id); @@ -141,8 +141,8 @@ export default class Collections { * @method get * @memberof Collections.prototype * @param {string} collection collection name - * @param {object} itemId id for this entry - * @return {Promise} Promise object + * @param {string} itemId id for this entry + * @return {Promise>} * @example collection.get("food", "0c7db91c-67f9-11e8-bcd9-fe00a9219401") */ const response = await this.client.get>({ @@ -162,8 +162,8 @@ export default class Collections { * @memberof Collections.prototype * @param {string} collection collection name * @param {string} itemId entry id - * @param {object} itemData ObjectStore data - * @return {Promise} Promise object + * @param {CollectionType} itemData ObjectStore data + * @return {Promise>} * @example collection.add("food", "cheese101", {"name": "cheese burger","toppings": "cheese"}) */ const response = await this.client.post>({ @@ -186,9 +186,9 @@ export default class Collections { * @method update * @memberof Collections.prototype * @param {string} collection collection name - * @param {object} entryId Collection object id - * @param {object} data ObjectStore data - * @return {Promise} Promise object + * @param {string} entryId Collection object id + * @param {CollectionType} data ObjectStore data + * @return {Promise>} * @example store.update("0c7db91c-67f9-11e8-bcd9-fe00a9219401", {"name": "cheese burger","toppings": "cheese"}) * @example store.update("food", "cheese101", {"name": "cheese burger","toppings": "cheese"}) */ @@ -208,8 +208,9 @@ export default class Collections { * Delete entry from collection * @method delete * @memberof Collections.prototype - * @param {object} entryId Collection entry id - * @return {Promise} Promise object + * @param {string} collection collection name + * @param {string} entryId Collection entry id + * @return {Promise} Promise object * @example collection.delete("food", "cheese101") */ return this.client.delete({ @@ -224,8 +225,9 @@ export default class Collections { * * @method upsert * @memberof Collections.prototype - * @param {object|array} data - A single json object or an array of objects - * @return {Promise} Promise object. + * @param {string} collection collection name + * @param {NewCollectionEntry | NewCollectionEntry[]} data - A single json object or an array of objects + * @return {Promise>} */ if (!this.client.usingApiSecret) { throw new errors.SiteError('This method can only be used server-side using your API Secret'); @@ -247,8 +249,9 @@ export default class Collections { * * @method select * @memberof Collections.prototype - * @param {object|array} ids - A single json object or an array of objects - * @return {Promise} Promise object. + * @param {string} collection collection name + * @param {string | string[]} ids - A single object id or an array of ids + * @return {Promise>} */ if (!this.client.usingApiSecret) { throw new errors.SiteError('This method can only be used server-side using your API Secret'); @@ -270,8 +273,9 @@ export default class Collections { * * @method delete * @memberof Collections.prototype - * @param {object|array} ids - A single json object or an array of objects - * @return {Promise} Promise object. + * @param {string} collection collection name + * @param {string | string[]} ids - A single object id or an array of ids + * @return {Promise} */ if (!this.client.usingApiSecret) { throw new errors.SiteError('This method can only be used server-side using your API Secret'); diff --git a/src/connect.ts b/src/connect.ts index 38ed753a..a413b7b0 100644 --- a/src/connect.ts +++ b/src/connect.ts @@ -14,8 +14,12 @@ export function connect< * @param {string} apiKey API key * @param {string} [apiSecret] API secret (only use this on the server) * @param {string} [appId] Application identifier - * @param {object} [options] Additional options - * @param {string} [options.location] Datacenter location + * @param {ClientOptions} [options] - additional options + * @param {string} [options.location] - which data center to use + * @param {boolean} [options.expireTokens=false] - whether to use a JWT timestamp field (i.e. iat) + * @param {string} [options.version] - advanced usage, custom api version + * @param {boolean} [options.keepAlive] - axios keepAlive, default to true + * @param {number} [options.timeout] - axios timeout in Ms, default to 10s * @return {StreamClient} StreamClient * @example Basic usage * stream.connect(apiKey, apiSecret); diff --git a/src/feed.ts b/src/feed.ts index 05a9c67b..0ad1a7ce 100644 --- a/src/feed.ts +++ b/src/feed.ts @@ -254,8 +254,8 @@ export default class StreamFeed< * Adds the given activity to the feed * @method addActivity * @memberof StreamFeed.prototype - * @param {object} activity - The activity to add - * @return {Promise} Promise object + * @param {NewActivity} activity - The activity to add + * @return {Promise>} */ activity = utils.replaceStreamObjects(activity); @@ -272,15 +272,13 @@ export default class StreamFeed< removeActivity(activityId: string | { foreignId: string }) { /** - * Removes the activity by activityId + * Removes the activity by activityId or foreignId * @method removeActivity * @memberof StreamFeed.prototype * @param {string} activityId Identifier of activity to remove - * @return {Promise} Promise object - * @example - * feed.removeActivity(activityId); - * @example - * feed.removeActivity({'foreignId': foreignId}); + * @return {Promise} + * @example feed.removeActivity(activityId); + * @example feed.removeActivity({'foreignId': foreignId}); */ return this.client.delete({ url: `feed/${this.feedUrl}/${(activityId as { foreignId: string }).foreignId || activityId}/`, @@ -294,8 +292,8 @@ export default class StreamFeed< * Adds the given activities to the feed * @method addActivities * @memberof StreamFeed.prototype - * @param {Array} activities Array of activities to add - * @return {Promise} XHR request object + * @param {NewActivity[]} activities Array of activities to add + * @return {Promise[]>} */ return this.client.post[]>({ url: `feed/${this.feedUrl}/`, @@ -311,9 +309,9 @@ export default class StreamFeed< * @memberof StreamFeed.prototype * @param {string} targetSlug Slug of the target feed * @param {string} targetUserId User identifier of the target feed - * @param {object} options Additional options - * @param {number} options.limit Limit the amount of activities copied over on follow - * @return {Promise} Promise object + * @param {object} [options] Additional options + * @param {number} [options.limit] Limit the amount of activities copied over on follow + * @return {Promise} * @example feed.follow('user', '1'); * @example feed.follow('user', '1'); * @example feed.follow('user', '1', options); @@ -340,11 +338,11 @@ export default class StreamFeed< * @method unfollow * @memberof StreamFeed.prototype * @param {string} targetSlug Slug of the target feed - * @param {string} targetUserId [description] - * @param {object} options - * @param {boolean} options.keepHistory when provided the activities from target + * @param {string} targetUserId User identifier of the target feed + * @param {object} [options] + * @param {boolean} [options.keepHistory] when provided the activities from target * feed will not be kept in the feed - * @return {object} XHR request object + * @return {Promise} * @example feed.unfollow('user', '2'); */ const qs: { keep_history?: string } = {}; @@ -365,9 +363,11 @@ export default class StreamFeed< * List which feeds this feed is following * @method following * @memberof StreamFeed.prototype - * @param {object} options Additional options - * @param {string} options.filter Filter to apply on search operation - * @return {Promise} Promise object + * @param {GetFollowOptions} [options] Additional options + * @param {string[]} options.filter array of feed id to filter on + * @param {number} options.limit pagination + * @param {number} options.offset pagination + * @return {Promise} * @example feed.following({limit:10, filter: ['user:1', 'user:2']}); */ const extraOptions: { filter?: string } = {}; @@ -385,11 +385,12 @@ export default class StreamFeed< * List the followers of this feed * @method followers * @memberof StreamFeed.prototype - * @param {object} options Additional options - * @param {string} options.filter Filter to apply on search operation - * @return {Promise} Promise object - * @example - * feed.followers({limit:10, filter: ['user:1', 'user:2']}); + * @param {GetFollowOptions} [options] Additional options + * @param {string[]} options.filter array of feed id to filter on + * @param {number} options.limit pagination + * @param {number} options.offset pagination + * @return {Promise} + * @example feed.followers({limit:10, filter: ['user:1', 'user:2']}); */ const extraOptions: { filter?: string } = {}; if (options.filter) extraOptions.filter = options.filter.join(','); @@ -406,8 +407,8 @@ export default class StreamFeed< * Reads the feed * @method get * @memberof StreamFeed.prototype - * @param {object} options Additional options - * @return {Promise} Promise object + * @param {GetFeedOptions & NotificationFeedOptions} options Additional options + * @return {Promise} * @example feed.get({limit: 10, id_lte: 'activity-id'}) * @example feed.get({limit: 10, mark_seen: true}) */ @@ -439,8 +440,8 @@ export default class StreamFeed< * @method getActivityDetail * @memberof StreamFeed.prototype * @param {string} activityId Identifier of activity to retrieve - * @param {object} options Additional options - * @return {Promise} Promise object + * @param {EnrichOptions} options Additional options + * @return {Promise} * @example feed.getActivityDetail(activityId) * @example feed.getActivityDetail(activityId, {withRecentReactions: true}) * @example feed.getActivityDetail(activityId, {withReactionCounts: true}) @@ -460,7 +461,7 @@ export default class StreamFeed< * @method getFayeClient * @memberof StreamFeed.prototype * @access private - * @return {object} Faye client + * @return {Faye.Client} Faye client */ return this.client.getFayeClient(); } @@ -471,7 +472,7 @@ export default class StreamFeed< * @method subscribe * @memberof StreamFeed.prototype * @param {function} callback Callback to call on completion - * @return {Promise} Promise object + * @return {Promise} * @example * feed.subscribe(callback).then(function(){ * console.log('we are now listening to changes'); @@ -517,9 +518,9 @@ export default class StreamFeed< * @since 3.10.0 * @param {string} foreignId The foreign_id of the activity to update * @param {string} time The time of the activity to update - * @param {array} newTargets Set the new "to" targets for the activity - will remove old targets - * @param {array} added_targets Add these new targets to the activity - * @param {array} removedTargets Remove these targets from the activity + * @param {string[]} newTargets Set the new "to" targets for the activity - will remove old targets + * @param {string[]} added_targets Add these new targets to the activity + * @param {string[]} removedTargets Remove these targets from the activity */ if (!foreignId) throw new Error('Missing `foreign_id` parameter!'); diff --git a/src/files.ts b/src/files.ts index 43df7b99..d1013c3f 100644 --- a/src/files.ts +++ b/src/files.ts @@ -19,11 +19,11 @@ export default class StreamFileStore { ) { /** * upload a File instance or a readable stream of data - * @param {File|Buffer|string} uri - File object or Buffer or URI + * @param {File|NodeJS.ReadStream|string} uri - File object or stream or URI * @param {string} [name] - file name * @param {string} [contentType] - mime-type * @param {function} [onUploadProgress] - browser only, Function that is called with upload progress - * @return {Promise} + * @return {Promise} */ return this.client.upload('files/', uri, name, contentType, onUploadProgress); } diff --git a/src/images.ts b/src/images.ts index 07ab5913..a6991a66 100644 --- a/src/images.ts +++ b/src/images.ts @@ -27,11 +27,11 @@ export default class StreamImageStore { ) { /** * upload an Image File instance or a readable stream of data - * @param {File|Buffer|string} uri - File object or Buffer or URI + * @param {File|NodeJS.ReadStream|string} uri - File object or stream or URI * @param {string} [name] - file name * @param {string} [contentType] - mime-type * @param {function} [onUploadProgress] - browser only, Function that is called with upload progress - * @return {Promise} + * @return {Promise} */ return this.client.upload('images/', uri, name, contentType, onUploadProgress); } diff --git a/src/personalization.ts b/src/personalization.ts index 5f5d5ad8..0c82e4bd 100644 --- a/src/personalization.ts +++ b/src/personalization.ts @@ -37,7 +37,7 @@ export default class Personalization { * @memberof Personalization.prototype * @param {string} resource - personalized resource endpoint i.e "follow_recommendations" * @param {object} options Additional options - * @return {Promise} Promise object. Personalized feed + * @return {Promise>} Promise object. Personalized feed * @example client.personalization.get('follow_recommendations', {foo: 'bar', baz: 'qux'}) */ return this.client.get>({ @@ -57,7 +57,7 @@ export default class Personalization { * @param {string} resource - personalized resource endpoint i.e "follow_recommendations" * @param {object} options - Additional options * @param {object} data - Data to send in the payload - * @return {Promise} Promise object. Data that was posted if successful, or an error. + * @return {Promise>} Promise object. Data that was posted if successful, or an error. * @example client.personalization.post('follow_recommendations', {foo: 'bar', baz: 'qux'}) */ return this.client.post>({ @@ -77,7 +77,7 @@ export default class Personalization { * @memberof Personalization.prototype * @param {object} resource - personalized resource endpoint i.e "follow_recommendations" * @param {object} options - Additional options - * @return {Promise} Promise object. Data that was deleted if successful, or an error. + * @return {Promise>} Promise object. Data that was deleted if successful, or an error. * @example client.personalization.delete('follow_recommendations', {foo: 'bar', baz: 'qux'}) */ return this.client.delete>({ diff --git a/src/reaction.ts b/src/reaction.ts index 5b4330ac..506056e6 100644 --- a/src/reaction.ts +++ b/src/reaction.ts @@ -113,9 +113,13 @@ export default class StreamReaction>} * @example reactions.add("like", "0c7db91c-67f9-11e8-bcd9-fe00a9219401") * @example reactions.add("comment", "0c7db91c-67f9-11e8-bcd9-fe00a9219401", {"text": "love it!"},) */ @@ -140,7 +144,7 @@ export default class StreamReaction>} * @example reactions.add("like", "0c7db91c-67f9-11e8-bcd9-fe00a9219401") * @example reactions.add("comment", "0c7db91c-67f9-11e8-bcd9-fe00a9219401", {"text": "love it!"},) */ const body: ReactionBody = { parent: reaction instanceof Object ? (reaction as { id: string }).id : reaction, kind, - data, + data: data || {}, target_feeds: this._convertTargetFeeds(targetFeeds), user_id: userId, }; @@ -183,10 +190,10 @@ export default class StreamReaction>} * @example reactions.get("67b3e3b5-b201-4697-96ac-482eb14f88ec") */ return this.client.get>({ @@ -217,7 +224,7 @@ export default class StreamReaction>} * @example reactions.filter({activity_id: "0c7db91c-67f9-11e8-bcd9-fe00a9219401", kind:"like"}) * @example reactions.filter({user_id: "john", kinds:"like"}) */ @@ -257,12 +264,14 @@ export default class StreamReaction>} * @example reactions.update("67b3e3b5-b201-4697-96ac-482eb14f88ec", "0c7db91c-67f9-11e8-bcd9-fe00a9219401", "like") * @example reactions.update("67b3e3b5-b201-4697-96ac-482eb14f88ec", "0c7db91c-67f9-11e8-bcd9-fe00a9219401", "comment", {"text": "love it!"},) */ @@ -286,7 +295,7 @@ export default class StreamReaction} * @example reactions.delete("67b3e3b5-b201-4697-96ac-482eb14f88ec") */ return this.client.delete({ diff --git a/src/signing.ts b/src/signing.ts index 72b34fbe..6a785fbc 100644 --- a/src/signing.ts +++ b/src/signing.ts @@ -62,6 +62,7 @@ function JWTScopeToken( * @param {object} [options] - Optional additional options * @param {string} [options.feedId] - JWT payload feed identifier * @param {string} [options.userId] - JWT payload user identifier + * @param {boolean} [options.expireTokens] - JWT noTimestamp * @return {string} JWT Token */ const noTimestamp = options.expireTokens ? !options.expireTokens : true; diff --git a/src/user.ts b/src/user.ts index c879f517..23cf7f7f 100644 --- a/src/user.ts +++ b/src/user.ts @@ -24,7 +24,7 @@ export default class StreamUser { * @memberof StreamUser.prototype * @param {StreamClient} client Stream client this collection is constructed from * @param {string} userId The ID of the user - * @param {string} token JWT token + * @param {string} userAuthToken JWT token * @example new StreamUser(client, "123", "eyJhbGciOiJIUzI1...") */ this.client = client; From 57742bfcde2ad15d6f789aa3ec8d8669887a5a78 Mon Sep 17 00:00:00 2001 From: Amin Mahboubi Date: Wed, 29 Jul 2020 17:58:07 +0200 Subject: [PATCH 48/69] adding eslint sort keys plugin --- .eslintrc.js | 8 +++++++- package.json | 1 + yarn.lock | 42 ++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 50 insertions(+), 1 deletion(-) diff --git a/.eslintrc.js b/.eslintrc.js index 0a286051..306edd75 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -45,7 +45,7 @@ module.exports = { overrides: [ { files: ['**/*.ts'], - plugins: ['prettier', '@typescript-eslint'], + plugins: ['prettier', '@typescript-eslint', 'typescript-sort-keys'], extends: [ 'airbnb-base', 'eslint:recommended', @@ -63,6 +63,12 @@ module.exports = { '@typescript-eslint/explicit-module-boundary-types': 0, '@typescript-eslint/ban-ts-comment': 0, 'no-useless-constructor': 0, + 'typescript-sort-keys/interface': [ + 'error', + 'asc', + { caseSensitive: false, natural: true, requiredFirst: true }, + ], + 'typescript-sort-keys/string-enum': ['error', 'asc', { caseSensitive: false, natural: true }], }, }, ], diff --git a/package.json b/package.json index 47154eae..f1a7a235 100644 --- a/package.json +++ b/package.json @@ -82,6 +82,7 @@ "eslint-plugin-import": "^2.22.0", "eslint-plugin-prettier": "^3.1.4", "eslint-plugin-sonarjs": "^0.5.0", + "eslint-plugin-typescript-sort-keys": "^1.3.0", "expect.js": "^0.3.1", "husky": "^4.2.5", "jsdoc": "^3.6.4", diff --git a/yarn.lock b/yarn.lock index 804f88a2..49120e17 100644 --- a/yarn.lock +++ b/yarn.lock @@ -1303,6 +1303,16 @@ eslint-scope "^5.0.0" eslint-utils "^2.0.0" +"@typescript-eslint/experimental-utils@~2.32.0": + version "2.32.0" + resolved "https://registry.yarnpkg.com/@typescript-eslint/experimental-utils/-/experimental-utils-2.32.0.tgz#bee7fbe1d21d13a273066d70abc82549d0b7943e" + integrity sha512-oDWuB2q5AXsQ/mLq2N4qtWiBASWXPf7KhqXgeGH4QsyVKx+km8F6Vfqd3bspJQyhyCqxcbLO/jKJuIV3DzHZ6A== + dependencies: + "@types/json-schema" "^7.0.3" + "@typescript-eslint/typescript-estree" "2.32.0" + eslint-scope "^5.0.0" + eslint-utils "^2.0.0" + "@typescript-eslint/parser@^3.6.1": version "3.6.1" resolved "https://registry.yarnpkg.com/@typescript-eslint/parser/-/parser-3.6.1.tgz#216e8adf4ee9c629f77c985476a2ea07fb80e1dc" @@ -1319,6 +1329,19 @@ resolved "https://registry.yarnpkg.com/@typescript-eslint/types/-/types-3.6.1.tgz#87600fe79a1874235d3cc1cf5c7e1a12eea69eee" integrity sha512-NPxd5yXG63gx57WDTW1rp0cF3XlNuuFFB5G+Kc48zZ+51ZnQn9yjDEsjTPQ+aWM+V+Z0I4kuTFKjKvgcT1F7xQ== +"@typescript-eslint/typescript-estree@2.32.0": + version "2.32.0" + resolved "https://registry.yarnpkg.com/@typescript-eslint/typescript-estree/-/typescript-estree-2.32.0.tgz#0e4ae2e883557f94039b13ac0ecfcfbb09835b8d" + integrity sha512-hQpbWM/Y2iq6jB9FHYJBqa3h1R9IEGodOtajhb261cVHt9cz30AKjXM6WP7LxJdEPPlyJ9rPTZVgBUgZgiyPgw== + dependencies: + debug "^4.1.1" + eslint-visitor-keys "^1.1.0" + glob "^7.1.6" + is-glob "^4.0.1" + lodash "^4.17.15" + semver "^7.3.2" + tsutils "^3.17.1" + "@typescript-eslint/typescript-estree@3.6.1": version "3.6.1" resolved "https://registry.yarnpkg.com/@typescript-eslint/typescript-estree/-/typescript-estree-3.6.1.tgz#a5c91fcc5497cce7922ff86bc37d5e5891dcdefa" @@ -3528,6 +3551,15 @@ eslint-plugin-sonarjs@^0.5.0: resolved "https://registry.yarnpkg.com/eslint-plugin-sonarjs/-/eslint-plugin-sonarjs-0.5.0.tgz#ce17b2daba65a874c2862213a9e38e8986ad7d7d" integrity sha512-XW5MnzlRjhXpIdbULC/qAdJYHWw3rRLws/DyawdlPU/IdVr9AmRK1r2LaCvabwKOAW2XYYSo3kDX58E4MrB7PQ== +eslint-plugin-typescript-sort-keys@^1.3.0: + version "1.3.0" + resolved "https://registry.yarnpkg.com/eslint-plugin-typescript-sort-keys/-/eslint-plugin-typescript-sort-keys-1.3.0.tgz#3b7cbf5b82c8e13283ad6b96efb06816851bd50d" + integrity sha512-8/pHhSvcsfWMGNxToCfGiD3RSDWLemlCLZMEOuBJsmt05o68/+uqI/R358yuZqE+Uqe6yXfjjQ8lkYBw1ayIAA== + dependencies: + "@typescript-eslint/experimental-utils" "~2.32.0" + json-schema "~0.2.5" + natural-compare-lite "~1.4.0" + eslint-scope@^4.0.3: version "4.0.3" resolved "https://registry.yarnpkg.com/eslint-scope/-/eslint-scope-4.0.3.tgz#ca03833310f6889a3264781aa82e63eb9cfe7848" @@ -5187,6 +5219,11 @@ json-schema@0.2.3: resolved "https://registry.yarnpkg.com/json-schema/-/json-schema-0.2.3.tgz#b480c892e59a2f05954ce727bd3f2a4e882f9e13" integrity sha1-tIDIkuWaLwWVTOcnvT8qTogvnhM= +json-schema@~0.2.5: + version "0.2.5" + resolved "https://registry.yarnpkg.com/json-schema/-/json-schema-0.2.5.tgz#97997f50972dd0500214e208c407efa4b5d7063b" + integrity sha512-gWJOWYFrhQ8j7pVm0EM8Slr+EPVq1Phf6lvzvD/WCeqkrx/f2xBI0xOsRRS9xCn3I4vKtP519dvs3TP09r24wQ== + json-stable-stringify-without-jsonify@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz#9db7b59496ad3f3cfef30a75142d2d930ad72651" @@ -5958,6 +5995,11 @@ nanomatch@^1.2.9: snapdragon "^0.8.1" to-regex "^3.0.1" +natural-compare-lite@~1.4.0: + version "1.4.0" + resolved "https://registry.yarnpkg.com/natural-compare-lite/-/natural-compare-lite-1.4.0.tgz#17b09581988979fddafe0201e931ba933c96cbb4" + integrity sha1-F7CVgZiJef3a/gIB6TG6kzyWy7Q= + natural-compare@^1.4.0: version "1.4.0" resolved "https://registry.yarnpkg.com/natural-compare/-/natural-compare-1.4.0.tgz#4abebfeed7541f2c27acfb29bdbbd15c8d5ba4f7" From 51436f57ce5ff887db95ca9395099d74e65b5f48 Mon Sep 17 00:00:00 2001 From: Amin Mahboubi Date: Wed, 29 Jul 2020 18:06:41 +0200 Subject: [PATCH 49/69] run lint-fix for sorting ts keys --- src/client.ts | 60 +++++++++++++++++++++--------------------- src/collections.ts | 6 ++--- src/feed.ts | 54 ++++++++++++++++++------------------- src/images.ts | 4 +-- src/modules_types.ts | 2 +- src/personalization.ts | 4 +-- src/reaction.ts | 32 +++++++++++----------- src/signing.ts | 4 +-- src/user.ts | 4 +-- src/utils.ts | 2 +- 10 files changed, 85 insertions(+), 87 deletions(-) diff --git a/src/client.ts b/src/client.ts index 4fcbc464..9cf87aa5 100644 --- a/src/client.ts +++ b/src/client.ts @@ -37,23 +37,23 @@ export type FileUploadAPIResponse = APIResponse & { file: string }; export type OnUploadProgress = (progressEvent: ProgressEvent) => void; export type ClientOptions = { - location?: string; + browser?: boolean; expireTokens?: boolean; - version?: string; + fayeUrl?: string; group?: string; keepAlive?: boolean; - timeout?: number; - browser?: boolean; - fayeUrl?: string; - protocol?: string; local?: boolean; + location?: string; + protocol?: string; + timeout?: number; urlOverride?: Record; + version?: string; }; type OGResource = { - url?: string; secure_url?: string; type?: string; + url?: string; }; type OGAudio = OGResource & { @@ -61,50 +61,50 @@ type OGAudio = OGResource & { }; type OGImage = OGResource & { + alt?: string; + height?: number; image?: string; width?: number; - height?: number; - alt?: string; }; type OGVideo = OGResource & { + height?: number; video?: string; width?: number; - height?: number; }; export type OGAPIResponse = APIResponse & { - title?: string; - type?: string; - url?: string; - site?: string; - site_name?: string; + audios?: OGAudio[]; description?: string; - favicon?: string; determiner?: string; - locale?: string; - audios?: OGAudio[]; + favicon?: string; images?: OGImage[]; + locale?: string; + site?: string; + site_name?: string; + title?: string; + type?: string; + url?: string; videos?: OGVideo[]; }; type AxiosConfig = { signature: string; url: string; - serviceName?: string; + axiosOptions?: axios.AxiosRequestConfig; body?: unknown; - qs?: Record; headers?: Record; - axiosOptions?: axios.AxiosRequestConfig; + qs?: Record; + serviceName?: string; }; export type HandlerCallback = (...args: unknown[]) => unknown; export type ActivityPartialChanges = { - id?: string; foreignID?: string; - time?: Date; + id?: string; set?: Record; + time?: Date; unset?: string[]; }; @@ -144,7 +144,7 @@ export default class StreamClient< request: axios.AxiosInstance; subscriptions: Record< string, - { userId: string; token: string; fayeSubscription: Faye.Subscription | Promise } + { fayeSubscription: Faye.Subscription | Promise; token: string; userId: string } >; handlers: Record; @@ -463,10 +463,10 @@ export default class StreamClient< replaceReactionOptions = (options: { reactions?: Record; + withOwnChildren?: boolean; withOwnReactions?: boolean; - withRecentReactions?: boolean; withReactionCounts?: boolean; - withOwnChildren?: boolean; + withRecentReactions?: boolean; }) => { // Shortcut options for reaction enrichment if (options?.reactions) { @@ -490,9 +490,9 @@ export default class StreamClient< options: { enrich?: boolean; ownReactions?: boolean; - withRecentReactions?: boolean; - withReactionCounts?: boolean; withOwnChildren?: boolean; + withReactionCounts?: boolean; + withRecentReactions?: boolean; } = {}, ) { if (options.enrich) { @@ -733,8 +733,8 @@ export default class StreamClient< foreignIDTimes, ...params }: EnrichOptions & { - ids?: string[]; foreignIDTimes?: { foreignID: string; time: Date }[]; + ids?: string[]; reactions?: Record; }) { /** @@ -743,7 +743,7 @@ export default class StreamClient< * @param {object} params object containing either the list of activity IDs as {ids: ['...', ...]} or foreign IDs and time as {foreignIDTimes: [{foreignID: ..., time: ...}, ...]} * @return {Promise} */ - const extraParams: { ids?: string; foreign_ids?: string; timestamps?: string } = {}; + const extraParams: { foreign_ids?: string; ids?: string; timestamps?: string } = {}; if (ids) { if (!(ids instanceof Array)) { diff --git a/src/collections.ts b/src/collections.ts index fb82418a..ea895961 100644 --- a/src/collections.ts +++ b/src/collections.ts @@ -3,13 +3,13 @@ import * as errors from './errors'; type BaseCollection = { collection: string; - id: string; data: CollectionType; + id: string; }; export type CollectionResponse = BaseCollection & { - foregin_id: string; created_at: Date; + foregin_id: string; updated_at: Date; }; @@ -28,8 +28,8 @@ export type SelectCollectionAPIResponse = APIResponse & { export type UpsertCollectionAPIResponse = APIResponse & { data: { [key: string]: { - id: string; data: CollectionType; + id: string; }[]; }; }; diff --git a/src/feed.ts b/src/feed.ts index 0ad1a7ce..d8b0adae 100644 --- a/src/feed.ts +++ b/src/feed.ts @@ -8,20 +8,20 @@ import { CollectionResponse } from './collections'; export type EnrichOptions = { enrich?: boolean; - withOwnReactions?: boolean; - withOwnChildren?: boolean; ownReactions?: boolean; // best not to use it, will removed by clinet.replaceReactionOptions() + reactionKindsFilter?: string; // TODO: add support for array sample: kind,kind,kind + recentReactionsLimit?: number; + withOwnChildren?: boolean; + withOwnReactions?: boolean; withReactionCounts?: boolean; withRecentReactions?: boolean; - recentReactionsLimit?: number; - reactionKindsFilter?: string; // TODO: add support for array sample: kind,kind,kind }; export type FeedPaginationOptions = { - id_lt?: string; - id_lte?: string; id_gt?: string; id_gte?: string; + id_lt?: string; + id_lte?: string; limit?: number; }; @@ -39,37 +39,35 @@ export type NotificationFeedOptions = { }; export type GetFollowOptions = { + filter?: string[]; limit?: number; offset?: number; - filter?: string[]; }; export type GetFollowAPIResponse = APIResponse & { - results: { feed_id: string; target_id: string; created_at: Date; updated_at: Date }[]; + results: { created_at: Date; feed_id: string; target_id: string; updated_at: Date }[]; }; type BaseActivity = ActivityType & { actor: string; - verb: string; object: string | unknown; - to?: string[]; + verb: string; target?: string; + to?: string[]; }; -export type NewActivity = BaseActivity & { time?: string; foreign_id?: string }; +export type NewActivity = BaseActivity & { foreign_id?: string; time?: string }; -export type UpdateActivity = BaseActivity & { time: string; foreign_id: string }; +export type UpdateActivity = BaseActivity & { foreign_id: string; time: string }; export type Activity = BaseActivity & { + foreign_id: string; id: string; time: Date; - foreign_id: string; - origin?: string; + analytics?: Record; // ranked feeds only extra_context?: Record; - - // ranked feeds - score?: number; - analytics?: Record; + origin?: string; + score?: number; // ranked feeds only }; export type ReactionsRecords = Record< @@ -88,14 +86,14 @@ export type EnrichedActivity | CollectionResponse; - // enriched reactions - reaction_counts?: Record; latest_reactions?: ReactionsRecords; - own_reactions?: ReactionsRecords[]; latest_reactions_extra?: Record; + own_reactions?: ReactionsRecords[]; own_reactions_extra?: Record; // Reaction posted to feed reaction?: EnrichedReaction; + // enriched reactions + reaction_counts?: Record; }; export type FlatActivity = Activity; @@ -109,13 +107,13 @@ export type FlatActivityEnriched< > = EnrichedActivity; type BaseAggregatedActivity = { - id: string; - verb: string; - group: string; activity_count: number; actor_count: number; - updated_at: Date; created_at: Date; + group: string; + id: string; + updated_at: Date; + verb: string; score?: number; }; @@ -167,11 +165,11 @@ export type PersonalizationFeedAPIResponse< ReactionType, ChildReactionType > = APIResponse & { - next: string; limit: number; + next: string; offset: number; - version: string; results: FlatActivityEnriched[]; + version: string; }; export type GetActivitiesAPIResponse< @@ -550,8 +548,8 @@ export default class StreamFeed< const body: { foreign_id: string; time: string; - new_targets?: string[]; added_targets?: string[]; + new_targets?: string[]; removed_targets?: string[]; } = { foreign_id: foreignId, time }; if (newTargets) body.new_targets = newTargets; diff --git a/src/images.ts b/src/images.ts index a6991a66..2a2ab8a0 100644 --- a/src/images.ts +++ b/src/images.ts @@ -1,10 +1,10 @@ import StreamClient, { FileUploadAPIResponse, OnUploadProgress } from './client'; export type ImageProcessOptions = { - w?: number | string; + crop?: string | 'top' | 'bottom' | 'left' | 'right' | 'center'; h?: number | string; resize?: string | 'clip' | 'crop' | 'scale' | 'fill'; - crop?: string | 'top' | 'bottom' | 'left' | 'right' | 'center'; + w?: number | string; }; export default class StreamImageStore { diff --git a/src/modules_types.ts b/src/modules_types.ts index 06d6308f..012113b4 100644 --- a/src/modules_types.ts +++ b/src/modules_types.ts @@ -1,8 +1,8 @@ declare module 'faye' { type Message = { - subscription?: string; // TODO: generalize [key: string]: unknown; + subscription?: string; }; type Subscription = { diff --git a/src/personalization.ts b/src/personalization.ts index 0c82e4bd..4a1afb52 100644 --- a/src/personalization.ts +++ b/src/personalization.ts @@ -8,10 +8,10 @@ import StreamClient, { APIResponse } from './client'; export type PersonalizationAPIResponse = APIResponse & { app_id: string; - results: PersonalizationType[]; next: string; - offset?: number; + results: PersonalizationType[]; limit?: number; + offset?: number; version?: string; }; diff --git a/src/reaction.ts b/src/reaction.ts index 506056e6..7db94727 100644 --- a/src/reaction.ts +++ b/src/reaction.ts @@ -9,27 +9,27 @@ export type TargetFeed = string | StreamFeed; export type TargetFeedsExtraData = Record; type ReactionBody = { + activity_id?: string; // only required for reactions + data?: T | Record; id?: string; // api will generate an id if it's missing kind?: string; // required only for add/addChile, not update - user_id?: string; // optional when using client tokens - activity_id?: string; // only required for reactions parent?: string; // only required for child reactions - data?: T | Record; target_feeds?: string[]; target_feeds_extra_data?: TargetFeedsExtraData; + user_id?: string; // optional when using client tokens }; export type Reaction = { - id: string; - kind: string; activity_id: string; - user_id: string; - data: T; created_at: Date; + data: T; + id: string; + kind: string; + parent: string; updated_at: Date; + user_id: string; target_feeds?: string[]; target_feeds_extra_data?: TargetFeedsExtraData; - parent: string; }; export type ReactionAPIResponse = APIResponse & Reaction; @@ -45,11 +45,11 @@ export type EnrichedReactionAPIResponse; export type ReactionFilterAPIResponse = APIResponse & { - activity?: ActivityType; next: string; results: | ReactionAPIResponse[] | EnrichedReactionAPIResponse[]; + activity?: ActivityType; }; export default class StreamReaction { @@ -105,7 +105,7 @@ export default class StreamReaction = APIResponse & { - id: string; - data: UserType; created_at: Date; + data: UserType; + id: string; updated_at: Date; followers_count?: number; following_count?: number; diff --git a/src/utils.ts b/src/utils.ts index 6495fc98..e2af1a4f 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -53,7 +53,7 @@ function validateFeedId(feedId: string) { function addFileToFormData(uri: string | File | NodeJS.ReadStream, name?: string, contentType?: string) { const data = new FormData(); - let fileField: File | NodeJS.ReadStream | { uri: string; name: string; type?: string }; + let fileField: File | NodeJS.ReadStream | { name: string; uri: string; type?: string }; if (isReadableStream(uri as NodeJS.ReadStream)) { fileField = uri as NodeJS.ReadStream; From 35b8b464dce1d13562eb409f8bf6c49ac9d1b4ad Mon Sep 17 00:00:00 2001 From: Amin Mahboubi Date: Wed, 29 Jul 2020 18:12:50 +0200 Subject: [PATCH 50/69] swap Date types coming back from api to string --- src/client.ts | 6 +++--- src/collections.ts | 4 ++-- src/feed.ts | 8 ++++---- src/reaction.ts | 4 ++-- src/user.ts | 4 ++-- 5 files changed, 13 insertions(+), 13 deletions(-) diff --git a/src/client.ts b/src/client.ts index 9cf87aa5..15c4c1ee 100644 --- a/src/client.ts +++ b/src/client.ts @@ -104,7 +104,7 @@ export type ActivityPartialChanges = { foreignID?: string; id?: string; set?: Record; - time?: Date; + time?: Date | string; unset?: string[]; }; @@ -733,7 +733,7 @@ export default class StreamClient< foreignIDTimes, ...params }: EnrichOptions & { - foreignIDTimes?: { foreignID: string; time: Date }[]; + foreignIDTimes?: { foreignID: string; time: Date | string }[]; ids?: string[]; reactions?: Record; }) { @@ -755,7 +755,7 @@ export default class StreamClient< throw new TypeError('The foreignIDTimes argument should be an Array'); } const foreignIDs: string[] = []; - const timestamps: Date[] = []; + const timestamps: (Date | string)[] = []; foreignIDTimes.forEach((fidTime) => { if (!(fidTime instanceof Object)) { throw new TypeError('foreignIDTimes elements should be Objects'); diff --git a/src/collections.ts b/src/collections.ts index ea895961..d0066474 100644 --- a/src/collections.ts +++ b/src/collections.ts @@ -8,9 +8,9 @@ type BaseCollection = { }; export type CollectionResponse = BaseCollection & { - created_at: Date; + created_at: string; foregin_id: string; - updated_at: Date; + updated_at: string; }; export type NewCollectionEntry = BaseCollection & { diff --git a/src/feed.ts b/src/feed.ts index d8b0adae..e3baa597 100644 --- a/src/feed.ts +++ b/src/feed.ts @@ -45,7 +45,7 @@ export type GetFollowOptions = { }; export type GetFollowAPIResponse = APIResponse & { - results: { created_at: Date; feed_id: string; target_id: string; updated_at: Date }[]; + results: { created_at: string; feed_id: string; target_id: string; updated_at: string }[]; }; type BaseActivity = ActivityType & { @@ -63,7 +63,7 @@ export type UpdateActivity = BaseActivity & { foreig export type Activity = BaseActivity & { foreign_id: string; id: string; - time: Date; + time: string; analytics?: Record; // ranked feeds only extra_context?: Record; origin?: string; @@ -109,10 +109,10 @@ export type FlatActivityEnriched< type BaseAggregatedActivity = { activity_count: number; actor_count: number; - created_at: Date; + created_at: string; group: string; id: string; - updated_at: Date; + updated_at: string; verb: string; score?: number; }; diff --git a/src/reaction.ts b/src/reaction.ts index 7db94727..b17bd981 100644 --- a/src/reaction.ts +++ b/src/reaction.ts @@ -21,12 +21,12 @@ type ReactionBody = { export type Reaction = { activity_id: string; - created_at: Date; + created_at: string; data: T; id: string; kind: string; parent: string; - updated_at: Date; + updated_at: string; user_id: string; target_feeds?: string[]; target_feeds_extra_data?: TargetFeedsExtraData; diff --git a/src/user.ts b/src/user.ts index e4e3b69f..f575b265 100644 --- a/src/user.ts +++ b/src/user.ts @@ -1,10 +1,10 @@ import StreamClient, { APIResponse } from './client'; export type UserAPIResponse = APIResponse & { - created_at: Date; + created_at: string; data: UserType; id: string; - updated_at: Date; + updated_at: string; followers_count?: number; following_count?: number; }; From 1f009d951a71e1cc68ba31a69a9dfb8b7dd3527f Mon Sep 17 00:00:00 2001 From: Amin Mahboubi Date: Thu, 30 Jul 2020 09:44:48 +0200 Subject: [PATCH 51/69] add some default types --- src/feed.ts | 1 + src/reaction.ts | 6 +++--- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/src/feed.ts b/src/feed.ts index e3baa597..b9cf0f01 100644 --- a/src/feed.ts +++ b/src/feed.ts @@ -132,6 +132,7 @@ export type AggregatedActivityEnriched< }; type BaseNotificationActivity = { is_read: boolean; is_seen: boolean }; + export type NotificationActivity = AggregatedActivity & BaseNotificationActivity; export type NotificationActivityEnriched< diff --git a/src/reaction.ts b/src/reaction.ts index b17bd981..820b409b 100644 --- a/src/reaction.ts +++ b/src/reaction.ts @@ -1,4 +1,4 @@ -import StreamClient, { APIResponse } from './client'; +import StreamClient, { APIResponse, UnknownType } from './client'; import StreamFeed from './feed'; import * as errors from './errors'; @@ -10,7 +10,7 @@ export type TargetFeedsExtraData = Record; type ReactionBody = { activity_id?: string; // only required for reactions - data?: T | Record; + data?: T | UnknownType; id?: string; // api will generate an id if it's missing kind?: string; // required only for add/addChile, not update parent?: string; // only required for child reactions @@ -19,7 +19,7 @@ type ReactionBody = { user_id?: string; // optional when using client tokens }; -export type Reaction = { +export type Reaction = { activity_id: string; created_at: string; data: T; From 312aba6364d4a2e4e403da3f837bd3dbb524c611 Mon Sep 17 00:00:00 2001 From: Amin Mahboubi Date: Thu, 30 Jul 2020 09:47:43 +0200 Subject: [PATCH 52/69] rename UnknownType to UnknownRecord --- src/client.ts | 14 +++++++------- src/connect.ts | 14 +++++++------- src/reaction.ts | 6 +++--- 3 files changed, 17 insertions(+), 17 deletions(-) diff --git a/src/client.ts b/src/client.ts index 15c4c1ee..83381571 100644 --- a/src/client.ts +++ b/src/client.ts @@ -28,7 +28,7 @@ import StreamFeed, { // eslint-disable-next-line @typescript-eslint/no-var-requires const pkg = require('../package.json'); -export type UnknownType = Record; +export type UnknownRecord = Record; export type APIResponse = { duration?: string }; @@ -113,12 +113,12 @@ export type ActivityPartialChanges = { * @class StreamClient */ export default class StreamClient< - UserType extends UnknownType = UnknownType, - ActivityType extends UnknownType = UnknownType, - CollectionType extends UnknownType = UnknownType, - ReactionType extends UnknownType = UnknownType, - ChildReactionType extends UnknownType = UnknownType, - PersonalizationType extends UnknownType = UnknownType + UserType extends UnknownRecord = UnknownRecord, + ActivityType extends UnknownRecord = UnknownRecord, + CollectionType extends UnknownRecord = UnknownRecord, + ReactionType extends UnknownRecord = UnknownRecord, + ChildReactionType extends UnknownRecord = UnknownRecord, + PersonalizationType extends UnknownRecord = UnknownRecord > { baseUrl: string; baseAnalyticsUrl: string; diff --git a/src/connect.ts b/src/connect.ts index a413b7b0..1ccf0ada 100644 --- a/src/connect.ts +++ b/src/connect.ts @@ -1,12 +1,12 @@ -import StreamClient, { UnknownType, ClientOptions } from './client'; +import StreamClient, { UnknownRecord, ClientOptions } from './client'; export function connect< - UserType extends UnknownType = UnknownType, - ActivityType extends UnknownType = UnknownType, - CollectionType extends UnknownType = UnknownType, - ReactionType extends UnknownType = UnknownType, - ChildReactionType extends UnknownType = UnknownType, - PersonalizationType extends UnknownType = UnknownType + UserType extends UnknownRecord = UnknownRecord, + ActivityType extends UnknownRecord = UnknownRecord, + CollectionType extends UnknownRecord = UnknownRecord, + ReactionType extends UnknownRecord = UnknownRecord, + ChildReactionType extends UnknownRecord = UnknownRecord, + PersonalizationType extends UnknownRecord = UnknownRecord >(apiKey: string, apiSecret: string | null, appId?: string, options?: ClientOptions) { /** * Create StreamClient diff --git a/src/reaction.ts b/src/reaction.ts index 820b409b..544ee14a 100644 --- a/src/reaction.ts +++ b/src/reaction.ts @@ -1,4 +1,4 @@ -import StreamClient, { APIResponse, UnknownType } from './client'; +import StreamClient, { APIResponse, UnknownRecord } from './client'; import StreamFeed from './feed'; import * as errors from './errors'; @@ -10,7 +10,7 @@ export type TargetFeedsExtraData = Record; type ReactionBody = { activity_id?: string; // only required for reactions - data?: T | UnknownType; + data?: T | UnknownRecord; id?: string; // api will generate an id if it's missing kind?: string; // required only for add/addChile, not update parent?: string; // only required for child reactions @@ -19,7 +19,7 @@ type ReactionBody = { user_id?: string; // optional when using client tokens }; -export type Reaction = { +export type Reaction = { activity_id: string; created_at: string; data: T; From 1dc1a926bee7d40d482e8a6ca82c9014c77722d5 Mon Sep 17 00:00:00 2001 From: Amin Mahboubi Date: Thu, 30 Jul 2020 14:23:19 +0200 Subject: [PATCH 53/69] add default typeRoots --- tsconfig.json | 1 + 1 file changed, 1 insertion(+) diff --git a/tsconfig.json b/tsconfig.json index bee777d0..0a6fe9aa 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -13,6 +13,7 @@ "strictNullChecks": true, "strict": true, "lib": ["DOM", "ES6"], + "typeRoots": ["node_modules/@types"], "target": "ES5" }, "include": ["src"], From a64bbdbda6a3e17d4f80fe35296633b258560365 Mon Sep 17 00:00:00 2001 From: Amin Mahboubi Date: Thu, 30 Jul 2020 16:23:02 +0200 Subject: [PATCH 54/69] put type packages in deps --- package.json | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/package.json b/package.json index f1a7a235..0da6bafa 100644 --- a/package.json +++ b/package.json @@ -65,10 +65,6 @@ "@babel/preset-env": "^7.10.4", "@babel/preset-typescript": "^7.10.4", "@babel/register": "^7.10.4", - "@types/jsonwebtoken": "^8.5.0", - "@types/jwt-decode": "^2.2.1", - "@types/node": "^14.0.14", - "@types/qs": "^6.9.3", "@typescript-eslint/eslint-plugin": "^3.6.1", "@typescript-eslint/parser": "^3.6.1", "babel-eslint": "^10.1.0", @@ -107,6 +103,9 @@ }, "dependencies": { "@babel/runtime": "^7.10.4", + "@types/jsonwebtoken": "^8.5.0", + "@types/jwt-decode": "^2.2.0", + "@types/qs": "^6.9.4", "Base64": "^1.1.0", "axios": "^0.19.2", "faye": "^1.3.0", @@ -115,6 +114,9 @@ "jwt-decode": "^2.2.0", "qs": "^6.9.4" }, + "peerDependencies": { + "@types/node": ">=10" + }, "repository": { "type": "git", "url": "git://github.com/GetStream/stream-js.git" From 2ff2889d4f545549439e11a7d029ff08650ee6d8 Mon Sep 17 00:00:00 2001 From: Amin Mahboubi Date: Thu, 30 Jul 2020 16:26:54 +0200 Subject: [PATCH 55/69] fix faye type ref --- .eslintrc.js | 1 + package.json | 1 + src/client.ts | 2 ++ src/feed.ts | 2 ++ tsconfig.json | 2 +- src/modules_types.ts => types/modules.d.ts | 0 6 files changed, 7 insertions(+), 1 deletion(-) rename src/modules_types.ts => types/modules.d.ts (100%) diff --git a/.eslintrc.js b/.eslintrc.js index 306edd75..beeb5257 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -63,6 +63,7 @@ module.exports = { '@typescript-eslint/explicit-module-boundary-types': 0, '@typescript-eslint/ban-ts-comment': 0, 'no-useless-constructor': 0, + '@typescript-eslint/triple-slash-reference': 0, 'typescript-sort-keys/interface': [ 'error', 'asc', diff --git a/package.json b/package.json index 0da6bafa..b1addecc 100644 --- a/package.json +++ b/package.json @@ -124,6 +124,7 @@ "files": [ "src", "dist", + "types", "lib" ], "engines": { diff --git a/src/client.ts b/src/client.ts index 83381571..af671b28 100644 --- a/src/client.ts +++ b/src/client.ts @@ -1,3 +1,5 @@ +/// + import * as axios from 'axios'; import http from 'http'; import https from 'https'; diff --git a/src/feed.ts b/src/feed.ts index b9cf0f01..2b941abb 100644 --- a/src/feed.ts +++ b/src/feed.ts @@ -1,3 +1,5 @@ +/// + import * as Faye from 'faye'; import StreamClient, { APIResponse } from './client'; import StreamUser from './user'; diff --git a/tsconfig.json b/tsconfig.json index 0a6fe9aa..1a1d5978 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -16,6 +16,6 @@ "typeRoots": ["node_modules/@types"], "target": "ES5" }, - "include": ["src"], + "include": ["src", "types"], "exclude": ["node_modules", "test", "lib", "dist"] } diff --git a/src/modules_types.ts b/types/modules.d.ts similarity index 100% rename from src/modules_types.ts rename to types/modules.d.ts From c68894de1edf36e75218721228c3edb5159b98b0 Mon Sep 17 00:00:00 2001 From: Amin Mahboubi Date: Thu, 30 Jul 2020 17:29:21 +0200 Subject: [PATCH 56/69] 5.1.0-0 --- dist/js/getstream.js | 8532 +++++++++++++++++++------------------- dist/js_min/getstream.js | 2 +- package.json | 2 +- 3 files changed, 4359 insertions(+), 4177 deletions(-) diff --git a/dist/js/getstream.js b/dist/js/getstream.js index c5a40b01..08161a91 100644 --- a/dist/js/getstream.js +++ b/dist/js/getstream.js @@ -96,28 +96,57 @@ return /******/ (function(modules) { // webpackBootstrap /************************************************************************/ /******/ ([ /* 0 */ +/***/ (function(module, exports) { + +function _defineProperty(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; + } + + return obj; +} + +module.exports = _defineProperty; + +/***/ }), +/* 1 */ /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__(71); /***/ }), -/* 1 */ +/* 2 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; -/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2); +__webpack_require__.r(__webpack_exports__); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FeedError", function() { return FeedError; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SiteError", function() { return SiteError; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MissingSchemaError", function() { return MissingSchemaError; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StreamApiError", function() { return StreamApiError; }); +/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3); /* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var _babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(31); +/* harmony import */ var _babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(16); /* harmony import */ var _babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_1__); -/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(15); +/* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(17); /* harmony import */ var _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_2__); -/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(57); +/* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(62); /* harmony import */ var _babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_possibleConstructorReturn__WEBPACK_IMPORTED_MODULE_3__); -/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(25); +/* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(32); /* harmony import */ var _babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_getPrototypeOf__WEBPACK_IMPORTED_MODULE_4__); -/* harmony import */ var _babel_runtime_helpers_wrapNativeSuper__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(58); +/* harmony import */ var _babel_runtime_helpers_wrapNativeSuper__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(63); /* harmony import */ var _babel_runtime_helpers_wrapNativeSuper__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_wrapNativeSuper__WEBPACK_IMPORTED_MODULE_5__); +/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(0); +/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6__); + @@ -149,10 +178,13 @@ var ErrorAbstract = /*#__PURE__*/function (_Error) { _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, ErrorAbstract); _this = _super.call(this, msg); + + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6___default()(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_1___default()(_this), "message", void 0); + _this.message = msg; if (canCapture) { - Error.captureStackTrace(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_1___default()(_this), constructor); + Error.captureStackTrace(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_1___default()(_this), ErrorAbstract.constructor); } else if (canStack) { _this.stack = new Error().stack; } else { @@ -196,7 +228,6 @@ var FeedError = /*#__PURE__*/function (_ErrorAbstract) { * @param {string} [msg] An error message that will probably end up in a log. */ - var SiteError = /*#__PURE__*/function (_ErrorAbstract2) { _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_2___default()(SiteError, _ErrorAbstract2); @@ -219,7 +250,6 @@ var SiteError = /*#__PURE__*/function (_ErrorAbstract2) { * @param {string} msg */ - var MissingSchemaError = /*#__PURE__*/function (_ErrorAbstract3) { _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_2___default()(MissingSchemaError, _ErrorAbstract3); @@ -244,7 +274,6 @@ var MissingSchemaError = /*#__PURE__*/function (_ErrorAbstract3) { * @param {object} response */ - var StreamApiError = /*#__PURE__*/function (_ErrorAbstract4) { _babel_runtime_helpers_inherits__WEBPACK_IMPORTED_MODULE_2___default()(StreamApiError, _ErrorAbstract4); @@ -256,6 +285,11 @@ var StreamApiError = /*#__PURE__*/function (_ErrorAbstract4) { _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, StreamApiError); _this2 = _super5.call(this, msg); + + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6___default()(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_1___default()(_this2), "error", void 0); + + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_6___default()(_babel_runtime_helpers_assertThisInitialized__WEBPACK_IMPORTED_MODULE_1___default()(_this2), "response", void 0); + _this2.error = data; _this2.response = response; return _this2; @@ -264,15 +298,8 @@ var StreamApiError = /*#__PURE__*/function (_ErrorAbstract4) { return StreamApiError; }(ErrorAbstract); -/* harmony default export */ __webpack_exports__["a"] = ({ - FeedError: FeedError, - SiteError: SiteError, - MissingSchemaError: MissingSchemaError, - StreamApiError: StreamApiError -}); - /***/ }), -/* 2 */ +/* 3 */ /***/ (function(module, exports) { function _classCallCheck(instance, Constructor) { @@ -284,7 +311,7 @@ function _classCallCheck(instance, Constructor) { module.exports = _classCallCheck; /***/ }), -/* 3 */ +/* 4 */ /***/ (function(module, exports) { function _defineProperties(target, props) { @@ -305,39 +332,18 @@ function _createClass(Constructor, protoProps, staticProps) { module.exports = _createClass; -/***/ }), -/* 4 */ -/***/ (function(module, exports) { - -function _defineProperty(obj, key, value) { - if (key in obj) { - Object.defineProperty(obj, key, { - value: value, - enumerable: true, - configurable: true, - writable: true - }); - } else { - obj[key] = value; - } - - return obj; -} - -module.exports = _defineProperty; - /***/ }), /* 5 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; -/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(4); +/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0); /* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var _babel_runtime_helpers_typeof__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(14); +/* harmony import */ var _babel_runtime_helpers_typeof__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(21); /* harmony import */ var _babel_runtime_helpers_typeof__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_typeof__WEBPACK_IMPORTED_MODULE_1__); -/* harmony import */ var jsonwebtoken__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(33); +/* harmony import */ var jsonwebtoken__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(40); /* harmony import */ var jsonwebtoken__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(jsonwebtoken__WEBPACK_IMPORTED_MODULE_2__); -/* harmony import */ var Base64__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(66); +/* harmony import */ var Base64__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(65); /* harmony import */ var Base64__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(Base64__WEBPACK_IMPORTED_MODULE_3__); @@ -395,7 +401,9 @@ function headerFromJWS(jwsSig) { return safeJsonParse(decodeBase64Url(encodedHeader)); } -function JWTScopeToken(apiSecret, resource, action, opts) { +function JWTScopeToken(apiSecret, resource, action) { + var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; + /** * Creates the JWT token for feedId, resource and action using the apiSecret * @method JWTScopeToken @@ -407,24 +415,17 @@ function JWTScopeToken(apiSecret, resource, action, opts) { * @param {object} [options] - Optional additional options * @param {string} [options.feedId] - JWT payload feed identifier * @param {string} [options.userId] - JWT payload user identifier + * @param {boolean} [options.expireTokens] - JWT noTimestamp * @return {string} JWT Token */ - var options = opts || {}; var noTimestamp = options.expireTokens ? !options.expireTokens : true; var payload = { resource: resource, action: action }; - - if (options.feedId) { - payload.feed_id = options.feedId; - } - - if (options.userId) { - payload.user_id = options.userId; - } - - return jsonwebtoken__WEBPACK_IMPORTED_MODULE_2___default.a.sign(payload, apiSecret, { + if (options.feedId) payload.feed_id = options.feedId; + if (options.userId) payload.user_id = options.userId; + return jsonwebtoken__WEBPACK_IMPORTED_MODULE_2__["sign"](payload, apiSecret, { algorithm: 'HS256', noTimestamp: noTimestamp }); @@ -441,7 +442,7 @@ function JWTUserSessionToken(apiSecret, userId) { * @private * @param {string} apiSecret - API Secret key * @param {string} userId - The user_id key in the JWT payload - * @param {string} [extraData] - Extra that should be part of the JWT token + * @param {object} [extraData] - Extra that should be part of the JWT token * @param {object} [jwtOptions] - Options that can be past to jwt.sign * @return {string} JWT Token */ @@ -458,7 +459,7 @@ function JWTUserSessionToken(apiSecret, userId) { noTimestamp: true }, jwtOptions); - return jsonwebtoken__WEBPACK_IMPORTED_MODULE_2___default.a.sign(payload, apiSecret, opts); + return jsonwebtoken__WEBPACK_IMPORTED_MODULE_2__["sign"](payload, apiSecret, opts); } function isJWTSignature(signature) { @@ -533,13 +534,13 @@ module.exports = _asyncToGenerator; /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; -/* harmony import */ var _babel_runtime_helpers_slicedToArray__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(60); +/* harmony import */ var _babel_runtime_helpers_slicedToArray__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(66); /* harmony import */ var _babel_runtime_helpers_slicedToArray__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_slicedToArray__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var _babel_runtime_helpers_typeof__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(14); +/* harmony import */ var _babel_runtime_helpers_typeof__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(21); /* harmony import */ var _babel_runtime_helpers_typeof__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_typeof__WEBPACK_IMPORTED_MODULE_1__); -/* harmony import */ var form_data__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(61); +/* harmony import */ var form_data__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(67); /* harmony import */ var form_data__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(form_data__WEBPACK_IMPORTED_MODULE_2__); -/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1); +/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(2); @@ -552,7 +553,7 @@ function validateFeedSlug(feedSlug) { * Validate that the feedSlug matches \w */ if (!validFeedSlugRe.test(feedSlug)) { - throw new _errors__WEBPACK_IMPORTED_MODULE_3__[/* default */ "a"].FeedError("Invalid feedSlug, please use letters, numbers or _: ".concat(feedSlug)); + throw new _errors__WEBPACK_IMPORTED_MODULE_3__["FeedError"]("Invalid feedSlug, please use letters, numbers or _: ".concat(feedSlug)); } return feedSlug; @@ -563,7 +564,7 @@ function validateUserId(userId) { * Validate the userId matches \w */ if (!validUserIdRe.test(userId)) { - throw new _errors__WEBPACK_IMPORTED_MODULE_3__[/* default */ "a"].FeedError("Invalid userId, please use letters, numbers, - or _: ".concat(userId)); + throw new _errors__WEBPACK_IMPORTED_MODULE_3__["FeedError"]("Invalid userId, please use letters, numbers, - or _: ".concat(userId)); } return userId; @@ -576,7 +577,7 @@ function rfc3986(str) { } function isReadableStream(obj) { - return obj && _babel_runtime_helpers_typeof__WEBPACK_IMPORTED_MODULE_1___default()(obj) === 'object' && typeof obj._read === 'function' && _babel_runtime_helpers_typeof__WEBPACK_IMPORTED_MODULE_1___default()(obj._readableState) === 'object'; + return obj !== null && _babel_runtime_helpers_typeof__WEBPACK_IMPORTED_MODULE_1___default()(obj) === 'object' && typeof obj._read === 'function'; } function validateFeedId(feedId) { @@ -586,7 +587,7 @@ function validateFeedId(feedId) { var parts = feedId.split(':'); if (parts.length !== 2) { - throw new _errors__WEBPACK_IMPORTED_MODULE_3__[/* default */ "a"].FeedError("Invalid feedId, expected something like user:1 got ".concat(feedId)); + throw new _errors__WEBPACK_IMPORTED_MODULE_3__["FeedError"]("Invalid feedId, expected something like user:1 got ".concat(feedId)); } var _parts = _babel_runtime_helpers_slicedToArray__WEBPACK_IMPORTED_MODULE_0___default()(parts, 2), @@ -602,7 +603,9 @@ function addFileToFormData(uri, name, contentType) { var data = new form_data__WEBPACK_IMPORTED_MODULE_2___default.a(); var fileField; - if (isReadableStream(uri) || uri && uri.toString && uri.toString() === '[object File]') { + if (isReadableStream(uri)) { + fileField = uri; + } else if (uri && uri.toString && uri.toString() === '[object File]') { fileField = uri; } else { fileField = { @@ -614,18 +617,24 @@ function addFileToFormData(uri, name, contentType) { data.append('file', fileField); return data; -} +} // TODO: refactor and add proper types + function replaceStreamObjects(obj) { + // @ts-expect-error if (Array.isArray(obj)) return obj.map(function (v) { return replaceStreamObjects(v); - }); - if (Object.prototype.toString.call(obj) !== '[object Object]') return obj; + }); // @ts-expect-error + + if (Object.prototype.toString.call(obj) !== '[object Object]') return obj; // @ts-expect-error + if (typeof obj.ref === 'function') return obj.ref(); var cloned = {}; Object.keys(obj).forEach(function (k) { + // @ts-expect-error cloned[k] = replaceStreamObjects(obj[k]); - }); + }); // @ts-expect-error + return cloned; } @@ -669,7 +678,7 @@ module.exports = function(target) { "use strict"; -var bind = __webpack_require__(34); +var bind = __webpack_require__(41); /*global toString:true*/ @@ -1071,1141 +1080,1059 @@ module.exports = g; /***/ }), /* 12 */ -/***/ (function(module, exports, __webpack_require__) { +/***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; +/* WEBPACK VAR INJECTION */(function(process) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return StreamClient; }); +/* harmony import */ var _babel_runtime_helpers_objectWithoutProperties__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(22); +/* harmony import */ var _babel_runtime_helpers_objectWithoutProperties__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_objectWithoutProperties__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1); +/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1__); +/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(6); +/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2__); +/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(3); +/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_3__); +/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(4); +/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_4__); +/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(0); +/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_5__); +/* harmony import */ var axios__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(57); +/* harmony import */ var axios__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(axios__WEBPACK_IMPORTED_MODULE_6__); +/* harmony import */ var http__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(58); +/* harmony import */ var http__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(http__WEBPACK_IMPORTED_MODULE_7__); +/* harmony import */ var https__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(59); +/* harmony import */ var https__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(https__WEBPACK_IMPORTED_MODULE_8__); +/* harmony import */ var faye__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(60); +/* harmony import */ var faye__WEBPACK_IMPORTED_MODULE_9___default = /*#__PURE__*/__webpack_require__.n(faye__WEBPACK_IMPORTED_MODULE_9__); +/* harmony import */ var jwt_decode__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(61); +/* harmony import */ var jwt_decode__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(jwt_decode__WEBPACK_IMPORTED_MODULE_10__); +/* harmony import */ var _personalization__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(26); +/* harmony import */ var _collections__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(27); +/* harmony import */ var _files__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(28); +/* harmony import */ var _images__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(29); +/* harmony import */ var _reaction__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(30); +/* harmony import */ var _user__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(13); +/* harmony import */ var _redirect_url__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(39); +/* harmony import */ var _redirect_url__WEBPACK_IMPORTED_MODULE_17___default = /*#__PURE__*/__webpack_require__.n(_redirect_url__WEBPACK_IMPORTED_MODULE_17__); +/* harmony import */ var _signing__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(5); +/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(2); +/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(7); +/* harmony import */ var _batch_operations__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(23); +/* harmony import */ var _batch_operations__WEBPACK_IMPORTED_MODULE_21___default = /*#__PURE__*/__webpack_require__.n(_batch_operations__WEBPACK_IMPORTED_MODULE_21__); +/* harmony import */ var _feed__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(31); -module.exports = { - isURI: function(uri) { - return uri && uri.protocol && uri.host && uri.path; - }, - isSameOrigin: function(uri) { - return uri.protocol === location.protocol && - uri.hostname === location.hostname && - uri.port === location.port; - }, - parse: function(url) { - if (typeof url !== 'string') return url; - var uri = {}, parts, query, pairs, i, n, data; - var consume = function(name, pattern) { - url = url.replace(pattern, function(match) { - uri[name] = match; - return ''; - }); - uri[name] = uri[name] || ''; - }; - consume('protocol', /^[a-z]+\:/i); - consume('host', /^\/\/[^\/\?#]+/); - if (!/^\//.test(url) && !uri.host) - url = location.pathname.replace(/[^\/]*$/, '') + url; +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } - consume('pathname', /^[^\?#]*/); - consume('search', /^\?[^#]*/); - consume('hash', /^#.*/); +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_5___default()(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } - uri.protocol = uri.protocol || location.protocol; +/// - if (uri.host) { - uri.host = uri.host.substr(2); - if (/@/.test(uri.host)) { - uri.auth = uri.host.split('@')[0]; - uri.host = uri.host.split('@')[1]; - } - parts = uri.host.match(/^\[([^\]]+)\]|^[^:]+/); - uri.hostname = parts[1] || parts[0]; - uri.port = (uri.host.match(/:(\d+)$/) || [])[1] || ''; - } else { - uri.host = location.host; - uri.hostname = location.hostname; - uri.port = location.port; - } - uri.pathname = uri.pathname || '/'; - uri.path = uri.pathname + uri.search; - query = uri.search.replace(/^\?/, ''); - pairs = query ? query.split('&') : []; - data = {}; - for (i = 0, n = pairs.length; i < n; i++) { - parts = pairs[i].split('='); - data[decodeURIComponent(parts[0] || '')] = decodeURIComponent(parts[1] || ''); - } - uri.query = data; - uri.href = this.stringify(uri); - return uri; - }, - stringify: function(uri) { - var auth = uri.auth ? uri.auth + '@' : '', - string = uri.protocol + '//' + auth + uri.host; - string += uri.pathname + this.queryString(uri.query) + (uri.hash || ''); - return string; - }, - queryString: function(query) { - var pairs = []; - for (var key in query) { - if (!query.hasOwnProperty(key)) continue; - pairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(query[key])); - } - if (pairs.length === 0) return ''; - return '?' + pairs.join('&'); - } -}; -/***/ }), -/* 13 */ -/***/ (function(module, exports, __webpack_require__) { -"use strict"; -/* WEBPACK VAR INJECTION */(function(process) { -var Class = __webpack_require__(10), - Cookie = __webpack_require__(46).Cookie, - Promise = __webpack_require__(23), - array = __webpack_require__(26), - assign = __webpack_require__(8), - Logging = __webpack_require__(16), - Timeouts = __webpack_require__(94), - Channel = __webpack_require__(44); -var Transport = assign(Class({ className: 'Transport', - DEFAULT_PORTS: { 'http:': 80, 'https:': 443, 'ws:': 80, 'wss:': 443 }, - MAX_DELAY: 0, + // no import since typescript json loader shifts the final output structure +// eslint-disable-next-line @typescript-eslint/no-var-requires - batching: true, +var pkg = __webpack_require__(115); - initialize: function(dispatcher, endpoint) { - this._dispatcher = dispatcher; - this.endpoint = endpoint; - this._outbox = []; - this._proxy = assign({}, this._dispatcher.proxy); +/** + * Client to connect to Stream api + * @class StreamClient + */ +var StreamClient = /*#__PURE__*/function () { + function StreamClient(apiKey, apiSecretOrToken, appId) { + var _this = this, + _process, + _process$env, + _process2, + _process2$env; - if (!this._proxy.origin) - this._proxy.origin = this._findProxy(); - }, + var _options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; - close: function() {}, + _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_3___default()(this, StreamClient); - encode: function(messages) { - return ''; - }, + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_5___default()(this, "baseUrl", void 0); - sendMessage: function(message) { - this.debug('Client ? sending message to ?: ?', - this._dispatcher.clientId, this.endpoint.href, message); + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_5___default()(this, "baseAnalyticsUrl", void 0); - if (!this.batching) return Promise.resolve(this.request([message])); + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_5___default()(this, "apiKey", void 0); - this._outbox.push(message); - this._flushLargeBatch(); + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_5___default()(this, "appId", void 0); - if (message.channel === Channel.HANDSHAKE) - return this._publish(0.01); + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_5___default()(this, "usingApiSecret", void 0); - if (message.channel === Channel.CONNECT) - this._connectMessage = message; + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_5___default()(this, "apiSecret", void 0); - return this._publish(this.MAX_DELAY); - }, + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_5___default()(this, "userToken", void 0); - _makePromise: function() { - var self = this; + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_5___default()(this, "enrichByDefault", void 0); - this._requestPromise = this._requestPromise || new Promise(function(resolve) { - self._resolvePromise = resolve; - }); - }, + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_5___default()(this, "options", void 0); - _publish: function(delay) { - this._makePromise(); + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_5___default()(this, "userId", void 0); - this.addTimeout('publish', delay, function() { - this._flush(); - delete this._requestPromise; - }, this); + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_5___default()(this, "authPayload", void 0); - return this._requestPromise; - }, + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_5___default()(this, "version", void 0); - _flush: function() { - this.removeTimeout('publish'); + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_5___default()(this, "fayeUrl", void 0); - if (this._outbox.length > 1 && this._connectMessage) - this._connectMessage.advice = { timeout: 0 }; + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_5___default()(this, "group", void 0); - this._resolvePromise(this.request(this._outbox)); + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_5___default()(this, "expireTokens", void 0); - this._connectMessage = null; - this._outbox = []; - }, + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_5___default()(this, "location", void 0); - _flushLargeBatch: function() { - var string = this.encode(this._outbox); - if (string.length < this._dispatcher.maxRequestSize) return; - var last = this._outbox.pop(); + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_5___default()(this, "fayeClient", void 0); - this._makePromise(); - this._flush(); + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_5___default()(this, "browser", void 0); - if (last) this._outbox.push(last); - }, + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_5___default()(this, "node", void 0); - _receive: function(replies) { - if (!replies) return; - replies = [].concat(replies); + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_5___default()(this, "nodeOptions", void 0); - this.debug('Client ? received from ? via ?: ?', - this._dispatcher.clientId, this.endpoint.href, this.connectionType, replies); + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_5___default()(this, "request", void 0); - for (var i = 0, n = replies.length; i < n; i++) - this._dispatcher.handleResponse(replies[i]); - }, + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_5___default()(this, "subscriptions", void 0); - _handleError: function(messages, immediate) { - messages = [].concat(messages); + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_5___default()(this, "handlers", void 0); - this.debug('Client ? failed to send to ? via ?: ?', - this._dispatcher.clientId, this.endpoint.href, this.connectionType, messages); + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_5___default()(this, "currentUser", void 0); - for (var i = 0, n = messages.length; i < n; i++) - this._dispatcher.handleError(messages[i]); - }, + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_5___default()(this, "personalization", void 0); - _getCookies: function() { - var cookies = this._dispatcher.cookies, - url = this.endpoint.href; + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_5___default()(this, "collections", void 0); - if (!cookies) return ''; + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_5___default()(this, "files", void 0); - return array.map(cookies.getCookiesSync(url), function(cookie) { - return cookie.cookieString(); - }).join('; '); - }, + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_5___default()(this, "images", void 0); - _storeCookies: function(setCookie) { - var cookies = this._dispatcher.cookies, - url = this.endpoint.href, - cookie; + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_5___default()(this, "reactions", void 0); - if (!setCookie || !cookies) return; - setCookie = [].concat(setCookie); + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_5___default()(this, "_personalizationToken", void 0); - for (var i = 0, n = setCookie.length; i < n; i++) { - cookie = Cookie.parse(setCookie[i]); - cookies.setCookieSync(cookie, url); - } - }, + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_5___default()(this, "_collectionsToken", void 0); - _findProxy: function() { - if (typeof process === 'undefined') return undefined; + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_5___default()(this, "_getOrCreateToken", void 0); - var protocol = this.endpoint.protocol; - if (!protocol) return undefined; + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_5___default()(this, "addToMany", void 0); - var name = protocol.replace(/:$/, '').toLowerCase() + '_proxy', - upcase = name.toUpperCase(), - env = process.env, - keys, proxy; + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_5___default()(this, "followMany", void 0); - if (name === 'http_proxy' && env.REQUEST_METHOD) { - keys = Object.keys(env).filter(function(k) { return /^http_proxy$/i.test(k) }); - if (keys.length === 1) { - if (keys[0] === name && env[upcase] === undefined) - proxy = env[name]; - } else if (keys.length > 1) { - proxy = env[name]; - } - proxy = proxy || env['CGI_' + upcase]; - } else { - proxy = env[name] || env[upcase]; - if (proxy && !env[name]) - console.warn('The environment variable ' + upcase + - ' is discouraged. Use ' + name + '.'); - } - return proxy; - } + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_5___default()(this, "unfollowMany", void 0); -}), { - get: function(dispatcher, allowed, disabled, callback, context) { - var endpoint = dispatcher.endpoint; + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_5___default()(this, "createRedirectUrl", void 0); - array.asyncEach(this._transports, function(pair, resume) { - var connType = pair[0], klass = pair[1], - connEndpoint = dispatcher.endpointFor(connType); + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_5___default()(this, "replaceReactionOptions", function (options) { + // Shortcut options for reaction enrichment + if (options === null || options === void 0 ? void 0 : options.reactions) { + if (options.reactions.own != null) { + options.withOwnReactions = options.reactions.own; + } - if (array.indexOf(disabled, connType) >= 0) - return resume(); + if (options.reactions.recent != null) { + options.withRecentReactions = options.reactions.recent; + } - if (array.indexOf(allowed, connType) < 0) { - klass.isUsable(dispatcher, connEndpoint, function() {}); - return resume(); - } + if (options.reactions.counts != null) { + options.withReactionCounts = options.reactions.counts; + } - klass.isUsable(dispatcher, connEndpoint, function(isUsable) { - if (!isUsable) return resume(); - var transport = klass.hasOwnProperty('create') ? klass.create(dispatcher, connEndpoint) : new klass(dispatcher, connEndpoint); - callback.call(context, transport); - }); - }, function() { - throw new Error('Could not find a usable connection type for ' + endpoint.href); - }); - }, + if (options.reactions.own_children != null) { + options.withOwnChildren = options.reactions.own_children; + } - register: function(type, klass) { - this._transports.push([type, klass]); - klass.prototype.connectionType = type; - }, + delete options.reactions; + } + }); - getConnectionTypes: function() { - return array.map(this._transports, function(t) { return t[0] }); - }, + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_5___default()(this, "handleResponse", function (response) { + if (/^2/.test("".concat(response.status))) { + _this.send('response', null, response, response.data); - disable: function(feature) { - if (feature !== 'autodisconnect') return; + return response.data; + } - for (var i = 0; i < this._transports.length; i++) - this._transports[i][1]._unloaded = false; - }, + throw new _errors__WEBPACK_IMPORTED_MODULE_19__["StreamApiError"]("".concat(JSON.stringify(response.data), " with HTTP status code ").concat(response.status), response.data, response); + }); - _transports: [] -}); + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_5___default()(this, "doAxiosRequest", /*#__PURE__*/function () { + var _ref = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.mark(function _callee(method, options) { + var response; + return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + _this.send('request', method, options); -assign(Transport.prototype, Logging); -assign(Transport.prototype, Timeouts); + _context.prev = 1; + _context.next = 4; + return _this.request(_this.enrichKwargs(_objectSpread({ + method: method + }, options))); -module.exports = Transport; + case 4: + response = _context.sent; + return _context.abrupt("return", _this.handleResponse(response)); -/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(22))) + case 8: + _context.prev = 8; + _context.t0 = _context["catch"](1); -/***/ }), -/* 14 */ -/***/ (function(module, exports) { + if (!_context.t0.response) { + _context.next = 12; + break; + } -function _typeof(obj) { - "@babel/helpers - typeof"; + return _context.abrupt("return", _this.handleResponse(_context.t0.response)); - if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { - module.exports = _typeof = function _typeof(obj) { - return typeof obj; - }; - } else { - module.exports = _typeof = function _typeof(obj) { - return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; - }; - } + case 12: + throw new _errors__WEBPACK_IMPORTED_MODULE_19__["SiteError"](_context.t0.message); - return _typeof(obj); -} + case 13: + case "end": + return _context.stop(); + } + } + }, _callee, null, [[1, 8]]); + })); -module.exports = _typeof; + return function (_x, _x2) { + return _ref.apply(this, arguments); + }; + }()); -/***/ }), -/* 15 */ -/***/ (function(module, exports, __webpack_require__) { + /** + * Initialize a client + * @method initialize + * @memberof StreamClient.prototype + * @param {string} apiKey - the api key + * @param {string} [apiSecret] - the api secret + * @param {string} [appId] - id of the app + * @param {ClientOptions} [options] - additional options + * @param {string} [options.location] - which data center to use + * @param {boolean} [options.expireTokens=false] - whether to use a JWT timestamp field (i.e. iat) + * @param {string} [options.version] - advanced usage, custom api version + * @param {boolean} [options.keepAlive] - axios keepAlive, default to true + * @param {number} [options.timeout] - axios timeout in Ms, default to 10s + * @example initialize is not directly called by via stream.connect, ie: + * stream.connect(apiKey, apiSecret) + * @example secret is optional and only used in server side mode + * stream.connect(apiKey, null, appId); + */ + this.baseUrl = 'https://api.stream-io-api.com/api/'; + this.baseAnalyticsUrl = 'https://analytics.stream-io-api.com/analytics/'; + this.apiKey = apiKey; + this.usingApiSecret = apiSecretOrToken != null && !_signing__WEBPACK_IMPORTED_MODULE_18__[/* default */ "a"].isJWT(apiSecretOrToken); + this.apiSecret = this.usingApiSecret ? apiSecretOrToken : null; + this.userToken = this.usingApiSecret ? null : apiSecretOrToken; + this.enrichByDefault = !this.usingApiSecret; -var setPrototypeOf = __webpack_require__(30); + if (this.userToken != null) { + var jwtBody = jwt_decode__WEBPACK_IMPORTED_MODULE_10___default()(this.userToken); -function _inherits(subClass, superClass) { - if (typeof superClass !== "function" && superClass !== null) { - throw new TypeError("Super expression must either be null or a function"); - } + if (!jwtBody.user_id) { + throw new TypeError('user_id is missing in user token'); + } - subClass.prototype = Object.create(superClass && superClass.prototype, { - constructor: { - value: subClass, - writable: true, - configurable: true + this.userId = jwtBody.user_id; + this.currentUser = this.user(this.userId); + this.authPayload = jwtBody; } - }); - if (superClass) setPrototypeOf(subClass, superClass); -} -module.exports = _inherits; + this.appId = appId; + this.options = _options; + this.version = this.options.version || 'v1.0'; + this.fayeUrl = this.options.fayeUrl || 'https://faye-us-east.stream-io-api.com/faye'; + this.fayeClient = null; // track a source name for the api calls, ie get started or databrowser -/***/ }), -/* 16 */ -/***/ (function(module, exports, __webpack_require__) { + this.group = this.options.group || 'unspecified'; // track subscriptions made on feeds created by this client -"use strict"; + this.subscriptions = {}; + this.expireTokens = this.options.expireTokens ? this.options.expireTokens : false; // which data center to use + this.location = this.options.location; + this.baseUrl = this.getBaseUrl(); + if ((_process = process) === null || _process === void 0 ? void 0 : (_process$env = _process.env) === null || _process$env === void 0 ? void 0 : _process$env.LOCAL_FAYE) this.fayeUrl = 'http://localhost:9999/faye/'; + if ((_process2 = process) === null || _process2 === void 0 ? void 0 : (_process2$env = _process2.env) === null || _process2$env === void 0 ? void 0 : _process2$env.STREAM_ANALYTICS_BASE_URL) this.baseAnalyticsUrl = process.env.STREAM_ANALYTICS_BASE_URL; + this.handlers = {}; + this.browser = typeof this.options.browser !== 'undefined' ? this.options.browser : typeof window !== 'undefined'; + this.node = !this.browser; -var toJSON = __webpack_require__(17); + if (this.node) { + var keepAlive = this.options.keepAlive === undefined ? true : this.options.keepAlive; + this.nodeOptions = { + httpAgent: new http__WEBPACK_IMPORTED_MODULE_7___default.a.Agent({ + keepAlive: keepAlive, + keepAliveMsecs: 3000 + }), + httpsAgent: new https__WEBPACK_IMPORTED_MODULE_8___default.a.Agent({ + keepAlive: keepAlive, + keepAliveMsecs: 3000 + }) + }; + } -var Logging = { - LOG_LEVELS: { - fatal: 4, - error: 3, - warn: 2, - info: 1, - debug: 0 - }, + this.request = axios__WEBPACK_IMPORTED_MODULE_6___default.a.create(_objectSpread({ + timeout: this.options.timeout || 10 * 1000, + // 10 seconds + withCredentials: false + }, this.nodeOptions || {})); + this.personalization = new _personalization__WEBPACK_IMPORTED_MODULE_11__[/* default */ "a"](this); - writeLog: function(messageArgs, level) { - var logger = Logging.logger || (Logging.wrapper || Logging).logger; - if (!logger) return; + if (this.browser && this.usingApiSecret) { + throw new _errors__WEBPACK_IMPORTED_MODULE_19__["FeedError"]('You are publicly sharing your App Secret. Do not expose the App Secret in browsers, "native" mobile apps, or other non-trusted environments.'); + } - var args = Array.prototype.slice.apply(messageArgs), - banner = '[Faye', - klass = this.className, + this.collections = new _collections__WEBPACK_IMPORTED_MODULE_12__[/* default */ "a"](this, this.getOrCreateToken()); + this.files = new _files__WEBPACK_IMPORTED_MODULE_13__[/* default */ "a"](this, this.getOrCreateToken()); + this.images = new _images__WEBPACK_IMPORTED_MODULE_14__[/* default */ "a"](this, this.getOrCreateToken()); + this.reactions = new _reaction__WEBPACK_IMPORTED_MODULE_15__[/* default */ "a"](this, this.getOrCreateToken()); // If we are in a node environment and batchOperations/createRedirectUrl is available add the methods to the prototype of StreamClient - message = args.shift().replace(/\?/g, function() { - try { - return toJSON(args.shift()); - } catch (error) { - return '[Object]'; - } - }); + if (_batch_operations__WEBPACK_IMPORTED_MODULE_21___default.a && _redirect_url__WEBPACK_IMPORTED_MODULE_17___default.a) { + this.addToMany = _batch_operations__WEBPACK_IMPORTED_MODULE_21___default.a.addToMany; + this.followMany = _batch_operations__WEBPACK_IMPORTED_MODULE_21___default.a.followMany; + this.unfollowMany = _batch_operations__WEBPACK_IMPORTED_MODULE_21___default.a.unfollowMany; + this.createRedirectUrl = _redirect_url__WEBPACK_IMPORTED_MODULE_17___default.a; + } + } - if (klass) banner += '.' + klass; - banner += '] '; - - if (typeof logger[level] === 'function') - logger[level](banner + message); - else if (typeof logger === 'function') - logger(banner + message); - } -}; - -for (var key in Logging.LOG_LEVELS) - (function(level) { - Logging[level] = function() { - this.writeLog(arguments, level); - }; - })(key); - -module.exports = Logging; - - -/***/ }), -/* 17 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -// http://assanka.net/content/tech/2009/09/02/json2-js-vs-prototype/ - -module.exports = function(object) { - return JSON.stringify(object, function(key, value) { - return (this[key] instanceof Array) ? this[key] : value; - }); -}; - - -/***/ }), -/* 18 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; -/* WEBPACK VAR INJECTION */(function(global) { + _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_4___default()(StreamClient, [{ + key: "_throwMissingApiSecret", + value: function _throwMissingApiSecret() { + if (!this.usingApiSecret) { + throw new _errors__WEBPACK_IMPORTED_MODULE_19__["SiteError"]('This method can only be used server-side using your API Secret, use client = stream.connect(key, secret);'); + } + } + }, { + key: "getPersonalizationToken", + value: function getPersonalizationToken() { + if (this._personalizationToken) return this._personalizationToken; -var Promise = __webpack_require__(23); + this._throwMissingApiSecret(); -module.exports = { - then: function(callback, errback) { - var self = this; - if (!this._promise) - this._promise = new Promise(function(resolve, reject) { - self._resolve = resolve; - self._reject = reject; + this._personalizationToken = _signing__WEBPACK_IMPORTED_MODULE_18__[/* default */ "a"].JWTScopeToken(this.apiSecret, 'personalization', '*', { + userId: '*', + feedId: '*', + expireTokens: this.expireTokens }); - - if (arguments.length === 0) - return this._promise; - else - return this._promise.then(callback, errback); - }, - - callback: function(callback, context) { - return this.then(function(value) { callback.call(context, value) }); - }, - - errback: function(callback, context) { - return this.then(null, function(reason) { callback.call(context, reason) }); - }, - - timeout: function(seconds, message) { - this.then(); - var self = this; - this._timer = global.setTimeout(function() { - self._reject(message); - }, seconds * 1000); - }, - - setDeferredStatus: function(status, value) { - if (this._timer) global.clearTimeout(this._timer); - - this.then(); - - if (status === 'succeeded') - this._resolve(value); - else if (status === 'failed') - this._reject(value); - else - delete this._promise; - } -}; - -/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(11))) - -/***/ }), -/* 19 */ -/***/ (function(module, exports, __webpack_require__) { - -var objectWithoutPropertiesLoose = __webpack_require__(70); - -function _objectWithoutProperties(source, excluded) { - if (source == null) return {}; - var target = objectWithoutPropertiesLoose(source, excluded); - var key, i; - - if (Object.getOwnPropertySymbols) { - var sourceSymbolKeys = Object.getOwnPropertySymbols(source); - - for (i = 0; i < sourceSymbolKeys.length; i++) { - key = sourceSymbolKeys[i]; - if (excluded.indexOf(key) >= 0) continue; - if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; - target[key] = source[key]; + return this._personalizationToken; } - } - - return target; -} - -module.exports = _objectWithoutProperties; - -/***/ }), -/* 20 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return StreamUser; }); -/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0); -/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(4); -/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_1__); -/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(6); -/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2__); -/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(2); -/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_3__); -/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(3); -/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_4__); - - - - - - -function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } - -function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_1___default()(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } - -var StreamUser = /*#__PURE__*/function () { - function StreamUser(client, userId, userAuthToken) { - _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_3___default()(this, StreamUser); + }, { + key: "getCollectionsToken", + value: function getCollectionsToken() { + if (this._collectionsToken) return this._collectionsToken; - /** - * Initialize a user session object - * @method constructor - * @memberof StreamUser.prototype - * @param {StreamClient} client Stream client this collection is constructed from - * @param {string} userId The ID of the user - * @param {string} token JWT token - * @example new StreamUser(client, "123", "eyJhbGciOiJIUzI1...") - */ - this.client = client; - this.id = userId; - this.data = undefined; - this.full = undefined; - this.token = userAuthToken; - this.url = "user/".concat(this.id, "/"); - } + this._throwMissingApiSecret(); - _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_4___default()(StreamUser, [{ - key: "ref", - value: function ref() { - return "SU:".concat(this.id); + this._collectionsToken = _signing__WEBPACK_IMPORTED_MODULE_18__[/* default */ "a"].JWTScopeToken(this.apiSecret, 'collections', '*', { + feedId: '*', + expireTokens: this.expireTokens + }); + return this._collectionsToken; } }, { - key: "delete", - value: function _delete() { - return this.client.delete({ - url: this.url, - signature: this.token + key: "getAnalyticsToken", + value: function getAnalyticsToken() { + this._throwMissingApiSecret(); + + return _signing__WEBPACK_IMPORTED_MODULE_18__[/* default */ "a"].JWTScopeToken(this.apiSecret, 'analytics', '*', { + userId: '*', + expireTokens: this.expireTokens }); } }, { - key: "get", - value: function () { - var _get = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee(options) { - var response; - return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - _context.next = 2; - return this.client.get({ - url: this.url, - signature: this.token, - qs: options - }); - - case 2: - response = _context.sent; - this.full = _objectSpread({}, response); - delete this.full.duration; - this.data = this.full.data; - return _context.abrupt("return", this); + key: "getBaseUrl", + value: function getBaseUrl(serviceName) { + var _process3, _process3$env, _process4, _process4$env; - case 7: - case "end": - return _context.stop(); - } - } - }, _callee, this); - })); + if (!serviceName) serviceName = 'api'; + if (this.options.urlOverride && this.options.urlOverride[serviceName]) return this.options.urlOverride[serviceName]; + var urlEnvironmentKey = serviceName === 'api' ? 'STREAM_BASE_URL' : "STREAM_".concat(serviceName.toUpperCase(), "_URL"); + if ((_process3 = process) === null || _process3 === void 0 ? void 0 : (_process3$env = _process3.env) === null || _process3$env === void 0 ? void 0 : _process3$env[urlEnvironmentKey]) return process.env[urlEnvironmentKey]; + if (((_process4 = process) === null || _process4 === void 0 ? void 0 : (_process4$env = _process4.env) === null || _process4$env === void 0 ? void 0 : _process4$env.LOCAL) || this.options.local) return "http://localhost:8000/".concat(serviceName, "/"); - function get(_x) { - return _get.apply(this, arguments); + if (this.location) { + var protocol = this.options.protocol || 'https'; + return "".concat(protocol, "://").concat(this.location, "-").concat(serviceName, ".stream-io-api.com/").concat(serviceName, "/"); } - return get; - }() + if (serviceName !== 'api') return "https://".concat(serviceName, ".stream-io-api.com/").concat(serviceName, "/"); + return this.baseUrl; + } }, { - key: "create", - value: function () { - var _create = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee2(data, options) { - var response; - return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee2$(_context2) { - while (1) { - switch (_context2.prev = _context2.next) { - case 0: - _context2.next = 2; - return this.client.post({ - url: 'user/', - body: { - id: this.id, - data: data || this.data || {} - }, - qs: options, - signature: this.token - }); - - case 2: - response = _context2.sent; - this.full = _objectSpread({}, response); - delete this.full.duration; - this.data = this.full.data; - return _context2.abrupt("return", this); - - case 7: - case "end": - return _context2.stop(); - } - } - }, _callee2, this); - })); - - function create(_x2, _x3) { - return _create.apply(this, arguments); + key: "on", + value: function on(event, callback) { + /** + * Support for global event callbacks + * This is useful for generic error and loading handling + * @method on + * @memberof StreamClient.prototype + * @param {string} event - Name of the event + * @param {function} callback - Function that is called when the event fires + * @example + * client.on('request', callback); + * client.on('response', callback); + */ + this.handlers[event] = callback; + } + }, { + key: "off", + value: function off(key) { + /** + * Remove one or more event handlers + * @method off + * @memberof StreamClient.prototype + * @param {string} [key] - Name of the handler + * @example + * client.off() removes all handlers + * client.off(name) removes the specified handler + */ + if (key === undefined) { + this.handlers = {}; + } else { + delete this.handlers[key]; } - - return create; - }() + } }, { - key: "update", - value: function () { - var _update = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee3(data) { - var response; - return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee3$(_context3) { - while (1) { - switch (_context3.prev = _context3.next) { - case 0: - _context3.next = 2; - return this.client.put({ - url: this.url, - body: { - data: data || this.data || {} - }, - signature: this.token - }); - - case 2: - response = _context3.sent; - this.full = _objectSpread({}, response); - delete this.full.duration; - this.data = this.full.data; - return _context3.abrupt("return", this); - - case 7: - case "end": - return _context3.stop(); - } - } - }, _callee3, this); - })); - - function update(_x4) { - return _update.apply(this, arguments); + key: "send", + value: function send(key) { + for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + args[_key - 1] = arguments[_key]; } - return update; - }() + /** + * Call the given handler with the arguments + * @method send + * @memberof StreamClient.prototype + * @access private + */ + if (this.handlers[key]) this.handlers[key].apply(this, args); + } }, { - key: "getOrCreate", - value: function getOrCreate(data) { - return this.create(data, { - get_or_create: true + key: "userAgent", + value: function userAgent() { + /** + * Get the current user agent + * @method userAgent + * @memberof StreamClient.prototype + * @return {string} current user agent + */ + return "stream-javascript-client-".concat(this.node ? 'node' : 'browser', "-").concat(pkg.version); + } + }, { + key: "getReadOnlyToken", + value: function getReadOnlyToken(feedSlug, userId) { + /** + * Returns a token that allows only read operations + * + * @method getReadOnlyToken + * @memberof StreamClient.prototype + * @param {string} feedSlug - The feed slug to get a read only token for + * @param {string} userId - The user identifier + * @return {string} token + * @example client.getReadOnlyToken('user', '1'); + */ + _utils__WEBPACK_IMPORTED_MODULE_20__[/* default */ "a"].validateFeedSlug(feedSlug); + _utils__WEBPACK_IMPORTED_MODULE_20__[/* default */ "a"].validateUserId(userId); + return _signing__WEBPACK_IMPORTED_MODULE_18__[/* default */ "a"].JWTScopeToken(this.apiSecret, '*', 'read', { + feedId: "".concat(feedSlug).concat(userId), + expireTokens: this.expireTokens }); } }, { - key: "profile", - value: function profile() { - return this.get({ - with_follow_counts: true + key: "getReadWriteToken", + value: function getReadWriteToken(feedSlug, userId) { + /** + * Returns a token that allows read and write operations + * + * @method getReadWriteToken + * @memberof StreamClient.prototype + * @param {string} feedSlug - The feed slug to get a read only token for + * @param {string} userId - The user identifier + * @return {string} token + * @example client.getReadWriteToken('user', '1'); + */ + _utils__WEBPACK_IMPORTED_MODULE_20__[/* default */ "a"].validateFeedSlug(feedSlug); + _utils__WEBPACK_IMPORTED_MODULE_20__[/* default */ "a"].validateUserId(userId); + return _signing__WEBPACK_IMPORTED_MODULE_18__[/* default */ "a"].JWTScopeToken(this.apiSecret, '*', '*', { + feedId: "".concat(feedSlug).concat(userId), + expireTokens: this.expireTokens }); } - }]); - - return StreamUser; -}(); - - - -/***/ }), -/* 21 */ -/***/ (function(module, exports) { - - - -/***/ }), -/* 22 */ -/***/ (function(module, exports) { - -// shim for using process in browser -var process = module.exports = {}; - -// cached from whatever global is present so that test runners that stub it -// don't break things. But we need to wrap it in a try catch in case it is -// wrapped in strict mode code which doesn't define any globals. It's inside a -// function because try/catches deoptimize in certain engines. - -var cachedSetTimeout; -var cachedClearTimeout; + }, { + key: "feed", + value: function feed(feedSlug, userId, token) { + /** + * Returns a feed object for the given feed id and token + * @method feed + * @memberof StreamClient.prototype + * @param {string} feedSlug - The feed slug + * @param {string} [userId] - The user identifier + * @param {string} [token] - The token + * @return {StreamFeed} + * @example client.feed('user', '1'); + */ + if (userId instanceof _user__WEBPACK_IMPORTED_MODULE_16__[/* default */ "a"]) userId = userId.id; -function defaultSetTimout() { - throw new Error('setTimeout has not been defined'); -} -function defaultClearTimeout () { - throw new Error('clearTimeout has not been defined'); -} -(function () { - try { - if (typeof setTimeout === 'function') { - cachedSetTimeout = setTimeout; - } else { - cachedSetTimeout = defaultSetTimout; - } - } catch (e) { - cachedSetTimeout = defaultSetTimout; - } - try { - if (typeof clearTimeout === 'function') { - cachedClearTimeout = clearTimeout; + if (token === undefined) { + if (this.usingApiSecret) { + token = _signing__WEBPACK_IMPORTED_MODULE_18__[/* default */ "a"].JWTScopeToken(this.apiSecret, '*', '*', { + feedId: "".concat(feedSlug).concat(userId) + }); } else { - cachedClearTimeout = defaultClearTimeout; + token = this.userToken; } - } catch (e) { - cachedClearTimeout = defaultClearTimeout; - } -} ()) -function runTimeout(fun) { - if (cachedSetTimeout === setTimeout) { - //normal enviroments in sane situations - return setTimeout(fun, 0); - } - // if setTimeout wasn't available but was latter defined - if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { - cachedSetTimeout = setTimeout; - return setTimeout(fun, 0); + } + + return new _feed__WEBPACK_IMPORTED_MODULE_22__[/* default */ "a"](this, feedSlug, userId || this.userId, token); } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedSetTimeout(fun, 0); - } catch(e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedSetTimeout.call(null, fun, 0); - } catch(e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error - return cachedSetTimeout.call(this, fun, 0); - } + }, { + key: "enrichUrl", + value: function enrichUrl(relativeUrl, serviceName) { + /** + * Combines the base url with version and the relative url + * @method enrichUrl + * @memberof StreamClient.prototype + * @private + * @param {string} relativeUrl + * @param {string} [serviceName] + * @return {string} + */ + return "".concat(this.getBaseUrl(serviceName)).concat(this.version, "/").concat(relativeUrl); } + }, { + key: "shouldUseEnrichEndpoint", + value: function shouldUseEnrichEndpoint() { + var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + if (options.enrich) { + var result = options.enrich; + delete options.enrich; + return result; + } -} -function runClearTimeout(marker) { - if (cachedClearTimeout === clearTimeout) { - //normal enviroments in sane situations - return clearTimeout(marker); - } - // if clearTimeout wasn't available but was latter defined - if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { - cachedClearTimeout = clearTimeout; - return clearTimeout(marker); + return this.enrichByDefault || options.ownReactions != null || options.withRecentReactions != null || options.withReactionCounts != null || options.withOwnChildren != null; } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedClearTimeout(marker); - } catch (e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedClearTimeout.call(null, marker); - } catch (e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. - // Some versions of I.E. have different rules for clearTimeout vs setTimeout - return cachedClearTimeout.call(this, marker); - } + }, { + key: "enrichKwargs", + value: function enrichKwargs(_ref2) { + var method = _ref2.method, + signature = _ref2.signature, + kwargs = _babel_runtime_helpers_objectWithoutProperties__WEBPACK_IMPORTED_MODULE_0___default()(_ref2, ["method", "signature"]); + + /** + * Adds the API key and the signature + * @method enrichKwargs + * @private + * @memberof StreamClient.prototype + * @param {AxiosConfig} kwargs + * @return {axios.AxiosRequestConfig} + */ + var isJWT = _signing__WEBPACK_IMPORTED_MODULE_18__[/* default */ "a"].isJWTSignature(signature); + return _objectSpread({ + method: method, + url: this.enrichUrl(kwargs.url, kwargs.serviceName), + data: kwargs.body, + params: _objectSpread({ + api_key: this.apiKey, + location: this.group + }, kwargs.qs || {}), + headers: _objectSpread({ + 'X-Stream-Client': this.userAgent(), + 'stream-auth-type': isJWT ? 'jwt' : 'simple', + Authorization: isJWT ? signature.split(' ').reverse()[0] : signature + }, kwargs.headers || {}) + }, kwargs.axiosOptions || {}); } + }, { + key: "getFayeAuthorization", + value: function getFayeAuthorization() { + var _this2 = this; + /** + * Get the authorization middleware to use Faye with getstream.io + * @method getFayeAuthorization + * @memberof StreamClient.prototype + * @private + * @return {Faye.Middleware} Faye authorization middleware + */ + return { + incoming: function incoming(message, callback) { + return callback(message); + }, + outgoing: function outgoing(message, callback) { + if (message.subscription && _this2.subscriptions[message.subscription]) { + var subscription = _this2.subscriptions[message.subscription]; + message.ext = { + user_id: subscription.userId, + api_key: _this2.apiKey, + signature: subscription.token + }; + } + callback(message); + } + }; + } + }, { + key: "getFayeClient", + value: function getFayeClient() { + var timeout = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 10; -} -var queue = []; -var draining = false; -var currentQueue; -var queueIndex = -1; + /** + * Returns this client's current Faye client + * @method getFayeClient + * @memberof StreamClient.prototype + * @private + * @param {number} timeout + * @return {Faye.Client} Faye client + */ + if (this.fayeClient === null) { + this.fayeClient = new faye__WEBPACK_IMPORTED_MODULE_9__["Client"](this.fayeUrl, { + timeout: timeout + }); + var authExtension = this.getFayeAuthorization(); + this.fayeClient.addExtension(authExtension); + } -function cleanUpNextTick() { - if (!draining || !currentQueue) { - return; - } - draining = false; - if (currentQueue.length) { - queue = currentQueue.concat(queue); - } else { - queueIndex = -1; + return this.fayeClient; } - if (queue.length) { - drainQueue(); + }, { + key: "upload", + value: function upload(url, uri, name, contentType, onUploadProgress) { + var fd = _utils__WEBPACK_IMPORTED_MODULE_20__[/* default */ "a"].addFileToFormData(uri, name, contentType); + return this.doAxiosRequest('POST', { + url: url, + body: fd, + headers: fd.getHeaders ? fd.getHeaders() : {}, + // node vs browser + signature: this.getOrCreateToken(), + axiosOptions: { + timeout: 0, + maxContentLength: Infinity, + onUploadProgress: onUploadProgress + } + }); } -} - -function drainQueue() { - if (draining) { - return; + }, { + key: "get", + value: function get(kwargs) { + /** + * Shorthand function for get request + * @method get + * @memberof StreamClient.prototype + * @private + * @param {AxiosConfig} kwargs + * @return {Promise} Promise object + */ + return this.doAxiosRequest('GET', kwargs); } - var timeout = runTimeout(cleanUpNextTick); - draining = true; - - var len = queue.length; - while(len) { - currentQueue = queue; - queue = []; - while (++queueIndex < len) { - if (currentQueue) { - currentQueue[queueIndex].run(); - } - } - queueIndex = -1; - len = queue.length; + }, { + key: "post", + value: function post(kwargs) { + /** + * Shorthand function for post request + * @method post + * @memberof StreamClient.prototype + * @private + * @param {AxiosConfig} kwargs + * @return {Promise} Promise object + */ + return this.doAxiosRequest('POST', kwargs); } - currentQueue = null; - draining = false; - runClearTimeout(timeout); -} - -process.nextTick = function (fun) { - var args = new Array(arguments.length - 1); - if (arguments.length > 1) { - for (var i = 1; i < arguments.length; i++) { - args[i - 1] = arguments[i]; - } + }, { + key: "delete", + value: function _delete(kwargs) { + /** + * Shorthand function for delete request + * @method delete + * @memberof StreamClient.prototype + * @private + * @param {AxiosConfig} kwargs + * @return {Promise} Promise object + */ + return this.doAxiosRequest('DELETE', kwargs); } - queue.push(new Item(fun, args)); - if (queue.length === 1 && !draining) { - runTimeout(drainQueue); + }, { + key: "put", + value: function put(kwargs) { + /** + * Shorthand function for put request + * @method put + * @memberof StreamClient.prototype + * @private + * @param {AxiosConfig} kwargs + * @return {Promise} Promise object + */ + return this.doAxiosRequest('PUT', kwargs); } -}; + }, { + key: "createUserToken", + value: function createUserToken(userId) { + var extraData = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; -// v8 likes predictible objects -function Item(fun, array) { - this.fun = fun; - this.array = array; -} -Item.prototype.run = function () { - this.fun.apply(null, this.array); -}; -process.title = 'browser'; -process.browser = true; -process.env = {}; -process.argv = []; -process.version = ''; // empty string to avoid regexp issues -process.versions = {}; + /** + * @param {string} userId + * @param {object} extraData + * @return {string} + */ + this._throwMissingApiSecret(); -function noop() {} + return _signing__WEBPACK_IMPORTED_MODULE_18__[/* default */ "a"].JWTUserSessionToken(this.apiSecret, userId, extraData, { + noTimestamp: !this.expireTokens + }); + } + }, { + key: "updateActivities", + value: function updateActivities(activities) { + /** + * Updates all supplied activities on the getstream-io api + * @since 3.1.0 + * @param {UpdateActivity[]} activities list of activities to update + * @return {Promise} + */ + this._throwMissingApiSecret(); -process.on = noop; -process.addListener = noop; -process.once = noop; -process.off = noop; -process.removeListener = noop; -process.removeAllListeners = noop; -process.emit = noop; -process.prependListener = noop; -process.prependOnceListener = noop; + if (!(activities instanceof Array)) { + throw new TypeError('The activities argument should be an Array'); + } -process.listeners = function (name) { return [] } + var authToken = _signing__WEBPACK_IMPORTED_MODULE_18__[/* default */ "a"].JWTScopeToken(this.apiSecret, 'activities', '*', { + feedId: '*', + expireTokens: this.expireTokens + }); + return this.post({ + url: 'activities/', + body: { + activities: activities + }, + signature: authToken + }); + } + }, { + key: "updateActivity", + value: function updateActivity(activity) { + /** + * Updates one activity on the getstream-io api + * @since 3.1.0 + * @param {UpdateActivity} activity The activity to update + * @return {Promise} + */ + this._throwMissingApiSecret(); -process.binding = function (name) { - throw new Error('process.binding is not supported'); -}; - -process.cwd = function () { return '/' }; -process.chdir = function (dir) { - throw new Error('process.chdir is not supported'); -}; -process.umask = function() { return 0; }; - - -/***/ }), -/* 23 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - - -var asap = __webpack_require__(43); - -var PENDING = -1, - FULFILLED = 0, - REJECTED = 1; - -var Promise = function(task) { - this._state = PENDING; - this._value = null; - this._defer = []; - - execute(this, task); -}; - -Promise.prototype.then = function(onFulfilled, onRejected) { - var promise = new Promise(); - - var deferred = { - promise: promise, - onFulfilled: onFulfilled, - onRejected: onRejected - }; - - if (this._state === PENDING) - this._defer.push(deferred); - else - propagate(this, deferred); - - return promise; -}; - -Promise.prototype['catch'] = function(onRejected) { - return this.then(null, onRejected); -}; + return this.updateActivities([activity]); + } + }, { + key: "getActivities", + value: function getActivities(_ref3) { + var ids = _ref3.ids, + foreignIDTimes = _ref3.foreignIDTimes, + params = _babel_runtime_helpers_objectWithoutProperties__WEBPACK_IMPORTED_MODULE_0___default()(_ref3, ["ids", "foreignIDTimes"]); -var execute = function(promise, task) { - if (typeof task !== 'function') return; + /** + * Retrieve activities by ID or foreign ID and time + * @since 3.19.0 + * @param {object} params object containing either the list of activity IDs as {ids: ['...', ...]} or foreign IDs and time as {foreignIDTimes: [{foreignID: ..., time: ...}, ...]} + * @return {Promise} + */ + var extraParams = {}; - var calls = 0; + if (ids) { + if (!(ids instanceof Array)) { + throw new TypeError('The ids argument should be an Array'); + } - var resolvePromise = function(value) { - if (calls++ === 0) resolve(promise, value); - }; + extraParams.ids = ids.join(','); + } else if (foreignIDTimes) { + if (!(foreignIDTimes instanceof Array)) { + throw new TypeError('The foreignIDTimes argument should be an Array'); + } - var rejectPromise = function(reason) { - if (calls++ === 0) reject(promise, reason); - }; + var foreignIDs = []; + var timestamps = []; + foreignIDTimes.forEach(function (fidTime) { + if (!(fidTime instanceof Object)) { + throw new TypeError('foreignIDTimes elements should be Objects'); + } - try { - task(resolvePromise, rejectPromise); - } catch (error) { - rejectPromise(error); - } -}; + foreignIDs.push(fidTime.foreignID); + timestamps.push(fidTime.time); + }); + extraParams.foreign_ids = foreignIDs.join(','); + extraParams.timestamps = timestamps.join(','); + } else { + throw new TypeError('Missing ids or foreignIDTimes params'); + } -var propagate = function(promise, deferred) { - var state = promise._state, - value = promise._value, - next = deferred.promise, - handler = [deferred.onFulfilled, deferred.onRejected][state], - pass = [resolve, reject][state]; + var token = this.userToken; - if (typeof handler !== 'function') - return pass(next, value); + if (this.usingApiSecret) { + token = _signing__WEBPACK_IMPORTED_MODULE_18__[/* default */ "a"].JWTScopeToken(this.apiSecret, 'activities', '*', { + feedId: '*', + expireTokens: this.expireTokens + }); + } - asap(function() { - try { - resolve(next, handler(value)); - } catch (error) { - reject(next, error); + this.replaceReactionOptions(params); + var path = this.shouldUseEnrichEndpoint(params) ? 'enrich/activities/' : 'activities/'; + return this.get({ + url: path, + qs: _objectSpread(_objectSpread({}, params), extraParams), + signature: token + }); } - }); -}; - -var resolve = function(promise, value) { - if (promise === value) - return reject(promise, new TypeError('Recursive promise chain detected')); - - var then; + }, { + key: "getOrCreateToken", + value: function getOrCreateToken() { + if (!this._getOrCreateToken) { + this._getOrCreateToken = this.usingApiSecret ? _signing__WEBPACK_IMPORTED_MODULE_18__[/* default */ "a"].JWTScopeToken(this.apiSecret, '*', '*', { + feedId: '*' + }) : this.userToken; + } - try { - then = getThen(value); - } catch (error) { - return reject(promise, error); - } + return this._getOrCreateToken; + } + }, { + key: "user", + value: function user(userId) { + return new _user__WEBPACK_IMPORTED_MODULE_16__[/* default */ "a"](this, userId, this.getOrCreateToken()); + } + }, { + key: "setUser", + value: function () { + var _setUser = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.mark(function _callee2(data) { + var body, user; + return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + if (!this.usingApiSecret) { + _context2.next = 2; + break; + } - if (!then) return fulfill(promise, value); + throw new _errors__WEBPACK_IMPORTED_MODULE_19__["SiteError"]('This method can only be used client-side using a user token'); - execute(promise, function(resolvePromise, rejectPromise) { - then.call(value, resolvePromise, rejectPromise); - }); -}; + case 2: + body = _objectSpread({}, data); + delete body.id; + _context2.next = 6; + return this.currentUser.getOrCreate(body); -var getThen = function(value) { - var type = typeof value, - then = (type === 'object' || type === 'function') && value && value.then; + case 6: + user = _context2.sent; + this.currentUser = user; + return _context2.abrupt("return", user); - return (typeof then === 'function') - ? then - : null; -}; + case 9: + case "end": + return _context2.stop(); + } + } + }, _callee2, this); + })); -var fulfill = function(promise, value) { - settle(promise, FULFILLED, value); -}; + function setUser(_x3) { + return _setUser.apply(this, arguments); + } -var reject = function(promise, reason) { - settle(promise, REJECTED, reason); -}; + return setUser; + }() + }, { + key: "og", + value: function og(url) { + return this.get({ + url: 'og/', + qs: { + url: url + }, + signature: this.getOrCreateToken() + }); + } + }, { + key: "personalizedFeed", + value: function personalizedFeed() { + var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + return this.get({ + url: 'enrich/personalization/feed/', + qs: options, + signature: this.getOrCreateToken() + }); + } + }, { + key: "activityPartialUpdate", + value: function () { + var _activityPartialUpdate = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.mark(function _callee3(data) { + var response, activity; + return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.wrap(function _callee3$(_context3) { + while (1) { + switch (_context3.prev = _context3.next) { + case 0: + _context3.next = 2; + return this.activitiesPartialUpdate([data]); -var settle = function(promise, state, value) { - var defer = promise._defer, i = 0; + case 2: + response = _context3.sent; + activity = response.activities[0]; + delete response.activities; + return _context3.abrupt("return", _objectSpread(_objectSpread({}, activity), response)); - promise._state = state; - promise._value = value; - promise._defer = null; + case 6: + case "end": + return _context3.stop(); + } + } + }, _callee3, this); + })); - if (defer.length === 0) return; - while (i < defer.length) propagate(promise, defer[i++]); -}; + function activityPartialUpdate(_x4) { + return _activityPartialUpdate.apply(this, arguments); + } -Promise.resolve = function(value) { - try { - if (getThen(value)) return value; - } catch (error) { - return Promise.reject(error); - } - - return new Promise(function(resolve, reject) { resolve(value) }); -}; + return activityPartialUpdate; + }() + }, { + key: "activitiesPartialUpdate", + value: function activitiesPartialUpdate(changes) { + /** + * Update multiple activities with partial operations. + * @since v3.20.0 + * @param {ActivityPartialChanges[]} changes array containing the changesets to be applied. Every changeset contains the activity identifier which is either the ID or the pair of of foreign ID and time of the activity. The operations to issue can be set:{...} and unset:[...]. + * @return {Promise<{ activities: Activity[] }>} + * @example + * client.activitiesPartialUpdate([ + * { + * id: "4b39fda2-d6e2-42c9-9abf-5301ef071b12", + * set: { + * "product.price.eur": 12.99, + * "colors": { + * "blue": "#0000ff", + * "green": "#00ff00", + * }, + * }, + * unset: [ "popularity", "size.x2" ], + * }, + * { + * id: "8d2dcad8-1e34-11e9-8b10-9cb6d0925edd", + * set: { + * "product.price.eur": 17.99, + * "colors": { + * "red": "#ff0000", + * "green": "#00ff00", + * }, + * }, + * unset: [ "rating" ], + * }, + * ]) + * @example + * client.activitiesPartialUpdate([ + * { + * foreignID: "product:123", + * time: "2016-11-10T13:20:00.000000", + * set: { + * ... + * }, + * unset: [ + * ... + * ] + * }, + * { + * foreignID: "product:321", + * time: "2016-11-10T13:20:00.000000", + * set: { + * ... + * }, + * unset: [ + * ... + * ] + * }, + * ]) + */ + if (!(changes instanceof Array)) { + throw new TypeError('changes should be an Array'); + } -Promise.reject = function(reason) { - return new Promise(function(resolve, reject) { reject(reason) }); -}; + changes.forEach(function (item) { + if (!(item instanceof Object)) { + throw new TypeError("changeset should be and Object"); + } -Promise.all = function(promises) { - return new Promise(function(resolve, reject) { - var list = [], n = promises.length, i; + if (item.foreignID) { + item.foreign_id = item.foreignID; + } - if (n === 0) return resolve(list); + if (item.id === undefined && (item.foreign_id === undefined || item.time === undefined)) { + throw new TypeError('missing id or foreign ID and time'); + } - var push = function(promise, i) { - Promise.resolve(promise).then(function(value) { - list[i] = value; - if (--n === 0) resolve(list); - }, reject); - }; + if (item.set && !(item.set instanceof Object)) { + throw new TypeError('set field should be an Object'); + } - for (i = 0; i < n; i++) push(promises[i], i); - }); -}; + if (item.unset && !(item.unset instanceof Array)) { + throw new TypeError('unset field should be an Array'); + } + }); + var authToken = this.userToken; -Promise.race = function(promises) { - return new Promise(function(resolve, reject) { - for (var i = 0, n = promises.length; i < n; i++) - Promise.resolve(promises[i]).then(resolve, reject); - }); -}; + if (this.usingApiSecret) { + authToken = _signing__WEBPACK_IMPORTED_MODULE_18__[/* default */ "a"].JWTScopeToken(this.apiSecret, 'activities', '*', { + feedId: '*', + expireTokens: this.expireTokens + }); + } -Promise.deferred = function() { - var tuple = {}; + return this.post({ + url: 'activity/', + body: { + changes: changes + }, + signature: authToken + }); + } + }]); - tuple.promise = new Promise(function(resolve, reject) { - tuple.resolve = resolve; - tuple.reject = reject; - }); - return tuple; -}; + return StreamClient; +}(); -module.exports = Promise; +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(24))) /***/ }), -/* 24 */ +/* 13 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; -/* WEBPACK VAR INJECTION */(function(process) {/* harmony import */ var _babel_runtime_helpers_objectWithoutProperties__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(19); -/* harmony import */ var _babel_runtime_helpers_objectWithoutProperties__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_objectWithoutProperties__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(0); -/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1__); -/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(6); -/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2__); -/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(2); -/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_3__); -/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(3); -/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_4__); -/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(4); -/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_5__); -/* harmony import */ var axios__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(50); -/* harmony import */ var axios__WEBPACK_IMPORTED_MODULE_6___default = /*#__PURE__*/__webpack_require__.n(axios__WEBPACK_IMPORTED_MODULE_6__); -/* harmony import */ var http__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(51); -/* harmony import */ var http__WEBPACK_IMPORTED_MODULE_7___default = /*#__PURE__*/__webpack_require__.n(http__WEBPACK_IMPORTED_MODULE_7__); -/* harmony import */ var https__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(52); -/* harmony import */ var https__WEBPACK_IMPORTED_MODULE_8___default = /*#__PURE__*/__webpack_require__.n(https__WEBPACK_IMPORTED_MODULE_8__); -/* harmony import */ var faye__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(53); -/* harmony import */ var faye__WEBPACK_IMPORTED_MODULE_9___default = /*#__PURE__*/__webpack_require__.n(faye__WEBPACK_IMPORTED_MODULE_9__); -/* harmony import */ var jwt_decode__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(54); -/* harmony import */ var jwt_decode__WEBPACK_IMPORTED_MODULE_10___default = /*#__PURE__*/__webpack_require__.n(jwt_decode__WEBPACK_IMPORTED_MODULE_10__); -/* harmony import */ var _personalization__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(55); -/* harmony import */ var _batch_operations__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(21); -/* harmony import */ var _batch_operations__WEBPACK_IMPORTED_MODULE_12___default = /*#__PURE__*/__webpack_require__.n(_batch_operations__WEBPACK_IMPORTED_MODULE_12__); -/* harmony import */ var _collections__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(56); -/* harmony import */ var _feed__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(59); -/* harmony import */ var _files__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(62); -/* harmony import */ var _images__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(63); -/* harmony import */ var _reaction__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(65); -/* harmony import */ var _user__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(20); -/* harmony import */ var _redirect_url__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(32); -/* harmony import */ var _redirect_url__WEBPACK_IMPORTED_MODULE_19___default = /*#__PURE__*/__webpack_require__.n(_redirect_url__WEBPACK_IMPORTED_MODULE_19__); -/* harmony import */ var _signing__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(5); -/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(1); -/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(7); -/* harmony import */ var _package_json__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(67); -var _package_json__WEBPACK_IMPORTED_MODULE_23___namespace = /*#__PURE__*/__webpack_require__.t(67, 1); - +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return StreamUser; }); +/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1); +/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(6); +/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__); +/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(3); +/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__); +/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4); +/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__); +/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(0); +/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_4__); @@ -2214,3706 +2141,3953 @@ var _package_json__WEBPACK_IMPORTED_MODULE_23___namespace = /*#__PURE__*/__webpa function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } -function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_5___default()(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } - - - - +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_4___default()(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } +var StreamUser = /*#__PURE__*/function () { + function StreamUser(client, userId, userAuthToken) { + _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default()(this, StreamUser); + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_4___default()(this, "client", void 0); + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_4___default()(this, "token", void 0); + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_4___default()(this, "id", void 0); + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_4___default()(this, "data", void 0); + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_4___default()(this, "full", void 0); + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_4___default()(this, "url", void 0); + /** + * Initialize a user session object + * @method constructor + * @memberof StreamUser.prototype + * @param {StreamClient} client Stream client this collection is constructed from + * @param {string} userId The ID of the user + * @param {string} userAuthToken JWT token + * @example new StreamUser(client, "123", "eyJhbGciOiJIUzI1...") + */ + this.client = client; + this.id = userId; + this.data = undefined; + this.full = undefined; + this.token = userAuthToken; + this.url = "user/".concat(this.id, "/"); + } + _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default()(StreamUser, [{ + key: "ref", + value: function ref() { + return "SU:".concat(this.id); + } + }, { + key: "delete", + value: function _delete() { + return this.client.delete({ + url: this.url, + signature: this.token + }); + } + }, { + key: "get", + value: function () { + var _get = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee(options) { + var response; + return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return this.client.get({ + url: this.url, + signature: this.token, + qs: options + }); + case 2: + response = _context.sent; + this.full = _objectSpread({}, response); + delete this.full.duration; + this.data = this.full.data; + return _context.abrupt("return", this); + case 7: + case "end": + return _context.stop(); + } + } + }, _callee, this); + })); + function get(_x) { + return _get.apply(this, arguments); + } + return get; + }() + }, { + key: "create", + value: function () { + var _create = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee2(data, options) { + var response; + return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + _context2.next = 2; + return this.client.post({ + url: 'user/', + body: { + id: this.id, + data: data || this.data || {} + }, + qs: options, + signature: this.token + }); + case 2: + response = _context2.sent; + this.full = _objectSpread({}, response); + delete this.full.duration; + this.data = this.full.data; + return _context2.abrupt("return", this); -/** - * Client to connect to Stream api - * @class StreamClient - */ + case 7: + case "end": + return _context2.stop(); + } + } + }, _callee2, this); + })); -var StreamClient = /*#__PURE__*/function () { - function StreamClient(apiKey, apiSecretOrToken, appId) { - var _this = this; + function create(_x2, _x3) { + return _create.apply(this, arguments); + } - var _options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; + return create; + }() + }, { + key: "update", + value: function () { + var _update = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee3(data) { + var response; + return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee3$(_context3) { + while (1) { + switch (_context3.prev = _context3.next) { + case 0: + _context3.next = 2; + return this.client.put({ + url: this.url, + body: { + data: data || this.data || {} + }, + signature: this.token + }); - _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_3___default()(this, StreamClient); + case 2: + response = _context3.sent; + this.full = _objectSpread({}, response); + delete this.full.duration; + this.data = this.full.data; + return _context3.abrupt("return", this); - _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_5___default()(this, "replaceReactionOptions", function () { - var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + case 7: + case "end": + return _context3.stop(); + } + } + }, _callee3, this); + })); - // Shortcut options for reaction enrichment - if (options.reactions) { - if (options.reactions.own != null) { - options.withOwnReactions = options.reactions.own; - } + function update(_x4) { + return _update.apply(this, arguments); + } - if (options.reactions.recent != null) { - options.withRecentReactions = options.reactions.recent; - } + return update; + }() + }, { + key: "getOrCreate", + value: function getOrCreate(data) { + return this.create(data, { + get_or_create: true + }); + } + }, { + key: "profile", + value: function profile() { + return this.get({ + with_follow_counts: true + }); + } + }]); - if (options.reactions.counts != null) { - options.withReactionCounts = options.reactions.counts; - } + return StreamUser; +}(); - if (options.reactions.own_children != null) { - options.withOwnChildren = options.reactions.own_children; - } - delete options.reactions; - } - }); - _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_5___default()(this, "handleResponse", function (response) { - if (/^2/.test("".concat(response.status))) { - _this.send('response', null, response, response.data); +/***/ }), +/* 14 */ +/***/ (function(module, exports, __webpack_require__) { - return response.data; - } +"use strict"; - throw new _errors__WEBPACK_IMPORTED_MODULE_21__[/* default */ "a"].StreamApiError("".concat(JSON.stringify(response.data), " with HTTP status code ").concat(response.status), response.data, response); - }); - _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_5___default()(this, "doAxiosRequest", /*#__PURE__*/function () { - var _ref = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.mark(function _callee(method, options) { - var response; - return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - _this.send('request', method, options); +module.exports = { + isURI: function(uri) { + return uri && uri.protocol && uri.host && uri.path; + }, - _context.prev = 1; - _context.next = 4; - return _this.request(_this.enrichKwargs(_objectSpread({ - method: method - }, options))); + isSameOrigin: function(uri) { + return uri.protocol === location.protocol && + uri.hostname === location.hostname && + uri.port === location.port; + }, - case 4: - response = _context.sent; - return _context.abrupt("return", _this.handleResponse(response)); + parse: function(url) { + if (typeof url !== 'string') return url; + var uri = {}, parts, query, pairs, i, n, data; - case 8: - _context.prev = 8; - _context.t0 = _context["catch"](1); + var consume = function(name, pattern) { + url = url.replace(pattern, function(match) { + uri[name] = match; + return ''; + }); + uri[name] = uri[name] || ''; + }; - if (!_context.t0.response) { - _context.next = 12; - break; - } + consume('protocol', /^[a-z]+\:/i); + consume('host', /^\/\/[^\/\?#]+/); - return _context.abrupt("return", _this.handleResponse(_context.t0.response)); + if (!/^\//.test(url) && !uri.host) + url = location.pathname.replace(/[^\/]*$/, '') + url; - case 12: - throw new _errors__WEBPACK_IMPORTED_MODULE_21__[/* default */ "a"].SiteError(_context.t0.message); + consume('pathname', /^[^\?#]*/); + consume('search', /^\?[^#]*/); + consume('hash', /^#.*/); - case 13: - case "end": - return _context.stop(); - } - } - }, _callee, null, [[1, 8]]); - })); + uri.protocol = uri.protocol || location.protocol; - return function (_x, _x2) { - return _ref.apply(this, arguments); - }; - }()); + if (uri.host) { + uri.host = uri.host.substr(2); - /** - * Initialize a client - * @method initialize - * @memberof StreamClient.prototype - * @param {string} apiKey - the api key - * @param {string} [apiSecret] - the api secret - * @param {string} [appId] - id of the app - * @param {object} [options] - additional options - * @param {string} [options.location] - which data center to use - * @param {boolean} [options.expireTokens=false] - whether to use a JWT timestamp field (i.e. iat) - * @example initialize is not directly called by via stream.connect, ie: - * stream.connect(apiKey, apiSecret) - * @example secret is optional and only used in server side mode - * stream.connect(apiKey, null, appId); - */ - this.baseUrl = 'https://api.stream-io-api.com/api/'; - this.baseAnalyticsUrl = 'https://analytics.stream-io-api.com/analytics/'; - this.apiKey = apiKey; - this.usingApiSecret = apiSecretOrToken != null && !_signing__WEBPACK_IMPORTED_MODULE_20__[/* default */ "a"].isJWT(apiSecretOrToken); - this.apiSecret = this.usingApiSecret ? apiSecretOrToken : null; - this.userToken = this.usingApiSecret ? null : apiSecretOrToken; - this.enrichByDefault = !this.usingApiSecret; + if (/@/.test(uri.host)) { + uri.auth = uri.host.split('@')[0]; + uri.host = uri.host.split('@')[1]; + } + parts = uri.host.match(/^\[([^\]]+)\]|^[^:]+/); + uri.hostname = parts[1] || parts[0]; + uri.port = (uri.host.match(/:(\d+)$/) || [])[1] || ''; + } else { + uri.host = location.host; + uri.hostname = location.hostname; + uri.port = location.port; + } - if (this.userToken != null) { - var jwtBody = jwt_decode__WEBPACK_IMPORTED_MODULE_10___default()(this.userToken); + uri.pathname = uri.pathname || '/'; + uri.path = uri.pathname + uri.search; - if (!jwtBody.user_id) { - throw new TypeError('user_id is missing in user token'); - } + query = uri.search.replace(/^\?/, ''); + pairs = query ? query.split('&') : []; + data = {}; - this.userId = jwtBody.user_id; - this.currentUser = this.user(this.userId); - this.authPayload = jwtBody; + for (i = 0, n = pairs.length; i < n; i++) { + parts = pairs[i].split('='); + data[decodeURIComponent(parts[0] || '')] = decodeURIComponent(parts[1] || ''); } - this.appId = appId; - this.options = _options; - this.version = this.options.version || 'v1.0'; - this.fayeUrl = this.options.fayeUrl || 'https://faye-us-east.stream-io-api.com/faye'; - this.fayeClient = null; // track a source name for the api calls, ie get started or databrowser + uri.query = data; - this.group = this.options.group || 'unspecified'; // track subscriptions made on feeds created by this client + uri.href = this.stringify(uri); + return uri; + }, - this.subscriptions = {}; - this.expireTokens = this.options.expireTokens ? this.options.expireTokens : false; // which data center to use + stringify: function(uri) { + var auth = uri.auth ? uri.auth + '@' : '', + string = uri.protocol + '//' + auth + uri.host; - this.location = this.options.location; - this.baseUrl = this.getBaseUrl(); + string += uri.pathname + this.queryString(uri.query) + (uri.hash || ''); - if (typeof process !== 'undefined' && process.env.LOCAL_FAYE) { - this.fayeUrl = 'http://localhost:9999/faye/'; - } + return string; + }, - if (typeof process !== 'undefined' && process.env.STREAM_ANALYTICS_BASE_URL) { - this.baseAnalyticsUrl = process.env.STREAM_ANALYTICS_BASE_URL; + queryString: function(query) { + var pairs = []; + for (var key in query) { + if (!query.hasOwnProperty(key)) continue; + pairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(query[key])); } + if (pairs.length === 0) return ''; + return '?' + pairs.join('&'); + } +}; - this.handlers = {}; - this.browser = typeof this.options.browser !== 'undefined' ? this.options.browser : typeof window !== 'undefined'; - this.node = !this.browser; - - if (this.node) { - var keepAlive = this.options.keepAlive === undefined ? true : this.options.keepAlive; - this.nodeOptions = { - httpAgent: new http__WEBPACK_IMPORTED_MODULE_7___default.a.Agent({ - keepAlive: keepAlive, - keepAliveMsecs: 3000 - }), - httpsAgent: new https__WEBPACK_IMPORTED_MODULE_8___default.a.Agent({ - keepAlive: keepAlive, - keepAliveMsecs: 3000 - }) - }; - } - this.request = axios__WEBPACK_IMPORTED_MODULE_6___default.a.create(_objectSpread({ - timeout: this.options.timeout || 10 * 1000, - // 10 seconds - withCredentials: false - }, this.nodeOptions || {})); - this.personalization = new _personalization__WEBPACK_IMPORTED_MODULE_11__[/* default */ "a"](this); +/***/ }), +/* 15 */ +/***/ (function(module, exports, __webpack_require__) { - if (this.browser && this.usingApiSecret) { - throw new _errors__WEBPACK_IMPORTED_MODULE_21__[/* default */ "a"].FeedError('You are publicly sharing your App Secret. Do not expose the App Secret in browsers, "native" mobile apps, or other non-trusted environments.'); - } +"use strict"; +/* WEBPACK VAR INJECTION */(function(process) { - this.collections = new _collections__WEBPACK_IMPORTED_MODULE_13__[/* default */ "a"](this, this.getOrCreateToken()); - this.files = new _files__WEBPACK_IMPORTED_MODULE_15__[/* default */ "a"](this, this.getOrCreateToken()); - this.images = new _images__WEBPACK_IMPORTED_MODULE_16__[/* default */ "a"](this, this.getOrCreateToken()); - this.reactions = new _reaction__WEBPACK_IMPORTED_MODULE_17__[/* default */ "a"](this, this.getOrCreateToken()); - } +var Class = __webpack_require__(10), + Cookie = __webpack_require__(53).Cookie, + Promise = __webpack_require__(25), + array = __webpack_require__(33), + assign = __webpack_require__(8), + Logging = __webpack_require__(18), + Timeouts = __webpack_require__(94), + Channel = __webpack_require__(51); - _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_4___default()(StreamClient, [{ - key: "_throwMissingApiSecret", - value: function _throwMissingApiSecret() { - if (!this.usingApiSecret) { - throw new _errors__WEBPACK_IMPORTED_MODULE_21__[/* default */ "a"].SiteError('This method can only be used server-side using your API Secret, use client = stream.connect(key, secret);'); - } - } - }, { - key: "getPersonalizationToken", - value: function getPersonalizationToken() { - if (this._personalizationToken) return this._personalizationToken; +var Transport = assign(Class({ className: 'Transport', + DEFAULT_PORTS: { 'http:': 80, 'https:': 443, 'ws:': 80, 'wss:': 443 }, + MAX_DELAY: 0, - this._throwMissingApiSecret(); + batching: true, - this._personalizationToken = _signing__WEBPACK_IMPORTED_MODULE_20__[/* default */ "a"].JWTScopeToken(this.apiSecret, 'personalization', '*', { - userId: '*', - feedId: '*', - expireTokens: this.expireTokens - }); - return this._personalizationToken; - } - }, { - key: "getCollectionsToken", - value: function getCollectionsToken() { - if (this._collectionsToken) return this._collectionsToken; + initialize: function(dispatcher, endpoint) { + this._dispatcher = dispatcher; + this.endpoint = endpoint; + this._outbox = []; + this._proxy = assign({}, this._dispatcher.proxy); - this._throwMissingApiSecret(); + if (!this._proxy.origin) + this._proxy.origin = this._findProxy(); + }, - this._collectionsToken = _signing__WEBPACK_IMPORTED_MODULE_20__[/* default */ "a"].JWTScopeToken(this.apiSecret, 'collections', '*', { - feedId: '*', - expireTokens: this.expireTokens - }); - return this._collectionsToken; - } - }, { - key: "getAnalyticsToken", - value: function getAnalyticsToken() { - this._throwMissingApiSecret(); + close: function() {}, - return _signing__WEBPACK_IMPORTED_MODULE_20__[/* default */ "a"].JWTScopeToken(this.apiSecret, 'analytics', '*', { - userId: '*', - expireTokens: this.expireTokens - }); - } - }, { - key: "getBaseUrl", - value: function getBaseUrl(serviceName) { - if (!serviceName) serviceName = 'api'; - if (this.options.urlOverride && this.options.urlOverride[serviceName]) return this.options.urlOverride[serviceName]; - var urlEnvironmentKey = serviceName === 'api' ? 'STREAM_BASE_URL' : "STREAM_".concat(serviceName.toUpperCase(), "_URL"); - if (typeof process !== 'undefined' && process.env[urlEnvironmentKey]) return process.env[urlEnvironmentKey]; - if (typeof process !== 'undefined' && process.env.LOCAL || this.options.local) return "http://localhost:8000/".concat(serviceName, "/"); + encode: function(messages) { + return ''; + }, - if (this.location) { - var protocol = this.options.protocol || 'https'; - return "".concat(protocol, "://").concat(this.location, "-").concat(serviceName, ".stream-io-api.com/").concat(serviceName, "/"); - } + sendMessage: function(message) { + this.debug('Client ? sending message to ?: ?', + this._dispatcher.clientId, this.endpoint.href, message); - if (serviceName !== 'api') return "https://".concat(serviceName, ".stream-io-api.com/").concat(serviceName, "/"); - return this.baseUrl; - } - }, { - key: "on", - value: function on(event, callback) { - /** - * Support for global event callbacks - * This is useful for generic error and loading handling - * @method on - * @memberof StreamClient.prototype - * @param {string} event - Name of the event - * @param {function} callback - Function that is called when the event fires - * @example - * client.on('request', callback); - * client.on('response', callback); - */ - this.handlers[event] = callback; - } - }, { - key: "off", - value: function off(key) { - /** - * Remove one or more event handlers - * @method off - * @memberof StreamClient.prototype - * @param {string} [key] - Name of the handler - * @example - * client.off() removes all handlers - * client.off(name) removes the specified handler - */ - if (key === undefined) { - this.handlers = {}; - } else { - delete this.handlers[key]; - } - } - }, { - key: "send", - value: function send(key) { - for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - args[_key - 1] = arguments[_key]; - } + if (!this.batching) return Promise.resolve(this.request([message])); - /** - * Call the given handler with the arguments - * @method send - * @memberof StreamClient.prototype - * @access private - */ - if (this.handlers[key]) this.handlers[key].apply(this, args); - } - }, { - key: "userAgent", - value: function userAgent() { - /** - * Get the current user agent - * @method userAgent - * @memberof StreamClient.prototype - * @return {string} current user agent - */ - return "stream-javascript-client-".concat(this.node ? 'node' : 'browser', "-").concat(_package_json__WEBPACK_IMPORTED_MODULE_23__.version); - } - }, { - key: "getReadOnlyToken", - value: function getReadOnlyToken(feedSlug, userId) { - /** - * Returns a token that allows only read operations - * - * @method getReadOnlyToken - * @memberof StreamClient.prototype - * @param {string} feedSlug - The feed slug to get a read only token for - * @param {string} userId - The user identifier - * @return {string} token - * @example - * client.getReadOnlyToken('user', '1'); - */ - _utils__WEBPACK_IMPORTED_MODULE_22__[/* default */ "a"].validateFeedSlug(feedSlug); - _utils__WEBPACK_IMPORTED_MODULE_22__[/* default */ "a"].validateUserId(userId); - return _signing__WEBPACK_IMPORTED_MODULE_20__[/* default */ "a"].JWTScopeToken(this.apiSecret, '*', 'read', { - feedId: "".concat(feedSlug).concat(userId), - expireTokens: this.expireTokens - }); - } - }, { - key: "getReadWriteToken", - value: function getReadWriteToken(feedSlug, userId) { - /** - * Returns a token that allows read and write operations - * - * @method getReadWriteToken - * @memberof StreamClient.prototype - * @param {string} feedSlug - The feed slug to get a read only token for - * @param {string} userId - The user identifier - * @return {string} token - * @example - * client.getReadWriteToken('user', '1'); - */ - _utils__WEBPACK_IMPORTED_MODULE_22__[/* default */ "a"].validateFeedSlug(feedSlug); - _utils__WEBPACK_IMPORTED_MODULE_22__[/* default */ "a"].validateUserId(userId); - return _signing__WEBPACK_IMPORTED_MODULE_20__[/* default */ "a"].JWTScopeToken(this.apiSecret, '*', '*', { - feedId: "".concat(feedSlug).concat(userId), - expireTokens: this.expireTokens - }); - } - }, { - key: "feed", - value: function feed(feedSlug) { - var userId = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.userId; - var token = arguments.length > 2 ? arguments[2] : undefined; + this._outbox.push(message); + this._flushLargeBatch(); - /** - * Returns a feed object for the given feed id and token - * @method feed - * @memberof StreamClient.prototype - * @param {string} feedSlug - The feed slug - * @param {string} userId - The user identifier - * @param {string} [token] - The token (DEPRECATED), used for internal testing - * @return {StreamFeed} - * @example - * client.feed('user', '1'); - */ - if (userId instanceof _user__WEBPACK_IMPORTED_MODULE_18__[/* default */ "a"]) userId = userId.id; + if (message.channel === Channel.HANDSHAKE) + return this._publish(0.01); - if (token === undefined) { - if (this.usingApiSecret) { - token = _signing__WEBPACK_IMPORTED_MODULE_20__[/* default */ "a"].JWTScopeToken(this.apiSecret, '*', '*', { - feedId: "".concat(feedSlug).concat(userId) - }); - } else { - token = this.userToken; - } - } + if (message.channel === Channel.CONNECT) + this._connectMessage = message; - return new _feed__WEBPACK_IMPORTED_MODULE_14__[/* default */ "a"](this, feedSlug, userId, token); - } - }, { - key: "enrichUrl", - value: function enrichUrl(relativeUrl, serviceName) { - /** - * Combines the base url with version and the relative url - * @method enrichUrl - * @memberof StreamClient.prototype - * @private - * @param {string} relativeUrl - */ - return "".concat(this.getBaseUrl(serviceName)).concat(this.version, "/").concat(relativeUrl); - } - }, { - key: "shouldUseEnrichEndpoint", - value: function shouldUseEnrichEndpoint() { - var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + return this._publish(this.MAX_DELAY); + }, - if (options.enrich) { - var result = options.enrich; - delete options.enrich; - return result; - } + _makePromise: function() { + var self = this; - return this.enrichByDefault || options.ownReactions != null || options.withRecentReactions != null || options.withReactionCounts != null || options.withOwnChildren != null; - } - }, { - key: "enrichKwargs", - value: function enrichKwargs(_ref2) { - var method = _ref2.method, - kwargs = _babel_runtime_helpers_objectWithoutProperties__WEBPACK_IMPORTED_MODULE_0___default()(_ref2, ["method"]); + this._requestPromise = this._requestPromise || new Promise(function(resolve) { + self._resolvePromise = resolve; + }); + }, - /** - * Adds the API key and the signature - * @method enrichKwargs - * @memberof StreamClient.prototype - * @param {object} kwargs - * @private - */ - var signature = kwargs.signature || this.signature; - var isJWT = _signing__WEBPACK_IMPORTED_MODULE_20__[/* default */ "a"].isJWTSignature(signature); - return _objectSpread({ - method: method, - url: this.enrichUrl(kwargs.url, kwargs.serviceName), - data: kwargs.body, - params: _objectSpread({ - api_key: this.apiKey, - location: this.group - }, kwargs.qs || {}), - headers: _objectSpread({ - 'X-Stream-Client': this.userAgent(), - 'stream-auth-type': isJWT ? 'jwt' : 'simple', - Authorization: isJWT ? signature.split(' ').reverse()[0] : signature - }, kwargs.headers || {}) - }, kwargs.axiosOptions || {}); - } - }, { - key: "getFayeAuthorization", - value: function getFayeAuthorization() { - var _this2 = this; + _publish: function(delay) { + this._makePromise(); - /** - * Get the authorization middleware to use Faye with getstream.io - * @method getFayeAuthorization - * @memberof StreamClient.prototype - * @private - * @return {object} Faye authorization middleware - */ - return { - incoming: function incoming(message, callback) { - return callback(message); - }, - outgoing: function outgoing(message, callback) { - if (message.subscription && _this2.subscriptions[message.subscription]) { - var subscription = _this2.subscriptions[message.subscription]; - message.ext = { - user_id: subscription.userId, - api_key: _this2.apiKey, - signature: subscription.token - }; + this.addTimeout('publish', delay, function() { + this._flush(); + delete this._requestPromise; + }, this); + + return this._requestPromise; + }, + + _flush: function() { + this.removeTimeout('publish'); + + if (this._outbox.length > 1 && this._connectMessage) + this._connectMessage.advice = { timeout: 0 }; + + this._resolvePromise(this.request(this._outbox)); + + this._connectMessage = null; + this._outbox = []; + }, + + _flushLargeBatch: function() { + var string = this.encode(this._outbox); + if (string.length < this._dispatcher.maxRequestSize) return; + var last = this._outbox.pop(); + + this._makePromise(); + this._flush(); + + if (last) this._outbox.push(last); + }, + + _receive: function(replies) { + if (!replies) return; + replies = [].concat(replies); + + this.debug('Client ? received from ? via ?: ?', + this._dispatcher.clientId, this.endpoint.href, this.connectionType, replies); + + for (var i = 0, n = replies.length; i < n; i++) + this._dispatcher.handleResponse(replies[i]); + }, + + _handleError: function(messages, immediate) { + messages = [].concat(messages); + + this.debug('Client ? failed to send to ? via ?: ?', + this._dispatcher.clientId, this.endpoint.href, this.connectionType, messages); + + for (var i = 0, n = messages.length; i < n; i++) + this._dispatcher.handleError(messages[i]); + }, + + _getCookies: function() { + var cookies = this._dispatcher.cookies, + url = this.endpoint.href; + + if (!cookies) return ''; + + return array.map(cookies.getCookiesSync(url), function(cookie) { + return cookie.cookieString(); + }).join('; '); + }, + + _storeCookies: function(setCookie) { + var cookies = this._dispatcher.cookies, + url = this.endpoint.href, + cookie; + + if (!setCookie || !cookies) return; + setCookie = [].concat(setCookie); + + for (var i = 0, n = setCookie.length; i < n; i++) { + cookie = Cookie.parse(setCookie[i]); + cookies.setCookieSync(cookie, url); + } + }, + + _findProxy: function() { + if (typeof process === 'undefined') return undefined; + + var protocol = this.endpoint.protocol; + if (!protocol) return undefined; + + var name = protocol.replace(/:$/, '').toLowerCase() + '_proxy', + upcase = name.toUpperCase(), + env = process.env, + keys, proxy; + + if (name === 'http_proxy' && env.REQUEST_METHOD) { + keys = Object.keys(env).filter(function(k) { return /^http_proxy$/i.test(k) }); + if (keys.length === 1) { + if (keys[0] === name && env[upcase] === undefined) + proxy = env[name]; + } else if (keys.length > 1) { + proxy = env[name]; + } + proxy = proxy || env['CGI_' + upcase]; + } else { + proxy = env[name] || env[upcase]; + if (proxy && !env[name]) + console.warn('The environment variable ' + upcase + + ' is discouraged. Use ' + name + '.'); + } + return proxy; + } + +}), { + get: function(dispatcher, allowed, disabled, callback, context) { + var endpoint = dispatcher.endpoint; + + array.asyncEach(this._transports, function(pair, resume) { + var connType = pair[0], klass = pair[1], + connEndpoint = dispatcher.endpointFor(connType); + + if (array.indexOf(disabled, connType) >= 0) + return resume(); + + if (array.indexOf(allowed, connType) < 0) { + klass.isUsable(dispatcher, connEndpoint, function() {}); + return resume(); + } + + klass.isUsable(dispatcher, connEndpoint, function(isUsable) { + if (!isUsable) return resume(); + var transport = klass.hasOwnProperty('create') ? klass.create(dispatcher, connEndpoint) : new klass(dispatcher, connEndpoint); + callback.call(context, transport); + }); + }, function() { + throw new Error('Could not find a usable connection type for ' + endpoint.href); + }); + }, + + register: function(type, klass) { + this._transports.push([type, klass]); + klass.prototype.connectionType = type; + }, + + getConnectionTypes: function() { + return array.map(this._transports, function(t) { return t[0] }); + }, + + disable: function(feature) { + if (feature !== 'autodisconnect') return; + + for (var i = 0; i < this._transports.length; i++) + this._transports[i][1]._unloaded = false; + }, + + _transports: [] +}); + +assign(Transport.prototype, Logging); +assign(Transport.prototype, Timeouts); + +module.exports = Transport; + +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(24))) + +/***/ }), +/* 16 */ +/***/ (function(module, exports) { + +function _assertThisInitialized(self) { + if (self === void 0) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + + return self; +} + +module.exports = _assertThisInitialized; + +/***/ }), +/* 17 */ +/***/ (function(module, exports, __webpack_require__) { + +var setPrototypeOf = __webpack_require__(37); + +function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError("Super expression must either be null or a function"); + } + + subClass.prototype = Object.create(superClass && superClass.prototype, { + constructor: { + value: subClass, + writable: true, + configurable: true + } + }); + if (superClass) setPrototypeOf(subClass, superClass); +} + +module.exports = _inherits; + +/***/ }), +/* 18 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var toJSON = __webpack_require__(19); + +var Logging = { + LOG_LEVELS: { + fatal: 4, + error: 3, + warn: 2, + info: 1, + debug: 0 + }, + + writeLog: function(messageArgs, level) { + var logger = Logging.logger || (Logging.wrapper || Logging).logger; + if (!logger) return; + + var args = Array.prototype.slice.apply(messageArgs), + banner = '[Faye', + klass = this.className, + + message = args.shift().replace(/\?/g, function() { + try { + return toJSON(args.shift()); + } catch (error) { + return '[Object]'; } + }); - callback(message); + if (klass) banner += '.' + klass; + banner += '] '; + + if (typeof logger[level] === 'function') + logger[level](banner + message); + else if (typeof logger === 'function') + logger(banner + message); + } +}; + +for (var key in Logging.LOG_LEVELS) + (function(level) { + Logging[level] = function() { + this.writeLog(arguments, level); + }; + })(key); + +module.exports = Logging; + + +/***/ }), +/* 19 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +// http://assanka.net/content/tech/2009/09/02/json2-js-vs-prototype/ + +module.exports = function(object) { + return JSON.stringify(object, function(key, value) { + return (this[key] instanceof Array) ? this[key] : value; + }); +}; + + +/***/ }), +/* 20 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(global) { + +var Promise = __webpack_require__(25); + +module.exports = { + then: function(callback, errback) { + var self = this; + if (!this._promise) + this._promise = new Promise(function(resolve, reject) { + self._resolve = resolve; + self._reject = reject; + }); + + if (arguments.length === 0) + return this._promise; + else + return this._promise.then(callback, errback); + }, + + callback: function(callback, context) { + return this.then(function(value) { callback.call(context, value) }); + }, + + errback: function(callback, context) { + return this.then(null, function(reason) { callback.call(context, reason) }); + }, + + timeout: function(seconds, message) { + this.then(); + var self = this; + this._timer = global.setTimeout(function() { + self._reject(message); + }, seconds * 1000); + }, + + setDeferredStatus: function(status, value) { + if (this._timer) global.clearTimeout(this._timer); + + this.then(); + + if (status === 'succeeded') + this._resolve(value); + else if (status === 'failed') + this._reject(value); + else + delete this._promise; + } +}; + +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(11))) + +/***/ }), +/* 21 */ +/***/ (function(module, exports) { + +function _typeof(obj) { + "@babel/helpers - typeof"; + + if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { + module.exports = _typeof = function _typeof(obj) { + return typeof obj; + }; + } else { + module.exports = _typeof = function _typeof(obj) { + return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; + }; + } + + return _typeof(obj); +} + +module.exports = _typeof; + +/***/ }), +/* 22 */ +/***/ (function(module, exports, __webpack_require__) { + +var objectWithoutPropertiesLoose = __webpack_require__(70); + +function _objectWithoutProperties(source, excluded) { + if (source == null) return {}; + var target = objectWithoutPropertiesLoose(source, excluded); + var key, i; + + if (Object.getOwnPropertySymbols) { + var sourceSymbolKeys = Object.getOwnPropertySymbols(source); + + for (i = 0; i < sourceSymbolKeys.length; i++) { + key = sourceSymbolKeys[i]; + if (excluded.indexOf(key) >= 0) continue; + if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; + target[key] = source[key]; + } + } + + return target; +} + +module.exports = _objectWithoutProperties; + +/***/ }), +/* 23 */ +/***/ (function(module, exports) { + + + +/***/ }), +/* 24 */ +/***/ (function(module, exports) { + +// shim for using process in browser +var process = module.exports = {}; + +// cached from whatever global is present so that test runners that stub it +// don't break things. But we need to wrap it in a try catch in case it is +// wrapped in strict mode code which doesn't define any globals. It's inside a +// function because try/catches deoptimize in certain engines. + +var cachedSetTimeout; +var cachedClearTimeout; + +function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); +} +function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); +} +(function () { + try { + if (typeof setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } else { + cachedSetTimeout = defaultSetTimout; + } + } catch (e) { + cachedSetTimeout = defaultSetTimout; + } + try { + if (typeof clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } else { + cachedClearTimeout = defaultClearTimeout; + } + } catch (e) { + cachedClearTimeout = defaultClearTimeout; + } +} ()) +function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + +} +function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); } - }; } - }, { - key: "getFayeClient", - value: function getFayeClient() { - var timeout = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 10; - /** - * Returns this client's current Faye client - * @method getFayeClient - * @memberof StreamClient.prototype - * @private - * @return {object} Faye client - */ - if (this.fayeClient === null) { - this.fayeClient = new faye__WEBPACK_IMPORTED_MODULE_9___default.a.Client(this.fayeUrl, { - timeout: timeout - }); - var authExtension = this.getFayeAuthorization(); - this.fayeClient.addExtension(authExtension); - } - return this.fayeClient; + +} +var queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; + +function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; } - }, { - key: "upload", - value: function upload(url, uri, name, contentType, onUploadProgress) { - var fd = _utils__WEBPACK_IMPORTED_MODULE_22__[/* default */ "a"].addFileToFormData(uri, name, contentType); - return this.doAxiosRequest('POST', { - url: url, - body: fd, - headers: fd.getHeaders ? fd.getHeaders() : {}, - // node vs browser - signature: this.getOrCreateToken(), - axiosOptions: { - timeout: 0, - maxContentLength: Infinity, - maxBodyLength: Infinity, - onUploadProgress: onUploadProgress - } - }); + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; } - }, { - key: "get", - value: function get(kwargs) { - /** - * Shorthand function for get request - * @method get - * @memberof StreamClient.prototype - * @private - * @param {object} kwargs - * @return {Promise} Promise object - */ - return this.doAxiosRequest('GET', kwargs); + if (queue.length) { + drainQueue(); } - }, { - key: "post", - value: function post(kwargs) { - /** - * Shorthand function for post request - * @method post - * @memberof StreamClient.prototype - * @private - * @param {object} kwargs - * @return {Promise} Promise object - */ - return this.doAxiosRequest('POST', kwargs); +} + +function drainQueue() { + if (draining) { + return; } - }, { - key: "delete", - value: function _delete(kwargs) { - /** - * Shorthand function for delete request - * @method delete - * @memberof StreamClient.prototype - * @private - * @param {object} kwargs - * @return {Promise} Promise object - */ - return this.doAxiosRequest('DELETE', kwargs); + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; } - }, { - key: "put", - value: function put(kwargs) { - /** - * Shorthand function for put request - * @method put - * @memberof StreamClient.prototype - * @private - * @param {object} kwargs - * @return {Promise} Promise object - */ - return this.doAxiosRequest('PUT', kwargs); + currentQueue = null; + draining = false; + runClearTimeout(timeout); +} + +process.nextTick = function (fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } } - /** - * @param {string} userId - * @param {object} extraData - */ + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } +}; - }, { - key: "createUserToken", - value: function createUserToken(userId) { - var extraData = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; +// v8 likes predictible objects +function Item(fun, array) { + this.fun = fun; + this.array = array; +} +Item.prototype.run = function () { + this.fun.apply(null, this.array); +}; +process.title = 'browser'; +process.browser = true; +process.env = {}; +process.argv = []; +process.version = ''; // empty string to avoid regexp issues +process.versions = {}; - this._throwMissingApiSecret(); +function noop() {} - return _signing__WEBPACK_IMPORTED_MODULE_20__[/* default */ "a"].JWTUserSessionToken(this.apiSecret, userId, extraData, { - noTimestamp: !this.expireTokens - }); - } - }, { - key: "updateActivities", - value: function updateActivities(activities) { - /** - * Updates all supplied activities on the getstream-io api - * @since 3.1.0 - * @param {array} activities list of activities to update - * @return {Promise} - */ - this._throwMissingApiSecret(); +process.on = noop; +process.addListener = noop; +process.once = noop; +process.off = noop; +process.removeListener = noop; +process.removeAllListeners = noop; +process.emit = noop; +process.prependListener = noop; +process.prependOnceListener = noop; - if (!(activities instanceof Array)) { - throw new TypeError('The activities argument should be an Array'); - } +process.listeners = function (name) { return [] } - var authToken = _signing__WEBPACK_IMPORTED_MODULE_20__[/* default */ "a"].JWTScopeToken(this.apiSecret, 'activities', '*', { - feedId: '*', - expireTokens: this.expireTokens - }); - return this.post({ - url: 'activities/', - body: { - activities: activities - }, - signature: authToken - }); - } - }, { - key: "updateActivity", - value: function updateActivity(activity) { - /** - * Updates one activity on the getstream-io api - * @since 3.1.0 - * @param {object} activity The activity to update - * @return {Promise} - */ - this._throwMissingApiSecret(); +process.binding = function (name) { + throw new Error('process.binding is not supported'); +}; - return this.updateActivities([activity]); - } - }, { - key: "getActivities", - value: function getActivities(_ref3) { - var ids = _ref3.ids, - foreignIDTimes = _ref3.foreignIDTimes, - params = _babel_runtime_helpers_objectWithoutProperties__WEBPACK_IMPORTED_MODULE_0___default()(_ref3, ["ids", "foreignIDTimes"]); +process.cwd = function () { return '/' }; +process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); +}; +process.umask = function() { return 0; }; + + +/***/ }), +/* 25 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; + + +var asap = __webpack_require__(50); + +var PENDING = -1, + FULFILLED = 0, + REJECTED = 1; + +var Promise = function(task) { + this._state = PENDING; + this._value = null; + this._defer = []; + + execute(this, task); +}; + +Promise.prototype.then = function(onFulfilled, onRejected) { + var promise = new Promise(); + + var deferred = { + promise: promise, + onFulfilled: onFulfilled, + onRejected: onRejected + }; + + if (this._state === PENDING) + this._defer.push(deferred); + else + propagate(this, deferred); - /** - * Retrieve activities by ID or foreign ID and time - * @since 3.19.0 - * @param {object} params object containing either the list of activity IDs as {ids: ['...', ...]} or foreign IDs and time as {foreignIDTimes: [{foreignID: ..., time: ...}, ...]} - * @return {Promise} - */ - if (ids) { - if (!(ids instanceof Array)) { - throw new TypeError('The ids argument should be an Array'); - } + return promise; +}; - params.ids = ids.join(','); - } else if (foreignIDTimes) { - if (!(foreignIDTimes instanceof Array)) { - throw new TypeError('The foreignIDTimes argument should be an Array'); - } +Promise.prototype['catch'] = function(onRejected) { + return this.then(null, onRejected); +}; - var foreignIDs = []; - var timestamps = []; - foreignIDTimes.forEach(function (fidTime) { - if (!(fidTime instanceof Object)) { - throw new TypeError('foreignIDTimes elements should be Objects'); - } +var execute = function(promise, task) { + if (typeof task !== 'function') return; - foreignIDs.push(fidTime.foreignID); - timestamps.push(fidTime.time); - }); - params.foreign_ids = foreignIDs.join(','); - params.timestamps = timestamps.join(','); - } else { - throw new TypeError('Missing ids or foreignIDTimes params'); - } + var calls = 0; - var token = this.userToken; + var resolvePromise = function(value) { + if (calls++ === 0) resolve(promise, value); + }; - if (this.usingApiSecret) { - token = _signing__WEBPACK_IMPORTED_MODULE_20__[/* default */ "a"].JWTScopeToken(this.apiSecret, 'activities', '*', { - feedId: '*', - expireTokens: this.expireTokens - }); - } + var rejectPromise = function(reason) { + if (calls++ === 0) reject(promise, reason); + }; - this.replaceReactionOptions(params); - var path = this.shouldUseEnrichEndpoint(params) ? 'enrich/activities/' : 'activities/'; - return this.get({ - url: path, - qs: params, - signature: token - }); - } - }, { - key: "getOrCreateToken", - value: function getOrCreateToken() { - if (!this._getOrCreateToken) { - this._getOrCreateToken = this.usingApiSecret ? _signing__WEBPACK_IMPORTED_MODULE_20__[/* default */ "a"].JWTScopeToken(this.apiSecret, '*', '*', { - feedId: '*' - }) : this.userToken; - } + try { + task(resolvePromise, rejectPromise); + } catch (error) { + rejectPromise(error); + } +}; - return this._getOrCreateToken; - } - }, { - key: "user", - value: function user(userId) { - return new _user__WEBPACK_IMPORTED_MODULE_18__[/* default */ "a"](this, userId, this.getOrCreateToken()); - } - }, { - key: "setUser", - value: function () { - var _setUser = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.mark(function _callee2(data) { - var body, user; - return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.wrap(function _callee2$(_context2) { - while (1) { - switch (_context2.prev = _context2.next) { - case 0: - if (!this.usingApiSecret) { - _context2.next = 2; - break; - } +var propagate = function(promise, deferred) { + var state = promise._state, + value = promise._value, + next = deferred.promise, + handler = [deferred.onFulfilled, deferred.onRejected][state], + pass = [resolve, reject][state]; - throw new _errors__WEBPACK_IMPORTED_MODULE_21__[/* default */ "a"].SiteError('This method can only be used client-side using a user token'); + if (typeof handler !== 'function') + return pass(next, value); - case 2: - body = _objectSpread({}, data); - delete body.id; - _context2.next = 6; - return this.currentUser.getOrCreate(body); + asap(function() { + try { + resolve(next, handler(value)); + } catch (error) { + reject(next, error); + } + }); +}; - case 6: - user = _context2.sent; - this.currentUser = user; - return _context2.abrupt("return", user); +var resolve = function(promise, value) { + if (promise === value) + return reject(promise, new TypeError('Recursive promise chain detected')); - case 9: - case "end": - return _context2.stop(); - } - } - }, _callee2, this); - })); + var then; - function setUser(_x3) { - return _setUser.apply(this, arguments); - } + try { + then = getThen(value); + } catch (error) { + return reject(promise, error); + } - return setUser; - }() - }, { - key: "og", - value: function og(url) { - return this.get({ - url: 'og/', - qs: { - url: url - }, - signature: this.getOrCreateToken() - }); - } - }, { - key: "personalizedFeed", - value: function personalizedFeed() { - var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - return this.get({ - url: 'enrich/personalization/feed/', - qs: options, - signature: this.getOrCreateToken() - }); - } - }, { - key: "activityPartialUpdate", - value: function () { - var _activityPartialUpdate = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.mark(function _callee3(data) { - var response, activity; - return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.wrap(function _callee3$(_context3) { - while (1) { - switch (_context3.prev = _context3.next) { - case 0: - _context3.next = 2; - return this.activitiesPartialUpdate([data]); + if (!then) return fulfill(promise, value); - case 2: - response = _context3.sent; - activity = response.activities[0]; - delete response.activities; - return _context3.abrupt("return", _objectSpread(_objectSpread({}, activity), response)); + execute(promise, function(resolvePromise, rejectPromise) { + then.call(value, resolvePromise, rejectPromise); + }); +}; - case 6: - case "end": - return _context3.stop(); - } - } - }, _callee3, this); - })); +var getThen = function(value) { + var type = typeof value, + then = (type === 'object' || type === 'function') && value && value.then; - function activityPartialUpdate(_x4) { - return _activityPartialUpdate.apply(this, arguments); - } + return (typeof then === 'function') + ? then + : null; +}; - return activityPartialUpdate; - }() - }, { - key: "activitiesPartialUpdate", - value: function activitiesPartialUpdate(changes) { - /** - * Update multiple activities with partial operations. - * @since v3.20.0 - * @param {array} changes array containing the changesets to be applied. Every changeset contains the activity identifier which is either the ID or the pair of of foreign ID and time of the activity. The operations to issue can be set:{...} and unset:[...]. - * @return {Promise} - * @xample - * client.activitiesPartialUpdate([ - * { - * id: "4b39fda2-d6e2-42c9-9abf-5301ef071b12", - * set: { - * "product.price.eur": 12.99, - * "colors": { - * "blue": "#0000ff", - * "green": "#00ff00", - * }, - * }, - * unset: [ "popularity", "size.x2" ], - * }, - * { - * id: "8d2dcad8-1e34-11e9-8b10-9cb6d0925edd", - * set: { - * "product.price.eur": 17.99, - * "colors": { - * "red": "#ff0000", - * "green": "#00ff00", - * }, - * }, - * unset: [ "rating" ], - * }, - * ]) - * @example - * client.activitiesPartialUpdate([ - * { - * foreignID: "product:123", - * time: "2016-11-10T13:20:00.000000", - * set: { - * ... - * }, - * unset: [ - * ... - * ] - * }, - * { - * foreignID: "product:321", - * time: "2016-11-10T13:20:00.000000", - * set: { - * ... - * }, - * unset: [ - * ... - * ] - * }, - * ]) - */ - if (!(changes instanceof Array)) { - throw new TypeError('changes should be an Array'); - } +var fulfill = function(promise, value) { + settle(promise, FULFILLED, value); +}; + +var reject = function(promise, reason) { + settle(promise, REJECTED, reason); +}; - changes.forEach(function (item) { - if (!(item instanceof Object)) { - throw new TypeError("changeset should be and Object"); - } +var settle = function(promise, state, value) { + var defer = promise._defer, i = 0; - if (item.foreignID) { - item.foreign_id = item.foreignID; - } + promise._state = state; + promise._value = value; + promise._defer = null; - if (item.id === undefined && (item.foreign_id === undefined || item.time === undefined)) { - throw new TypeError('missing id or foreign ID and time'); - } + if (defer.length === 0) return; + while (i < defer.length) propagate(promise, defer[i++]); +}; - if (item.set && !(item.set instanceof Object)) { - throw new TypeError('set field should be an Object'); - } +Promise.resolve = function(value) { + try { + if (getThen(value)) return value; + } catch (error) { + return Promise.reject(error); + } - if (item.unset && !(item.unset instanceof Array)) { - throw new TypeError('unset field should be an Array'); - } - }); - var authToken = this.userToken; + return new Promise(function(resolve, reject) { resolve(value) }); +}; - if (this.usingApiSecret) { - authToken = _signing__WEBPACK_IMPORTED_MODULE_20__[/* default */ "a"].JWTScopeToken(this.apiSecret, 'activities', '*', { - feedId: '*', - expireTokens: this.expireTokens - }); - } +Promise.reject = function(reason) { + return new Promise(function(resolve, reject) { reject(reason) }); +}; - return this.post({ - url: 'activity/', - body: { - changes: changes - }, - signature: authToken - }); - } - }]); +Promise.all = function(promises) { + return new Promise(function(resolve, reject) { + var list = [], n = promises.length, i; - return StreamClient; -}(); // If we are in a node environment and batchOperations is available add the methods to the prototype of StreamClient + if (n === 0) return resolve(list); + var push = function(promise, i) { + Promise.resolve(promise).then(function(value) { + list[i] = value; + if (--n === 0) resolve(list); + }, reject); + }; -if (_batch_operations__WEBPACK_IMPORTED_MODULE_12___default.a) { - Object.keys(_batch_operations__WEBPACK_IMPORTED_MODULE_12___default.a).forEach(function (key) { - if (Object.prototype.hasOwnProperty.call(_batch_operations__WEBPACK_IMPORTED_MODULE_12___default.a, key)) { - StreamClient.prototype[key] = _batch_operations__WEBPACK_IMPORTED_MODULE_12___default.a[key]; - } + for (i = 0; i < n; i++) push(promises[i], i); }); -} // If we are in a node environment and redirectUrl is available add the methods to the prototype of StreamClient - +}; -if (_redirect_url__WEBPACK_IMPORTED_MODULE_19___default.a) { - StreamClient.prototype.createRedirectUrl = _redirect_url__WEBPACK_IMPORTED_MODULE_19___default.a; -} +Promise.race = function(promises) { + return new Promise(function(resolve, reject) { + for (var i = 0, n = promises.length; i < n; i++) + Promise.resolve(promises[i]).then(resolve, reject); + }); +}; -/* harmony default export */ __webpack_exports__["a"] = (StreamClient); -/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(22))) +Promise.deferred = function() { + var tuple = {}; -/***/ }), -/* 25 */ -/***/ (function(module, exports) { + tuple.promise = new Promise(function(resolve, reject) { + tuple.resolve = resolve; + tuple.reject = reject; + }); + return tuple; +}; -function _getPrototypeOf(o) { - module.exports = _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { - return o.__proto__ || Object.getPrototypeOf(o); - }; - return _getPrototypeOf(o); -} +module.exports = Promise; -module.exports = _getPrototypeOf; /***/ }), /* 26 */ -/***/ (function(module, exports, __webpack_require__) { +/***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Personalization; }); +/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3); +/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(4); +/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__); +/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(0); +/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_2__); -module.exports = { - commonElement: function(lista, listb) { - for (var i = 0, n = lista.length; i < n; i++) { - if (this.indexOf(listb, lista[i]) !== -1) - return lista[i]; - } - return null; - }, - indexOf: function(list, needle) { - if (list.indexOf) return list.indexOf(needle); - for (var i = 0, n = list.length; i < n; i++) { - if (list[i] === needle) return i; - } - return -1; - }, +/** + * Manage api calls for personalization + * The collection object contains convenience functions such as get, post, delete + * @class Personalization + */ +var Personalization = /*#__PURE__*/function () { + function Personalization(client) { + _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, Personalization); - map: function(object, callback, context) { - if (object.map) return object.map(callback, context); - var result = []; + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_2___default()(this, "client", void 0); - if (object instanceof Array) { - for (var i = 0, n = object.length; i < n; i++) { - result.push(callback.call(context || null, object[i], i)); - } - } else { - for (var key in object) { - if (!object.hasOwnProperty(key)) continue; - result.push(callback.call(context || null, key, object[key])); - } - } - return result; - }, + /** + * Initialize the Personalization class + * + * @method constructor + * @memberof Personalization.prototype + * @param {StreamClient} client - The stream client + */ + this.client = client; + } - filter: function(array, callback, context) { - if (array.filter) return array.filter(callback, context); - var result = []; - for (var i = 0, n = array.length; i < n; i++) { - if (callback.call(context || null, array[i], i)) - result.push(array[i]); + _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default()(Personalization, [{ + key: "get", + value: function get(resource) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + /** + * Get personalized activities for this feed + * + * @method get + * @memberof Personalization.prototype + * @param {string} resource - personalized resource endpoint i.e "follow_recommendations" + * @param {object} options Additional options + * @return {Promise>} Promise object. Personalized feed + * @example client.personalization.get('follow_recommendations', {foo: 'bar', baz: 'qux'}) + */ + return this.client.get({ + url: "".concat(resource, "/"), + serviceName: 'personalization', + qs: options, + signature: options.token || this.client.getPersonalizationToken() + }); } - return result; - }, + }, { + key: "post", + value: function post(resource) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + var data = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; - asyncEach: function(list, iterator, callback, context) { - var n = list.length, - i = -1, - calls = 0, - looping = false; + /** + * Post data to personalization endpoint + * + * @method post + * @memberof Personalization.prototype + * @param {string} resource - personalized resource endpoint i.e "follow_recommendations" + * @param {object} options - Additional options + * @param {object} data - Data to send in the payload + * @return {Promise>} Promise object. Data that was posted if successful, or an error. + * @example client.personalization.post('follow_recommendations', {foo: 'bar', baz: 'qux'}) + */ + return this.client.post({ + url: "".concat(resource, "/"), + serviceName: 'personalization', + qs: options, + body: data, + signature: this.client.getPersonalizationToken() + }); + } + }, { + key: "delete", + value: function _delete(resource) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - var iterate = function() { - calls -= 1; - i += 1; - if (i === n) return callback && callback.call(context); - iterator(list[i], resume); - }; + /** + * Delete metadata or activities + * + * @method delete + * @memberof Personalization.prototype + * @param {object} resource - personalized resource endpoint i.e "follow_recommendations" + * @param {object} options - Additional options + * @return {Promise>} Promise object. Data that was deleted if successful, or an error. + * @example client.personalization.delete('follow_recommendations', {foo: 'bar', baz: 'qux'}) + */ + return this.client.delete({ + url: "".concat(resource, "/"), + serviceName: 'personalization', + qs: options, + signature: this.client.getPersonalizationToken() + }); + } + }]); - var loop = function() { - if (looping) return; - looping = true; - while (calls > 0) iterate(); - looping = false; - }; + return Personalization; +}(); - var resume = function() { - calls += 1; - loop(); - }; - resume(); - } -}; /***/ }), /* 27 */ -/***/ (function(module, exports, __webpack_require__) { +/***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; -/* WEBPACK VAR INJECTION */(function(global) { +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Collections; }); +/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1); +/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(6); +/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1__); +/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(3); +/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2__); +/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4); +/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3__); +/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(0); +/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_4__); +/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(2); -var Event = { - _registry: [], - on: function(element, eventName, callback, context) { - var wrapped = function() { callback.call(context) }; - if (element.addEventListener) - element.addEventListener(eventName, wrapped, false); - else - element.attachEvent('on' + eventName, wrapped); - this._registry.push({ - _element: element, - _type: eventName, - _callback: callback, - _context: context, - _handler: wrapped - }); - }, - detach: function(element, eventName, callback, context) { - var i = this._registry.length, register; - while (i--) { - register = this._registry[i]; - if ((element && element !== register._element) || - (eventName && eventName !== register._type) || - (callback && callback !== register._callback) || - (context && context !== register._context)) - continue; - if (register._element.removeEventListener) - register._element.removeEventListener(register._type, register._handler, false); - else - register._element.detachEvent('on' + register._type, register._handler); +var CollectionEntry = /*#__PURE__*/function () { + function CollectionEntry(store, collection, id, data) { + _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default()(this, CollectionEntry); - this._registry.splice(i,1); - register = null; - } - } -}; + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_4___default()(this, "id", void 0); -if (global.onunload !== undefined) - Event.on(global, 'unload', Event.detach, Event); + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_4___default()(this, "collection", void 0); -module.exports = { - Event: Event -}; + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_4___default()(this, "store", void 0); -/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(11))) + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_4___default()(this, "data", void 0); -/***/ }), -/* 28 */ -/***/ (function(module, exports, __webpack_require__) { + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_4___default()(this, "full", void 0); -"use strict"; + this.collection = collection; + this.store = store; + this.id = id; + this.data = data; + } + _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default()(CollectionEntry, [{ + key: "ref", + value: function ref() { + return "SO:".concat(this.collection, ":").concat(this.id); + } + }, { + key: "get", + value: function () { + var _get = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee() { + var response; + return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return this.store.get(this.collection, this.id); -var assign = __webpack_require__(8), - EventEmitter = __webpack_require__(91); + case 2: + response = _context.sent; + this.data = response.data; + this.full = response; + return _context.abrupt("return", response); -var Publisher = { - countListeners: function(eventType) { - return this.listeners(eventType).length; - }, + case 6: + case "end": + return _context.stop(); + } + } + }, _callee, this); + })); - bind: function(eventType, listener, context) { - var slice = Array.prototype.slice, - handler = function() { listener.apply(context, slice.call(arguments)) }; + function get() { + return _get.apply(this, arguments); + } - this._listeners = this._listeners || []; - this._listeners.push([eventType, listener, context, handler]); - return this.on(eventType, handler); - }, + return get; + }() + }, { + key: "add", + value: function () { + var _add = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee2() { + var response; + return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + _context2.next = 2; + return this.store.add(this.collection, this.id, this.data); - unbind: function(eventType, listener, context) { - this._listeners = this._listeners || []; - var n = this._listeners.length, tuple; + case 2: + response = _context2.sent; + this.data = response.data; + this.full = response; + return _context2.abrupt("return", response); - while (n--) { - tuple = this._listeners[n]; - if (tuple[0] !== eventType) continue; - if (listener && (tuple[1] !== listener || tuple[2] !== context)) continue; - this._listeners.splice(n, 1); - this.removeListener(eventType, tuple[3]); - } - } -}; + case 6: + case "end": + return _context2.stop(); + } + } + }, _callee2, this); + })); -assign(Publisher, EventEmitter.prototype); -Publisher.trigger = Publisher.emit; + function add() { + return _add.apply(this, arguments); + } -module.exports = Publisher; + return add; + }() + }, { + key: "update", + value: function () { + var _update = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee3() { + var response; + return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee3$(_context3) { + while (1) { + switch (_context3.prev = _context3.next) { + case 0: + _context3.next = 2; + return this.store.update(this.collection, this.id, this.data); + case 2: + response = _context3.sent; + this.data = response.data; + this.full = response; + return _context3.abrupt("return", response); -/***/ }), -/* 29 */ -/***/ (function(module, exports, __webpack_require__) { + case 6: + case "end": + return _context3.stop(); + } + } + }, _callee3, this); + })); -"use strict"; + function update() { + return _update.apply(this, arguments); + } + return update; + }() + }, { + key: "delete", + value: function () { + var _delete2 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee4() { + var response; + return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee4$(_context4) { + while (1) { + switch (_context4.prev = _context4.next) { + case 0: + _context4.next = 2; + return this.store.delete(this.collection, this.id); -var copyObject = function(object) { - var clone, i, key; - if (object instanceof Array) { - clone = []; - i = object.length; - while (i--) clone[i] = copyObject(object[i]); - return clone; - } else if (typeof object === 'object') { - clone = (object === null) ? null : {}; - for (key in object) clone[key] = copyObject(object[key]); - return clone; - } else { - return object; - } -}; + case 2: + response = _context4.sent; + this.data = null; + this.full = null; + return _context4.abrupt("return", response); -module.exports = copyObject; + case 6: + case "end": + return _context4.stop(); + } + } + }, _callee4, this); + })); + function _delete() { + return _delete2.apply(this, arguments); + } -/***/ }), -/* 30 */ -/***/ (function(module, exports) { + return _delete; + }() + }]); -function _setPrototypeOf(o, p) { - module.exports = _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { - o.__proto__ = p; - return o; - }; + return CollectionEntry; +}(); - return _setPrototypeOf(o, p); -} +var Collections = /*#__PURE__*/function () { + /** + * Initialize a feed object + * @method constructor + * @memberof Collections.prototype + * @param {StreamCloudClient} client Stream client this collection is constructed from + * @param {string} token JWT token + */ + function Collections(client, token) { + _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_2___default()(this, Collections); -module.exports = _setPrototypeOf; + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_4___default()(this, "client", void 0); -/***/ }), -/* 31 */ -/***/ (function(module, exports) { + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_4___default()(this, "token", void 0); -function _assertThisInitialized(self) { - if (self === void 0) { - throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_4___default()(this, "buildURL", function (collection, itemId) { + var url = "collections/".concat(collection, "/"); + return itemId === undefined ? url : "".concat(url).concat(itemId, "/"); + }); + + this.client = client; + this.token = token; } - return self; -} + _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_3___default()(Collections, [{ + key: "entry", + value: function entry(collection, itemId, itemData) { + return new CollectionEntry(this, collection, itemId, itemData); + } + }, { + key: "get", + value: function () { + var _get2 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee5(collection, itemId) { + var response, entry; + return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee5$(_context5) { + while (1) { + switch (_context5.prev = _context5.next) { + case 0: + _context5.next = 2; + return this.client.get({ + url: this.buildURL(collection, itemId), + signature: this.token + }); + + case 2: + response = _context5.sent; + entry = this.entry(response.collection, response.id, response.data); + entry.full = response; + return _context5.abrupt("return", entry); + + case 6: + case "end": + return _context5.stop(); + } + } + }, _callee5, this); + })); -module.exports = _assertThisInitialized; + function get(_x, _x2) { + return _get2.apply(this, arguments); + } -/***/ }), -/* 32 */ -/***/ (function(module, exports) { + return get; + }() + }, { + key: "add", + value: function () { + var _add2 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee6(collection, itemId, itemData) { + var response, entry; + return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee6$(_context6) { + while (1) { + switch (_context6.prev = _context6.next) { + case 0: + _context6.next = 2; + return this.client.post({ + url: this.buildURL(collection), + body: { + id: itemId === null ? undefined : itemId, + data: itemData + }, + signature: this.token + }); + case 2: + response = _context6.sent; + entry = this.entry(response.collection, response.id, response.data); + entry.full = response; + return _context6.abrupt("return", entry); + case 6: + case "end": + return _context6.stop(); + } + } + }, _callee6, this); + })); -/***/ }), -/* 33 */ -/***/ (function(module, exports) { + function add(_x3, _x4, _x5) { + return _add2.apply(this, arguments); + } -/* (ignored) */ + return add; + }() + }, { + key: "update", + value: function () { + var _update2 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_1___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee7(collection, entryId, data) { + var response, entry; + return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee7$(_context7) { + while (1) { + switch (_context7.prev = _context7.next) { + case 0: + _context7.next = 2; + return this.client.put({ + url: this.buildURL(collection, entryId), + body: { + data: data + }, + signature: this.token + }); -/***/ }), -/* 34 */ -/***/ (function(module, exports, __webpack_require__) { + case 2: + response = _context7.sent; + entry = this.entry(response.collection, response.id, response.data); + entry.full = response; + return _context7.abrupt("return", entry); -"use strict"; + case 6: + case "end": + return _context7.stop(); + } + } + }, _callee7, this); + })); + function update(_x6, _x7, _x8) { + return _update2.apply(this, arguments); + } -module.exports = function bind(fn, thisArg) { - return function wrap() { - var args = new Array(arguments.length); - for (var i = 0; i < args.length; i++) { - args[i] = arguments[i]; + return update; + }() + }, { + key: "delete", + value: function _delete(collection, entryId) { + /** + * Delete entry from collection + * @method delete + * @memberof Collections.prototype + * @param {string} collection collection name + * @param {string} entryId Collection entry id + * @return {Promise} Promise object + * @example collection.delete("food", "cheese101") + */ + return this.client.delete({ + url: this.buildURL(collection, entryId), + signature: this.token + }); } - return fn.apply(thisArg, args); - }; -}; - + }, { + key: "upsert", + value: function upsert(collection, data) { + /** + * Upsert one or more items within a collection. + * + * @method upsert + * @memberof Collections.prototype + * @param {string} collection collection name + * @param {NewCollectionEntry | NewCollectionEntry[]} data - A single json object or an array of objects + * @return {Promise>} + */ + if (!this.client.usingApiSecret) { + throw new _errors__WEBPACK_IMPORTED_MODULE_5__["SiteError"]('This method can only be used server-side using your API Secret'); + } -/***/ }), -/* 35 */ -/***/ (function(module, exports, __webpack_require__) { + if (!Array.isArray(data)) data = [data]; + return this.client.post({ + url: 'collections/', + serviceName: 'api', + body: { + data: _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_4___default()({}, collection, data) + }, + signature: this.client.getCollectionsToken() + }); + } + }, { + key: "select", + value: function select(collection, ids) { + /** + * Select all objects with ids from the collection. + * + * @method select + * @memberof Collections.prototype + * @param {string} collection collection name + * @param {string | string[]} ids - A single object id or an array of ids + * @return {Promise>} + */ + if (!this.client.usingApiSecret) { + throw new _errors__WEBPACK_IMPORTED_MODULE_5__["SiteError"]('This method can only be used server-side using your API Secret'); + } -"use strict"; + if (!Array.isArray(ids)) ids = [ids]; + return this.client.get({ + url: 'collections/', + serviceName: 'api', + qs: { + foreign_ids: ids.map(function (id) { + return "".concat(collection, ":").concat(id); + }).join(',') + }, + signature: this.client.getCollectionsToken() + }); + } + }, { + key: "deleteMany", + value: function deleteMany(collection, ids) { + /** + * Remove all objects by id from the collection. + * + * @method delete + * @memberof Collections.prototype + * @param {string} collection collection name + * @param {string | string[]} ids - A single object id or an array of ids + * @return {Promise} + */ + if (!this.client.usingApiSecret) { + throw new _errors__WEBPACK_IMPORTED_MODULE_5__["SiteError"]('This method can only be used server-side using your API Secret'); + } + if (!Array.isArray(ids)) ids = [ids]; + var params = { + collection_name: collection, + ids: ids.map(function (id) { + return id.toString(); + }).join(',') + }; + return this.client.delete({ + url: 'collections/', + serviceName: 'api', + qs: params, + signature: this.client.getCollectionsToken() + }); + } + }]); -var utils = __webpack_require__(9); + return Collections; +}(); -function encode(val) { - return encodeURIComponent(val). - replace(/%40/gi, '@'). - replace(/%3A/gi, ':'). - replace(/%24/g, '$'). - replace(/%2C/gi, ','). - replace(/%20/g, '+'). - replace(/%5B/gi, '['). - replace(/%5D/gi, ']'); -} -/** - * Build a URL by appending params to the end - * - * @param {string} url The base of the url (e.g., http://www.google.com) - * @param {object} [params] The params to be appended - * @returns {string} The formatted url - */ -module.exports = function buildURL(url, params, paramsSerializer) { - /*eslint no-param-reassign:0*/ - if (!params) { - return url; - } - var serializedParams; - if (paramsSerializer) { - serializedParams = paramsSerializer(params); - } else if (utils.isURLSearchParams(params)) { - serializedParams = params.toString(); - } else { - var parts = []; +/***/ }), +/* 28 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { - utils.forEach(params, function serialize(val, key) { - if (val === null || typeof val === 'undefined') { - return; - } +"use strict"; +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return StreamFileStore; }); +/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3); +/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(4); +/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__); +/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(0); +/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_2__); - if (utils.isArray(val)) { - key = key + '[]'; - } else { - val = [val]; - } - utils.forEach(val, function parseValue(v) { - if (utils.isDate(v)) { - v = v.toISOString(); - } else if (utils.isObject(v)) { - v = JSON.stringify(v); - } - parts.push(encode(key) + '=' + encode(v)); - }); - }); - serializedParams = parts.join('&'); - } - if (serializedParams) { - var hashmarkIndex = url.indexOf('#'); - if (hashmarkIndex !== -1) { - url = url.slice(0, hashmarkIndex); - } +var StreamFileStore = /*#__PURE__*/function () { + function StreamFileStore(client, token) { + _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, StreamFileStore); - url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams; - } + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_2___default()(this, "client", void 0); - return url; -}; + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_2___default()(this, "token", void 0); + this.client = client; + this.token = token; + } // React Native does not auto-detect MIME type, you need to pass that via contentType + // param. If you don't then Android will refuse to perform the upload -/***/ }), -/* 36 */ -/***/ (function(module, exports, __webpack_require__) { -"use strict"; + _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default()(StreamFileStore, [{ + key: "upload", + value: function upload(uri, name, contentType, onUploadProgress) { + /** + * upload a File instance or a readable stream of data + * @param {File|NodeJS.ReadStream|string} uri - File object or stream or URI + * @param {string} [name] - file name + * @param {string} [contentType] - mime-type + * @param {function} [onUploadProgress] - browser only, Function that is called with upload progress + * @return {Promise} + */ + return this.client.upload('files/', uri, name, contentType, onUploadProgress); + } + }, { + key: "delete", + value: function _delete(uri) { + return this.client.delete({ + url: "files/", + qs: { + url: uri + }, + signature: this.token + }); + } + }]); + return StreamFileStore; +}(); -module.exports = function isCancel(value) { - return !!(value && value.__CANCEL__); -}; /***/ }), -/* 37 */ -/***/ (function(module, exports, __webpack_require__) { +/* 29 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; -/* WEBPACK VAR INJECTION */(function(process) { +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return StreamImageStore; }); +/* harmony import */ var _babel_runtime_helpers_extends__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(64); +/* harmony import */ var _babel_runtime_helpers_extends__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_extends__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3); +/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_1__); +/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(4); +/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_2__); +/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(0); +/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_3__); -var utils = __webpack_require__(9); -var normalizeHeaderName = __webpack_require__(77); -var DEFAULT_CONTENT_TYPE = { - 'Content-Type': 'application/x-www-form-urlencoded' -}; -function setContentTypeIfUnset(headers, value) { - if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) { - headers['Content-Type'] = value; - } -} -function getDefaultAdapter() { - var adapter; - if (typeof XMLHttpRequest !== 'undefined') { - // For browsers use XHR adapter - adapter = __webpack_require__(38); - } else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') { - // For node use HTTP adapter - adapter = __webpack_require__(38); - } - return adapter; -} -var defaults = { - adapter: getDefaultAdapter(), +var StreamImageStore = /*#__PURE__*/function () { + function StreamImageStore(client, token) { + _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_1___default()(this, StreamImageStore); - transformRequest: [function transformRequest(data, headers) { - normalizeHeaderName(headers, 'Accept'); - normalizeHeaderName(headers, 'Content-Type'); - if (utils.isFormData(data) || - utils.isArrayBuffer(data) || - utils.isBuffer(data) || - utils.isStream(data) || - utils.isFile(data) || - utils.isBlob(data) - ) { - return data; - } - if (utils.isArrayBufferView(data)) { - return data.buffer; - } - if (utils.isURLSearchParams(data)) { - setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8'); - return data.toString(); - } - if (utils.isObject(data)) { - setContentTypeIfUnset(headers, 'application/json;charset=utf-8'); - return JSON.stringify(data); - } - return data; - }], + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_3___default()(this, "client", void 0); - transformResponse: [function transformResponse(data) { - /*eslint no-param-reassign:0*/ - if (typeof data === 'string') { - try { - data = JSON.parse(data); - } catch (e) { /* Ignore */ } - } - return data; - }], + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_3___default()(this, "token", void 0); - /** - * A timeout in milliseconds to abort a request. If set to 0 (default) a - * timeout is not created. - */ - timeout: 0, + this.client = client; + this.token = token; + } // React Native does not auto-detect MIME type, you need to pass that via contentType + // param. If you don't then Android will refuse to perform the upload - xsrfCookieName: 'XSRF-TOKEN', - xsrfHeaderName: 'X-XSRF-TOKEN', - maxContentLength: -1, + _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_2___default()(StreamImageStore, [{ + key: "upload", + value: function upload(uri, name, contentType, onUploadProgress) { + /** + * upload an Image File instance or a readable stream of data + * @param {File|NodeJS.ReadStream|string} uri - File object or stream or URI + * @param {string} [name] - file name + * @param {string} [contentType] - mime-type + * @param {function} [onUploadProgress] - browser only, Function that is called with upload progress + * @return {Promise} + */ + return this.client.upload('images/', uri, name, contentType, onUploadProgress); + } + }, { + key: "delete", + value: function _delete(uri) { + return this.client.delete({ + url: "images/", + qs: { + url: uri + }, + signature: this.token + }); + } + }, { + key: "process", + value: function process(uri, options) { + var params = _babel_runtime_helpers_extends__WEBPACK_IMPORTED_MODULE_0___default()(options, { + url: uri + }); - validateStatus: function validateStatus(status) { - return status >= 200 && status < 300; - } -}; + if (Array.isArray(params.crop)) { + params.crop = params.crop.join(','); + } -defaults.headers = { - common: { - 'Accept': 'application/json, text/plain, */*' - } -}; + return this.client.get({ + url: "images/", + qs: params, + signature: this.token + }); + } + }, { + key: "thumbnail", + value: function thumbnail(uri, w, h) { + var _ref = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : { + crop: 'center', + resize: 'clip' + }, + crop = _ref.crop, + resize = _ref.resize; -utils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) { - defaults.headers[method] = {}; -}); + return this.process(uri, { + w: w, + h: h, + crop: crop, + resize: resize + }); + } + }]); -utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { - defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE); -}); + return StreamImageStore; +}(); -module.exports = defaults; -/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(22))) /***/ }), -/* 38 */ -/***/ (function(module, exports, __webpack_require__) { +/* 30 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return StreamReaction; }); +/* harmony import */ var _babel_runtime_helpers_objectWithoutProperties__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(22); +/* harmony import */ var _babel_runtime_helpers_objectWithoutProperties__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_objectWithoutProperties__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3); +/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_1__); +/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(4); +/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_2__); +/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(0); +/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_3__); +/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(2); -var utils = __webpack_require__(9); -var settle = __webpack_require__(78); -var buildURL = __webpack_require__(35); -var buildFullPath = __webpack_require__(80); -var parseHeaders = __webpack_require__(83); -var isURLSameOrigin = __webpack_require__(84); -var createError = __webpack_require__(39); - -module.exports = function xhrAdapter(config) { - return new Promise(function dispatchXhrRequest(resolve, reject) { - var requestData = config.data; - var requestHeaders = config.headers; - if (utils.isFormData(requestData)) { - delete requestHeaders['Content-Type']; // Let the browser set it - } - var request = new XMLHttpRequest(); - // HTTP basic authentication - if (config.auth) { - var username = config.auth.username || ''; - var password = config.auth.password || ''; - requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password); - } - var fullPath = buildFullPath(config.baseURL, config.url); - request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true); +var StreamReaction = /*#__PURE__*/function () { + function StreamReaction(client, token) { + _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_1___default()(this, StreamReaction); - // Set the request timeout in MS - request.timeout = config.timeout; + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_3___default()(this, "client", void 0); - // Listen for ready state - request.onreadystatechange = function handleLoad() { - if (!request || request.readyState !== 4) { - return; - } + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_3___default()(this, "token", void 0); - // The request errored out and we didn't get a response, this will be - // handled by onerror instead - // With one exception: request that using file: protocol, most browsers - // will return status as 0 even though it's a successful request - if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) { - return; + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_3___default()(this, "buildURL", function () { + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; } - // Prepare the response - var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null; - var responseData = !config.responseType || config.responseType === 'text' ? request.responseText : request.response; - var response = { - data: responseData, - status: request.status, - statusText: request.statusText, - headers: responseHeaders, - config: config, - request: request - }; - - settle(resolve, reject, response); + return "".concat(['reaction'].concat(args).join('/'), "/"); + }); - // Clean up request - request = null; - }; + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_3___default()(this, "_convertTargetFeeds", function () { + var targetFeeds = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; + return targetFeeds.map(function (elem) { + return typeof elem === 'string' ? elem : elem.id; + }); + }); - // Handle browser request cancellation (as opposed to a manual cancellation) - request.onabort = function handleAbort() { - if (!request) { - return; - } + /** + * Initialize a reaction object + * @method constructor + * @memberof StreamReaction.prototype + * @param {StreamClient} client Stream client this feed is constructed from + * @param {string} token JWT token + * @example new StreamReaction(client, "eyJhbGciOiJIUzI1...") + */ + this.client = client; + this.token = token; + } - reject(createError('Request aborted', config, 'ECONNABORTED', request)); + _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_2___default()(StreamReaction, [{ + key: "all", + // DEPRECATED + value: function all() { + var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - // Clean up request - request = null; - }; + /** + * get all reactions + * @method all + * @memberof StreamReaction.prototype + * @param {object} options {limit:} + * @return {Promise} Promise object + * @example reactions.all() + * @example reactions.all({limit:100}) + */ + console.warn('Deprecated function, please use reactions.filter()'); // eslint-disable-line - // Handle low level network errors - request.onerror = function handleError() { - // Real errors are hidden from us by the browser - // onerror should only fire if it's a network error - reject(createError('Network Error', config, null, request)); + return this.client.get({ + url: this.buildURL(), + signature: this.token, + qs: options + }); + } + }, { + key: "add", + value: function add(kind, activity, data) { + var _ref = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}, + id = _ref.id, + _ref$targetFeeds = _ref.targetFeeds, + targetFeeds = _ref$targetFeeds === void 0 ? [] : _ref$targetFeeds, + userId = _ref.userId, + targetFeedsExtraData = _ref.targetFeedsExtraData; - // Clean up request - request = null; - }; + /** + * add reaction + * @method add + * @memberof StreamReaction.prototype + * @param {string} kind kind of reaction + * @param {string} activity Activity or an ActivityID + * @param {ReactionType} data data related to reaction + * @param {object} [options] + * @param {string} [options.id] id associated with reaction + * @param {string[]} [options.targetFeeds] an array of feeds to which to send an activity with the reaction + * @param {string} [options.userId] useful for adding reaction with server token + * @param {object} [options.targetFeedsExtraData] extra data related to target feeds + * @return {Promise>} + * @example reactions.add("like", "0c7db91c-67f9-11e8-bcd9-fe00a9219401") + * @example reactions.add("comment", "0c7db91c-67f9-11e8-bcd9-fe00a9219401", {"text": "love it!"},) + */ + var body = { + id: id, + activity_id: activity instanceof Object ? activity.id : activity, + kind: kind, + data: data || {}, + target_feeds: this._convertTargetFeeds(targetFeeds), + user_id: userId + }; - // Handle timeout - request.ontimeout = function handleTimeout() { - var timeoutErrorMessage = 'timeout of ' + config.timeout + 'ms exceeded'; - if (config.timeoutErrorMessage) { - timeoutErrorMessage = config.timeoutErrorMessage; + if (targetFeedsExtraData != null) { + body.target_feeds_extra_data = targetFeedsExtraData; } - reject(createError(timeoutErrorMessage, config, 'ECONNABORTED', - request)); - // Clean up request - request = null; - }; - - // Add xsrf header - // This is only done if running in a standard browser environment. - // Specifically not if we're in a web worker, or react-native. - if (utils.isStandardBrowserEnv()) { - var cookies = __webpack_require__(85); + return this.client.post({ + url: this.buildURL(), + body: body, + signature: this.token + }); + } + }, { + key: "addChild", + value: function addChild(kind, reaction, data) { + var _ref2 = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}, + _ref2$targetFeeds = _ref2.targetFeeds, + targetFeeds = _ref2$targetFeeds === void 0 ? [] : _ref2$targetFeeds, + userId = _ref2.userId, + targetFeedsExtraData = _ref2.targetFeedsExtraData; - // Add xsrf header - var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ? - cookies.read(config.xsrfCookieName) : - undefined; + /** + * add child reaction + * @method addChild + * @memberof StreamReaction.prototype + * @param {string} kind kind of reaction + * @param {string} reaction Reaction or a ReactionID + * @param {ChildReactionType} data data related to reaction + * @param {object} [options] + * @param {string[]} [options.targetFeeds] an array of feeds to which to send an activity with the reaction + * @param {string} [options.userId] useful for adding reaction with server token + * @param {object} [options.targetFeedsExtraData] extra data related to target feeds + * @return {Promise>} + * @example reactions.add("like", "0c7db91c-67f9-11e8-bcd9-fe00a9219401") + * @example reactions.add("comment", "0c7db91c-67f9-11e8-bcd9-fe00a9219401", {"text": "love it!"},) + */ + var body = { + parent: reaction instanceof Object ? reaction.id : reaction, + kind: kind, + data: data || {}, + target_feeds: this._convertTargetFeeds(targetFeeds), + user_id: userId + }; - if (xsrfValue) { - requestHeaders[config.xsrfHeaderName] = xsrfValue; + if (targetFeedsExtraData != null) { + body.target_feeds_extra_data = targetFeedsExtraData; } - } - // Add headers to the request - if ('setRequestHeader' in request) { - utils.forEach(requestHeaders, function setRequestHeader(val, key) { - if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') { - // Remove Content-Type if data is undefined - delete requestHeaders[key]; - } else { - // Otherwise add header to the request - request.setRequestHeader(key, val); - } + return this.client.post({ + url: this.buildURL(), + body: body, + signature: this.token }); } - - // Add withCredentials to request if needed - if (!utils.isUndefined(config.withCredentials)) { - request.withCredentials = !!config.withCredentials; + }, { + key: "get", + value: function get(id) { + /** + * get reaction + * @method get + * @memberof StreamReaction.prototype + * @param {string} id Reaction Id + * @return {Promise>} + * @example reactions.get("67b3e3b5-b201-4697-96ac-482eb14f88ec") + */ + return this.client.get({ + url: this.buildURL(id), + signature: this.token + }); } + }, { + key: "filter", + value: function filter(conditions) { + /** + * retrieve reactions by activity_id, user_id or reaction_id (to paginate children reactions), pagination can be done using id_lt, id_lte, id_gt and id_gte parameters + * id_lt and id_lte return reactions order by creation descending starting from the reaction with the ID provided, when id_lte is used + * the reaction with ID equal to the value provided is included. + * id_gt and id_gte return reactions order by creation ascending (oldest to newest) starting from the reaction with the ID provided, when id_gte is used + * the reaction with ID equal to the value provided is included. + * results are limited to 25 at most and are ordered newest to oldest by default. + * @method filter + * @memberof StreamReaction.prototype + * @param {object} conditions Reaction Id {activity_id|user_id|reaction_id:string, kind:string, limit:integer} + * @return {Promise>} + * @example reactions.filter({activity_id: "0c7db91c-67f9-11e8-bcd9-fe00a9219401", kind:"like"}) + * @example reactions.filter({user_id: "john", kinds:"like"}) + */ + var userId = conditions.user_id, + activityId = conditions.activity_id, + reactionId = conditions.reaction_id, + qs = _babel_runtime_helpers_objectWithoutProperties__WEBPACK_IMPORTED_MODULE_0___default()(conditions, ["user_id", "activity_id", "reaction_id"]); - // Add responseType to request if needed - if (config.responseType) { - try { - request.responseType = config.responseType; - } catch (e) { - // Expected DOMException thrown by browsers not compatible XMLHttpRequest Level 2. - // But, this can be suppressed for 'json' type as it can be parsed by default 'transformResponse' function. - if (config.responseType !== 'json') { - throw e; - } + if (!qs.limit) { + qs.limit = 10; } - } - // Handle progress if needed - if (typeof config.onDownloadProgress === 'function') { - request.addEventListener('progress', config.onDownloadProgress); - } + if ((userId ? 1 : 0) + (activityId ? 1 : 0) + (reactionId ? 1 : 0) !== 1) { + throw new _errors__WEBPACK_IMPORTED_MODULE_4__["SiteError"]('Must provide exactly one value for one of these params: user_id, activity_id, reaction_id'); + } - // Not all browsers support upload events - if (typeof config.onUploadProgress === 'function' && request.upload) { - request.upload.addEventListener('progress', config.onUploadProgress); + var lookupType = userId && 'user_id' || activityId && 'activity_id' || reactionId && 'reaction_id'; + var value = userId || activityId || reactionId; + var url = conditions.kind ? this.buildURL(lookupType, value, conditions.kind) : this.buildURL(lookupType, value); + return this.client.get({ + url: url, + qs: qs, + signature: this.token + }); } + }, { + key: "update", + value: function update(id, data) { + var _ref3 = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}, + _ref3$targetFeeds = _ref3.targetFeeds, + targetFeeds = _ref3$targetFeeds === void 0 ? [] : _ref3$targetFeeds, + targetFeedsExtraData = _ref3.targetFeedsExtraData; - if (config.cancelToken) { - // Handle cancellation - config.cancelToken.promise.then(function onCanceled(cancel) { - if (!request) { - return; - } + /** + * update reaction + * @method update + * @memberof StreamReaction.prototype + * @param {string} id Reaction Id + * @param {ReactionType | ChildReactionType} data Data associated to reaction or childReaction + * @param {object} [options] + * @param {string[]} [options.targetFeeds] Optional feeds to post the activity to. If you sent this before and don't set it here it will be removed. + * @param {object} [options.targetFeedsExtraData] extra data related to target feeds + * @return {Promise>} + * @example reactions.update("67b3e3b5-b201-4697-96ac-482eb14f88ec", "0c7db91c-67f9-11e8-bcd9-fe00a9219401", "like") + * @example reactions.update("67b3e3b5-b201-4697-96ac-482eb14f88ec", "0c7db91c-67f9-11e8-bcd9-fe00a9219401", "comment", {"text": "love it!"},) + */ + var body = { + data: data, + target_feeds: this._convertTargetFeeds(targetFeeds) + }; - request.abort(); - reject(cancel); - // Clean up request - request = null; + if (targetFeedsExtraData != null) { + body.target_feeds_extra_data = targetFeedsExtraData; + } + + return this.client.put({ + url: this.buildURL(id), + body: body, + signature: this.token + }); + } + }, { + key: "delete", + value: function _delete(id) { + /** + * delete reaction + * @method delete + * @memberof StreamReaction.prototype + * @param {string} id Reaction Id + * @return {Promise} + * @example reactions.delete("67b3e3b5-b201-4697-96ac-482eb14f88ec") + */ + return this.client.delete({ + url: this.buildURL(id), + signature: this.token }); } + }]); - if (requestData === undefined) { - requestData = null; - } + return StreamReaction; +}(); - // Send the request - request.send(requestData); - }); -}; /***/ }), -/* 39 */ -/***/ (function(module, exports, __webpack_require__) { +/* 31 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return StreamFeed; }); +/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3); +/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__); +/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(4); +/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__); +/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(0); +/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_2__); +/* harmony import */ var _user__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(13); +/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(2); +/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(7); -var enhanceError = __webpack_require__(79); -/** - * Create an Error with the specified message, config, error code, request and response. - * - * @param {string} message The error message. - * @param {Object} config The config. - * @param {string} [code] The error code (for example, 'ECONNABORTED'). - * @param {Object} [request] The request. - * @param {Object} [response] The response. - * @returns {Error} The created error. - */ -module.exports = function createError(message, config, code, request, response) { - var error = new Error(message); - return enhanceError(error, config, code, request, response); -}; +function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } -/***/ }), -/* 40 */ -/***/ (function(module, exports, __webpack_require__) { +function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_2___default()(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } + +/// -"use strict"; -var utils = __webpack_require__(9); /** - * Config-specific merge-function which creates a new config-object - * by merging two configuration objects together. - * - * @param {Object} config1 - * @param {Object} config2 - * @returns {Object} New object resulting from merging config2 to config1 + * Manage api calls for specific feeds + * The feed object contains convenience functions such add activity, remove activity etc + * @class StreamFeed */ -module.exports = function mergeConfig(config1, config2) { - // eslint-disable-next-line no-param-reassign - config2 = config2 || {}; - var config = {}; - - var valueFromConfig2Keys = ['url', 'method', 'params', 'data']; - var mergeDeepPropertiesKeys = ['headers', 'auth', 'proxy']; - var defaultToConfig2Keys = [ - 'baseURL', 'url', 'transformRequest', 'transformResponse', 'paramsSerializer', - 'timeout', 'withCredentials', 'adapter', 'responseType', 'xsrfCookieName', - 'xsrfHeaderName', 'onUploadProgress', 'onDownloadProgress', - 'maxContentLength', 'validateStatus', 'maxRedirects', 'httpAgent', - 'httpsAgent', 'cancelToken', 'socketPath' - ]; - - utils.forEach(valueFromConfig2Keys, function valueFromConfig2(prop) { - if (typeof config2[prop] !== 'undefined') { - config[prop] = config2[prop]; - } - }); - - utils.forEach(mergeDeepPropertiesKeys, function mergeDeepProperties(prop) { - if (utils.isObject(config2[prop])) { - config[prop] = utils.deepMerge(config1[prop], config2[prop]); - } else if (typeof config2[prop] !== 'undefined') { - config[prop] = config2[prop]; - } else if (utils.isObject(config1[prop])) { - config[prop] = utils.deepMerge(config1[prop]); - } else if (typeof config1[prop] !== 'undefined') { - config[prop] = config1[prop]; - } - }); - - utils.forEach(defaultToConfig2Keys, function defaultToConfig2(prop) { - if (typeof config2[prop] !== 'undefined') { - config[prop] = config2[prop]; - } else if (typeof config1[prop] !== 'undefined') { - config[prop] = config1[prop]; - } - }); - - var axiosKeys = valueFromConfig2Keys - .concat(mergeDeepPropertiesKeys) - .concat(defaultToConfig2Keys); - - var otherKeys = Object - .keys(config2) - .filter(function filterAxiosKeys(key) { - return axiosKeys.indexOf(key) === -1; - }); - - utils.forEach(otherKeys, function otherKeysDefaultToConfig2(prop) { - if (typeof config2[prop] !== 'undefined') { - config[prop] = config2[prop]; - } else if (typeof config1[prop] !== 'undefined') { - config[prop] = config1[prop]; - } - }); +var StreamFeed = /*#__PURE__*/function () { + function StreamFeed(client, feedSlug, userId, token) { + _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, StreamFeed); - return config; -}; + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_2___default()(this, "client", void 0); + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_2___default()(this, "token", void 0); -/***/ }), -/* 41 */ -/***/ (function(module, exports, __webpack_require__) { + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_2___default()(this, "id", void 0); -"use strict"; + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_2___default()(this, "slug", void 0); + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_2___default()(this, "userId", void 0); -/** - * A `Cancel` is an object that is thrown when an operation is canceled. - * - * @class - * @param {string=} message The message. - */ -function Cancel(message) { - this.message = message; -} + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_2___default()(this, "feedUrl", void 0); -Cancel.prototype.toString = function toString() { - return 'Cancel' + (this.message ? ': ' + this.message : ''); -}; + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_2___default()(this, "feedTogether", void 0); -Cancel.prototype.__CANCEL__ = true; + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_2___default()(this, "signature", void 0); -module.exports = Cancel; + _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_2___default()(this, "notificationChannel", void 0); + /** + * Initialize a feed object + * @method constructor + * @memberof StreamFeed.prototype + * @param {StreamClient} client - The stream client this feed is constructed from + * @param {string} feedSlug - The feed slug + * @param {string} userId - The user id + * @param {string} [token] - The authentication token + */ + if (!feedSlug || !userId) { + throw new _errors__WEBPACK_IMPORTED_MODULE_4__["FeedError"]('Please provide a feed slug and user id, ie client.feed("user", "1")'); + } -/***/ }), -/* 42 */ -/***/ (function(module, exports) { + if (feedSlug.indexOf(':') !== -1) { + throw new _errors__WEBPACK_IMPORTED_MODULE_4__["FeedError"]('Please initialize the feed using client.feed("user", "1") not client.feed("user:1")'); + } -module.exports = { - VERSION: '1.3.0', + _utils__WEBPACK_IMPORTED_MODULE_5__[/* default */ "a"].validateFeedSlug(feedSlug); + _utils__WEBPACK_IMPORTED_MODULE_5__[/* default */ "a"].validateUserId(userId); // raise an error if there is no token - BAYEUX_VERSION: '1.0', - ID_LENGTH: 160, - JSONP_CALLBACK: 'jsonpcallback', - CONNECTION_TYPES: ['long-polling', 'cross-origin-long-polling', 'callback-polling', 'websocket', 'eventsource', 'in-process'], + if (!token) { + throw new _errors__WEBPACK_IMPORTED_MODULE_4__["FeedError"]('Missing token, in client side mode please provide a feed secret'); + } - MANDATORY_CONNECTION_TYPES: ['long-polling', 'callback-polling', 'in-process'] -}; + this.client = client; + this.slug = feedSlug; + this.userId = userId; + this.id = "".concat(this.slug, ":").concat(this.userId); + this.token = token; + this.feedUrl = this.id.replace(':', '/'); + this.feedTogether = this.id.replace(':', ''); + this.signature = "".concat(this.feedTogether, " ").concat(this.token); // faye setup + this.notificationChannel = "site-".concat(this.client.appId, "-feed-").concat(this.feedTogether); + } -/***/ }), -/* 43 */ -/***/ (function(module, exports, __webpack_require__) { + _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default()(StreamFeed, [{ + key: "addActivity", + value: function addActivity(activity) { + /** + * Adds the given activity to the feed + * @method addActivity + * @memberof StreamFeed.prototype + * @param {NewActivity} activity - The activity to add + * @return {Promise>} + */ + activity = _utils__WEBPACK_IMPORTED_MODULE_5__[/* default */ "a"].replaceStreamObjects(activity); -"use strict"; + if (!activity.actor && this.client.currentUser) { + activity.actor = this.client.currentUser.ref(); + } + return this.client.post({ + url: "feed/".concat(this.feedUrl, "/"), + body: activity, + signature: this.signature + }); + } + }, { + key: "removeActivity", + value: function removeActivity(activityId) { + /** + * Removes the activity by activityId or foreignId + * @method removeActivity + * @memberof StreamFeed.prototype + * @param {string} activityId Identifier of activity to remove + * @return {Promise} + * @example feed.removeActivity(activityId); + * @example feed.removeActivity({'foreignId': foreignId}); + */ + return this.client.delete({ + url: "feed/".concat(this.feedUrl, "/").concat(activityId.foreignId || activityId, "/"), + qs: activityId.foreignId ? { + foreign_id: '1' + } : {}, + signature: this.signature + }); + } + }, { + key: "addActivities", + value: function addActivities(activities) { + /** + * Adds the given activities to the feed + * @method addActivities + * @memberof StreamFeed.prototype + * @param {NewActivity[]} activities Array of activities to add + * @return {Promise[]>} + */ + return this.client.post({ + url: "feed/".concat(this.feedUrl, "/"), + body: { + activities: _utils__WEBPACK_IMPORTED_MODULE_5__[/* default */ "a"].replaceStreamObjects(activities) + }, + signature: this.signature + }); + } + }, { + key: "follow", + value: function follow(targetSlug, targetUserId) { + var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; -// rawAsap provides everything we need except exception management. -var rawAsap = __webpack_require__(89); -// RawTasks are recycled to reduce GC churn. -var freeTasks = []; -// We queue errors to ensure they are thrown in right order (FIFO). -// Array-as-queue is good enough here, since we are just dealing with exceptions. -var pendingErrors = []; -var requestErrorThrow = rawAsap.makeRequestCallFromTimer(throwFirstError); + /** + * Follows the given target feed + * @method follow + * @memberof StreamFeed.prototype + * @param {string} targetSlug Slug of the target feed + * @param {string} targetUserId User identifier of the target feed + * @param {object} [options] Additional options + * @param {number} [options.limit] Limit the amount of activities copied over on follow + * @return {Promise} + * @example feed.follow('user', '1'); + * @example feed.follow('user', '1'); + * @example feed.follow('user', '1', options); + */ + if (targetUserId instanceof _user__WEBPACK_IMPORTED_MODULE_3__[/* default */ "a"]) { + targetUserId = targetUserId.id; + } -function throwFirstError() { - if (pendingErrors.length) { - throw pendingErrors.shift(); + _utils__WEBPACK_IMPORTED_MODULE_5__[/* default */ "a"].validateFeedSlug(targetSlug); + _utils__WEBPACK_IMPORTED_MODULE_5__[/* default */ "a"].validateUserId(targetUserId); + var body = { + target: "".concat(targetSlug, ":").concat(targetUserId) + }; + if (typeof options.limit === 'number') body.activity_copy_limit = options.limit; + return this.client.post({ + url: "feed/".concat(this.feedUrl, "/following/"), + body: body, + signature: this.signature + }); } -} + }, { + key: "unfollow", + value: function unfollow(targetSlug, targetUserId) { + var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; -/** - * Calls a task as soon as possible after returning, in its own event, with priority - * over other events like animation, reflow, and repaint. An error thrown from an - * event will not interrupt, nor even substantially slow down the processing of - * other events, but will be rather postponed to a lower priority event. - * @param {{call}} task A callable object, typically a function that takes no - * arguments. - */ -module.exports = asap; -function asap(task) { - var rawTask; - if (freeTasks.length) { - rawTask = freeTasks.pop(); - } else { - rawTask = new RawTask(); + /** + * Unfollow the given feed + * @method unfollow + * @memberof StreamFeed.prototype + * @param {string} targetSlug Slug of the target feed + * @param {string} targetUserId User identifier of the target feed + * @param {object} [options] + * @param {boolean} [options.keepHistory] when provided the activities from target + * feed will not be kept in the feed + * @return {Promise} + * @example feed.unfollow('user', '2'); + */ + var qs = {}; + if (typeof options.keepHistory === 'boolean' && options.keepHistory) qs.keep_history = '1'; + _utils__WEBPACK_IMPORTED_MODULE_5__[/* default */ "a"].validateFeedSlug(targetSlug); + _utils__WEBPACK_IMPORTED_MODULE_5__[/* default */ "a"].validateUserId(targetUserId); + var targetFeedId = "".concat(targetSlug, ":").concat(targetUserId); + return this.client.delete({ + url: "feed/".concat(this.feedUrl, "/following/").concat(targetFeedId, "/"), + qs: qs, + signature: this.signature + }); } - rawTask.task = task; - rawAsap(rawTask); -} - -// We wrap tasks with recyclable task objects. A task object implements -// `call`, just like a function. -function RawTask() { - this.task = null; -} + }, { + key: "following", + value: function following() { + var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; -// The sole purpose of wrapping the task is to catch the exception and recycle -// the task object after its single use. -RawTask.prototype.call = function () { - try { - this.task.call(); - } catch (error) { - if (asap.onerror) { - // This hook exists purely for testing purposes. - // Its name will be periodically randomized to break any code that - // depends on its existence. - asap.onerror(error); - } else { - // In a web browser, exceptions are not fatal. However, to avoid - // slowing down the queue of pending tasks, we rethrow the error in a - // lower priority turn. - pendingErrors.push(error); - requestErrorThrow(); - } - } finally { - this.task = null; - freeTasks[freeTasks.length] = this; + /** + * List which feeds this feed is following + * @method following + * @memberof StreamFeed.prototype + * @param {GetFollowOptions} [options] Additional options + * @param {string[]} options.filter array of feed id to filter on + * @param {number} options.limit pagination + * @param {number} options.offset pagination + * @return {Promise} + * @example feed.following({limit:10, filter: ['user:1', 'user:2']}); + */ + var extraOptions = {}; + if (options.filter) extraOptions.filter = options.filter.join(','); + return this.client.get({ + url: "feed/".concat(this.feedUrl, "/following/"), + qs: _objectSpread(_objectSpread({}, options), extraOptions), + signature: this.signature + }); } -}; + }, { + key: "followers", + value: function followers() { + var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + /** + * List the followers of this feed + * @method followers + * @memberof StreamFeed.prototype + * @param {GetFollowOptions} [options] Additional options + * @param {string[]} options.filter array of feed id to filter on + * @param {number} options.limit pagination + * @param {number} options.offset pagination + * @return {Promise} + * @example feed.followers({limit:10, filter: ['user:1', 'user:2']}); + */ + var extraOptions = {}; + if (options.filter) extraOptions.filter = options.filter.join(','); + return this.client.get({ + url: "feed/".concat(this.feedUrl, "/followers/"), + qs: _objectSpread(_objectSpread({}, options), extraOptions), + signature: this.signature + }); + } + }, { + key: "get", + value: function get() { + var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; -/***/ }), -/* 44 */ -/***/ (function(module, exports, __webpack_require__) { + /** + * Reads the feed + * @method get + * @memberof StreamFeed.prototype + * @param {GetFeedOptions & NotificationFeedOptions} options Additional options + * @return {Promise} + * @example feed.get({limit: 10, id_lte: 'activity-id'}) + * @example feed.get({limit: 10, mark_seen: true}) + */ + var extraOptions = {}; -"use strict"; + if (options.mark_read && options.mark_read.join) { + extraOptions.mark_read = options.mark_read.join(','); + } + if (options.mark_seen && options.mark_seen.join) { + extraOptions.mark_seen = options.mark_seen.join(','); + } -var Class = __webpack_require__(10), - assign = __webpack_require__(8), - Publisher = __webpack_require__(28), - Grammar = __webpack_require__(45); + this.client.replaceReactionOptions(options); + var path = this.client.shouldUseEnrichEndpoint(options) ? 'enrich/feed/' : 'feed/'; + return this.client.get({ + url: "".concat(path).concat(this.feedUrl, "/"), + qs: _objectSpread(_objectSpread({}, options), extraOptions), + signature: this.signature + }); + } + }, { + key: "getActivityDetail", + value: function getActivityDetail(activityId, options) { + /** + * Retrieves one activity from a feed and adds enrichment + * @method getActivityDetail + * @memberof StreamFeed.prototype + * @param {string} activityId Identifier of activity to retrieve + * @param {EnrichOptions} options Additional options + * @return {Promise} + * @example feed.getActivityDetail(activityId) + * @example feed.getActivityDetail(activityId, {withRecentReactions: true}) + * @example feed.getActivityDetail(activityId, {withReactionCounts: true}) + * @example feed.getActivityDetail(activityId, {withOwnReactions: true, withReactionCounts: true}) + */ + return this.get(_objectSpread({ + id_lte: activityId, + id_gte: activityId, + limit: 1 + }, options || {})); + } + }, { + key: "getFayeClient", + value: function getFayeClient() { + /** + * Returns the current faye client object + * @method getFayeClient + * @memberof StreamFeed.prototype + * @access private + * @return {Faye.Client} Faye client + */ + return this.client.getFayeClient(); + } + }, { + key: "subscribe", + value: function subscribe(callback) { + /** + * Subscribes to any changes in the feed, return a promise + * @method subscribe + * @memberof StreamFeed.prototype + * @param {function} callback Callback to call on completion + * @return {Promise} + * @example + * feed.subscribe(callback).then(function(){ + * console.log('we are now listening to changes'); + * }); + */ + if (!this.client.appId) { + throw new _errors__WEBPACK_IMPORTED_MODULE_4__["SiteError"]('Missing app id, which is needed to subscribe, use var client = stream.connect(key, secret, appId);'); + } -var Channel = Class({ - initialize: function(name) { - this.id = this.name = name; - }, + var subscription = this.getFayeClient().subscribe("/".concat(this.notificationChannel), callback); + this.client.subscriptions["/".concat(this.notificationChannel)] = { + token: this.token, + userId: this.notificationChannel, + fayeSubscription: subscription + }; + return subscription; + } + }, { + key: "unsubscribe", + value: function unsubscribe() { + /** + * Cancel updates created via feed.subscribe() + * @return void + */ + var streamSubscription = this.client.subscriptions["/".concat(this.notificationChannel)]; - push: function(message) { - this.trigger('message', message); - }, + if (streamSubscription) { + delete this.client.subscriptions["/".concat(this.notificationChannel)]; + streamSubscription.fayeSubscription.cancel(); + } + } + }, { + key: "updateActivityToTargets", + value: function updateActivityToTargets(foreignId, time, newTargets, addedTargets, removedTargets) { + /** + * Updates an activity's "to" fields + * @since 3.10.0 + * @param {string} foreignId The foreign_id of the activity to update + * @param {string} time The time of the activity to update + * @param {string[]} newTargets Set the new "to" targets for the activity - will remove old targets + * @param {string[]} added_targets Add these new targets to the activity + * @param {string[]} removedTargets Remove these targets from the activity + */ + if (!foreignId) throw new Error('Missing `foreign_id` parameter!'); + if (!time) throw new Error('Missing `time` parameter!'); - isUnused: function() { - return this.countListeners('message') === 0; - } -}); + if (!newTargets && !addedTargets && !removedTargets) { + throw new Error('Requires you to provide at least one parameter for `newTargets`, `addedTargets`, or `removedTargets` - example: `updateActivityToTargets("foreignID:1234", new Date(), [newTargets...], [addedTargets...], [removedTargets...])`'); + } -assign(Channel.prototype, Publisher); + if (newTargets) { + if (addedTargets || removedTargets) { + throw new Error("Can't include add_targets or removedTargets if you're also including newTargets"); + } + } -assign(Channel, { - HANDSHAKE: '/meta/handshake', - CONNECT: '/meta/connect', - SUBSCRIBE: '/meta/subscribe', - UNSUBSCRIBE: '/meta/unsubscribe', - DISCONNECT: '/meta/disconnect', + if (addedTargets && removedTargets) { + // brute force - iterate through added, check to see if removed contains that element + addedTargets.forEach(function (addedTarget) { + if (removedTargets.includes(addedTarget)) { + throw new Error("Can't have the same feed ID in addedTargets and removedTargets."); + } + }); + } - META: 'meta', - SERVICE: 'service', + var body = { + foreign_id: foreignId, + time: time + }; + if (newTargets) body.new_targets = newTargets; + if (addedTargets) body.added_targets = addedTargets; + if (removedTargets) body.removed_targets = removedTargets; + return this.client.post({ + url: "feed_targets/".concat(this.feedUrl, "/activity_to_targets/"), + signature: this.signature, + body: body + }); + } + }]); - expand: function(name) { - var segments = this.parse(name), - channels = ['/**', name]; + return StreamFeed; +}(); - var copy = segments.slice(); - copy[copy.length - 1] = '*'; - channels.push(this.unparse(copy)); - for (var i = 1, n = segments.length; i < n; i++) { - copy = segments.slice(0, i); - copy.push('**'); - channels.push(this.unparse(copy)); - } - return channels; - }, +/***/ }), +/* 32 */ +/***/ (function(module, exports) { - isValid: function(name) { - return Grammar.CHANNEL_NAME.test(name) || - Grammar.CHANNEL_PATTERN.test(name); - }, +function _getPrototypeOf(o) { + module.exports = _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { + return o.__proto__ || Object.getPrototypeOf(o); + }; + return _getPrototypeOf(o); +} - parse: function(name) { - if (!this.isValid(name)) return null; - return name.split('/').slice(1); - }, +module.exports = _getPrototypeOf; - unparse: function(segments) { - return '/' + segments.join('/'); - }, +/***/ }), +/* 33 */ +/***/ (function(module, exports, __webpack_require__) { - isMeta: function(name) { - var segments = this.parse(name); - return segments ? (segments[0] === this.META) : null; - }, +"use strict"; - isService: function(name) { - var segments = this.parse(name); - return segments ? (segments[0] === this.SERVICE) : null; - }, - isSubscribable: function(name) { - if (!this.isValid(name)) return null; - return !this.isMeta(name) && !this.isService(name); +module.exports = { + commonElement: function(lista, listb) { + for (var i = 0, n = lista.length; i < n; i++) { + if (this.indexOf(listb, lista[i]) !== -1) + return lista[i]; + } + return null; }, - Set: Class({ - initialize: function() { - this._channels = {}; - }, - - getKeys: function() { - var keys = []; - for (var key in this._channels) keys.push(key); - return keys; - }, + indexOf: function(list, needle) { + if (list.indexOf) return list.indexOf(needle); - remove: function(name) { - delete this._channels[name]; - }, + for (var i = 0, n = list.length; i < n; i++) { + if (list[i] === needle) return i; + } + return -1; + }, - hasSubscription: function(name) { - return this._channels.hasOwnProperty(name); - }, + map: function(object, callback, context) { + if (object.map) return object.map(callback, context); + var result = []; - subscribe: function(names, subscription) { - var name; - for (var i = 0, n = names.length; i < n; i++) { - name = names[i]; - var channel = this._channels[name] = this._channels[name] || new Channel(name); - channel.bind('message', subscription); + if (object instanceof Array) { + for (var i = 0, n = object.length; i < n; i++) { + result.push(callback.call(context || null, object[i], i)); } - }, + } else { + for (var key in object) { + if (!object.hasOwnProperty(key)) continue; + result.push(callback.call(context || null, key, object[key])); + } + } + return result; + }, - unsubscribe: function(name, subscription) { - var channel = this._channels[name]; - if (!channel) return false; - channel.unbind('message', subscription); + filter: function(array, callback, context) { + if (array.filter) return array.filter(callback, context); + var result = []; + for (var i = 0, n = array.length; i < n; i++) { + if (callback.call(context || null, array[i], i)) + result.push(array[i]); + } + return result; + }, - if (channel.isUnused()) { - this.remove(name); - return true; - } else { - return false; - } - }, + asyncEach: function(list, iterator, callback, context) { + var n = list.length, + i = -1, + calls = 0, + looping = false; - distributeMessage: function(message) { - var channels = Channel.expand(message.channel); + var iterate = function() { + calls -= 1; + i += 1; + if (i === n) return callback && callback.call(context); + iterator(list[i], resume); + }; - for (var i = 0, n = channels.length; i < n; i++) { - var channel = this._channels[channels[i]]; - if (channel) channel.trigger('message', message); - } - } - }) -}); + var loop = function() { + if (looping) return; + looping = true; + while (calls > 0) iterate(); + looping = false; + }; -module.exports = Channel; + var resume = function() { + calls += 1; + loop(); + }; + resume(); + } +}; /***/ }), -/* 45 */ +/* 34 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; +/* WEBPACK VAR INJECTION */(function(global) { +var Event = { + _registry: [], -module.exports = { - CHANNEL_NAME: /^\/(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)))+(\/(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)))+)*$/, - CHANNEL_PATTERN: /^(\/(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)))+)*\/\*{1,2}$/, - ERROR: /^([0-9][0-9][0-9]:(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)| |\/|\*|\.))*(,(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)| |\/|\*|\.))*)*:(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)| |\/|\*|\.))*|[0-9][0-9][0-9]::(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)| |\/|\*|\.))*)$/, - VERSION: /^([0-9])+(\.(([a-z]|[A-Z])|[0-9])(((([a-z]|[A-Z])|[0-9])|\-|\_))*)*$/ -}; + on: function(element, eventName, callback, context) { + var wrapped = function() { callback.call(context) }; + if (element.addEventListener) + element.addEventListener(eventName, wrapped, false); + else + element.attachEvent('on' + eventName, wrapped); -/***/ }), -/* 46 */ -/***/ (function(module, exports, __webpack_require__) { + this._registry.push({ + _element: element, + _type: eventName, + _callback: callback, + _context: context, + _handler: wrapped + }); + }, -"use strict"; + detach: function(element, eventName, callback, context) { + var i = this._registry.length, register; + while (i--) { + register = this._registry[i]; + if ((element && element !== register._element) || + (eventName && eventName !== register._type) || + (callback && callback !== register._callback) || + (context && context !== register._context)) + continue; -module.exports = {}; + if (register._element.removeEventListener) + register._element.removeEventListener(register._type, register._handler, false); + else + register._element.detachEvent('on' + register._type, register._handler); + this._registry.splice(i,1); + register = null; + } + } +}; -/***/ }), -/* 47 */ -/***/ (function(module, exports, __webpack_require__) { +if (global.onunload !== undefined) + Event.on(global, 'unload', Event.detach, Event); -"use strict"; +module.exports = { + Event: Event +}; +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(11))) -var Class = __webpack_require__(10); +/***/ }), +/* 35 */ +/***/ (function(module, exports, __webpack_require__) { -module.exports = Class({ - initialize: function() { - this._index = {}; - }, +"use strict"; - add: function(item) { - var key = (item.id !== undefined) ? item.id : item; - if (this._index.hasOwnProperty(key)) return false; - this._index[key] = item; - return true; - }, - forEach: function(block, context) { - for (var key in this._index) { - if (this._index.hasOwnProperty(key)) - block.call(context, this._index[key]); - } - }, +var assign = __webpack_require__(8), + EventEmitter = __webpack_require__(91); - isEmpty: function() { - for (var key in this._index) { - if (this._index.hasOwnProperty(key)) return false; - } - return true; +var Publisher = { + countListeners: function(eventType) { + return this.listeners(eventType).length; }, - member: function(item) { - for (var key in this._index) { - if (this._index[key] === item) return true; - } - return false; - }, + bind: function(eventType, listener, context) { + var slice = Array.prototype.slice, + handler = function() { listener.apply(context, slice.call(arguments)) }; - remove: function(item) { - var key = (item.id !== undefined) ? item.id : item; - var removed = this._index[key]; - delete this._index[key]; - return removed; + this._listeners = this._listeners || []; + this._listeners.push([eventType, listener, context, handler]); + return this.on(eventType, handler); }, - toArray: function() { - var array = []; - this.forEach(function(item) { array.push(item) }); - return array; + unbind: function(eventType, listener, context) { + this._listeners = this._listeners || []; + var n = this._listeners.length, tuple; + + while (n--) { + tuple = this._listeners[n]; + if (tuple[0] !== eventType) continue; + if (listener && (tuple[1] !== listener || tuple[2] !== context)) continue; + this._listeners.splice(n, 1); + this.removeListener(eventType, tuple[3]); + } } -}); +}; + +assign(Publisher, EventEmitter.prototype); +Publisher.trigger = Publisher.emit; + +module.exports = Publisher; /***/ }), -/* 48 */ +/* 36 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -/* WEBPACK VAR INJECTION */(function(global) { -var Class = __webpack_require__(10), - URI = __webpack_require__(12), - browser = __webpack_require__(27), - assign = __webpack_require__(8), - toJSON = __webpack_require__(17), - Transport = __webpack_require__(13); -var XHR = assign(Class(Transport, { - encode: function(messages) { - return toJSON(messages); - }, +var copyObject = function(object) { + var clone, i, key; + if (object instanceof Array) { + clone = []; + i = object.length; + while (i--) clone[i] = copyObject(object[i]); + return clone; + } else if (typeof object === 'object') { + clone = (object === null) ? null : {}; + for (key in object) clone[key] = copyObject(object[key]); + return clone; + } else { + return object; + } +}; - request: function(messages) { - var href = this.endpoint.href, - self = this, - xhr; +module.exports = copyObject; - // Prefer XMLHttpRequest over ActiveXObject if they both exist - if (global.XMLHttpRequest) { - xhr = new XMLHttpRequest(); - } else if (global.ActiveXObject) { - xhr = new ActiveXObject('Microsoft.XMLHTTP'); - } else { - return this._handleError(messages); - } - xhr.open('POST', href, true); - xhr.setRequestHeader('Content-Type', 'application/json'); - xhr.setRequestHeader('Pragma', 'no-cache'); - xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); +/***/ }), +/* 37 */ +/***/ (function(module, exports) { - var headers = this._dispatcher.headers; - for (var key in headers) { - if (!headers.hasOwnProperty(key)) continue; - xhr.setRequestHeader(key, headers[key]); - } +function _setPrototypeOf(o, p) { + module.exports = _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { + o.__proto__ = p; + return o; + }; - var abort = function() { xhr.abort() }; - if (global.onbeforeunload !== undefined) - browser.Event.on(global, 'beforeunload', abort); + return _setPrototypeOf(o, p); +} - xhr.onreadystatechange = function() { - if (!xhr || xhr.readyState !== 4) return; +module.exports = _setPrototypeOf; - var replies = null, - status = xhr.status, - text = xhr.responseText, - successful = (status >= 200 && status < 300) || status === 304 || status === 1223; +/***/ }), +/* 38 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { - if (global.onbeforeunload !== undefined) - browser.Event.detach(global, 'beforeunload', abort); +"use strict"; +/* WEBPACK VAR INJECTION */(function(process) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return connect; }); +/* harmony import */ var _client__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(12); - xhr.onreadystatechange = function() {}; - xhr = null; +function connect(apiKey, apiSecret, appId, options) { + /** + * Create StreamClient + * @method connect + * @param {string} apiKey API key + * @param {string} [apiSecret] API secret (only use this on the server) + * @param {string} [appId] Application identifier + * @param {ClientOptions} [options] - additional options + * @param {string} [options.location] - which data center to use + * @param {boolean} [options.expireTokens=false] - whether to use a JWT timestamp field (i.e. iat) + * @param {string} [options.version] - advanced usage, custom api version + * @param {boolean} [options.keepAlive] - axios keepAlive, default to true + * @param {number} [options.timeout] - axios timeout in Ms, default to 10s + * @return {StreamClient} StreamClient + * @example Basic usage + * stream.connect(apiKey, apiSecret); + * @example or if you want to be able to subscribe and listen + * stream.connect(apiKey, apiSecret, appId); + * @example or on Heroku + * stream.connect(streamURL); + * @example where streamURL looks like + * "https://thierry:pass@gestream.io/?app=1" + */ + if (process && process.env && process.env.STREAM_URL && !apiKey) { + var parts = /https:\/\/(\w+):(\w+)@([\w-]*).*\?app_id=(\d+)/.exec(process.env.STREAM_URL) || []; + apiKey = parts[1]; + apiSecret = parts[2]; + var location = parts[3]; + appId = parts[4]; - if (!successful) return self._handleError(messages); + if (options === undefined) { + options = {}; + } - try { - replies = JSON.parse(text); - } catch (error) {} + if (location !== 'getstream' && location !== 'stream-io-api') { + options.location = location; + } + } - if (replies) - self._receive(replies); - else - self._handleError(messages); - }; + return new _client__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"](apiKey, apiSecret, appId, options); +} +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(24))) - xhr.send(this.encode(messages)); - return xhr; - } -}), { - isUsable: function(dispatcher, endpoint, callback, context) { - var usable = (navigator.product === 'ReactNative') - || URI.isSameOrigin(endpoint); +/***/ }), +/* 39 */ +/***/ (function(module, exports) { - callback.call(context, usable); - } -}); -module.exports = XHR; -/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(11))) +/***/ }), +/* 40 */ +/***/ (function(module, exports) { + +/* (ignored) */ /***/ }), -/* 49 */ +/* 41 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var assign = __webpack_require__(8); - -var Scheduler = function(message, options) { - this.message = message; - this.options = options; - this.attempts = 0; +module.exports = function bind(fn, thisArg) { + return function wrap() { + var args = new Array(arguments.length); + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i]; + } + return fn.apply(thisArg, args); + }; }; -assign(Scheduler.prototype, { - getTimeout: function() { - return this.options.timeout; - }, - - getInterval: function() { - return this.options.interval; - }, - - isDeliverable: function() { - var attempts = this.options.attempts, - made = this.attempts, - deadline = this.options.deadline, - now = new Date().getTime(); - if (attempts !== undefined && made >= attempts) - return false; +/***/ }), +/* 42 */ +/***/ (function(module, exports, __webpack_require__) { - if (deadline !== undefined && now > deadline) - return false; +"use strict"; - return true; - }, - send: function() { - this.attempts += 1; - }, +var utils = __webpack_require__(9); - succeed: function() {}, +function encode(val) { + return encodeURIComponent(val). + replace(/%40/gi, '@'). + replace(/%3A/gi, ':'). + replace(/%24/g, '$'). + replace(/%2C/gi, ','). + replace(/%20/g, '+'). + replace(/%5B/gi, '['). + replace(/%5D/gi, ']'); +} - fail: function() {}, +/** + * Build a URL by appending params to the end + * + * @param {string} url The base of the url (e.g., http://www.google.com) + * @param {object} [params] The params to be appended + * @returns {string} The formatted url + */ +module.exports = function buildURL(url, params, paramsSerializer) { + /*eslint no-param-reassign:0*/ + if (!params) { + return url; + } - abort: function() {} -}); + var serializedParams; + if (paramsSerializer) { + serializedParams = paramsSerializer(params); + } else if (utils.isURLSearchParams(params)) { + serializedParams = params.toString(); + } else { + var parts = []; -module.exports = Scheduler; + utils.forEach(params, function serialize(val, key) { + if (val === null || typeof val === 'undefined') { + return; + } + if (utils.isArray(val)) { + key = key + '[]'; + } else { + val = [val]; + } -/***/ }), -/* 50 */ -/***/ (function(module, exports, __webpack_require__) { + utils.forEach(val, function parseValue(v) { + if (utils.isDate(v)) { + v = v.toISOString(); + } else if (utils.isObject(v)) { + v = JSON.stringify(v); + } + parts.push(encode(key) + '=' + encode(v)); + }); + }); -module.exports = __webpack_require__(72); + serializedParams = parts.join('&'); + } -/***/ }), -/* 51 */ -/***/ (function(module, exports) { + if (serializedParams) { + var hashmarkIndex = url.indexOf('#'); + if (hashmarkIndex !== -1) { + url = url.slice(0, hashmarkIndex); + } -/* (ignored) */ + url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams; + } -/***/ }), -/* 52 */ -/***/ (function(module, exports) { + return url; +}; -/* (ignored) */ /***/ }), -/* 53 */ +/* 43 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; -var constants = __webpack_require__(42), - Logging = __webpack_require__(16); - -var Faye = { - VERSION: constants.VERSION, - - Client: __webpack_require__(88), - Scheduler: __webpack_require__(49) +module.exports = function isCancel(value) { + return !!(value && value.__CANCEL__); }; -Logging.wrapper = Faye; - -module.exports = Faye; - /***/ }), -/* 54 */ +/* 44 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; +/* WEBPACK VAR INJECTION */(function(process) { +var utils = __webpack_require__(9); +var normalizeHeaderName = __webpack_require__(77); -var base64_url_decode = __webpack_require__(104); - -function InvalidTokenError(message) { - this.message = message; -} - -InvalidTokenError.prototype = new Error(); -InvalidTokenError.prototype.name = 'InvalidTokenError'; +var DEFAULT_CONTENT_TYPE = { + 'Content-Type': 'application/x-www-form-urlencoded' +}; -module.exports = function (token,options) { - if (typeof token !== 'string') { - throw new InvalidTokenError('Invalid token specified'); +function setContentTypeIfUnset(headers, value) { + if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) { + headers['Content-Type'] = value; } +} - options = options || {}; - var pos = options.header === true ? 0 : 1; - try { - return JSON.parse(base64_url_decode(token.split('.')[pos])); - } catch (e) { - throw new InvalidTokenError('Invalid token specified: ' + e.message); +function getDefaultAdapter() { + var adapter; + if (typeof XMLHttpRequest !== 'undefined') { + // For browsers use XHR adapter + adapter = __webpack_require__(45); + } else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') { + // For node use HTTP adapter + adapter = __webpack_require__(45); } -}; - -module.exports.InvalidTokenError = InvalidTokenError; + return adapter; +} +var defaults = { + adapter: getDefaultAdapter(), -/***/ }), -/* 55 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { + transformRequest: [function transformRequest(data, headers) { + normalizeHeaderName(headers, 'Accept'); + normalizeHeaderName(headers, 'Content-Type'); + if (utils.isFormData(data) || + utils.isArrayBuffer(data) || + utils.isBuffer(data) || + utils.isStream(data) || + utils.isFile(data) || + utils.isBlob(data) + ) { + return data; + } + if (utils.isArrayBufferView(data)) { + return data.buffer; + } + if (utils.isURLSearchParams(data)) { + setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8'); + return data.toString(); + } + if (utils.isObject(data)) { + setContentTypeIfUnset(headers, 'application/json;charset=utf-8'); + return JSON.stringify(data); + } + return data; + }], -"use strict"; -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Personalization; }); -/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2); -/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3); -/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__); + transformResponse: [function transformResponse(data) { + /*eslint no-param-reassign:0*/ + if (typeof data === 'string') { + try { + data = JSON.parse(data); + } catch (e) { /* Ignore */ } + } + return data; + }], + /** + * A timeout in milliseconds to abort a request. If set to 0 (default) a + * timeout is not created. + */ + timeout: 0, + xsrfCookieName: 'XSRF-TOKEN', + xsrfHeaderName: 'X-XSRF-TOKEN', -/** - * Manage api calls for personalization - * The collection object contains convenience functions such as get, post, delete - * @class Personalization - */ -var Personalization = /*#__PURE__*/function () { - function Personalization(client) { - _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, Personalization); + maxContentLength: -1, - /** - * Initialize the Personalization class - * - * @method constructor - * @memberof Personalization.prototype - * @param {StreamClient} client - The stream client - */ - this.client = client; + validateStatus: function validateStatus(status) { + return status >= 200 && status < 300; } +}; - _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default()(Personalization, [{ - key: "get", - value: function get(resource) { - var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - - /** - * Get personalized activities for this feed - * - * @method get - * @memberof Personalization.prototype - * @param {object} resource - personalized resource endpoint i.e "follow_recommendations" - * @param {object} options Additional options - * @return {Promise} Promise object. Personalized feed - * @example client.personalization.get('follow_recommendations', {foo: 'bar', baz: 'qux'}) - */ - return this.client.get({ - url: "".concat(resource, "/"), - serviceName: 'personalization', - qs: options, - signature: options.token || this.client.getPersonalizationToken() - }); - } - }, { - key: "post", - value: function post(resource) { - var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - var data = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; - - /** - * Post data to personalization endpoint - * - * @method post - * @memberof Personalization.prototype - * @param {object} resource - personalized resource endpoint i.e "follow_recommendations" - * @param {object} options - Additional options - * @param {object} data - Data to send in the payload - * @return {Promise} Promise object. Data that was posted if successful, or an error. - * @example client.personalization.post('follow_recommendations', {foo: 'bar', baz: 'qux'}) - */ - return this.client.post({ - url: "".concat(resource, "/"), - serviceName: 'personalization', - qs: options, - body: data, - signature: this.client.getPersonalizationToken() - }); - } - }, { - key: "delete", - value: function _delete(resource) { - var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; +defaults.headers = { + common: { + 'Accept': 'application/json, text/plain, */*' + } +}; - /** - * Delete metadata or activities - * - * @method delete - * @memberof Personalization.prototype - * @param {object} resource - personalized resource endpoint i.e "follow_recommendations" - * @param {object} options - Additional options - * @return {Promise} Promise object. Data that was deleted if successful, or an error. - * @example client.personalization.delete('follow_recommendations', {foo: 'bar', baz: 'qux'}) - */ - return this.client.delete({ - url: "".concat(resource, "/"), - serviceName: 'personalization', - qs: options, - signature: this.client.getPersonalizationToken() - }); - } - }]); +utils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) { + defaults.headers[method] = {}; +}); - return Personalization; -}(); +utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { + defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE); +}); +module.exports = defaults; +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(24))) /***/ }), -/* 56 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { +/* 45 */ +/***/ (function(module, exports, __webpack_require__) { "use strict"; -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Collections; }); -/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(4); -/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(0); -/* harmony import */ var _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1__); -/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(6); -/* harmony import */ var _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2__); -/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(2); -/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_3__); -/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(3); -/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_4___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_4__); -/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1); +var utils = __webpack_require__(9); +var settle = __webpack_require__(78); +var buildURL = __webpack_require__(42); +var buildFullPath = __webpack_require__(80); +var parseHeaders = __webpack_require__(83); +var isURLSameOrigin = __webpack_require__(84); +var createError = __webpack_require__(46); + +module.exports = function xhrAdapter(config) { + return new Promise(function dispatchXhrRequest(resolve, reject) { + var requestData = config.data; + var requestHeaders = config.headers; + + if (utils.isFormData(requestData)) { + delete requestHeaders['Content-Type']; // Let the browser set it + } + var request = new XMLHttpRequest(); + // HTTP basic authentication + if (config.auth) { + var username = config.auth.username || ''; + var password = config.auth.password || ''; + requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password); + } + var fullPath = buildFullPath(config.baseURL, config.url); + request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true); + // Set the request timeout in MS + request.timeout = config.timeout; -var CollectionEntry = /*#__PURE__*/function () { - function CollectionEntry(store, collection, id, data) { - _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_3___default()(this, CollectionEntry); + // Listen for ready state + request.onreadystatechange = function handleLoad() { + if (!request || request.readyState !== 4) { + return; + } - this.collection = collection; - this.store = store; - this.id = id; - this.data = data; - } + // The request errored out and we didn't get a response, this will be + // handled by onerror instead + // With one exception: request that using file: protocol, most browsers + // will return status as 0 even though it's a successful request + if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) { + return; + } - _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_4___default()(CollectionEntry, [{ - key: "ref", - value: function ref() { - return "SO:".concat(this.collection, ":").concat(this.id); - } - }, { - key: "get", - value: function () { - var _get = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.mark(function _callee() { - var response; - return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - _context.next = 2; - return this.store.get(this.collection, this.id); + // Prepare the response + var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null; + var responseData = !config.responseType || config.responseType === 'text' ? request.responseText : request.response; + var response = { + data: responseData, + status: request.status, + statusText: request.statusText, + headers: responseHeaders, + config: config, + request: request + }; - case 2: - response = _context.sent; - this.data = response.data; - this.full = response; - return _context.abrupt("return", response); + settle(resolve, reject, response); - case 6: - case "end": - return _context.stop(); - } - } - }, _callee, this); - })); + // Clean up request + request = null; + }; - function get() { - return _get.apply(this, arguments); + // Handle browser request cancellation (as opposed to a manual cancellation) + request.onabort = function handleAbort() { + if (!request) { + return; } - return get; - }() - }, { - key: "add", - value: function () { - var _add = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.mark(function _callee2() { - var response; - return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.wrap(function _callee2$(_context2) { - while (1) { - switch (_context2.prev = _context2.next) { - case 0: - _context2.next = 2; - return this.store.add(this.collection, this.id, this.data); + reject(createError('Request aborted', config, 'ECONNABORTED', request)); - case 2: - response = _context2.sent; - this.data = response.data; - this.full = response; - return _context2.abrupt("return", response); + // Clean up request + request = null; + }; - case 6: - case "end": - return _context2.stop(); - } - } - }, _callee2, this); - })); + // Handle low level network errors + request.onerror = function handleError() { + // Real errors are hidden from us by the browser + // onerror should only fire if it's a network error + reject(createError('Network Error', config, null, request)); - function add() { - return _add.apply(this, arguments); + // Clean up request + request = null; + }; + + // Handle timeout + request.ontimeout = function handleTimeout() { + var timeoutErrorMessage = 'timeout of ' + config.timeout + 'ms exceeded'; + if (config.timeoutErrorMessage) { + timeoutErrorMessage = config.timeoutErrorMessage; } + reject(createError(timeoutErrorMessage, config, 'ECONNABORTED', + request)); - return add; - }() - }, { - key: "update", - value: function () { - var _update = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.mark(function _callee3() { - var response; - return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.wrap(function _callee3$(_context3) { - while (1) { - switch (_context3.prev = _context3.next) { - case 0: - _context3.next = 2; - return this.store.update(this.collection, this.id, this.data); + // Clean up request + request = null; + }; - case 2: - response = _context3.sent; - this.data = response.data; - this.full = response; - return _context3.abrupt("return", response); + // Add xsrf header + // This is only done if running in a standard browser environment. + // Specifically not if we're in a web worker, or react-native. + if (utils.isStandardBrowserEnv()) { + var cookies = __webpack_require__(85); - case 6: - case "end": - return _context3.stop(); - } - } - }, _callee3, this); - })); + // Add xsrf header + var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ? + cookies.read(config.xsrfCookieName) : + undefined; - function update() { - return _update.apply(this, arguments); + if (xsrfValue) { + requestHeaders[config.xsrfHeaderName] = xsrfValue; } + } - return update; - }() - }, { - key: "delete", - value: function () { - var _delete2 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.mark(function _callee4() { - var response; - return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.wrap(function _callee4$(_context4) { - while (1) { - switch (_context4.prev = _context4.next) { - case 0: - _context4.next = 2; - return this.store.delete(this.collection, this.id); - - case 2: - response = _context4.sent; - this.data = null; - this.full = null; - return _context4.abrupt("return", response); + // Add headers to the request + if ('setRequestHeader' in request) { + utils.forEach(requestHeaders, function setRequestHeader(val, key) { + if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') { + // Remove Content-Type if data is undefined + delete requestHeaders[key]; + } else { + // Otherwise add header to the request + request.setRequestHeader(key, val); + } + }); + } - case 6: - case "end": - return _context4.stop(); - } - } - }, _callee4, this); - })); + // Add withCredentials to request if needed + if (!utils.isUndefined(config.withCredentials)) { + request.withCredentials = !!config.withCredentials; + } - function _delete() { - return _delete2.apply(this, arguments); + // Add responseType to request if needed + if (config.responseType) { + try { + request.responseType = config.responseType; + } catch (e) { + // Expected DOMException thrown by browsers not compatible XMLHttpRequest Level 2. + // But, this can be suppressed for 'json' type as it can be parsed by default 'transformResponse' function. + if (config.responseType !== 'json') { + throw e; + } } + } - return _delete; - }() - }]); - - return CollectionEntry; -}(); + // Handle progress if needed + if (typeof config.onDownloadProgress === 'function') { + request.addEventListener('progress', config.onDownloadProgress); + } -var Collections = /*#__PURE__*/function () { - /** - * Initialize a feed object - * @method constructor - * @memberof Collections.prototype - * @param {StreamCloudClient} client Stream client this collection is constructed from - * @param {string} token JWT token - */ - function Collections(client, token) { - _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_3___default()(this, Collections); + // Not all browsers support upload events + if (typeof config.onUploadProgress === 'function' && request.upload) { + request.upload.addEventListener('progress', config.onUploadProgress); + } - _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0___default()(this, "buildURL", function (collection, itemId) { - var url = "collections/".concat(collection, "/"); - return itemId === undefined ? url : "".concat(url).concat(itemId, "/"); - }); + if (config.cancelToken) { + // Handle cancellation + config.cancelToken.promise.then(function onCanceled(cancel) { + if (!request) { + return; + } - this.client = client; - this.token = token; - } + request.abort(); + reject(cancel); + // Clean up request + request = null; + }); + } - _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_4___default()(Collections, [{ - key: "entry", - value: function entry(collection, itemId, itemData) { - return new CollectionEntry(this, collection, itemId, itemData); + if (requestData === undefined) { + requestData = null; } - }, { - key: "get", - value: function () { - var _get2 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.mark(function _callee5(collection, itemId) { - var response, entry; - return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.wrap(function _callee5$(_context5) { - while (1) { - switch (_context5.prev = _context5.next) { - case 0: - _context5.next = 2; - return this.client.get({ - url: this.buildURL(collection, itemId), - signature: this.token - }); - case 2: - response = _context5.sent; - entry = this.client.collections.entry(response.collection, response.id, response.data); - entry.full = response; - return _context5.abrupt("return", entry); + // Send the request + request.send(requestData); + }); +}; - case 6: - case "end": - return _context5.stop(); - } - } - }, _callee5, this); - })); - function get(_x, _x2) { - return _get2.apply(this, arguments); - } +/***/ }), +/* 46 */ +/***/ (function(module, exports, __webpack_require__) { - return get; - }() - }, { - key: "add", - value: function () { - var _add2 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.mark(function _callee6(collection, itemId, itemData) { - var response, entry; - return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.wrap(function _callee6$(_context6) { - while (1) { - switch (_context6.prev = _context6.next) { - case 0: - _context6.next = 2; - return this.client.post({ - url: this.buildURL(collection), - body: { - id: itemId === null ? undefined : itemId, - data: itemData - }, - signature: this.token - }); +"use strict"; - case 2: - response = _context6.sent; - entry = this.client.collections.entry(response.collection, response.id, response.data); - entry.full = response; - return _context6.abrupt("return", entry); - case 6: - case "end": - return _context6.stop(); - } - } - }, _callee6, this); - })); +var enhanceError = __webpack_require__(79); - function add(_x3, _x4, _x5) { - return _add2.apply(this, arguments); - } +/** + * Create an Error with the specified message, config, error code, request and response. + * + * @param {string} message The error message. + * @param {Object} config The config. + * @param {string} [code] The error code (for example, 'ECONNABORTED'). + * @param {Object} [request] The request. + * @param {Object} [response] The response. + * @returns {Error} The created error. + */ +module.exports = function createError(message, config, code, request, response) { + var error = new Error(message); + return enhanceError(error, config, code, request, response); +}; - return add; - }() - }, { - key: "update", - value: function () { - var _update2 = _babel_runtime_helpers_asyncToGenerator__WEBPACK_IMPORTED_MODULE_2___default()( /*#__PURE__*/_babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.mark(function _callee7(collection, entryId, data) { - var response, entry; - return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_1___default.a.wrap(function _callee7$(_context7) { - while (1) { - switch (_context7.prev = _context7.next) { - case 0: - _context7.next = 2; - return this.client.put({ - url: this.buildURL(collection, entryId), - body: { - data: data - }, - signature: this.token - }); - case 2: - response = _context7.sent; - entry = this.client.collections.entry(response.collection, response.id, response.data); - entry.full = response; - return _context7.abrupt("return", entry); +/***/ }), +/* 47 */ +/***/ (function(module, exports, __webpack_require__) { - case 6: - case "end": - return _context7.stop(); - } - } - }, _callee7, this); - })); +"use strict"; - function update(_x6, _x7, _x8) { - return _update2.apply(this, arguments); - } - return update; - }() - }, { - key: "delete", - value: function _delete(collection, entryId) { - /** - * Delete entry from collection - * @method delete - * @memberof Collections.prototype - * @param {object} entryId Collection entry id - * @return {Promise} Promise object - * @example collection.delete("food", "cheese101") - */ - return this.client.delete({ - url: this.buildURL(collection, entryId), - signature: this.token - }); - } - }, { - key: "upsert", - value: function upsert(collection, data) { - /** - * Upsert one or more items within a collection. - * - * @method upsert - * @memberof Collections.prototype - * @param {object|array} data - A single json object or an array of objects - * @return {Promise} Promise object. - */ - if (!this.client.usingApiSecret) { - throw new _errors__WEBPACK_IMPORTED_MODULE_5__[/* default */ "a"].SiteError('This method can only be used server-side using your API Secret'); - } +var utils = __webpack_require__(9); - if (!Array.isArray(data)) data = [data]; - return this.client.post({ - url: 'collections/', - serviceName: 'api', - body: { - data: _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0___default()({}, collection, data) - }, - signature: this.client.getCollectionsToken() - }); +/** + * Config-specific merge-function which creates a new config-object + * by merging two configuration objects together. + * + * @param {Object} config1 + * @param {Object} config2 + * @returns {Object} New object resulting from merging config2 to config1 + */ +module.exports = function mergeConfig(config1, config2) { + // eslint-disable-next-line no-param-reassign + config2 = config2 || {}; + var config = {}; + + var valueFromConfig2Keys = ['url', 'method', 'params', 'data']; + var mergeDeepPropertiesKeys = ['headers', 'auth', 'proxy']; + var defaultToConfig2Keys = [ + 'baseURL', 'url', 'transformRequest', 'transformResponse', 'paramsSerializer', + 'timeout', 'withCredentials', 'adapter', 'responseType', 'xsrfCookieName', + 'xsrfHeaderName', 'onUploadProgress', 'onDownloadProgress', + 'maxContentLength', 'validateStatus', 'maxRedirects', 'httpAgent', + 'httpsAgent', 'cancelToken', 'socketPath' + ]; + + utils.forEach(valueFromConfig2Keys, function valueFromConfig2(prop) { + if (typeof config2[prop] !== 'undefined') { + config[prop] = config2[prop]; } - }, { - key: "select", - value: function select(collection, ids) { - /** - * Select all objects with ids from the collection. - * - * @method select - * @memberof Collections.prototype - * @param {object|array} ids - A single json object or an array of objects - * @return {Promise} Promise object. - */ - if (!this.client.usingApiSecret) { - throw new _errors__WEBPACK_IMPORTED_MODULE_5__[/* default */ "a"].SiteError('This method can only be used server-side using your API Secret'); - } + }); - if (!Array.isArray(ids)) ids = [ids]; - return this.client.get({ - url: 'collections/', - serviceName: 'api', - qs: { - foreign_ids: ids.map(function (id) { - return "".concat(collection, ":").concat(id); - }).join(',') - }, - signature: this.client.getCollectionsToken() - }); + utils.forEach(mergeDeepPropertiesKeys, function mergeDeepProperties(prop) { + if (utils.isObject(config2[prop])) { + config[prop] = utils.deepMerge(config1[prop], config2[prop]); + } else if (typeof config2[prop] !== 'undefined') { + config[prop] = config2[prop]; + } else if (utils.isObject(config1[prop])) { + config[prop] = utils.deepMerge(config1[prop]); + } else if (typeof config1[prop] !== 'undefined') { + config[prop] = config1[prop]; } - }, { - key: "deleteMany", - value: function deleteMany(collection, ids) { - /** - * Remove all objects by id from the collection. - * - * @method delete - * @memberof Collections.prototype - * @param {object|array} ids - A single json object or an array of objects - * @return {Promise} Promise object. - */ - if (!this.client.usingApiSecret) { - throw new _errors__WEBPACK_IMPORTED_MODULE_5__[/* default */ "a"].SiteError('This method can only be used server-side using your API Secret'); - } + }); - if (!Array.isArray(ids)) ids = [ids]; - var params = { - collection_name: collection, - ids: ids.map(function (id) { - return id.toString(); - }).join(',') - }; - return this.client.delete({ - url: 'collections/', - serviceName: 'api', - qs: params, - signature: this.client.getCollectionsToken() - }); + utils.forEach(defaultToConfig2Keys, function defaultToConfig2(prop) { + if (typeof config2[prop] !== 'undefined') { + config[prop] = config2[prop]; + } else if (typeof config1[prop] !== 'undefined') { + config[prop] = config1[prop]; } - }]); + }); + + var axiosKeys = valueFromConfig2Keys + .concat(mergeDeepPropertiesKeys) + .concat(defaultToConfig2Keys); + + var otherKeys = Object + .keys(config2) + .filter(function filterAxiosKeys(key) { + return axiosKeys.indexOf(key) === -1; + }); - return Collections; -}(); + utils.forEach(otherKeys, function otherKeysDefaultToConfig2(prop) { + if (typeof config2[prop] !== 'undefined') { + config[prop] = config2[prop]; + } else if (typeof config1[prop] !== 'undefined') { + config[prop] = config1[prop]; + } + }); + return config; +}; /***/ }), -/* 57 */ +/* 48 */ /***/ (function(module, exports, __webpack_require__) { -var _typeof = __webpack_require__(14); - -var assertThisInitialized = __webpack_require__(31); +"use strict"; -function _possibleConstructorReturn(self, call) { - if (call && (_typeof(call) === "object" || typeof call === "function")) { - return call; - } - return assertThisInitialized(self); +/** + * A `Cancel` is an object that is thrown when an operation is canceled. + * + * @class + * @param {string=} message The message. + */ +function Cancel(message) { + this.message = message; } -module.exports = _possibleConstructorReturn; +Cancel.prototype.toString = function toString() { + return 'Cancel' + (this.message ? ': ' + this.message : ''); +}; + +Cancel.prototype.__CANCEL__ = true; + +module.exports = Cancel; + /***/ }), -/* 58 */ -/***/ (function(module, exports, __webpack_require__) { +/* 49 */ +/***/ (function(module, exports) { -var getPrototypeOf = __webpack_require__(25); +module.exports = { + VERSION: '1.3.0', -var setPrototypeOf = __webpack_require__(30); + BAYEUX_VERSION: '1.0', + ID_LENGTH: 160, + JSONP_CALLBACK: 'jsonpcallback', + CONNECTION_TYPES: ['long-polling', 'cross-origin-long-polling', 'callback-polling', 'websocket', 'eventsource', 'in-process'], -var isNativeFunction = __webpack_require__(106); + MANDATORY_CONNECTION_TYPES: ['long-polling', 'callback-polling', 'in-process'] +}; -var construct = __webpack_require__(107); -function _wrapNativeSuper(Class) { - var _cache = typeof Map === "function" ? new Map() : undefined; +/***/ }), +/* 50 */ +/***/ (function(module, exports, __webpack_require__) { - module.exports = _wrapNativeSuper = function _wrapNativeSuper(Class) { - if (Class === null || !isNativeFunction(Class)) return Class; +"use strict"; - if (typeof Class !== "function") { - throw new TypeError("Super expression must either be null or a function"); - } - if (typeof _cache !== "undefined") { - if (_cache.has(Class)) return _cache.get(Class); +// rawAsap provides everything we need except exception management. +var rawAsap = __webpack_require__(89); +// RawTasks are recycled to reduce GC churn. +var freeTasks = []; +// We queue errors to ensure they are thrown in right order (FIFO). +// Array-as-queue is good enough here, since we are just dealing with exceptions. +var pendingErrors = []; +var requestErrorThrow = rawAsap.makeRequestCallFromTimer(throwFirstError); - _cache.set(Class, Wrapper); +function throwFirstError() { + if (pendingErrors.length) { + throw pendingErrors.shift(); } +} - function Wrapper() { - return construct(Class, arguments, getPrototypeOf(this).constructor); +/** + * Calls a task as soon as possible after returning, in its own event, with priority + * over other events like animation, reflow, and repaint. An error thrown from an + * event will not interrupt, nor even substantially slow down the processing of + * other events, but will be rather postponed to a lower priority event. + * @param {{call}} task A callable object, typically a function that takes no + * arguments. + */ +module.exports = asap; +function asap(task) { + var rawTask; + if (freeTasks.length) { + rawTask = freeTasks.pop(); + } else { + rawTask = new RawTask(); } + rawTask.task = task; + rawAsap(rawTask); +} - Wrapper.prototype = Object.create(Class.prototype, { - constructor: { - value: Wrapper, - enumerable: false, - writable: true, - configurable: true - } - }); - return setPrototypeOf(Wrapper, Class); - }; - - return _wrapNativeSuper(Class); +// We wrap tasks with recyclable task objects. A task object implements +// `call`, just like a function. +function RawTask() { + this.task = null; } -module.exports = _wrapNativeSuper; +// The sole purpose of wrapping the task is to catch the exception and recycle +// the task object after its single use. +RawTask.prototype.call = function () { + try { + this.task.call(); + } catch (error) { + if (asap.onerror) { + // This hook exists purely for testing purposes. + // Its name will be periodically randomized to break any code that + // depends on its existence. + asap.onerror(error); + } else { + // In a web browser, exceptions are not fatal. However, to avoid + // slowing down the queue of pending tasks, we rethrow the error in a + // lower priority turn. + pendingErrors.push(error); + requestErrorThrow(); + } + } finally { + this.task = null; + freeTasks[freeTasks.length] = this; + } +}; + /***/ }), -/* 59 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { +/* 51 */ +/***/ (function(module, exports, __webpack_require__) { "use strict"; -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return StreamFeed; }); -/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(4); -/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2); -/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_1__); -/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(3); -/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_2__); -/* harmony import */ var _user__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(20); -/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1); -/* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(7); +var Class = __webpack_require__(10), + assign = __webpack_require__(8), + Publisher = __webpack_require__(35), + Grammar = __webpack_require__(52); +var Channel = Class({ + initialize: function(name) { + this.id = this.name = name; + }, -function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } + push: function(message) { + this.trigger('message', message); + }, -function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_0___default()(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } + isUnused: function() { + return this.countListeners('message') === 0; + } +}); +assign(Channel.prototype, Publisher); +assign(Channel, { + HANDSHAKE: '/meta/handshake', + CONNECT: '/meta/connect', + SUBSCRIBE: '/meta/subscribe', + UNSUBSCRIBE: '/meta/unsubscribe', + DISCONNECT: '/meta/disconnect', + META: 'meta', + SERVICE: 'service', -/** - * Manage api calls for specific feeds - * The feed object contains convenience functions such add activity, remove activity etc - * @class StreamFeed - */ + expand: function(name) { + var segments = this.parse(name), + channels = ['/**', name]; -var StreamFeed = /*#__PURE__*/function () { - function StreamFeed(client, feedSlug, userId, token) { - _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_1___default()(this, StreamFeed); + var copy = segments.slice(); + copy[copy.length - 1] = '*'; + channels.push(this.unparse(copy)); - /** - * Initialize a feed object - * @method constructor - * @memberof StreamFeed.prototype - * @param {StreamClient} client - The stream client this feed is constructed from - * @param {string} feedSlug - The feed slug - * @param {string} userId - The user id - * @param {string} [token] - The authentication token - */ - if (!feedSlug || !userId) { - throw new _errors__WEBPACK_IMPORTED_MODULE_4__[/* default */ "a"].FeedError('Please provide a feed slug and user id, ie client.feed("user", "1")'); + for (var i = 1, n = segments.length; i < n; i++) { + copy = segments.slice(0, i); + copy.push('**'); + channels.push(this.unparse(copy)); } - if (feedSlug.indexOf(':') !== -1) { - throw new _errors__WEBPACK_IMPORTED_MODULE_4__[/* default */ "a"].FeedError('Please initialize the feed using client.feed("user", "1") not client.feed("user:1")'); - } + return channels; + }, + + isValid: function(name) { + return Grammar.CHANNEL_NAME.test(name) || + Grammar.CHANNEL_PATTERN.test(name); + }, + + parse: function(name) { + if (!this.isValid(name)) return null; + return name.split('/').slice(1); + }, + + unparse: function(segments) { + return '/' + segments.join('/'); + }, + + isMeta: function(name) { + var segments = this.parse(name); + return segments ? (segments[0] === this.META) : null; + }, + + isService: function(name) { + var segments = this.parse(name); + return segments ? (segments[0] === this.SERVICE) : null; + }, + + isSubscribable: function(name) { + if (!this.isValid(name)) return null; + return !this.isMeta(name) && !this.isService(name); + }, + + Set: Class({ + initialize: function() { + this._channels = {}; + }, + + getKeys: function() { + var keys = []; + for (var key in this._channels) keys.push(key); + return keys; + }, + + remove: function(name) { + delete this._channels[name]; + }, + + hasSubscription: function(name) { + return this._channels.hasOwnProperty(name); + }, + + subscribe: function(names, subscription) { + var name; + for (var i = 0, n = names.length; i < n; i++) { + name = names[i]; + var channel = this._channels[name] = this._channels[name] || new Channel(name); + channel.bind('message', subscription); + } + }, + + unsubscribe: function(name, subscription) { + var channel = this._channels[name]; + if (!channel) return false; + channel.unbind('message', subscription); - _utils__WEBPACK_IMPORTED_MODULE_5__[/* default */ "a"].validateFeedSlug(feedSlug); - _utils__WEBPACK_IMPORTED_MODULE_5__[/* default */ "a"].validateUserId(userId); // raise an error if there is no token + if (channel.isUnused()) { + this.remove(name); + return true; + } else { + return false; + } + }, - if (!token) { - throw new _errors__WEBPACK_IMPORTED_MODULE_4__[/* default */ "a"].FeedError('Missing token, in client side mode please provide a feed secret'); - } + distributeMessage: function(message) { + var channels = Channel.expand(message.channel); - this.client = client; - this.slug = feedSlug; - this.userId = userId; - this.id = "".concat(this.slug, ":").concat(this.userId); - this.token = token; - this.feedUrl = this.id.replace(':', '/'); - this.feedTogether = this.id.replace(':', ''); - this.signature = "".concat(this.feedTogether, " ").concat(this.token); // faye setup + for (var i = 0, n = channels.length; i < n; i++) { + var channel = this._channels[channels[i]]; + if (channel) channel.trigger('message', message); + } + } + }) +}); - this.notificationChannel = "site-".concat(this.client.appId, "-feed-").concat(this.feedTogether); - this.enrichByDefault = false; - } +module.exports = Channel; - _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_2___default()(StreamFeed, [{ - key: "addActivity", - value: function addActivity(activity) { - /** - * Adds the given activity to the feed - * @method addActivity - * @memberof StreamFeed.prototype - * @param {object} activity - The activity to add - * @return {Promise} Promise object - */ - activity = _utils__WEBPACK_IMPORTED_MODULE_5__[/* default */ "a"].replaceStreamObjects(activity); - if (!activity.actor && this.client.currentUser) { - activity.actor = this.client.currentUser.ref(); - } +/***/ }), +/* 52 */ +/***/ (function(module, exports, __webpack_require__) { - return this.client.post({ - url: "feed/".concat(this.feedUrl, "/"), - body: activity, - signature: this.signature - }); - } - }, { - key: "removeActivity", - value: function removeActivity(activityId) { - /** - * Removes the activity by activityId - * @method removeActivity - * @memberof StreamFeed.prototype - * @param {string} activityId Identifier of activity to remove - * @return {Promise} Promise object - * @example - * feed.removeActivity(activityId); - * @example - * feed.removeActivity({'foreignId': foreignId}); - */ - return this.client.delete({ - url: "feed/".concat(this.feedUrl, "/").concat(activityId.foreignId || activityId, "/"), - qs: activityId.foreignId ? { - foreign_id: '1' - } : {}, - signature: this.signature - }); - } - }, { - key: "addActivities", - value: function addActivities(activities) { - /** - * Adds the given activities to the feed - * @method addActivities - * @memberof StreamFeed.prototype - * @param {Array} activities Array of activities to add - * @return {Promise} XHR request object - */ - return this.client.post({ - url: "feed/".concat(this.feedUrl, "/"), - body: { - activities: _utils__WEBPACK_IMPORTED_MODULE_5__[/* default */ "a"].replaceStreamObjects(activities) - }, - signature: this.signature - }); - } - }, { - key: "follow", - value: function follow(targetSlug, targetUserId) { - var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; +"use strict"; - /** - * Follows the given target feed - * @method follow - * @memberof StreamFeed.prototype - * @param {string} targetSlug Slug of the target feed - * @param {string} targetUserId User identifier of the target feed - * @param {object} options Additional options - * @param {number} options.activityCopyLimit Limit the amount of activities copied over on follow - * @return {Promise} Promise object - * @example feed.follow('user', '1'); - * @example feed.follow('user', '1'); - * @example feed.follow('user', '1', options); - */ - if (targetUserId instanceof _user__WEBPACK_IMPORTED_MODULE_3__[/* default */ "a"]) { - targetUserId = targetUserId.id; - } - _utils__WEBPACK_IMPORTED_MODULE_5__[/* default */ "a"].validateFeedSlug(targetSlug); - _utils__WEBPACK_IMPORTED_MODULE_5__[/* default */ "a"].validateUserId(targetUserId); - var body = { - target: "".concat(targetSlug, ":").concat(targetUserId) - }; - if (typeof options.limit === 'number') body.activity_copy_limit = options.limit; - return this.client.post({ - url: "feed/".concat(this.feedUrl, "/following/"), - body: body, - signature: this.signature - }); - } - }, { - key: "unfollow", - value: function unfollow(targetSlug, targetUserId) { - var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; +module.exports = { + CHANNEL_NAME: /^\/(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)))+(\/(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)))+)*$/, + CHANNEL_PATTERN: /^(\/(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)))+)*\/\*{1,2}$/, + ERROR: /^([0-9][0-9][0-9]:(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)| |\/|\*|\.))*(,(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)| |\/|\*|\.))*)*:(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)| |\/|\*|\.))*|[0-9][0-9][0-9]::(((([a-z]|[A-Z])|[0-9])|(\-|\_|\!|\~|\(|\)|\$|\@)| |\/|\*|\.))*)$/, + VERSION: /^([0-9])+(\.(([a-z]|[A-Z])|[0-9])(((([a-z]|[A-Z])|[0-9])|\-|\_))*)*$/ +}; - /** - * Unfollow the given feed - * @method unfollow - * @memberof StreamFeed.prototype - * @param {string} targetSlug Slug of the target feed - * @param {string} targetUserId [description] - * @param {object} options - * @param {boolean} options.keepHistory when provided the activities from target - * feed will not be kept in the feed - * @return {object} XHR request object - * @example feed.unfollow('user', '2'); - */ - var qs = {}; - if (typeof options.keepHistory === 'boolean' && options.keepHistory) qs.keep_history = '1'; - _utils__WEBPACK_IMPORTED_MODULE_5__[/* default */ "a"].validateFeedSlug(targetSlug); - _utils__WEBPACK_IMPORTED_MODULE_5__[/* default */ "a"].validateUserId(targetUserId); - var targetFeedId = "".concat(targetSlug, ":").concat(targetUserId); - return this.client.delete({ - url: "feed/".concat(this.feedUrl, "/following/").concat(targetFeedId, "/"), - qs: qs, - signature: this.signature - }); - } - }, { - key: "following", - value: function following() { - var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - /** - * List which feeds this feed is following - * @method following - * @memberof StreamFeed.prototype - * @param {object} options Additional options - * @param {string} options.filter Filter to apply on search operation - * @return {Promise} Promise object - * @example feed.following({limit:10, filter: ['user:1', 'user:2']}); - */ - if (options.filter) { - options.filter = options.filter.join(','); - } +/***/ }), +/* 53 */ +/***/ (function(module, exports, __webpack_require__) { - return this.client.get({ - url: "feed/".concat(this.feedUrl, "/following/"), - qs: options, - signature: this.signature - }); - } - }, { - key: "followers", - value: function followers() { - var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; +"use strict"; - /** - * List the followers of this feed - * @method followers - * @memberof StreamFeed.prototype - * @param {object} options Additional options - * @param {string} options.filter Filter to apply on search operation - * @return {Promise} Promise object - * @example - * feed.followers({limit:10, filter: ['user:1', 'user:2']}); - */ - if (options.filter) { - options.filter = options.filter.join(','); - } - return this.client.get({ - url: "feed/".concat(this.feedUrl, "/followers/"), - qs: options, - signature: this.signature - }); - } - }, { - key: "get", - value: function get() { - var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; +module.exports = {}; - /** - * Reads the feed - * @method get - * @memberof StreamFeed.prototype - * @param {object} options Additional options - * @return {Promise} Promise object - * @example feed.get({limit: 10, id_lte: 'activity-id'}) - * @example feed.get({limit: 10, mark_seen: true}) - */ - if (options.mark_read && options.mark_read.join) { - options.mark_read = options.mark_read.join(','); - } - if (options.mark_seen && options.mark_seen.join) { - options.mark_seen = options.mark_seen.join(','); - } +/***/ }), +/* 54 */ +/***/ (function(module, exports, __webpack_require__) { - this.client.replaceReactionOptions(options); - var path = this.client.shouldUseEnrichEndpoint(options) ? 'enrich/feed/' : 'feed/'; - return this.client.get({ - url: "".concat(path).concat(this.feedUrl, "/"), - qs: options, - signature: this.signature - }); - } - }, { - key: "getActivityDetail", - value: function getActivityDetail(activityId, options) { - /** - * Retrieves one activity from a feed and adds enrichment - * @method getActivityDetail - * @memberof StreamFeed.prototype - * @param {string} activityId Identifier of activity to retrieve - * @param {object} options Additional options - * @return {Promise} Promise object - * @example feed.getActivityDetail(activityId) - * @example feed.getActivityDetail(activityId, {withRecentReactions: true}) - * @example feed.getActivityDetail(activityId, {withReactionCounts: true}) - * @example feed.getActivityDetail(activityId, {withOwnReactions: true, withReactionCounts: true}) - */ - return this.get(_objectSpread({ - id_lte: activityId, - id_gte: activityId, - limit: 1 - }, options || {})); - } - }, { - key: "getFayeClient", - value: function getFayeClient() { - /** - * Returns the current faye client object - * @method getFayeClient - * @memberof StreamFeed.prototype - * @access private - * @return {object} Faye client - */ - return this.client.getFayeClient(); +"use strict"; + + +var Class = __webpack_require__(10); + +module.exports = Class({ + initialize: function() { + this._index = {}; + }, + + add: function(item) { + var key = (item.id !== undefined) ? item.id : item; + if (this._index.hasOwnProperty(key)) return false; + this._index[key] = item; + return true; + }, + + forEach: function(block, context) { + for (var key in this._index) { + if (this._index.hasOwnProperty(key)) + block.call(context, this._index[key]); } - }, { - key: "subscribe", - value: function subscribe(callback) { - /** - * Subscribes to any changes in the feed, return a promise - * @method subscribe - * @memberof StreamFeed.prototype - * @param {function} callback Callback to call on completion - * @return {Promise} Promise object - * @example - * feed.subscribe(callback).then(function(){ - * console.log('we are now listening to changes'); - * }); - */ - if (!this.client.appId) { - throw new _errors__WEBPACK_IMPORTED_MODULE_4__[/* default */ "a"].SiteError('Missing app id, which is needed to subscribe, use var client = stream.connect(key, secret, appId);'); - } + }, - var subscription = this.getFayeClient().subscribe("/".concat(this.notificationChannel), callback); - this.client.subscriptions["/".concat(this.notificationChannel)] = { - token: this.token, - userId: this.notificationChannel, - fayeSubscription: subscription - }; - return subscription; + isEmpty: function() { + for (var key in this._index) { + if (this._index.hasOwnProperty(key)) return false; } - }, { - key: "unsubscribe", - value: function unsubscribe() { - /** - * Cancel updates created via feed.subscribe() - * @return void - */ - var streamSubscription = this.client.subscriptions["/".concat(this.notificationChannel)]; + return true; + }, - if (streamSubscription) { - delete this.client.subscriptions["/".concat(this.notificationChannel)]; - streamSubscription.fayeSubscription.cancel(); - } + member: function(item) { + for (var key in this._index) { + if (this._index[key] === item) return true; } - }, { - key: "updateActivityToTargets", - value: function updateActivityToTargets(foreignId, time, newTargets, addedTargets, removedTargets) { - /** - * Updates an activity's "to" fields - * @since 3.10.0 - * @param {string} foreignId The foreign_id of the activity to update - * @param {string} time The time of the activity to update - * @param {array} newTargets Set the new "to" targets for the activity - will remove old targets - * @param {array} added_targets Add these new targets to the activity - * @param {array} removedTargets Remove these targets from the activity - */ - if (!foreignId) { - throw new Error('Missing `foreign_id` parameter!'); - } else if (!time) { - throw new Error('Missing `time` parameter!'); - } + return false; + }, - if (!newTargets && !addedTargets && !removedTargets) { - throw new Error('Requires you to provide at least one parameter for `newTargets`, `addedTargets`, or `removedTargets` - example: `updateActivityToTargets("foreignID:1234", new Date(), [newTargets...], [addedTargets...], [removedTargets...])`'); - } + remove: function(item) { + var key = (item.id !== undefined) ? item.id : item; + var removed = this._index[key]; + delete this._index[key]; + return removed; + }, - if (newTargets) { - if (addedTargets || removedTargets) { - throw new Error("Can't include add_targets or removedTargets if you're also including newTargets"); - } - } + toArray: function() { + var array = []; + this.forEach(function(item) { array.push(item) }); + return array; + } +}); - if (addedTargets && removedTargets) { - // brute force - iterate through added, check to see if removed contains that element - addedTargets.forEach(function (addedTarget) { - if (removedTargets.includes(addedTarget)) { - throw new Error("Can't have the same feed ID in addedTargets and removedTargets."); - } - }); - } - var body = { - foreign_id: foreignId, - time: time - }; - if (newTargets) body.new_targets = newTargets; - if (addedTargets) body.added_targets = addedTargets; - if (removedTargets) body.removed_targets = removedTargets; - return this.client.post({ - url: "feed_targets/".concat(this.feedUrl, "/activity_to_targets/"), - signature: this.signature, - body: body - }); +/***/ }), +/* 55 */ +/***/ (function(module, exports, __webpack_require__) { + +"use strict"; +/* WEBPACK VAR INJECTION */(function(global) { + +var Class = __webpack_require__(10), + URI = __webpack_require__(14), + browser = __webpack_require__(34), + assign = __webpack_require__(8), + toJSON = __webpack_require__(19), + Transport = __webpack_require__(15); + +var XHR = assign(Class(Transport, { + encode: function(messages) { + return toJSON(messages); + }, + + request: function(messages) { + var href = this.endpoint.href, + self = this, + xhr; + + // Prefer XMLHttpRequest over ActiveXObject if they both exist + if (global.XMLHttpRequest) { + xhr = new XMLHttpRequest(); + } else if (global.ActiveXObject) { + xhr = new ActiveXObject('Microsoft.XMLHTTP'); + } else { + return this._handleError(messages); } - }]); - return StreamFeed; -}(); + xhr.open('POST', href, true); + xhr.setRequestHeader('Content-Type', 'application/json'); + xhr.setRequestHeader('Pragma', 'no-cache'); + xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); + var headers = this._dispatcher.headers; + for (var key in headers) { + if (!headers.hasOwnProperty(key)) continue; + xhr.setRequestHeader(key, headers[key]); + } + var abort = function() { xhr.abort() }; + if (global.onbeforeunload !== undefined) + browser.Event.on(global, 'beforeunload', abort); -/***/ }), -/* 60 */ -/***/ (function(module, exports, __webpack_require__) { + xhr.onreadystatechange = function() { + if (!xhr || xhr.readyState !== 4) return; -var arrayWithHoles = __webpack_require__(109); + var replies = null, + status = xhr.status, + text = xhr.responseText, + successful = (status >= 200 && status < 300) || status === 304 || status === 1223; -var iterableToArrayLimit = __webpack_require__(110); + if (global.onbeforeunload !== undefined) + browser.Event.detach(global, 'beforeunload', abort); -var unsupportedIterableToArray = __webpack_require__(111); + xhr.onreadystatechange = function() {}; + xhr = null; -var nonIterableRest = __webpack_require__(113); + if (!successful) return self._handleError(messages); -function _slicedToArray(arr, i) { - return arrayWithHoles(arr) || iterableToArrayLimit(arr, i) || unsupportedIterableToArray(arr, i) || nonIterableRest(); -} + try { + replies = JSON.parse(text); + } catch (error) {} -module.exports = _slicedToArray; + if (replies) + self._receive(replies); + else + self._handleError(messages); + }; -/***/ }), -/* 61 */ -/***/ (function(module, exports) { + xhr.send(this.encode(messages)); + return xhr; + } +}), { + isUsable: function(dispatcher, endpoint, callback, context) { + var usable = (navigator.product === 'ReactNative') + || URI.isSameOrigin(endpoint); -/* eslint-env browser */ -module.exports = typeof self == 'object' ? self.FormData : window.FormData; + callback.call(context, usable); + } +}); + +module.exports = XHR; +/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(11))) /***/ }), -/* 62 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { +/* 56 */ +/***/ (function(module, exports, __webpack_require__) { "use strict"; -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return StreamFileStore; }); -/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2); -/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3); -/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1__); +var assign = __webpack_require__(8); -var StreamFileStore = /*#__PURE__*/function () { - function StreamFileStore(client, token) { - _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_0___default()(this, StreamFileStore); +var Scheduler = function(message, options) { + this.message = message; + this.options = options; + this.attempts = 0; +}; - this.client = client; - this.token = token; - } // React Native does not auto-detect MIME type, you need to pass that via contentType - // param. If you don't then Android will refuse to perform the upload +assign(Scheduler.prototype, { + getTimeout: function() { + return this.options.timeout; + }, + getInterval: function() { + return this.options.interval; + }, - _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_1___default()(StreamFileStore, [{ - key: "upload", - value: function upload(uri, name, contentType, onUploadProgress) { - /** - * upload a File instance or a readable stream of data - * @param {File|Buffer|string} uri - File object or Buffer or URI - * @param {string} [name] - file name - * @param {string} [contentType] - mime-type - * @param {function} [onUploadProgress] - browser only, Function that is called with upload progress - * @return {Promise} - */ - return this.client.upload('files/', uri, name, contentType, onUploadProgress); - } - }, { - key: "delete", - value: function _delete(uri) { - return this.client.delete({ - url: "files/", - qs: { - url: uri - }, - signature: this.token - }); - } - }]); + isDeliverable: function() { + var attempts = this.options.attempts, + made = this.attempts, + deadline = this.options.deadline, + now = new Date().getTime(); - return StreamFileStore; -}(); + if (attempts !== undefined && made >= attempts) + return false; + if (deadline !== undefined && now > deadline) + return false; + return true; + }, -/***/ }), -/* 63 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { + send: function() { + this.attempts += 1; + }, -"use strict"; -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return StreamImageStore; }); -/* harmony import */ var _babel_runtime_helpers_extends__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(64); -/* harmony import */ var _babel_runtime_helpers_extends__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_extends__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2); -/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_1__); -/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(3); -/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_2__); + succeed: function() {}, + fail: function() {}, + abort: function() {} +}); +module.exports = Scheduler; -var StreamImageStore = /*#__PURE__*/function () { - function StreamImageStore(client, token) { - _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_1___default()(this, StreamImageStore); - this.client = client; - this.token = token; - } // React Native does not auto-detect MIME type, you need to pass that via contentType - // param. If you don't then Android will refuse to perform the upload +/***/ }), +/* 57 */ +/***/ (function(module, exports, __webpack_require__) { +module.exports = __webpack_require__(72); - _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_2___default()(StreamImageStore, [{ - key: "upload", - value: function upload(uri, name, contentType, onUploadProgress) { - /** - * upload an Image File instance or a readable stream of data - * @param {File|Buffer|string} uri - File object or Buffer or URI - * @param {string} [name] - file name - * @param {string} [contentType] - mime-type - * @param {function} [onUploadProgress] - browser only, Function that is called with upload progress - * @return {Promise} - */ - return this.client.upload('images/', uri, name, contentType, onUploadProgress); - } - }, { - key: "delete", - value: function _delete(uri) { - return this.client.delete({ - url: "images/", - qs: { - url: uri - }, - signature: this.token - }); - } - }, { - key: "process", - value: function process(uri, options) { - var params = _babel_runtime_helpers_extends__WEBPACK_IMPORTED_MODULE_0___default()(options, { - url: uri - }); +/***/ }), +/* 58 */ +/***/ (function(module, exports) { - if (Array.isArray(params.crop)) { - params.crop = params.crop.join(','); - } +/* (ignored) */ - return this.client.get({ - url: "images/", - qs: params, - signature: this.token - }); - } - }, { - key: "thumbnail", - value: function thumbnail(uri, w, h) { - var _ref = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : { - crop: 'center', - resize: 'clip' - }, - crop = _ref.crop, - resize = _ref.resize; +/***/ }), +/* 59 */ +/***/ (function(module, exports) { - return this.process(uri, { - w: w, - h: h, - crop: crop, - resize: resize - }); - } - }]); +/* (ignored) */ - return StreamImageStore; -}(); +/***/ }), +/* 60 */ +/***/ (function(module, exports, __webpack_require__) { +"use strict"; -/***/ }), -/* 64 */ -/***/ (function(module, exports) { +var constants = __webpack_require__(49), + Logging = __webpack_require__(18); -function _extends() { - module.exports = _extends = Object.assign || function (target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i]; +var Faye = { + VERSION: constants.VERSION, - for (var key in source) { - if (Object.prototype.hasOwnProperty.call(source, key)) { - target[key] = source[key]; - } - } - } + Client: __webpack_require__(88), + Scheduler: __webpack_require__(56) +}; - return target; - }; +Logging.wrapper = Faye; - return _extends.apply(this, arguments); -} +module.exports = Faye; -module.exports = _extends; /***/ }), -/* 65 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { +/* 61 */ +/***/ (function(module, exports, __webpack_require__) { "use strict"; -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return StreamReaction; }); -/* harmony import */ var _babel_runtime_helpers_objectWithoutProperties__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(19); -/* harmony import */ var _babel_runtime_helpers_objectWithoutProperties__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_objectWithoutProperties__WEBPACK_IMPORTED_MODULE_0__); -/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2); -/* harmony import */ var _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_1__); -/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(3); -/* harmony import */ var _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_2__); -/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4); -/* harmony import */ var _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_3__); -/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1); +var base64_url_decode = __webpack_require__(104); +function InvalidTokenError(message) { + this.message = message; +} +InvalidTokenError.prototype = new Error(); +InvalidTokenError.prototype.name = 'InvalidTokenError'; +module.exports = function (token,options) { + if (typeof token !== 'string') { + throw new InvalidTokenError('Invalid token specified'); + } -var StreamReaction = /*#__PURE__*/function () { - function StreamReaction(client, token) { - _babel_runtime_helpers_classCallCheck__WEBPACK_IMPORTED_MODULE_1___default()(this, StreamReaction); + options = options || {}; + var pos = options.header === true ? 0 : 1; + try { + return JSON.parse(base64_url_decode(token.split('.')[pos])); + } catch (e) { + throw new InvalidTokenError('Invalid token specified: ' + e.message); + } +}; - _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_3___default()(this, "buildURL", function () { - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } +module.exports.InvalidTokenError = InvalidTokenError; - return "".concat(['reaction'].concat(args).join('/'), "/"); - }); - _babel_runtime_helpers_defineProperty__WEBPACK_IMPORTED_MODULE_3___default()(this, "_convertTargetFeeds", function () { - var targetFeeds = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; - return targetFeeds.map(function (elem) { - return typeof elem === 'string' ? elem : elem.id; - }); - }); +/***/ }), +/* 62 */ +/***/ (function(module, exports, __webpack_require__) { - /** - * Initialize a reaction object - * @method constructor - * @memberof StreamReaction.prototype - * @param {StreamClient} client Stream client this feed is constructed from - * @param {string} token JWT token - * @example new StreamReaction(client, "eyJhbGciOiJIUzI1...") - */ - this.client = client; - this.token = token; - this.signature = token; +var _typeof = __webpack_require__(21); + +var assertThisInitialized = __webpack_require__(16); + +function _possibleConstructorReturn(self, call) { + if (call && (_typeof(call) === "object" || typeof call === "function")) { + return call; } - _babel_runtime_helpers_createClass__WEBPACK_IMPORTED_MODULE_2___default()(StreamReaction, [{ - key: "all", - value: function all() { - var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + return assertThisInitialized(self); +} - /** - * get all reactions - * @method all - * @memberof StreamReaction.prototype - * @param {object} options {limit:} - * @return {Promise} Promise object - * @example reactions.all() - * @example reactions.all({limit:100}) - */ - return this.client.get({ - url: this.buildURL(), - signature: this.signature, - qs: options - }); - } - }, { - key: "add", - value: function add(kind, activity) { - var data = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; +module.exports = _possibleConstructorReturn; - var _ref = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}, - id = _ref.id, - _ref$targetFeeds = _ref.targetFeeds, - targetFeeds = _ref$targetFeeds === void 0 ? [] : _ref$targetFeeds, - userId = _ref.userId, - targetFeedsExtraData = _ref.targetFeedsExtraData; +/***/ }), +/* 63 */ +/***/ (function(module, exports, __webpack_require__) { - /** - * add reaction - * @method add - * @memberof StreamReaction.prototype - * @param {string} kind kind of reaction - * @param {string} activity Activity or an ActivityID - * @param {object} data data related to reaction - * @param {array} targetFeeds an array of feeds to which to send an activity with the reaction - * @return {Promise} Promise object - * @example reactions.add("like", "0c7db91c-67f9-11e8-bcd9-fe00a9219401") - * @example reactions.add("comment", "0c7db91c-67f9-11e8-bcd9-fe00a9219401", {"text": "love it!"},) - */ - var body = { - id: id, - activity_id: activity instanceof Object ? activity.id : activity, - kind: kind, - data: data, - target_feeds: this._convertTargetFeeds(targetFeeds), - user_id: userId - }; +var getPrototypeOf = __webpack_require__(32); - if (targetFeedsExtraData != null) { - body.target_feeds_extra_data = targetFeedsExtraData; - } +var setPrototypeOf = __webpack_require__(37); - return this.client.post({ - url: this.buildURL(), - body: body, - signature: this.signature - }); - } - }, { - key: "addChild", - value: function addChild(kind, reaction) { - var data = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; +var isNativeFunction = __webpack_require__(106); + +var construct = __webpack_require__(107); - var _ref2 = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}, - _ref2$targetFeeds = _ref2.targetFeeds, - targetFeeds = _ref2$targetFeeds === void 0 ? [] : _ref2$targetFeeds, - userId = _ref2.userId, - targetFeedsExtraData = _ref2.targetFeedsExtraData; +function _wrapNativeSuper(Class) { + var _cache = typeof Map === "function" ? new Map() : undefined; - /** - * add reaction - * @method add - * @memberof StreamReaction.prototype - * @param {string} kind kind of reaction - * @param {string} reaction Reaction or a ReactionID - * @param {object} data data related to reaction - * @param {array} targetFeeds an array of feeds to which to send an activity with the reaction - * @return {Promise} Promise object - * @example reactions.add("like", "0c7db91c-67f9-11e8-bcd9-fe00a9219401") - * @example reactions.add("comment", "0c7db91c-67f9-11e8-bcd9-fe00a9219401", {"text": "love it!"},) - */ - var body = { - parent: reaction instanceof Object ? reaction.id : reaction, - kind: kind, - data: data, - target_feeds: this._convertTargetFeeds(targetFeeds), - user_id: userId - }; + module.exports = _wrapNativeSuper = function _wrapNativeSuper(Class) { + if (Class === null || !isNativeFunction(Class)) return Class; - if (targetFeedsExtraData != null) { - body.target_feeds_extra_data = targetFeedsExtraData; - } + if (typeof Class !== "function") { + throw new TypeError("Super expression must either be null or a function"); + } - return this.client.post({ - url: this.buildURL(), - body: body, - signature: this.signature - }); + if (typeof _cache !== "undefined") { + if (_cache.has(Class)) return _cache.get(Class); + + _cache.set(Class, Wrapper); } - }, { - key: "get", - value: function get(id) { - /** - * get reaction - * @method add - * @memberof StreamReaction.prototype - * @param {string} id Reaction Id - * @return {Promise} Promise object - * @example reactions.get("67b3e3b5-b201-4697-96ac-482eb14f88ec") - */ - return this.client.get({ - url: this.buildURL(id), - signature: this.signature - }); + + function Wrapper() { + return construct(Class, arguments, getPrototypeOf(this).constructor); } - }, { - key: "filter", - value: function filter(conditions) { - /** - * retrieve reactions by activity_id, user_id or reaction_id (to paginate children reactions), pagination can be done using id_lt, id_lte, id_gt and id_gte parameters - * id_lt and id_lte return reactions order by creation descending starting from the reaction with the ID provided, when id_lte is used - * the reaction with ID equal to the value provided is included. - * id_gt and id_gte return reactions order by creation ascending (oldest to newest) starting from the reaction with the ID provided, when id_gte is used - * the reaction with ID equal to the value provided is included. - * results are limited to 25 at most and are ordered newest to oldest by default. - * @method lookup - * @memberof StreamReaction.prototype - * @param {object} conditions Reaction Id {activity_id|user_id|foreign_id:string, kind:string, next:string, previous:string, limit:integer} - * @return {Promise} Promise object - * @example reactions.lookup({activity_id: "0c7db91c-67f9-11e8-bcd9-fe00a9219401", kind:"like"}) - * @example reactions.lookup({user_id: "john", kinds:"like"}) - */ - var userId = conditions.user_id, - activityId = conditions.activity_id, - reactionId = conditions.reaction_id, - qs = _babel_runtime_helpers_objectWithoutProperties__WEBPACK_IMPORTED_MODULE_0___default()(conditions, ["user_id", "activity_id", "reaction_id"]); - if (!qs.limit) { - qs.limit = 10; + Wrapper.prototype = Object.create(Class.prototype, { + constructor: { + value: Wrapper, + enumerable: false, + writable: true, + configurable: true } + }); + return setPrototypeOf(Wrapper, Class); + }; - if ((userId ? 1 : 0) + (activityId ? 1 : 0) + (reactionId ? 1 : 0) !== 1) { - throw new _errors__WEBPACK_IMPORTED_MODULE_4__[/* default */ "a"].SiteError('Must provide exactly one value for one of these params: user_id, activity_id, reaction_id'); - } + return _wrapNativeSuper(Class); +} - var lookupType = userId && 'user_id' || activityId && 'activity_id' || reactionId && 'reaction_id'; - var value = userId || activityId || reactionId; - var url = conditions.kind ? this.buildURL(lookupType, value, conditions.kind) : this.buildURL(lookupType, value); - return this.client.get({ - url: url, - qs: qs, - signature: this.signature - }); - } - }, { - key: "update", - value: function update(id, data) { - var _ref3 = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}, - _ref3$targetFeeds = _ref3.targetFeeds, - targetFeeds = _ref3$targetFeeds === void 0 ? [] : _ref3$targetFeeds, - targetFeedsExtraData = _ref3.targetFeedsExtraData; +module.exports = _wrapNativeSuper; - /** - * update reaction - * @method add - * @memberof StreamReaction.prototype - * @param {string} id Reaction Id - * @param {object} data Data associated to reaction - * @param {array} targetFeeds Optional feeds to post the activity to. If you sent this before and don't set it here it will be removed. - * @return {Promise} Promise object - * @example reactions.update("67b3e3b5-b201-4697-96ac-482eb14f88ec", "0c7db91c-67f9-11e8-bcd9-fe00a9219401", "like") - * @example reactions.update("67b3e3b5-b201-4697-96ac-482eb14f88ec", "0c7db91c-67f9-11e8-bcd9-fe00a9219401", "comment", {"text": "love it!"},) - */ - var body = { - data: data, - target_feeds: this._convertTargetFeeds(targetFeeds) - }; +/***/ }), +/* 64 */ +/***/ (function(module, exports) { - if (targetFeedsExtraData != null) { - body.target_feeds_extra_data = targetFeedsExtraData; - } +function _extends() { + module.exports = _extends = Object.assign || function (target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i]; - return this.client.put({ - url: this.buildURL(id), - body: body, - signature: this.signature - }); - } - }, { - key: "delete", - value: function _delete(id) { - /** - * delete reaction - * @method delete - * @memberof StreamReaction.prototype - * @param {string} id Reaction Id - * @return {Promise} Promise object - * @example reactions.delete("67b3e3b5-b201-4697-96ac-482eb14f88ec") - */ - return this.client.delete({ - url: this.buildURL(id), - signature: this.signature - }); + for (var key in source) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + target[key] = source[key]; + } + } } - }]); - return StreamReaction; -}(); + return target; + }; + return _extends.apply(this, arguments); +} +module.exports = _extends; /***/ }), -/* 66 */ +/* 65 */ /***/ (function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;(function(f) { @@ -5924,7 +6098,7 @@ var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_ if ( true && exports != null && typeof exports.nodeType !== 'number') { module.exports = f (); - } else if ( true && __webpack_require__(114) != null) { + } else if ( true && __webpack_require__(109) != null) { !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_FACTORY__ = (f), __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), @@ -6000,11 +6174,31 @@ var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_ })); +/***/ }), +/* 66 */ +/***/ (function(module, exports, __webpack_require__) { + +var arrayWithHoles = __webpack_require__(110); + +var iterableToArrayLimit = __webpack_require__(111); + +var unsupportedIterableToArray = __webpack_require__(112); + +var nonIterableRest = __webpack_require__(114); + +function _slicedToArray(arr, i) { + return arrayWithHoles(arr) || iterableToArrayLimit(arr, i) || unsupportedIterableToArray(arr, i) || nonIterableRest(); +} + +module.exports = _slicedToArray; + /***/ }), /* 67 */ -/***/ (function(module) { +/***/ (function(module, exports) { + +/* eslint-env browser */ +module.exports = typeof self == 'object' ? self.FormData : window.FormData; -module.exports = JSON.parse("{\"author\":{\"name\":\"Thierry Schellenbach\",\"company\":\"Stream.io Inc\"},\"name\":\"getstream\",\"description\":\"The official low-level GetStream.io client for Node.js and the browser.\",\"main\":\"./lib/getstream.js\",\"module\":\"./lib/getstream.js\",\"types\":\"./types/getstream/index.d.ts\",\"homepage\":\"https://getstream.io/docs/?language=js\",\"email\":\"support@getstream.io\",\"license\":\"BSD-3-Clause\",\"version\":\"5.0.2\",\"scripts\":{\"build\":\"babel src --out-dir lib\",\"dtslint\":\"dtslint types/getstream\",\"eslint\":\"eslint '**/*.js' --max-warnings 0\",\"prettier\":\"prettier --list-different '**/*.{js,ts}'\",\"lint\":\"yarn run prettier && yarn run eslint\",\"lint-fix\":\"prettier --write '**/*.{js,ts}' && eslint --fix '**/*.js'\",\"test\":\"yarn run test-unit-node\",\"test-unit-node\":\"mocha --require @babel/register test/unit/common test/unit/node\",\"test-integration-node\":\"mocha --require @babel/register test/integration/common test/integration/node --exit\",\"test-cloud\":\"mocha --require @babel/register test/integration/cloud --timeout 40000\",\"test-cloud-local\":\"LOCAL=true mocha --require @babel/register test/integration/cloud --timeout 40000 -i --grep 'Files|Images'\",\"test-browser\":\"karma start karma.config.js\",\"generate-docs\":\"jsdoc -c .jsdoc\",\"coverage\":\"nyc yarn run test-unit-node && nyc report --reporter=text-lcov | codecov --pipe\",\"preversion\":\"yarn run test-unit-node\",\"dist\":\"webpack && webpack --minify\",\"version\":\"yarn run dist && yarn run build && git add dist\",\"postversion\":\"git push && git push --tags\"},\"husky\":{\"hooks\":{\"pre-commit\":\"dotgit/hooks/pre-commit-format.sh && dotgit/hooks/pre-commit-reject-binaries.py\"}},\"browser\":{\"crypto\":false,\"jsonwebtoken\":false,\"./lib/lib/batch_operations.js\":false,\"qs\":false,\"url\":false,\"http\":false,\"https\":false},\"react-native\":{\"crypto\":false,\"jsonwebtoken\":false,\"./lib/lib/batch_operations.js\":false,\"qs\":false,\"url\":false},\"devDependencies\":{\"@babel/cli\":\"^7.10.4\",\"@babel/core\":\"^7.10.4\",\"@babel/node\":\"^7.10.4\",\"@babel/plugin-proposal-class-properties\":\"^7.10.4\",\"@babel/plugin-transform-object-assign\":\"^7.10.4\",\"@babel/plugin-transform-runtime\":\"^7.10.4\",\"@babel/preset-env\":\"^7.10.4\",\"@babel/register\":\"^7.10.4\",\"@types/node\":\"^14.0.14\",\"babel-eslint\":\"^10.1.0\",\"babel-loader\":\"^8.1.0\",\"chai\":\"^4.2.0\",\"codecov\":\"^3.7.0\",\"dtslint\":\"^3.6.12\",\"eslint\":\"^7.3.1\",\"eslint-config-airbnb-base\":\"^14.2.0\",\"eslint-config-prettier\":\"^6.11.0\",\"eslint-plugin-chai-friendly\":\"^0.6.0\",\"eslint-plugin-import\":\"^2.22.0\",\"eslint-plugin-prettier\":\"^3.1.4\",\"eslint-plugin-sonarjs\":\"^0.5.0\",\"expect.js\":\"^0.3.1\",\"husky\":\"^4.2.5\",\"jsdoc\":\"^3.6.4\",\"json-loader\":\"~0.5.7\",\"karma\":\"^5.1.0\",\"karma-chrome-launcher\":\"^3.1.0\",\"karma-mocha\":\"^2.0.1\",\"karma-mocha-reporter\":\"~2.2.5\",\"karma-sauce-launcher\":\"^4.1.5\",\"karma-sourcemap-loader\":\"~0.3.7\",\"karma-webpack\":\"^4.0.2\",\"mocha\":\"^8.0.1\",\"null-loader\":\"^4.0.0\",\"nyc\":\"^15.1.0\",\"prettier\":\"^2.0.5\",\"request\":\"^2.88.2\",\"testdouble\":\"^3.16.0\",\"typescript\":\"^3.9.5\",\"uglifyjs-webpack-plugin\":\"^2.2.0\",\"webpack\":\"^4.43.0\",\"webpack-cli\":\"^3.3.12\"},\"dependencies\":{\"@babel/runtime\":\"^7.10.4\",\"Base64\":\"^1.1.0\",\"axios\":\"^0.19.2\",\"faye\":\"^1.3.0\",\"form-data\":\"^3.0.0\",\"jsonwebtoken\":\"^8.5.1\",\"jwt-decode\":\"^2.2.0\",\"qs\":\"^6.9.4\"},\"repository\":{\"type\":\"git\",\"url\":\"git://github.com/GetStream/stream-js.git\"},\"files\":[\"dist\",\"lib\",\"types\"],\"engines\":{\"node\":\"10 || 12 || >=14\"}}"); /***/ }), /* 68 */ @@ -6019,16 +6213,24 @@ module.exports = __webpack_require__(69); "use strict"; __webpack_require__.r(__webpack_exports__); -/* WEBPACK VAR INJECTION */(function(process) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "connect", function() { return connect; }); -/* harmony import */ var _lib_client__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(24); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Client", function() { return _lib_client__WEBPACK_IMPORTED_MODULE_0__["a"]; }); - -/* harmony import */ var _lib_errors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "errors", function() { return _lib_errors__WEBPACK_IMPORTED_MODULE_1__["a"]; }); - -/* harmony import */ var _lib_signing__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(5); -/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "signing", function() { return _lib_signing__WEBPACK_IMPORTED_MODULE_2__["a"]; }); - +/* harmony import */ var _client__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(12); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Client", function() { return _client__WEBPACK_IMPORTED_MODULE_0__["a"]; }); + +/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2); +/* harmony reexport (module object) */ __webpack_require__.d(__webpack_exports__, "errors", function() { return _errors__WEBPACK_IMPORTED_MODULE_1__; }); +/* harmony import */ var _signing__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(5); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "signing", function() { return _signing__WEBPACK_IMPORTED_MODULE_2__["a"]; }); + +/* harmony import */ var _connect__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(38); +/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "connect", function() { return _connect__WEBPACK_IMPORTED_MODULE_3__["a"]; }); + +/* harmony import */ var _collections__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(27); +/* harmony import */ var _feed__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(31); +/* harmony import */ var _files__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(28); +/* harmony import */ var _images__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(29); +/* harmony import */ var _personalization__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(26); +/* harmony import */ var _reaction__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(30); +/* harmony import */ var _user__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(13); /** * @module stream * @author Thierry Schellenbach @@ -6038,54 +6240,28 @@ __webpack_require__.r(__webpack_exports__); -function connect(apiKey, apiSecret, appId, options) { - /** - * Create StreamClient - * @method connect - * @param {string} apiKey API key - * @param {string} [apiSecret] API secret (only use this on the server) - * @param {string} [appId] Application identifier - * @param {object} [options] Additional options - * @param {string} [options.location] Datacenter location - * @return {StreamClient} StreamClient - * @example Basic usage - * stream.connect(apiKey, apiSecret); - * @example or if you want to be able to subscribe and listen - * stream.connect(apiKey, apiSecret, appId); - * @example or on Heroku - * stream.connect(streamURL); - * @example where streamURL looks like - * "https://thierry:pass@gestream.io/?app=1" - */ - if (process && process.env && process.env.STREAM_URL && !apiKey) { - var parts = /https:\/\/(\w+):(\w+)@([\w-]*).*\?app_id=(\d+)/.exec(process.env.STREAM_URL); - apiKey = parts[1]; - apiSecret = parts[2]; - var location = parts[3]; - appId = parts[4]; - if (options === undefined) { - options = {}; - } +/* deprecated default export */ + +/* harmony default export */ __webpack_exports__["default"] = ({ + connect: _connect__WEBPACK_IMPORTED_MODULE_3__[/* connect */ "a"], + errors: _errors__WEBPACK_IMPORTED_MODULE_1__, + signing: _signing__WEBPACK_IMPORTED_MODULE_2__[/* default */ "a"], + Client: _client__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"] +}); +/* + * typescript does not export the default exports here + * useful for exposing exported internal types + */ + + + + - if (location !== 'getstream' && location !== 'stream-io-api') { - options.location = location; - } - } - return new _lib_client__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"](apiKey, apiSecret, appId, options); -} -/* deprecated default export */ -/* harmony default export */ __webpack_exports__["default"] = ({ - connect: connect, - errors: _lib_errors__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"], - signing: _lib_signing__WEBPACK_IMPORTED_MODULE_2__[/* default */ "a"], - Client: _lib_client__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"] -}); -/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(22))) /***/ }), /* 70 */ @@ -6851,10 +7027,10 @@ try { var utils = __webpack_require__(9); -var bind = __webpack_require__(34); +var bind = __webpack_require__(41); var Axios = __webpack_require__(73); -var mergeConfig = __webpack_require__(40); -var defaults = __webpack_require__(37); +var mergeConfig = __webpack_require__(47); +var defaults = __webpack_require__(44); /** * Create an instance of Axios @@ -6887,9 +7063,9 @@ axios.create = function create(instanceConfig) { }; // Expose Cancel & CancelToken -axios.Cancel = __webpack_require__(41); +axios.Cancel = __webpack_require__(48); axios.CancelToken = __webpack_require__(86); -axios.isCancel = __webpack_require__(36); +axios.isCancel = __webpack_require__(43); // Expose all/spread axios.all = function all(promises) { @@ -6911,10 +7087,10 @@ module.exports.default = axios; var utils = __webpack_require__(9); -var buildURL = __webpack_require__(35); +var buildURL = __webpack_require__(42); var InterceptorManager = __webpack_require__(74); var dispatchRequest = __webpack_require__(75); -var mergeConfig = __webpack_require__(40); +var mergeConfig = __webpack_require__(47); /** * Create a new instance of Axios @@ -7072,8 +7248,8 @@ module.exports = InterceptorManager; var utils = __webpack_require__(9); var transformData = __webpack_require__(76); -var isCancel = __webpack_require__(36); -var defaults = __webpack_require__(37); +var isCancel = __webpack_require__(43); +var defaults = __webpack_require__(44); /** * Throws a `Cancel` if cancellation has been requested. @@ -7202,7 +7378,7 @@ module.exports = function normalizeHeaderName(headers, normalizedName) { "use strict"; -var createError = __webpack_require__(39); +var createError = __webpack_require__(46); /** * Resolve or reject a Promise based on response status. @@ -7547,7 +7723,7 @@ module.exports = ( "use strict"; -var Cancel = __webpack_require__(41); +var Cancel = __webpack_require__(48); /** * A `CancelToken` is an object that can be used to request cancellation of an operation. @@ -7645,18 +7821,18 @@ module.exports = function spread(callback) { "use strict"; /* WEBPACK VAR INJECTION */(function(global) { -var asap = __webpack_require__(43), +var asap = __webpack_require__(50), Class = __webpack_require__(10), - Promise = __webpack_require__(23), - array = __webpack_require__(26), - browser = __webpack_require__(27), - constants = __webpack_require__(42), + Promise = __webpack_require__(25), + array = __webpack_require__(33), + browser = __webpack_require__(34), + constants = __webpack_require__(49), assign = __webpack_require__(8), validateOptions = __webpack_require__(90), - Deferrable = __webpack_require__(18), - Logging = __webpack_require__(16), - Publisher = __webpack_require__(28), - Channel = __webpack_require__(44), + Deferrable = __webpack_require__(20), + Logging = __webpack_require__(18), + Publisher = __webpack_require__(35), + Channel = __webpack_require__(51), Dispatcher = __webpack_require__(92), Error = __webpack_require__(100), Extensible = __webpack_require__(101), @@ -8269,7 +8445,7 @@ rawAsap.makeRequestCallFromTimer = makeRequestCallFromTimer; "use strict"; -var array = __webpack_require__(26); +var array = __webpack_require__(33); module.exports = function(options, validKeys) { for (var key in options) { @@ -8464,13 +8640,13 @@ EventEmitter.prototype.listeners = function(type) { /* WEBPACK VAR INJECTION */(function(global) { var Class = __webpack_require__(10), - URI = __webpack_require__(12), - cookies = __webpack_require__(46), + URI = __webpack_require__(14), + cookies = __webpack_require__(53), assign = __webpack_require__(8), - Logging = __webpack_require__(16), - Publisher = __webpack_require__(28), + Logging = __webpack_require__(18), + Publisher = __webpack_require__(35), Transport = __webpack_require__(93), - Scheduler = __webpack_require__(49); + Scheduler = __webpack_require__(56); var Dispatcher = Class({ className: 'Dispatcher', MAX_REQUEST_SIZE: 2048, @@ -8657,11 +8833,11 @@ module.exports = Dispatcher; "use strict"; -var Transport = __webpack_require__(13); +var Transport = __webpack_require__(15); Transport.register('websocket', __webpack_require__(95)); Transport.register('eventsource', __webpack_require__(97)); -Transport.register('long-polling', __webpack_require__(48)); +Transport.register('long-polling', __webpack_require__(55)); Transport.register('cross-origin-long-polling', __webpack_require__(98)); Transport.register('callback-polling', __webpack_require__(99)); @@ -8710,16 +8886,16 @@ module.exports = { /* WEBPACK VAR INJECTION */(function(global) { var Class = __webpack_require__(10), - Promise = __webpack_require__(23), - Set = __webpack_require__(47), - URI = __webpack_require__(12), - browser = __webpack_require__(27), - copyObject = __webpack_require__(29), + Promise = __webpack_require__(25), + Set = __webpack_require__(54), + URI = __webpack_require__(14), + browser = __webpack_require__(34), + copyObject = __webpack_require__(36), assign = __webpack_require__(8), - toJSON = __webpack_require__(17), + toJSON = __webpack_require__(19), ws = __webpack_require__(96), - Deferrable = __webpack_require__(18), - Transport = __webpack_require__(13); + Deferrable = __webpack_require__(20), + Transport = __webpack_require__(15); var WebSocket = assign(Class(Transport, { UNCONNECTED: 1, @@ -8897,12 +9073,12 @@ module.exports = { /* WEBPACK VAR INJECTION */(function(global) { var Class = __webpack_require__(10), - URI = __webpack_require__(12), - copyObject = __webpack_require__(29), + URI = __webpack_require__(14), + copyObject = __webpack_require__(36), assign = __webpack_require__(8), - Deferrable = __webpack_require__(18), - Transport = __webpack_require__(13), - XHR = __webpack_require__(48); + Deferrable = __webpack_require__(20), + Transport = __webpack_require__(15), + XHR = __webpack_require__(55); var EventSource = assign(Class(Transport, { initialize: function(dispatcher, endpoint) { @@ -9002,11 +9178,11 @@ module.exports = EventSource; /* WEBPACK VAR INJECTION */(function(global) { var Class = __webpack_require__(10), - Set = __webpack_require__(47), - URI = __webpack_require__(12), + Set = __webpack_require__(54), + URI = __webpack_require__(14), assign = __webpack_require__(8), - toJSON = __webpack_require__(17), - Transport = __webpack_require__(13); + toJSON = __webpack_require__(19), + Transport = __webpack_require__(15); var CORS = assign(Class(Transport, { encode: function(messages) { @@ -9095,11 +9271,11 @@ module.exports = CORS; /* WEBPACK VAR INJECTION */(function(global) { var Class = __webpack_require__(10), - URI = __webpack_require__(12), - copyObject = __webpack_require__(29), + URI = __webpack_require__(14), + copyObject = __webpack_require__(36), assign = __webpack_require__(8), - toJSON = __webpack_require__(17), - Transport = __webpack_require__(13); + toJSON = __webpack_require__(19), + Transport = __webpack_require__(15); var JSONP = assign(Class(Transport, { encode: function(messages) { @@ -9167,7 +9343,7 @@ module.exports = JSONP; var Class = __webpack_require__(10), - Grammar = __webpack_require__(45); + Grammar = __webpack_require__(52); var Error = Class({ initialize: function(code, params, message) { @@ -9229,7 +9405,7 @@ module.exports = Error; var assign = __webpack_require__(8), - Logging = __webpack_require__(16); + Logging = __webpack_require__(18); var Extensible = { addExtension: function(extension) { @@ -9283,7 +9459,7 @@ module.exports = Extensible; var Class = __webpack_require__(10), - Deferrable = __webpack_require__(18); + Deferrable = __webpack_require__(20); module.exports = Class(Deferrable); @@ -9297,7 +9473,7 @@ module.exports = Class(Deferrable); var Class = __webpack_require__(10), assign = __webpack_require__(8), - Deferrable = __webpack_require__(18); + Deferrable = __webpack_require__(20); var Subscription = Class({ initialize: function(client, channels, callback, context) { @@ -9436,7 +9612,7 @@ module.exports = _isNativeFunction; /* 107 */ /***/ (function(module, exports, __webpack_require__) { -var setPrototypeOf = __webpack_require__(30); +var setPrototypeOf = __webpack_require__(37); var isNativeReflectConstruct = __webpack_require__(108); @@ -9482,6 +9658,15 @@ module.exports = _isNativeReflectConstruct; /* 109 */ /***/ (function(module, exports) { +/* WEBPACK VAR INJECTION */(function(__webpack_amd_options__) {/* globals __webpack_amd_options__ */ +module.exports = __webpack_amd_options__; + +/* WEBPACK VAR INJECTION */}.call(this, {})) + +/***/ }), +/* 110 */ +/***/ (function(module, exports) { + function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } @@ -9489,7 +9674,7 @@ function _arrayWithHoles(arr) { module.exports = _arrayWithHoles; /***/ }), -/* 110 */ +/* 111 */ /***/ (function(module, exports) { function _iterableToArrayLimit(arr, i) { @@ -9522,10 +9707,10 @@ function _iterableToArrayLimit(arr, i) { module.exports = _iterableToArrayLimit; /***/ }), -/* 111 */ +/* 112 */ /***/ (function(module, exports, __webpack_require__) { -var arrayLikeToArray = __webpack_require__(112); +var arrayLikeToArray = __webpack_require__(113); function _unsupportedIterableToArray(o, minLen) { if (!o) return; @@ -9539,7 +9724,7 @@ function _unsupportedIterableToArray(o, minLen) { module.exports = _unsupportedIterableToArray; /***/ }), -/* 112 */ +/* 113 */ /***/ (function(module, exports) { function _arrayLikeToArray(arr, len) { @@ -9555,7 +9740,7 @@ function _arrayLikeToArray(arr, len) { module.exports = _arrayLikeToArray; /***/ }), -/* 113 */ +/* 114 */ /***/ (function(module, exports) { function _nonIterableRest() { @@ -9565,13 +9750,10 @@ function _nonIterableRest() { module.exports = _nonIterableRest; /***/ }), -/* 114 */ -/***/ (function(module, exports) { - -/* WEBPACK VAR INJECTION */(function(__webpack_amd_options__) {/* globals __webpack_amd_options__ */ -module.exports = __webpack_amd_options__; +/* 115 */ +/***/ (function(module) { -/* WEBPACK VAR INJECTION */}.call(this, {})) +module.exports = JSON.parse("{\"author\":{\"name\":\"Thierry Schellenbach\",\"company\":\"Stream.io Inc\"},\"name\":\"getstream\",\"description\":\"The official low-level GetStream.io client for Node.js and the browser.\",\"main\":\"./lib/index.js\",\"module\":\"./lib/index.js\",\"types\":\"./lib/index.d.ts\",\"homepage\":\"https://getstream.io/docs/?language=js\",\"email\":\"support@getstream.io\",\"license\":\"BSD-3-Clause\",\"version\":\"5.1.0-0\",\"scripts\":{\"transpile\":\"babel src --out-dir lib --extensions '.ts'\",\"types\":\"tsc --emitDeclarationOnly\",\"build\":\"rm -rf lib && yarn transpile && yarn types\",\"eslint\":\"eslint '**/*.{js,ts}' --max-warnings 0\",\"prettier\":\"prettier --list-different '**/*.{js,ts}'\",\"lint\":\"yarn run prettier && yarn run eslint\",\"lint-fix\":\"prettier --write '**/*.{js,ts}' && eslint --fix '**/*.{js,ts}'\",\"test\":\"yarn run test-unit-node\",\"test-unit-node\":\"mocha --require ./babel-register.js test/unit/common test/unit/node\",\"test-integration-node\":\"mocha --require ./babel-register.js test/integration/common test/integration/node --exit\",\"test-cloud\":\"mocha --require ./babel-register.js test/integration/cloud --timeout 40000\",\"test-cloud-local\":\"LOCAL=true mocha --require ./babel-register.js test/integration/cloud --timeout 40000 -i --grep 'Files|Images'\",\"test-browser\":\"karma start karma.config.js\",\"generate-docs\":\"jsdoc -c .jsdoc\",\"coverage\":\"nyc yarn run test-unit-node && nyc report --reporter=text-lcov | codecov --pipe\",\"preversion\":\"yarn run test-unit-node\",\"dist\":\"webpack && webpack --minify\",\"version\":\"yarn run dist && yarn run build && git add dist\",\"postversion\":\"git push && git push --tags\"},\"husky\":{\"hooks\":{\"pre-commit\":\"dotgit/hooks/pre-commit-format.sh && dotgit/hooks/pre-commit-reject-binaries.py\"}},\"browser\":{\"crypto\":false,\"jsonwebtoken\":false,\"./lib/batch_operations.js\":false,\"qs\":false,\"url\":false,\"http\":false,\"https\":false},\"react-native\":{\"crypto\":false,\"jsonwebtoken\":false,\"./lib/batch_operations.js\":false,\"qs\":false,\"url\":false},\"devDependencies\":{\"@babel/cli\":\"^7.10.4\",\"@babel/core\":\"^7.10.4\",\"@babel/node\":\"^7.10.4\",\"@babel/plugin-proposal-class-properties\":\"^7.10.4\",\"@babel/plugin-proposal-object-rest-spread\":\"^7.10.4\",\"@babel/plugin-transform-object-assign\":\"^7.10.4\",\"@babel/plugin-transform-runtime\":\"^7.10.4\",\"@babel/preset-env\":\"^7.10.4\",\"@babel/preset-typescript\":\"^7.10.4\",\"@babel/register\":\"^7.10.4\",\"@typescript-eslint/eslint-plugin\":\"^3.6.1\",\"@typescript-eslint/parser\":\"^3.6.1\",\"babel-eslint\":\"^10.1.0\",\"babel-loader\":\"^8.1.0\",\"chai\":\"^4.2.0\",\"codecov\":\"^3.7.1\",\"eslint\":\"^7.3.1\",\"eslint-config-airbnb-base\":\"^14.2.0\",\"eslint-config-prettier\":\"^6.11.0\",\"eslint-plugin-chai-friendly\":\"^0.6.0\",\"eslint-plugin-import\":\"^2.22.0\",\"eslint-plugin-prettier\":\"^3.1.4\",\"eslint-plugin-sonarjs\":\"^0.5.0\",\"eslint-plugin-typescript-sort-keys\":\"^1.3.0\",\"expect.js\":\"^0.3.1\",\"husky\":\"^4.2.5\",\"jsdoc\":\"^3.6.4\",\"json-loader\":\"~0.5.7\",\"karma\":\"^5.1.0\",\"karma-chrome-launcher\":\"^3.1.0\",\"karma-mocha\":\"^2.0.1\",\"karma-mocha-reporter\":\"~2.2.5\",\"karma-sauce-launcher\":\"^4.1.5\",\"karma-sourcemap-loader\":\"~0.3.7\",\"karma-webpack\":\"^4.0.2\",\"mocha\":\"^8.0.1\",\"null-loader\":\"^4.0.0\",\"nyc\":\"^15.1.0\",\"prettier\":\"^2.0.5\",\"request\":\"^2.88.2\",\"testdouble\":\"^3.16.0\",\"typescript\":\"^3.9.6\",\"uglifyjs-webpack-plugin\":\"^2.2.0\",\"webpack\":\"^4.43.0\",\"webpack-cli\":\"^3.3.12\"},\"dependencies\":{\"@babel/runtime\":\"^7.10.4\",\"@types/jsonwebtoken\":\"^8.5.0\",\"@types/jwt-decode\":\"^2.2.0\",\"@types/qs\":\"^6.9.4\",\"Base64\":\"^1.1.0\",\"axios\":\"^0.19.2\",\"faye\":\"^1.3.0\",\"form-data\":\"^3.0.0\",\"jsonwebtoken\":\"^8.5.1\",\"jwt-decode\":\"^2.2.0\",\"qs\":\"^6.9.4\"},\"peerDependencies\":{\"@types/node\":\">=10\"},\"repository\":{\"type\":\"git\",\"url\":\"git://github.com/GetStream/stream-js.git\"},\"files\":[\"src\",\"dist\",\"types\",\"lib\"],\"engines\":{\"node\":\"10 || 12 || >=14\"}}"); /***/ }) /******/ ]); diff --git a/dist/js_min/getstream.js b/dist/js_min/getstream.js index 2a29fc8a..01684343 100644 --- a/dist/js_min/getstream.js +++ b/dist/js_min/getstream.js @@ -1 +1 @@ -!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.stream=e():t.stream=e()}(window,function(){return r={},i.m=n=[function(t,e,n){t.exports=n(71)},function(t,e,n){"use strict";var r=n(2),s=n.n(r),i=n(31),o=n.n(i),a=n(15),c=n.n(a),u=n(57),l=n.n(u),h=n(25),f=n.n(h),p=n(58),d=n.n(p);function v(r){var i=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],function(){})),!0}catch(t){return!1}}();return function(){var t,e,n=f()(r);return e=i?(t=f()(this).constructor,Reflect.construct(n,arguments,t)):n.apply(this,arguments),l()(this,e)}}var g="function"==typeof Error.captureStackTrace,y=!!(new Error).stack,m=function(t){c()(r,t);var n=v(r);function r(t){var e;return s()(this,r),(e=n.call(this,t)).message=t,g?Error.captureStackTrace(o()(e),constructor):e.stack=y?(new Error).stack:"",e}return r}(d()(Error)),_=function(t){c()(n,t);var e=v(n);function n(){return s()(this,n),e.apply(this,arguments)}return n}(m),b=function(t){c()(n,t);var e=v(n);function n(){return s()(this,n),e.apply(this,arguments)}return n}(m),w=function(t){c()(n,t);var e=v(n);function n(){return s()(this,n),e.apply(this,arguments)}return n}(m),k=function(t){c()(o,t);var i=v(o);function o(t,e,n){var r;return s()(this,o),(r=i.call(this,t)).error=e,r.response=n,r}return o}(m);e.a={FeedError:_,SiteError:b,MissingSchemaError:w,StreamApiError:k}},function(t,e){t.exports=function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}},function(t,e){function r(t,e){for(var n=0;n>8-i%1*8)){if(255<(n=r.charCodeAt(i+=.75)))throw new c("'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.");e=e<<8|n}return s},atob:function(t){var e=String(t).replace(/[=]+$/,"");if(e.length%4==1)throw new c("'atob' failed: The string to be decoded is not correctly encoded.");for(var n,r,i=0,o=0,s="";r=e.charAt(o++);~r&&(n=i%4?64*n+r:r,i++%4)&&(s+=String.fromCharCode(255&n>>(-2*i&6))))r=a.indexOf(r);return s}}})},function(t){t.exports=JSON.parse('{"author":{"name":"Thierry Schellenbach","company":"Stream.io Inc"},"name":"getstream","description":"The official low-level GetStream.io client for Node.js and the browser.","main":"./lib/getstream.js","module":"./lib/getstream.js","types":"./types/getstream/index.d.ts","homepage":"https://getstream.io/docs/?language=js","email":"support@getstream.io","license":"BSD-3-Clause","version":"5.0.2","scripts":{"build":"babel src --out-dir lib","dtslint":"dtslint types/getstream","eslint":"eslint \'**/*.js\' --max-warnings 0","prettier":"prettier --list-different \'**/*.{js,ts}\'","lint":"yarn run prettier && yarn run eslint","lint-fix":"prettier --write \'**/*.{js,ts}\' && eslint --fix \'**/*.js\'","test":"yarn run test-unit-node","test-unit-node":"mocha --require @babel/register test/unit/common test/unit/node","test-integration-node":"mocha --require @babel/register test/integration/common test/integration/node --exit","test-cloud":"mocha --require @babel/register test/integration/cloud --timeout 40000","test-cloud-local":"LOCAL=true mocha --require @babel/register test/integration/cloud --timeout 40000 -i --grep \'Files|Images\'","test-browser":"karma start karma.config.js","generate-docs":"jsdoc -c .jsdoc","coverage":"nyc yarn run test-unit-node && nyc report --reporter=text-lcov | codecov --pipe","preversion":"yarn run test-unit-node","dist":"webpack && webpack --minify","version":"yarn run dist && yarn run build && git add dist","postversion":"git push && git push --tags"},"husky":{"hooks":{"pre-commit":"dotgit/hooks/pre-commit-format.sh && dotgit/hooks/pre-commit-reject-binaries.py"}},"browser":{"crypto":false,"jsonwebtoken":false,"./lib/lib/batch_operations.js":false,"qs":false,"url":false,"http":false,"https":false},"react-native":{"crypto":false,"jsonwebtoken":false,"./lib/lib/batch_operations.js":false,"qs":false,"url":false},"devDependencies":{"@babel/cli":"^7.10.4","@babel/core":"^7.10.4","@babel/node":"^7.10.4","@babel/plugin-proposal-class-properties":"^7.10.4","@babel/plugin-transform-object-assign":"^7.10.4","@babel/plugin-transform-runtime":"^7.10.4","@babel/preset-env":"^7.10.4","@babel/register":"^7.10.4","@types/node":"^14.0.14","babel-eslint":"^10.1.0","babel-loader":"^8.1.0","chai":"^4.2.0","codecov":"^3.7.0","dtslint":"^3.6.12","eslint":"^7.3.1","eslint-config-airbnb-base":"^14.2.0","eslint-config-prettier":"^6.11.0","eslint-plugin-chai-friendly":"^0.6.0","eslint-plugin-import":"^2.22.0","eslint-plugin-prettier":"^3.1.4","eslint-plugin-sonarjs":"^0.5.0","expect.js":"^0.3.1","husky":"^4.2.5","jsdoc":"^3.6.4","json-loader":"~0.5.7","karma":"^5.1.0","karma-chrome-launcher":"^3.1.0","karma-mocha":"^2.0.1","karma-mocha-reporter":"~2.2.5","karma-sauce-launcher":"^4.1.5","karma-sourcemap-loader":"~0.3.7","karma-webpack":"^4.0.2","mocha":"^8.0.1","null-loader":"^4.0.0","nyc":"^15.1.0","prettier":"^2.0.5","request":"^2.88.2","testdouble":"^3.16.0","typescript":"^3.9.5","uglifyjs-webpack-plugin":"^2.2.0","webpack":"^4.43.0","webpack-cli":"^3.3.12"},"dependencies":{"@babel/runtime":"^7.10.4","Base64":"^1.1.0","axios":"^0.19.2","faye":"^1.3.0","form-data":"^3.0.0","jsonwebtoken":"^8.5.1","jwt-decode":"^2.2.0","qs":"^6.9.4"},"repository":{"type":"git","url":"git://github.com/GetStream/stream-js.git"},"files":["dist","lib","types"],"engines":{"node":"10 || 12 || >=14"}}')},function(t,e,n){t.exports=n(69)},function(t,r,i){"use strict";i.r(r),function(s){i.d(r,"connect",function(){return n});var a=i(24);i.d(r,"Client",function(){return a.a});var t=i(1);i.d(r,"errors",function(){return t.a});var e=i(5);function n(t,e,n,r){var i,o;return s&&s.env&&s.env.STREAM_URL&&!t&&(t=(i=/https:\/\/(\w+):(\w+)@([\w-]*).*\?app_id=(\d+)/.exec(s.env.STREAM_URL))[1],e=i[2],o=i[3],n=i[4],void 0===r&&(r={}),"getstream"!==o&&"stream-io-api"!==o&&(r.location=o)),new a.a(t,e,n,r)}i.d(r,"signing",function(){return e.a}),r.default={connect:n,errors:t.a,signing:e.a,Client:a.a}}.call(this,i(22))},function(t,e){t.exports=function(t,e){if(null==t)return{};for(var n,r={},i=Object.keys(t),o=0;o=Math.pow(2,32)&&(this._messageId=0),this._messageId.toString(36)},_receiveMessage:function(t){var e,n=t.id;void 0!==t.successful&&(e=this._responseCallbacks[n],delete this._responseCallbacks[n]),this.pipeThroughExtensions("incoming",t,null,function(t){t&&(t.advice&&this._handleAdvice(t.advice),this._deliverMessage(t),e&&e[0].call(e[1],t))},this)},_handleAdvice:function(t){e(this._advice,t),this._dispatcher.timeout=this._advice.timeout/1e3,this._advice.reconnect===this.HANDSHAKE&&this._state!==this.DISCONNECTED&&(this._state=this.UNCONNECTED,this._dispatcher.clientId=null,this._cycleConnection())},_deliverMessage:function(t){t.channel&&void 0!==t.data&&(this.info("Client ? calling listeners for ? with ?",this._dispatcher.clientId,t.channel,t.data),this._channels.distributeMessage(t))},_cycleConnection:function(){this._connectRequest&&(this._connectRequest=null,this.info("Closed connection for ?",this._dispatcher.clientId));var t=this;i.setTimeout(function(){t.connect()},this._advice.interval)}});e(y.prototype,r),e(y.prototype,l),e(y.prototype,u),e(y.prototype,d),m.exports=y}).call(this,_(11))},function(f,t,e){"use strict";(function(t){function e(t){r.length||(n(),0),r[r.length]=t}f.exports=e;var n,r=[],i=0;function o(){for(;i>(-2*i&6))))r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(r);return s}},function(t,e){t.exports=function(t){return-1!==Function.toString.call(t).indexOf("[native code]")}},function(r,t,e){var o=e(30),i=e(108);function s(t,e,n){return i()?r.exports=s=Reflect.construct:r.exports=s=function(t,e,n){var r=[null];r.push.apply(r,e);var i=new(Function.bind.apply(t,r));return n&&o(i,n.prototype),i},s.apply(null,arguments)}r.exports=s},function(t,e){t.exports=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],function(){})),!0}catch(t){return!1}}},function(t,e){t.exports=function(t){if(Array.isArray(t))return t}},function(t,e){t.exports=function(t,e){if("undefined"!=typeof Symbol&&Symbol.iterator in Object(t)){var n=[],r=!0,i=!1,o=void 0;try{for(var s,a=t[Symbol.iterator]();!(r=(s=a.next()).done)&&(n.push(s.value),!e||n.length!==e);r=!0);}catch(t){i=!0,o=t}finally{try{r||null==a.return||a.return()}finally{if(i)throw o}}return n}}},function(t,e,n){var r=n(112);t.exports=function(t,e){if(t){if("string"==typeof t)return r(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?r(t,e):void 0}}},function(t,e){t.exports=function(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n>8-i%1*8)){if(255<(n=r.charCodeAt(i+=.75)))throw new c("'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.");e=e<<8|n}return s},atob:function(t){var e=String(t).replace(/[=]+$/,"");if(e.length%4==1)throw new c("'atob' failed: The string to be decoded is not correctly encoded.");for(var n,r,i=0,o=0,s="";r=e.charAt(o++);~r&&(n=i%4?64*n+r:r,i++%4)&&(s+=String.fromCharCode(255&n>>(-2*i&6))))r=a.indexOf(r);return s}}})},function(t,e,n){var r=n(110),i=n(111),o=n(112),s=n(114);t.exports=function(t,e){return r(t)||i(t,e)||o(t,e)||s()}},function(t,e){t.exports="object"==typeof self?self.FormData:window.FormData},function(t,e,n){t.exports=n(69)},function(t,e,n){"use strict";n.r(e);var r=n(12);n.d(e,"Client",function(){return r.a});var i=n(2);n.d(e,"errors",function(){return i});var o=n(5);n.d(e,"signing",function(){return o.a});var s=n(38);n.d(e,"connect",function(){return s.a});n(27),n(31),n(28),n(29),n(26),n(30),n(13);e.default={connect:s.a,errors:i,signing:o.a,Client:r.a}},function(t,e){t.exports=function(t,e){if(null==t)return{};for(var n,r={},i=Object.keys(t),o=0;o=Math.pow(2,32)&&(this._messageId=0),this._messageId.toString(36)},_receiveMessage:function(t){var e,n=t.id;void 0!==t.successful&&(e=this._responseCallbacks[n],delete this._responseCallbacks[n]),this.pipeThroughExtensions("incoming",t,null,function(t){t&&(t.advice&&this._handleAdvice(t.advice),this._deliverMessage(t),e&&e[0].call(e[1],t))},this)},_handleAdvice:function(t){e(this._advice,t),this._dispatcher.timeout=this._advice.timeout/1e3,this._advice.reconnect===this.HANDSHAKE&&this._state!==this.DISCONNECTED&&(this._state=this.UNCONNECTED,this._dispatcher.clientId=null,this._cycleConnection())},_deliverMessage:function(t){t.channel&&void 0!==t.data&&(this.info("Client ? calling listeners for ? with ?",this._dispatcher.clientId,t.channel,t.data),this._channels.distributeMessage(t))},_cycleConnection:function(){this._connectRequest&&(this._connectRequest=null,this.info("Closed connection for ?",this._dispatcher.clientId));var t=this;i.setTimeout(function(){t.connect()},this._advice.interval)}});e(y.prototype,r),e(y.prototype,l),e(y.prototype,u),e(y.prototype,p),m.exports=y}).call(this,_(11))},function(f,t,e){"use strict";(function(t){function e(t){r.length||(n(),0),r[r.length]=t}f.exports=e;var n,r=[],i=0;function o(){for(;i>(-2*i&6))))r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(r);return s}},function(t,e){t.exports=function(t){return-1!==Function.toString.call(t).indexOf("[native code]")}},function(r,t,e){var o=e(37),i=e(108);function s(t,e,n){return i()?r.exports=s=Reflect.construct:r.exports=s=function(t,e,n){var r=[null];r.push.apply(r,e);var i=new(Function.bind.apply(t,r));return n&&o(i,n.prototype),i},s.apply(null,arguments)}r.exports=s},function(t,e){t.exports=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],function(){})),!0}catch(t){return!1}}},function(e,t){(function(t){e.exports=t}).call(this,{})},function(t,e){t.exports=function(t){if(Array.isArray(t))return t}},function(t,e){t.exports=function(t,e){if("undefined"!=typeof Symbol&&Symbol.iterator in Object(t)){var n=[],r=!0,i=!1,o=void 0;try{for(var s,a=t[Symbol.iterator]();!(r=(s=a.next()).done)&&(n.push(s.value),!e||n.length!==e);r=!0);}catch(t){i=!0,o=t}finally{try{r||null==a.return||a.return()}finally{if(i)throw o}}return n}}},function(t,e,n){var r=n(113);t.exports=function(t,e){if(t){if("string"==typeof t)return r(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return"Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?r(t,e):void 0}}},function(t,e){t.exports=function(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=new Array(e);n=10"},"repository":{"type":"git","url":"git://github.com/GetStream/stream-js.git"},"files":["src","dist","types","lib"],"engines":{"node":"10 || 12 || >=14"}}')}],i.c=r,i.d=function(t,e,n){i.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:n})},i.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},i.t=function(e,t){if(1&t&&(e=i(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(i.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var r in e)i.d(n,r,function(t){return e[t]}.bind(null,r));return n},i.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return i.d(e,"a",e),e},i.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},i.p="dist/",i(i.s=68);function i(t){if(r[t])return r[t].exports;var e=r[t]={i:t,l:!1,exports:{}};return n[t].call(e.exports,e,e.exports,i),e.l=!0,e.exports}var n,r}); \ No newline at end of file diff --git a/package.json b/package.json index b1addecc..6471aa7b 100644 --- a/package.json +++ b/package.json @@ -11,7 +11,7 @@ "homepage": "https://getstream.io/docs/?language=js", "email": "support@getstream.io", "license": "BSD-3-Clause", - "version": "5.0.2", + "version": "5.1.0-0", "scripts": { "transpile": "babel src --out-dir lib --extensions '.ts'", "types": "tsc --emitDeclarationOnly", From 25223fb060fa1f8baa9cbb7df235a60b6e7c4a9e Mon Sep 17 00:00:00 2001 From: Amin Mahboubi Date: Mon, 3 Aug 2020 15:53:48 +0200 Subject: [PATCH 57/69] add prepare script to build on yarn install --- package.json | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/package.json b/package.json index 6471aa7b..9f51df5a 100644 --- a/package.json +++ b/package.json @@ -15,7 +15,8 @@ "scripts": { "transpile": "babel src --out-dir lib --extensions '.ts'", "types": "tsc --emitDeclarationOnly", - "build": "rm -rf lib && yarn transpile && yarn types", + "build": "rm -rf lib && yarn run transpile && yarn run types", + "dist": "webpack && webpack --minify", "eslint": "eslint '**/*.{js,ts}' --max-warnings 0", "prettier": "prettier --list-different '**/*.{js,ts}'", "lint": "yarn run prettier && yarn run eslint", @@ -28,10 +29,10 @@ "test-browser": "karma start karma.config.js", "generate-docs": "jsdoc -c .jsdoc", "coverage": "nyc yarn run test-unit-node && nyc report --reporter=text-lcov | codecov --pipe", + "prepare": "yarn run build", "preversion": "yarn run test-unit-node", - "dist": "webpack && webpack --minify", "version": "yarn run dist && yarn run build && git add dist", - "postversion": "git push && git push --tags" + "postversion": "git push && git push --tags && npm publish" }, "husky": { "hooks": { From ae8172e97e094959643836021a8e4cd553a1fd35 Mon Sep 17 00:00:00 2001 From: Amin Mahboubi Date: Mon, 3 Aug 2020 16:41:51 +0200 Subject: [PATCH 58/69] make types more strict default to UnknownRecord --- src/batch_operations.ts | 8 ++- src/client.ts | 12 +++-- src/collections.ts | 21 +++++--- src/feed.ts | 114 +++++++++++++++++++++++----------------- src/personalization.ts | 8 +-- src/reaction.ts | 32 ++++++++--- src/user.ts | 6 +-- 7 files changed, 126 insertions(+), 75 deletions(-) diff --git a/src/batch_operations.ts b/src/batch_operations.ts index 287f75b6..6d9d6f11 100644 --- a/src/batch_operations.ts +++ b/src/batch_operations.ts @@ -1,4 +1,4 @@ -import StreamClient, { APIResponse } from './client'; +import StreamClient, { APIResponse, UnknownRecord } from './client'; import utils from './utils'; type BaseFollowRelation = { @@ -14,7 +14,11 @@ export type UnfollowRelation = BaseFollowRelation & { keep_history?: boolean; }; -function addToMany(this: StreamClient, activity: ActivityType, feeds: string[]) { +function addToMany( + this: StreamClient, + activity: ActivityType, + feeds: string[], +) { /** * Add one activity to many feeds * @method addToMany diff --git a/src/client.ts b/src/client.ts index af671b28..411d66d4 100644 --- a/src/client.ts +++ b/src/client.ts @@ -95,8 +95,8 @@ type AxiosConfig = { url: string; axiosOptions?: axios.AxiosRequestConfig; body?: unknown; - headers?: Record; - qs?: Record; + headers?: UnknownRecord; + qs?: UnknownRecord; serviceName?: string; }; @@ -105,7 +105,7 @@ export type HandlerCallback = (...args: unknown[]) => unknown; export type ActivityPartialChanges = { foreignID?: string; id?: string; - set?: Record; + set?: UnknownRecord; time?: Date | string; unset?: string[]; }; @@ -161,7 +161,11 @@ export default class StreamClient< private _collectionsToken?: string; private _getOrCreateToken?: string; - addToMany?: (this: StreamClient, activity: ActivityType, feeds: string[]) => Promise; + addToMany?: ( + this: StreamClient, + activity: ActivityType, + feeds: string[], + ) => Promise; followMany?: (this: StreamClient, follows: FollowRelation[], activityCopyLimit?: number) => Promise; unfollowMany?: (this: StreamClient, unfollows: UnfollowRelation[]) => Promise; createRedirectUrl?: (this: StreamClient, targetUrl: string, userId: string, events: unknown[]) => string; diff --git a/src/collections.ts b/src/collections.ts index d0066474..6dcf8c99 100644 --- a/src/collections.ts +++ b/src/collections.ts @@ -1,4 +1,4 @@ -import StreamClient, { APIResponse } from './client'; +import StreamClient, { APIResponse, UnknownRecord } from './client'; import * as errors from './errors'; type BaseCollection = { @@ -7,25 +7,30 @@ type BaseCollection = { id: string; }; -export type CollectionResponse = BaseCollection & { +export type CollectionResponse = BaseCollection< + CollectionType +> & { created_at: string; foregin_id: string; updated_at: string; }; -export type NewCollectionEntry = BaseCollection & { +export type NewCollectionEntry = BaseCollection< + CollectionType +> & { user_id?: string; }; -export type CollectionAPIResponse = APIResponse & CollectionResponse; +export type CollectionAPIResponse = APIResponse & + CollectionResponse; -export type SelectCollectionAPIResponse = APIResponse & { +export type SelectCollectionAPIResponse = APIResponse & { response: { data: CollectionResponse[]; }; }; -export type UpsertCollectionAPIResponse = APIResponse & { +export type UpsertCollectionAPIResponse = APIResponse & { data: { [key: string]: { data: CollectionType; @@ -34,7 +39,7 @@ export type UpsertCollectionAPIResponse = APIResponse & { }; }; -class CollectionEntry { +class CollectionEntry { id: string; collection: string; store: Collections; @@ -110,7 +115,7 @@ class CollectionEntry { } } -export default class Collections { +export default class Collections { client: StreamClient; token: string; diff --git a/src/feed.ts b/src/feed.ts index 2b941abb..539886e8 100644 --- a/src/feed.ts +++ b/src/feed.ts @@ -1,7 +1,7 @@ /// import * as Faye from 'faye'; -import StreamClient, { APIResponse } from './client'; +import StreamClient, { APIResponse, UnknownRecord } from './client'; import StreamUser from './user'; import * as errors from './errors'; import utils from './utils'; @@ -58,28 +58,39 @@ type BaseActivity = ActivityType & { to?: string[]; }; -export type NewActivity = BaseActivity & { foreign_id?: string; time?: string }; +export type NewActivity = BaseActivity & { + foreign_id?: string; + time?: string; +}; -export type UpdateActivity = BaseActivity & { foreign_id: string; time: string }; +export type UpdateActivity = BaseActivity & { + foreign_id: string; + time: string; +}; -export type Activity = BaseActivity & { +export type Activity = BaseActivity & { foreign_id: string; id: string; time: string; analytics?: Record; // ranked feeds only - extra_context?: Record; + extra_context?: UnknownRecord; origin?: string; score?: number; // ranked feeds only }; -export type ReactionsRecords = Record< - string, - EnrichedReaction[] ->; - -export type EnrichedActivity = Activity< - ActivityType -> & { +export type ReactionsRecords< + ReactionType extends UnknownRecord = UnknownRecord, + ChildReactionType extends UnknownRecord = UnknownRecord, + UserType extends UnknownRecord = UnknownRecord +> = Record[]>; + +export type EnrichedActivity< + UserType extends UnknownRecord = UnknownRecord, + ActivityType extends UnknownRecord = UnknownRecord, + CollectionType extends UnknownRecord = UnknownRecord, + ReactionType extends UnknownRecord = UnknownRecord, + ChildReactionType extends UnknownRecord = UnknownRecord +> = Activity & { actor: UserType | string; object: | string @@ -98,14 +109,14 @@ export type EnrichedActivity; }; -export type FlatActivity = Activity; +export type FlatActivity = Activity; export type FlatActivityEnriched< - UserType, - ActivityType, - CollectionType, - ReactionType, - ChildReactionType + UserType extends UnknownRecord = UnknownRecord, + ActivityType extends UnknownRecord = UnknownRecord, + CollectionType extends UnknownRecord = UnknownRecord, + ReactionType extends UnknownRecord = UnknownRecord, + ChildReactionType extends UnknownRecord = UnknownRecord > = EnrichedActivity; type BaseAggregatedActivity = { @@ -119,34 +130,43 @@ type BaseAggregatedActivity = { score?: number; }; -export type AggregatedActivity = BaseAggregatedActivity & { +export type AggregatedActivity = BaseAggregatedActivity & { activities: Activity[]; }; export type AggregatedActivityEnriched< - UserType, - ActivityType, - CollectionType, - ReactionType, - ChildReactionType + UserType extends UnknownRecord = UnknownRecord, + ActivityType extends UnknownRecord = UnknownRecord, + CollectionType extends UnknownRecord = UnknownRecord, + ReactionType extends UnknownRecord = UnknownRecord, + ChildReactionType extends UnknownRecord = UnknownRecord > = BaseAggregatedActivity & { activities: EnrichedActivity; }; type BaseNotificationActivity = { is_read: boolean; is_seen: boolean }; -export type NotificationActivity = AggregatedActivity & BaseNotificationActivity; +export type NotificationActivity = AggregatedActivity< + ActivityType +> & + BaseNotificationActivity; export type NotificationActivityEnriched< - UserType, - ActivityType, - CollectionType, - ReactionType, - ChildReactionType + UserType extends UnknownRecord = UnknownRecord, + ActivityType extends UnknownRecord = UnknownRecord, + CollectionType extends UnknownRecord = UnknownRecord, + ReactionType extends UnknownRecord = UnknownRecord, + ChildReactionType extends UnknownRecord = UnknownRecord > = BaseNotificationActivity & AggregatedActivityEnriched; -export type FeedAPIResponse = APIResponse & { +export type FeedAPIResponse< + UserType extends UnknownRecord = UnknownRecord, + ActivityType extends UnknownRecord = UnknownRecord, + CollectionType extends UnknownRecord = UnknownRecord, + ReactionType extends UnknownRecord = UnknownRecord, + ChildReactionType extends UnknownRecord = UnknownRecord +> = APIResponse & { next: string; results: | FlatActivity[] @@ -162,11 +182,11 @@ export type FeedAPIResponse = APIResponse & { limit: number; next: string; @@ -176,11 +196,11 @@ export type PersonalizationFeedAPIResponse< }; export type GetActivitiesAPIResponse< - UserType, - ActivityType, - CollectionType, - ReactionType, - ChildReactionType + UserType extends UnknownRecord = UnknownRecord, + ActivityType extends UnknownRecord = UnknownRecord, + CollectionType extends UnknownRecord = UnknownRecord, + ReactionType extends UnknownRecord = UnknownRecord, + ChildReactionType extends UnknownRecord = UnknownRecord > = APIResponse & { results: | FlatActivity[] @@ -193,11 +213,11 @@ export type GetActivitiesAPIResponse< * @class StreamFeed */ export default class StreamFeed< - UserType = unknown, - ActivityType = unknown, - CollectionType = unknown, - ReactionType = unknown, - ChildReactionType = unknown + UserType extends UnknownRecord = UnknownRecord, + ActivityType extends UnknownRecord = UnknownRecord, + CollectionType extends UnknownRecord = UnknownRecord, + ReactionType extends UnknownRecord = UnknownRecord, + ChildReactionType extends UnknownRecord = UnknownRecord > { client: StreamClient; token: string; diff --git a/src/personalization.ts b/src/personalization.ts index 4a1afb52..d6ef1492 100644 --- a/src/personalization.ts +++ b/src/personalization.ts @@ -1,4 +1,4 @@ -import StreamClient, { APIResponse } from './client'; +import StreamClient, { APIResponse, UnknownRecord } from './client'; /** * Manage api calls for personalization @@ -6,7 +6,7 @@ import StreamClient, { APIResponse } from './client'; * @class Personalization */ -export type PersonalizationAPIResponse = APIResponse & { +export type PersonalizationAPIResponse = APIResponse & { app_id: string; next: string; results: PersonalizationType[]; @@ -15,7 +15,7 @@ export type PersonalizationAPIResponse = APIResponse & { version?: string; }; -export default class Personalization { +export default class Personalization { client: StreamClient; constructor(client: StreamClient) { @@ -48,7 +48,7 @@ export default class Personalization { }); } - post(resource: string, options: Record = {}, data: Record = {}) { + post(resource: string, options: Record = {}, data: UnknownRecord = {}) { /** * Post data to personalization endpoint * diff --git a/src/reaction.ts b/src/reaction.ts index 544ee14a..2bb4970d 100644 --- a/src/reaction.ts +++ b/src/reaction.ts @@ -19,7 +19,7 @@ type ReactionBody = { user_id?: string; // optional when using client tokens }; -export type Reaction = { +export type Reaction = { activity_id: string; created_at: string; data: T; @@ -32,19 +32,31 @@ export type Reaction = { target_feeds_extra_data?: TargetFeedsExtraData; }; -export type ReactionAPIResponse = APIResponse & Reaction; +export type ReactionAPIResponse = APIResponse & Reaction; -export type EnrichedReaction = Reaction & { +export type EnrichedReaction< + ReactionType extends UnknownRecord = UnknownRecord, + ChildReactionType extends UnknownRecord = UnknownRecord, + UserType extends UnknownRecord = UnknownRecord +> = Reaction & { children_counts: Record; latest_children: Record; own_children?: Record; user?: UserType; }; -export type EnrichedReactionAPIResponse = APIResponse & - EnrichedReaction; +export type EnrichedReactionAPIResponse< + ReactionType extends UnknownRecord = UnknownRecord, + ChildReactionType extends UnknownRecord = UnknownRecord, + UserType extends UnknownRecord = UnknownRecord +> = APIResponse & EnrichedReaction; -export type ReactionFilterAPIResponse = APIResponse & { +export type ReactionFilterAPIResponse< + ReactionType extends UnknownRecord = UnknownRecord, + ChildReactionType extends UnknownRecord = UnknownRecord, + ActivityType extends UnknownRecord = UnknownRecord, + UserType extends UnknownRecord = UnknownRecord +> = APIResponse & { next: string; results: | ReactionAPIResponse[] @@ -52,7 +64,13 @@ export type ReactionFilterAPIResponse { +export default class StreamReaction< + UserType extends UnknownRecord = UnknownRecord, + ActivityType extends UnknownRecord = UnknownRecord, + CollectionType extends UnknownRecord = UnknownRecord, + ReactionType extends UnknownRecord = UnknownRecord, + ChildReactionType extends UnknownRecord = UnknownRecord +> { client: StreamClient; token: string; diff --git a/src/user.ts b/src/user.ts index f575b265..84245475 100644 --- a/src/user.ts +++ b/src/user.ts @@ -1,6 +1,6 @@ -import StreamClient, { APIResponse } from './client'; +import StreamClient, { APIResponse, UnknownRecord } from './client'; -export type UserAPIResponse = APIResponse & { +export type UserAPIResponse = APIResponse & { created_at: string; data: UserType; id: string; @@ -9,7 +9,7 @@ export type UserAPIResponse = APIResponse & { following_count?: number; }; -export default class StreamUser { +export default class StreamUser { client: StreamClient; token: string; id: string; From 81a4aa84d8d1e9deef69caf4453e0e6f802cd20c Mon Sep 17 00:00:00 2001 From: Amin Mahboubi Date: Mon, 3 Aug 2020 17:09:37 +0200 Subject: [PATCH 59/69] make user get/create options optional --- src/user.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/user.ts b/src/user.ts index 84245475..bde3ca8a 100644 --- a/src/user.ts +++ b/src/user.ts @@ -46,7 +46,7 @@ export default class StreamUser }); } - async get(options: { with_follow_counts?: boolean }) { + async get(options?: { with_follow_counts?: boolean }) { const response = await this.client.get>({ url: this.url, signature: this.token, @@ -59,7 +59,7 @@ export default class StreamUser return this; } - async create(data: UserType, options: { get_or_create?: boolean }) { + async create(data?: UserType, options?: { get_or_create?: boolean }) { const response = await this.client.post>({ url: 'user/', body: { From 94be63edbe60052a53d3b6036e38ea1ad932a0aa Mon Sep 17 00:00:00 2001 From: Amin Mahboubi Date: Mon, 3 Aug 2020 17:15:26 +0200 Subject: [PATCH 60/69] add basic typescript usage to README --- README.md | 66 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) diff --git a/README.md b/README.md index 1cec9eea..99dd936f 100644 --- a/README.md +++ b/README.md @@ -258,6 +258,72 @@ client.feed('user', 'ken').updateActivityToTargets('foreign_id:1234', timestamp, client.feed('user', 'ken').updateActivityToTargets('foreign_id:1234', timestamp, null, null, ['feed:1234']); ``` +### Typescript + +```typescript +import { connect, EnrichedActivity, NotificationActivity } from getstream; + +type User1Type = { name: string; username: string; image?: string }; +type User2Type = { name: string; avatar?: string }; +type ActivityType = { attachments: string[]; text: string }; +type Collection1Type = { cid: string; rating?: number }; +type Collection2Type = { branch: number; location: string }; + +type ReactionType = { text: string }; +type ChildReactionType = { text?: string }; + +const client = connect< + User1Type | User2Type, + ActivityType, + Collection1Type | Collection2Type, + ReactionType, + ChildReactionType +>('api_key', 'secret!', 'app_id'); + +// if you have different union types like "User1Type | User2Type" you can use type guards as follow: +// https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-guards-and-differentiating-types +function isUser1Type(user: User1Type | User2Type): user is User1Type { + return (user as User1Type).username !== undefined; +} + +client + .user('user_id') + .get() + .then((user) => { + const { data, id } = user; + if (isUser1Type(data)) return data.username; + return id; + }); + +// notification: StreamFeed +const timeline = client.feed('timeline', 'feed_id'); +timeline.get({ withOwnChildren: true, withOwnReactions: true }).then((response) => { + // response: FeedAPIResponse + if (response.next !== '') return response.next; + + return (response.results as EnrichedActivity[]).map((activity) => { + return activity.id + activity.text + (activity.actor as User2Type).name; + }); +}); + +// notification: StreamFeed +const notification = client.feed('notification', 'feed_id'); +notification.get({ mark_read: true, mark_seen: true }).then((response) => { + // response: FeedAPIResponse + if (response.unread || response.unseen) return response.next; + + return (response.results as NotificationActivity[]).map((activityGroup) => { + const { activities, id, verb, activity_count, actor_count } = activityGroup; + return activities[0].text + id + actor_count + activity_count + verb; + }); +}); + +client.collections.get('collection_1', 'taco').then((item: CollectionEntry) => { + if (item.data.rating) return { [item.data.cid]: item.data.rating }; + return item.id; +}); +``` + ### Realtime (Faye) Stream uses [Faye](http://faye.jcoglan.com/browser.html) for realtime notifications. Below is quick guide to subscribing to feed changes From 4838ec1de300507e689ebe351d1219f0d9fa8611 Mon Sep 17 00:00:00 2001 From: Amin Mahboubi Date: Mon, 3 Aug 2020 17:15:46 +0200 Subject: [PATCH 61/69] export CollectionEntry type --- src/collections.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/collections.ts b/src/collections.ts index 6dcf8c99..35f717f7 100644 --- a/src/collections.ts +++ b/src/collections.ts @@ -39,7 +39,7 @@ export type UpsertCollectionAPIResponse { +export class CollectionEntry { id: string; collection: string; store: Collections; From 8f70653de862cd54c93e26aef51453b5ca7ebeb1 Mon Sep 17 00:00:00 2001 From: Amin Mahboubi Date: Mon, 10 Aug 2020 15:09:21 +0200 Subject: [PATCH 62/69] add latest_children_extra type --- src/reaction.ts | 1 + src/user.ts | 1 + 2 files changed, 2 insertions(+) diff --git a/src/reaction.ts b/src/reaction.ts index 2bb4970d..47b049db 100644 --- a/src/reaction.ts +++ b/src/reaction.ts @@ -41,6 +41,7 @@ export type EnrichedReaction< > = Reaction & { children_counts: Record; latest_children: Record; + latest_children_extra?: Record; own_children?: Record; user?: UserType; }; diff --git a/src/user.ts b/src/user.ts index bde3ca8a..ea8428c9 100644 --- a/src/user.ts +++ b/src/user.ts @@ -5,6 +5,7 @@ export type UserAPIResponse = AP data: UserType; id: string; updated_at: string; + // present only in profile response followers_count?: number; following_count?: number; }; From 44f3c4bea7d66844b1ea871e34825aafa6e1d50d Mon Sep 17 00:00:00 2001 From: Amin Mahboubi Date: Mon, 10 Aug 2020 18:06:44 +0200 Subject: [PATCH 63/69] fix ActivityPartialChanges unset type --- src/client.ts | 24 +++++++++++++----------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/src/client.ts b/src/client.ts index 411d66d4..a0863268 100644 --- a/src/client.ts +++ b/src/client.ts @@ -102,12 +102,12 @@ type AxiosConfig = { export type HandlerCallback = (...args: unknown[]) => unknown; -export type ActivityPartialChanges = { - foreignID?: string; +export type ForeignIDTimes = { foreignID: string; time: Date | string }; + +export type ActivityPartialChanges = Partial & { id?: string; - set?: UnknownRecord; - time?: Date | string; - unset?: string[]; + set?: Partial; + unset?: Array>; }; /** @@ -739,7 +739,7 @@ export default class StreamClient< foreignIDTimes, ...params }: EnrichOptions & { - foreignIDTimes?: { foreignID: string; time: Date | string }[]; + foreignIDTimes?: ForeignIDTimes[]; ids?: string[]; reactions?: Record; }) { @@ -838,11 +838,13 @@ export default class StreamClient< }); } - async activityPartialUpdate(data: ActivityPartialChanges): Promise> { + async activityPartialUpdate( + data: ActivityPartialChanges, + ): Promise> { /** * Update a single activity with partial operations. * @since 3.20.0 - * @param {ActivityPartialChanges} data object containing either the ID or the foreign ID and time of the activity and the operations to issue as set:{...} and unset:[...]. + * @param {ActivityPartialChanges} data object containing either the ID or the foreign ID and time of the activity and the operations to issue as set:{...} and unset:[...]. * @return {Promise>} * @example * client.activityPartialUpdate({ @@ -877,11 +879,11 @@ export default class StreamClient< return { ...activity, ...response }; } - activitiesPartialUpdate(changes: ActivityPartialChanges[]) { + activitiesPartialUpdate(changes: ActivityPartialChanges[]) { /** * Update multiple activities with partial operations. * @since v3.20.0 - * @param {ActivityPartialChanges[]} changes array containing the changesets to be applied. Every changeset contains the activity identifier which is either the ID or the pair of of foreign ID and time of the activity. The operations to issue can be set:{...} and unset:[...]. + * @param {ActivityPartialChanges[]} changes array containing the changesets to be applied. Every changeset contains the activity identifier which is either the ID or the pair of of foreign ID and time of the activity. The operations to issue can be set:{...} and unset:[...]. * @return {Promise<{ activities: Activity[] }>} * @example * client.activitiesPartialUpdate([ @@ -935,7 +937,7 @@ export default class StreamClient< if (!(changes instanceof Array)) { throw new TypeError('changes should be an Array'); } - changes.forEach(function (item: ActivityPartialChanges & { foreign_id?: string }) { + changes.forEach(function (item: ActivityPartialChanges & { foreign_id?: string }) { if (!(item instanceof Object)) { throw new TypeError(`changeset should be and Object`); } From 31af38e846a79b380b321b1c728cfa1766a1c33a Mon Sep 17 00:00:00 2001 From: Amin Mahboubi Date: Mon, 10 Aug 2020 18:22:22 +0200 Subject: [PATCH 64/69] basic sanity typescript test --- package.json | 1 + test/typescript/test.ts | 264 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 265 insertions(+) create mode 100644 test/typescript/test.ts diff --git a/package.json b/package.json index 9f51df5a..63d0cfaf 100644 --- a/package.json +++ b/package.json @@ -22,6 +22,7 @@ "lint": "yarn run prettier && yarn run eslint", "lint-fix": "prettier --write '**/*.{js,ts}' && eslint --fix '**/*.{js,ts}'", "test": "yarn run test-unit-node", + "test-types": "tsc --esModuleInterop true --noEmit true test/typescript/*.ts", "test-unit-node": "mocha --require ./babel-register.js test/unit/common test/unit/node", "test-integration-node": "mocha --require ./babel-register.js test/integration/common test/integration/node --exit", "test-cloud": "mocha --require ./babel-register.js test/integration/cloud --timeout 40000", diff --git a/test/typescript/test.ts b/test/typescript/test.ts new file mode 100644 index 00000000..090bb0d3 --- /dev/null +++ b/test/typescript/test.ts @@ -0,0 +1,264 @@ +/* eslint-disable */ +import * as Faye from 'faye'; +import { + connect, + Client, + EnrichedActivity, + NotificationActivity, + APIResponse, + FileUploadAPIResponse, + GetActivitiesAPIResponse, + OGAPIResponse, + PersonalizationFeedAPIResponse, + Activity, + CollectionEntry, +} from '../../lib'; +import StreamUser from '../../lib/user'; +import StreamFeed, { FeedAPIResponse, FlatActivity } from '../../lib/feed'; + +type UserType = { name: string; image?: string }; +type ActivityType = { aText: string; attachments?: string[] }; +type CollectionType = { cid: string }; +type ReactionType = { rText: string }; +type ChildReactionType = { cText: string }; +type T = {}; + +let voidReturn: void; +let voidPromise: Promise; +let emptyAPIPromise: Promise; + +let client: Client = connect< + UserType, + ActivityType, + CollectionType, + ReactionType, + ChildReactionType +>('api_key', 'secret!', 'app_id'); + +client = new Client( + 'api_key', + 'secret!', + 'app_id', +); + +connect('', null); +connect('', null, '', {}); +connect('', null, '', { timeout: 3000, keepAlive: true, expireTokens: false }); + +new Client('', null); +new Client('', null, '', {}); +new Client('', null, '', { timeout: 3000, keepAlive: true, expireTokens: false }); + +// @ts-expect-error +connect('', null, true, {}); +// @ts-expect-error +connect('', null, '', { missingOption: '' }); +// @ts-expect-error +new Client('', '', true, {}); +// @ts-expect-error +new Client('', '', '', { missingOption: '' }); + +const agent: string = client.userAgent(); + +const token: string = client.getOrCreateToken(); +const pToken: string = client.getPersonalizationToken(); +const cToken: string = client.getCollectionsToken(); +const aToken: string = client.getAnalyticsToken(); +const rToken: string = client.getReadOnlyToken('', ''); +const rwToken: string = client.getReadWriteToken('', ''); +const uToken: string = client.createUserToken(''); +client.createUserToken('', { anything: {} }); +// @ts-expect-error +client.getReadOnlyToken(); +// @ts-expect-error +client.getReadWriteToken(); + +const baseUrl: string = client.getBaseUrl(); +client.getBaseUrl('api'); + +const enrichedUrl: string = client.enrichUrl(''); +client.enrichUrl('', ''); + +// @ts-expect-error +client.enrichUrl(); + +voidReturn = client.on('', () => {}); +// @ts-expect-error +client.on(''); +voidReturn = client.off(); +voidReturn = client.off(''); + +voidReturn = client.send(''); +client.send('', 1, 3, true, []); + +const shouldEnrich: boolean = client.shouldUseEnrichEndpoint(); + +client.shouldUseEnrichEndpoint({ + enrich: true, + ownReactions: true, + withOwnChildren: true, + withReactionCounts: true, + withRecentReactions: true, +}); +// @ts-expect-error +client.shouldUseEnrichEndpoint({ enrich: '' }); + +const faye: Faye.Client = client.getFayeClient(); +client.getFayeClient(100); + +const upload: Promise = client.upload('/file', 'uri'); + +client.upload('/image', new File([], '')); +client.upload('/image', new File([], ''), '', ''); +// @ts-expect-error +client.upload('/image', []); + +const ogPromise: Promise = client.og(''); +ogPromise.then((og) => { + const { title } = og; + const { site } = og; + const { url } = og; + og.images[0].url as string; + og.images[0].width as number; + // @ts-expect-error + og.images[0].url as number; +}); +// @ts-expect-error +client.og(); + +const axiosConfig = { signature: '', url: '' }; +const response: T = client.handleResponse({ data: {}, status: 100, statusText: '', headers: {}, config: {} }); +const axiosReq: Promise = client.doAxiosRequest('GET', axiosConfig); +// @ts-expect-error +client.doAxiosRequest('', {}); +// @ts-expect-error +client.doAxiosRequest('POST', {}); + +const get: T = client.get(axiosConfig); +const post: T = client.post(axiosConfig); +const put: T = client.put(axiosConfig); +const del: T = client.delete(axiosConfig); +emptyAPIPromise = client.delete(axiosConfig); +// @ts-expect-error +client.get(); + +const emptyActivity = { + foreign_id: '', + time: '', + verb: '', + actor: '', + object: '', +}; +emptyAPIPromise = client.updateActivity({ ...emptyActivity, aText: '' }); +emptyAPIPromise = client.updateActivities([{ ...emptyActivity, aText: '' }]); +// @ts-expect-error +client.updateActivity(emptyActivity); +// @ts-expect-error +client.updateActivities([emptyActivity]); + +const partialUpdatePromise: Promise> = client.activityPartialUpdate({ + id: '', + set: { aText: '' }, + unset: ['attachments'], +}); +client.activityPartialUpdate({ time: '', foreignID: '', unset: ['aText'] }); + +// @ts-expect-error +client.activityPartialUpdate({ unset: ['missing'] }); +// @ts-expect-error +client.activityPartialUpdate({ set: { missing: '' } }); + +const partialUpdatesPromise: Promise<{ activities: Activity[] }> = client.activitiesPartialUpdate([ + { + id: '', + set: { aText: '' }, + unset: ['attachments'], + }, +]); +client.activitiesPartialUpdate([{ time: '', foreignID: '', unset: ['aText'] }]); + +// @ts-expect-error +client.activityPartialUpdate([{ unset: ['missing'] }]); +// @ts-expect-error +client.activityPartialUpdate([{ set: { missing: '' } }]); + +const activitiesPromise: Promise> = client.getActivities({ ids: ['', ''] }); +activitiesPromise.then(({ results }) => { + results[0].id as string; + results[0].time as string; + results[0].foreign_id as string; + results[0].actor as string; + const object: string = results[0].object as string; + results[0].aText as string; +}); + +client.getActivities({ foreignIDTimes: [{ foreignID: '', time: '' }] }); +client.getActivities({ ids: ['', ''], enrich: true, ownReactions: true }); +client.getActivities({}); +// @ts-expect-error +client.getActivities(); + +const pFeedPromise: Promise> = client.personalizedFeed({ enrich: true }); +pFeedPromise.then((pFeed) => { + pFeed.results as Array; + pFeed.version as string; + pFeed.next as string; + pFeed.limit as number; + pFeed.offset as number; +}); + +const userPromise: Promise> = client.setUser({ name: '' }); +// @ts-expect-error +client.setUser({ username: '' }); + +const user: StreamUser = client.user('user_id'); +const userGet: Promise> = client.user('user_id').get(); +client.user('user_id').get({ with_follow_counts: true }); +// @ts-expect-error +client.user('user_id').get({ with_follow_counts: 1 }); +// @ts-expect-error +client.user('user_id').get({ list: true }); + +const timeline: StreamFeed = client.feed( + 'timeline', + 'feed_id', +); + +timeline + .get({ withOwnChildren: true, withOwnReactions: true }) + .then((response: FeedAPIResponse) => { + response.next as string; + response.unread as number; + response.unseen as number; + response.results as FlatActivity[]; + }); + +client + .feed('notification', 'feed_id') + .get({ mark_read: true, mark_seen: true }) + .then((response) => { + response.next as string; + response.unread as number; + response.unseen as number; + response.results as NotificationActivity[]; + }); + +const collection: Promise> = client.collections.get('collection_1', 'taco'); + +collection.then((item) => { + item.id as string; + item.data.cid as string; + item.collection as string; +}); From 1eb15d301c5a6d98b580ad024ec250b3354a401e Mon Sep 17 00:00:00 2001 From: Amin Mahboubi Date: Mon, 10 Aug 2020 18:23:13 +0200 Subject: [PATCH 65/69] add test-types cmd to CI --- .github/workflows/ci.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index eacca9be..e5737867 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -44,4 +44,5 @@ jobs: if [ "$CLOUD_TESTS" == "yes" ]; then yarn run test-integration-node; fi if [ "$RUN_LINTERS" == "yes" ]; then yarn run lint; fi if [ "$RUN_LINTERS" == "yes" ]; then yarn run types; fi + if [ "$RUN_LINTERS" == "yes" ]; then yarn run test-types; fi if [ "$BROWSER_TESTS" == "yes" ]; then yarn run test-browser; fi From 1a77392bb84caf029e8e2f9f2e93c874057a9b51 Mon Sep 17 00:00:00 2001 From: Amin Mahboubi Date: Tue, 11 Aug 2020 14:24:02 +0200 Subject: [PATCH 66/69] bump dependencies --- package.json | 40 ++-- yarn.lock | 503 ++++++++++++++++++++++++++++++++++----------------- 2 files changed, 353 insertions(+), 190 deletions(-) diff --git a/package.json b/package.json index 63d0cfaf..9433c1c6 100644 --- a/package.json +++ b/package.json @@ -57,23 +57,23 @@ "url": false }, "devDependencies": { - "@babel/cli": "^7.10.4", - "@babel/core": "^7.10.4", - "@babel/node": "^7.10.4", + "@babel/cli": "^7.10.5", + "@babel/core": "^7.11.1", + "@babel/node": "^7.10.5", "@babel/plugin-proposal-class-properties": "^7.10.4", - "@babel/plugin-proposal-object-rest-spread": "^7.10.4", + "@babel/plugin-proposal-object-rest-spread": "^7.11.0", "@babel/plugin-transform-object-assign": "^7.10.4", - "@babel/plugin-transform-runtime": "^7.10.4", - "@babel/preset-env": "^7.10.4", + "@babel/plugin-transform-runtime": "^7.11.0", + "@babel/preset-env": "^7.11.0", "@babel/preset-typescript": "^7.10.4", - "@babel/register": "^7.10.4", - "@typescript-eslint/eslint-plugin": "^3.6.1", - "@typescript-eslint/parser": "^3.6.1", + "@babel/register": "^7.10.5", + "@typescript-eslint/eslint-plugin": "^3.9.0", + "@typescript-eslint/parser": "^3.9.0", "babel-eslint": "^10.1.0", "babel-loader": "^8.1.0", "chai": "^4.2.0", - "codecov": "^3.7.1", - "eslint": "^7.3.1", + "codecov": "^3.7.2", + "eslint": "^7.6.0", "eslint-config-airbnb-base": "^14.2.0", "eslint-config-prettier": "^6.11.0", "eslint-plugin-chai-friendly": "^0.6.0", @@ -83,34 +83,34 @@ "eslint-plugin-typescript-sort-keys": "^1.3.0", "expect.js": "^0.3.1", "husky": "^4.2.5", - "jsdoc": "^3.6.4", + "jsdoc": "^3.6.5", "json-loader": "~0.5.7", - "karma": "^5.1.0", + "karma": "^5.1.1", "karma-chrome-launcher": "^3.1.0", "karma-mocha": "^2.0.1", "karma-mocha-reporter": "~2.2.5", "karma-sauce-launcher": "^4.1.5", "karma-sourcemap-loader": "~0.3.7", "karma-webpack": "^4.0.2", - "mocha": "^8.0.1", + "mocha": "^8.1.1", "null-loader": "^4.0.0", "nyc": "^15.1.0", "prettier": "^2.0.5", "request": "^2.88.2", - "testdouble": "^3.16.0", - "typescript": "^3.9.6", + "testdouble": "^3.16.1", + "typescript": "^3.9.7", "uglifyjs-webpack-plugin": "^2.2.0", - "webpack": "^4.43.0", + "webpack": "^4.44.1", "webpack-cli": "^3.3.12" }, "dependencies": { - "@babel/runtime": "^7.10.4", + "@babel/runtime": "^7.11.2", "@types/jsonwebtoken": "^8.5.0", - "@types/jwt-decode": "^2.2.0", + "@types/jwt-decode": "^2.2.1", "@types/qs": "^6.9.4", "Base64": "^1.1.0", "axios": "^0.19.2", - "faye": "^1.3.0", + "faye": "^1.4.0", "form-data": "^3.0.0", "jsonwebtoken": "^8.5.1", "jwt-decode": "^2.2.0", diff --git a/yarn.lock b/yarn.lock index 97bbe8a4..81cb3df8 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2,16 +2,16 @@ # yarn lockfile v1 -"@babel/cli@^7.10.4": - version "7.10.4" - resolved "https://registry.yarnpkg.com/@babel/cli/-/cli-7.10.4.tgz#ba38ad6d0b4b772a67b106934b7c33d656031896" - integrity sha512-xX99K4V1BzGJdQANK5cwK+EpF1vP9gvqhn+iWvG+TubCjecplW7RSQimJ2jcCvu6fnK5pY6mZMdu6EWTj32QVA== +"@babel/cli@^7.10.5": + version "7.10.5" + resolved "https://registry.yarnpkg.com/@babel/cli/-/cli-7.10.5.tgz#57df2987c8cf89d0fc7d4b157ec59d7619f1b77a" + integrity sha512-j9H9qSf3kLdM0Ao3aGPbGZ73mEA9XazuupcS6cDGWuiyAcANoguhP0r2Lx32H5JGw4sSSoHG3x/mxVnHgvOoyA== dependencies: commander "^4.0.1" convert-source-map "^1.1.0" fs-readdir-recursive "^1.1.0" glob "^7.0.0" - lodash "^4.17.13" + lodash "^4.17.19" make-dir "^2.1.0" slash "^2.0.0" source-map "^0.5.0" @@ -41,24 +41,33 @@ invariant "^2.2.4" semver "^5.5.0" -"@babel/core@^7.10.4": - version "7.10.4" - resolved "https://registry.yarnpkg.com/@babel/core/-/core-7.10.4.tgz#780e8b83e496152f8dd7df63892b2e052bf1d51d" - integrity sha512-3A0tS0HWpy4XujGc7QtOIHTeNwUgWaZc/WuS5YQrfhU67jnVmsD6OGPc1AKHH0LJHQICGncy3+YUjIhVlfDdcA== +"@babel/compat-data@^7.11.0": + version "7.11.0" + resolved "https://registry.yarnpkg.com/@babel/compat-data/-/compat-data-7.11.0.tgz#e9f73efe09af1355b723a7f39b11bad637d7c99c" + integrity sha512-TPSvJfv73ng0pfnEOh17bYMPQbI95+nGWc71Ss4vZdRBHTDqmM9Z8ZV4rYz8Ks7sfzc95n30k6ODIq5UGnXcYQ== + dependencies: + browserslist "^4.12.0" + invariant "^2.2.4" + semver "^5.5.0" + +"@babel/core@^7.11.1": + version "7.11.1" + resolved "https://registry.yarnpkg.com/@babel/core/-/core-7.11.1.tgz#2c55b604e73a40dc21b0e52650b11c65cf276643" + integrity sha512-XqF7F6FWQdKGGWAzGELL+aCO1p+lRY5Tj5/tbT3St1G8NaH70jhhDIKknIZaDans0OQBG5wRAldROLHSt44BgQ== dependencies: "@babel/code-frame" "^7.10.4" - "@babel/generator" "^7.10.4" - "@babel/helper-module-transforms" "^7.10.4" + "@babel/generator" "^7.11.0" + "@babel/helper-module-transforms" "^7.11.0" "@babel/helpers" "^7.10.4" - "@babel/parser" "^7.10.4" + "@babel/parser" "^7.11.1" "@babel/template" "^7.10.4" - "@babel/traverse" "^7.10.4" - "@babel/types" "^7.10.4" + "@babel/traverse" "^7.11.0" + "@babel/types" "^7.11.0" convert-source-map "^1.7.0" debug "^4.1.0" gensync "^1.0.0-beta.1" json5 "^2.1.2" - lodash "^4.17.13" + lodash "^4.17.19" resolve "^1.3.2" semver "^5.4.1" source-map "^0.5.0" @@ -114,6 +123,15 @@ jsesc "^2.5.1" source-map "^0.5.0" +"@babel/generator@^7.11.0": + version "7.11.0" + resolved "https://registry.yarnpkg.com/@babel/generator/-/generator-7.11.0.tgz#4b90c78d8c12825024568cbe83ee6c9af193585c" + integrity sha512-fEm3Uzw7Mc9Xi//qU20cBKatTfs2aOtKqmvy/Vm7RkJEGFQ4xc9myCfbXxqK//ZS8MR/ciOHw6meGASJuKmDfQ== + dependencies: + "@babel/types" "^7.11.0" + jsesc "^2.5.1" + source-map "^0.5.0" + "@babel/helper-annotate-as-pure@^7.10.1": version "7.10.1" resolved "https://registry.yarnpkg.com/@babel/helper-annotate-as-pure/-/helper-annotate-as-pure-7.10.1.tgz#f6d08acc6f70bbd59b436262553fb2e259a1a268" @@ -306,6 +324,19 @@ "@babel/types" "^7.10.4" lodash "^4.17.13" +"@babel/helper-module-transforms@^7.11.0": + version "7.11.0" + resolved "https://registry.yarnpkg.com/@babel/helper-module-transforms/-/helper-module-transforms-7.11.0.tgz#b16f250229e47211abdd84b34b64737c2ab2d359" + integrity sha512-02EVu8COMuTRO1TAzdMtpBPbe6aQ1w/8fePD2YgQmxZU4gpNWaL9gK3Jp7dxlkUlUCJOTaSeA+Hrm1BRQwqIhg== + dependencies: + "@babel/helper-module-imports" "^7.10.4" + "@babel/helper-replace-supers" "^7.10.4" + "@babel/helper-simple-access" "^7.10.4" + "@babel/helper-split-export-declaration" "^7.11.0" + "@babel/template" "^7.10.4" + "@babel/types" "^7.11.0" + lodash "^4.17.19" + "@babel/helper-optimise-call-expression@^7.10.1": version "7.10.1" resolved "https://registry.yarnpkg.com/@babel/helper-optimise-call-expression/-/helper-optimise-call-expression-7.10.1.tgz#b4a1f2561870ce1247ceddb02a3860fa96d72543" @@ -325,7 +356,7 @@ resolved "https://registry.yarnpkg.com/@babel/helper-plugin-utils/-/helper-plugin-utils-7.10.1.tgz#ec5a5cf0eec925b66c60580328b122c01230a127" integrity sha512-fvoGeXt0bJc7VMWZGCAEBEMo/HAjW2mP8apF5eXK0wSqwLAVHAISCWRoLMBMUs2kqeaG77jltVqu4Hn8Egl3nA== -"@babel/helper-plugin-utils@^7.10.4": +"@babel/helper-plugin-utils@^7.10.4", "@babel/helper-plugin-utils@^7.8.3": version "7.10.4" resolved "https://registry.yarnpkg.com/@babel/helper-plugin-utils/-/helper-plugin-utils-7.10.4.tgz#2f75a831269d4f677de49986dff59927533cf375" integrity sha512-O4KCvQA6lLiMU9l2eawBPMf1xPP8xPfB3iEQw150hOVTqj/rfXz0ThTb4HEzqQfs2Bmo5Ay8BzxfzVtBrr9dVg== @@ -391,6 +422,13 @@ "@babel/template" "^7.10.4" "@babel/types" "^7.10.4" +"@babel/helper-skip-transparent-expression-wrappers@^7.11.0": + version "7.11.0" + resolved "https://registry.yarnpkg.com/@babel/helper-skip-transparent-expression-wrappers/-/helper-skip-transparent-expression-wrappers-7.11.0.tgz#eec162f112c2f58d3af0af125e3bb57665146729" + integrity sha512-0XIdiQln4Elglgjbwo9wuJpL/K7AGCY26kmEt0+pRP0TAj4jjyNq1MjoRvikrTVqKcx4Gysxt4cXvVFXP/JO2Q== + dependencies: + "@babel/types" "^7.11.0" + "@babel/helper-split-export-declaration@^7.10.1": version "7.10.1" resolved "https://registry.yarnpkg.com/@babel/helper-split-export-declaration/-/helper-split-export-declaration-7.10.1.tgz#c6f4be1cbc15e3a868e4c64a17d5d31d754da35f" @@ -405,6 +443,13 @@ dependencies: "@babel/types" "^7.10.4" +"@babel/helper-split-export-declaration@^7.11.0": + version "7.11.0" + resolved "https://registry.yarnpkg.com/@babel/helper-split-export-declaration/-/helper-split-export-declaration-7.11.0.tgz#f8a491244acf6a676158ac42072911ba83ad099f" + integrity sha512-74Vejvp6mHkGE+m+k5vHY93FX2cAtrw1zXrZXRlG4l410Nm9PxfEiVTn1PjDPV5SnmieiueY4AFg2xqhNFuuZg== + dependencies: + "@babel/types" "^7.11.0" + "@babel/helper-validator-identifier@^7.10.1": version "7.10.1" resolved "https://registry.yarnpkg.com/@babel/helper-validator-identifier/-/helper-validator-identifier-7.10.1.tgz#5770b0c1a826c4f53f5ede5e153163e0318e94b5" @@ -461,15 +506,15 @@ chalk "^2.0.0" js-tokens "^4.0.0" -"@babel/node@^7.10.4": - version "7.10.4" - resolved "https://registry.yarnpkg.com/@babel/node/-/node-7.10.4.tgz#f246ac8a63dddbd5f084fd90be58ee0b904378b7" - integrity sha512-U41uyQkG0J1ezCb8KCdhDJotQF68Z/OsUbcgdxaC0M4JoXKZVdaKQJ+ecnr7aaWjNLt0Vee6Vddj6VL4JEMJnQ== +"@babel/node@^7.10.5": + version "7.10.5" + resolved "https://registry.yarnpkg.com/@babel/node/-/node-7.10.5.tgz#30866322aa2c0251a9bdd73d07a9167bd1f4ed64" + integrity sha512-suosS7zZ2roj+fYVCnDuVezUbRc0sdoyF0Gj/1FzWxD4ebbGiBGtL5qyqHH4NO34B5m4vWWYWgyNhSsrqS8vwA== dependencies: - "@babel/register" "^7.10.4" + "@babel/register" "^7.10.5" commander "^4.0.1" core-js "^3.2.1" - lodash "^4.17.13" + lodash "^4.17.19" node-environment-flags "^1.0.5" regenerator-runtime "^0.13.4" resolve "^1.13.1" @@ -490,6 +535,11 @@ resolved "https://registry.yarnpkg.com/@babel/parser/-/parser-7.10.5.tgz#e7c6bf5a7deff957cec9f04b551e2762909d826b" integrity sha512-wfryxy4bE1UivvQKSQDU4/X6dr+i8bctjUjj8Zyt3DQy7NtPizJXT8M52nqpNKL+nq2PW8lxk4ZqLj0fD4B4hQ== +"@babel/parser@^7.11.0", "@babel/parser@^7.11.1": + version "7.11.3" + resolved "https://registry.yarnpkg.com/@babel/parser/-/parser-7.11.3.tgz#9e1eae46738bcd08e23e867bab43e7b95299a8f9" + integrity sha512-REo8xv7+sDxkKvoxEywIdsNFiZLybwdI7hcT5uEPyQrSMB4YQ973BfC9OOrD/81MaIjh6UxdulIQXkjmiH3PcA== + "@babel/plugin-proposal-async-generator-functions@^7.10.4": version "7.10.4" resolved "https://registry.yarnpkg.com/@babel/plugin-proposal-async-generator-functions/-/plugin-proposal-async-generator-functions-7.10.4.tgz#4b65abb3d9bacc6c657aaa413e56696f9f170fc6" @@ -515,6 +565,14 @@ "@babel/helper-plugin-utils" "^7.10.4" "@babel/plugin-syntax-dynamic-import" "^7.8.0" +"@babel/plugin-proposal-export-namespace-from@^7.10.4": + version "7.10.4" + resolved "https://registry.yarnpkg.com/@babel/plugin-proposal-export-namespace-from/-/plugin-proposal-export-namespace-from-7.10.4.tgz#570d883b91031637b3e2958eea3c438e62c05f54" + integrity sha512-aNdf0LY6/3WXkhh0Fdb6Zk9j1NMD8ovj3F6r0+3j837Pn1S1PdNtcwJ5EG9WkVPNHPxyJDaxMaAOVq4eki0qbg== + dependencies: + "@babel/helper-plugin-utils" "^7.10.4" + "@babel/plugin-syntax-export-namespace-from" "^7.8.3" + "@babel/plugin-proposal-json-strings@^7.10.4": version "7.10.4" resolved "https://registry.yarnpkg.com/@babel/plugin-proposal-json-strings/-/plugin-proposal-json-strings-7.10.4.tgz#593e59c63528160233bd321b1aebe0820c2341db" @@ -523,6 +581,14 @@ "@babel/helper-plugin-utils" "^7.10.4" "@babel/plugin-syntax-json-strings" "^7.8.0" +"@babel/plugin-proposal-logical-assignment-operators@^7.11.0": + version "7.11.0" + resolved "https://registry.yarnpkg.com/@babel/plugin-proposal-logical-assignment-operators/-/plugin-proposal-logical-assignment-operators-7.11.0.tgz#9f80e482c03083c87125dee10026b58527ea20c8" + integrity sha512-/f8p4z+Auz0Uaf+i8Ekf1iM7wUNLcViFUGiPxKeXvxTSl63B875YPiVdUDdem7hREcI0E0kSpEhS8tF5RphK7Q== + dependencies: + "@babel/helper-plugin-utils" "^7.10.4" + "@babel/plugin-syntax-logical-assignment-operators" "^7.10.4" + "@babel/plugin-proposal-nullish-coalescing-operator@^7.10.4": version "7.10.4" resolved "https://registry.yarnpkg.com/@babel/plugin-proposal-nullish-coalescing-operator/-/plugin-proposal-nullish-coalescing-operator-7.10.4.tgz#02a7e961fc32e6d5b2db0649e01bf80ddee7e04a" @@ -539,10 +605,10 @@ "@babel/helper-plugin-utils" "^7.10.4" "@babel/plugin-syntax-numeric-separator" "^7.10.4" -"@babel/plugin-proposal-object-rest-spread@^7.10.4": - version "7.10.4" - resolved "https://registry.yarnpkg.com/@babel/plugin-proposal-object-rest-spread/-/plugin-proposal-object-rest-spread-7.10.4.tgz#50129ac216b9a6a55b3853fdd923e74bf553a4c0" - integrity sha512-6vh4SqRuLLarjgeOf4EaROJAHjvu9Gl+/346PbDH9yWbJyfnJ/ah3jmYKYtswEyCoWZiidvVHjHshd4WgjB9BA== +"@babel/plugin-proposal-object-rest-spread@^7.11.0": + version "7.11.0" + resolved "https://registry.yarnpkg.com/@babel/plugin-proposal-object-rest-spread/-/plugin-proposal-object-rest-spread-7.11.0.tgz#bd81f95a1f746760ea43b6c2d3d62b11790ad0af" + integrity sha512-wzch41N4yztwoRw0ak+37wxwJM2oiIiy6huGCoqkvSTA9acYWcPfn9Y4aJqmFFJ70KTJUu29f3DQ43uJ9HXzEA== dependencies: "@babel/helper-plugin-utils" "^7.10.4" "@babel/plugin-syntax-object-rest-spread" "^7.8.0" @@ -556,12 +622,13 @@ "@babel/helper-plugin-utils" "^7.10.4" "@babel/plugin-syntax-optional-catch-binding" "^7.8.0" -"@babel/plugin-proposal-optional-chaining@^7.10.4": - version "7.10.4" - resolved "https://registry.yarnpkg.com/@babel/plugin-proposal-optional-chaining/-/plugin-proposal-optional-chaining-7.10.4.tgz#750f1255e930a1f82d8cdde45031f81a0d0adff7" - integrity sha512-ZIhQIEeavTgouyMSdZRap4VPPHqJJ3NEs2cuHs5p0erH+iz6khB0qfgU8g7UuJkG88+fBMy23ZiU+nuHvekJeQ== +"@babel/plugin-proposal-optional-chaining@^7.11.0": + version "7.11.0" + resolved "https://registry.yarnpkg.com/@babel/plugin-proposal-optional-chaining/-/plugin-proposal-optional-chaining-7.11.0.tgz#de5866d0646f6afdaab8a566382fe3a221755076" + integrity sha512-v9fZIu3Y8562RRwhm1BbMRxtqZNFmFA2EG+pT2diuU8PT3H6T/KXoZ54KgYisfOFZHV6PfvAiBIZ9Rcz+/JCxA== dependencies: "@babel/helper-plugin-utils" "^7.10.4" + "@babel/helper-skip-transparent-expression-wrappers" "^7.11.0" "@babel/plugin-syntax-optional-chaining" "^7.8.0" "@babel/plugin-proposal-private-methods@^7.10.4": @@ -609,6 +676,13 @@ dependencies: "@babel/helper-plugin-utils" "^7.8.0" +"@babel/plugin-syntax-export-namespace-from@^7.8.3": + version "7.8.3" + resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-export-namespace-from/-/plugin-syntax-export-namespace-from-7.8.3.tgz#028964a9ba80dbc094c915c487ad7c4e7a66465a" + integrity sha512-MXf5laXo6c1IbEbegDmzGPwGNTsHZmEy6QGznu5Sh2UCWvueywb2ee+CCE4zQiZstxU9BMoQO9i6zUFSY0Kj0Q== + dependencies: + "@babel/helper-plugin-utils" "^7.8.3" + "@babel/plugin-syntax-json-strings@^7.8.0": version "7.8.3" resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-json-strings/-/plugin-syntax-json-strings-7.8.3.tgz#01ca21b668cd8218c9e640cb6dd88c5412b2c96a" @@ -616,6 +690,13 @@ dependencies: "@babel/helper-plugin-utils" "^7.8.0" +"@babel/plugin-syntax-logical-assignment-operators@^7.10.4": + version "7.10.4" + resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-logical-assignment-operators/-/plugin-syntax-logical-assignment-operators-7.10.4.tgz#ca91ef46303530448b906652bac2e9fe9941f699" + integrity sha512-d8waShlpFDinQ5MtvGU9xDAOzKH47+FFoney2baFIoMr952hKOLp1HR7VszoZvOsV/4+RRszNY7D17ba0te0ig== + dependencies: + "@babel/helper-plugin-utils" "^7.10.4" + "@babel/plugin-syntax-nullish-coalescing-operator@^7.8.0": version "7.8.3" resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-nullish-coalescing-operator/-/plugin-syntax-nullish-coalescing-operator-7.8.3.tgz#167ed70368886081f74b5c36c65a88c03b66d1a9" @@ -879,10 +960,10 @@ dependencies: "@babel/helper-plugin-utils" "^7.10.4" -"@babel/plugin-transform-runtime@^7.10.4": - version "7.10.4" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-runtime/-/plugin-transform-runtime-7.10.4.tgz#594fb53453ea1b6f0779cceb48ce0718a447feb7" - integrity sha512-8ULlGv8p+Vuxu+kz2Y1dk6MYS2b/Dki+NO6/0ZlfSj5tMalfDL7jI/o/2a+rrWLqSXvnadEqc2WguB4gdQIxZw== +"@babel/plugin-transform-runtime@^7.11.0": + version "7.11.0" + resolved "https://registry.yarnpkg.com/@babel/plugin-transform-runtime/-/plugin-transform-runtime-7.11.0.tgz#e27f78eb36f19448636e05c33c90fd9ad9b8bccf" + integrity sha512-LFEsP+t3wkYBlis8w6/kmnd6Kb1dxTd+wGJ8MlxTGzQo//ehtqlVL4S9DNUa53+dtPSQobN2CXx4d81FqC58cw== dependencies: "@babel/helper-module-imports" "^7.10.4" "@babel/helper-plugin-utils" "^7.10.4" @@ -896,12 +977,13 @@ dependencies: "@babel/helper-plugin-utils" "^7.10.4" -"@babel/plugin-transform-spread@^7.10.4": - version "7.10.4" - resolved "https://registry.yarnpkg.com/@babel/plugin-transform-spread/-/plugin-transform-spread-7.10.4.tgz#4e2c85ea0d6abaee1b24dcfbbae426fe8d674cff" - integrity sha512-1e/51G/Ni+7uH5gktbWv+eCED9pP8ZpRhZB3jOaI3mmzfvJTWHkuyYTv0Z5PYtyM+Tr2Ccr9kUdQxn60fI5WuQ== +"@babel/plugin-transform-spread@^7.11.0": + version "7.11.0" + resolved "https://registry.yarnpkg.com/@babel/plugin-transform-spread/-/plugin-transform-spread-7.11.0.tgz#fa84d300f5e4f57752fe41a6d1b3c554f13f17cc" + integrity sha512-UwQYGOqIdQJe4aWNyS7noqAnN2VbaczPLiEtln+zPowRNlD+79w3oi2TWfYe0eZgd+gjZCbsydN7lzWysDt+gw== dependencies: "@babel/helper-plugin-utils" "^7.10.4" + "@babel/helper-skip-transparent-expression-wrappers" "^7.11.0" "@babel/plugin-transform-sticky-regex@^7.10.4": version "7.10.4" @@ -950,30 +1032,34 @@ "@babel/helper-create-regexp-features-plugin" "^7.10.4" "@babel/helper-plugin-utils" "^7.10.4" -"@babel/preset-env@^7.10.4": - version "7.10.4" - resolved "https://registry.yarnpkg.com/@babel/preset-env/-/preset-env-7.10.4.tgz#fbf57f9a803afd97f4f32e4f798bb62e4b2bef5f" - integrity sha512-tcmuQ6vupfMZPrLrc38d0sF2OjLT3/bZ0dry5HchNCQbrokoQi4reXqclvkkAT5b+gWc23meVWpve5P/7+w/zw== +"@babel/preset-env@^7.11.0": + version "7.11.0" + resolved "https://registry.yarnpkg.com/@babel/preset-env/-/preset-env-7.11.0.tgz#860ee38f2ce17ad60480c2021ba9689393efb796" + integrity sha512-2u1/k7rG/gTh02dylX2kL3S0IJNF+J6bfDSp4DI2Ma8QN6Y9x9pmAax59fsCk6QUQG0yqH47yJWA+u1I1LccAg== dependencies: - "@babel/compat-data" "^7.10.4" + "@babel/compat-data" "^7.11.0" "@babel/helper-compilation-targets" "^7.10.4" "@babel/helper-module-imports" "^7.10.4" "@babel/helper-plugin-utils" "^7.10.4" "@babel/plugin-proposal-async-generator-functions" "^7.10.4" "@babel/plugin-proposal-class-properties" "^7.10.4" "@babel/plugin-proposal-dynamic-import" "^7.10.4" + "@babel/plugin-proposal-export-namespace-from" "^7.10.4" "@babel/plugin-proposal-json-strings" "^7.10.4" + "@babel/plugin-proposal-logical-assignment-operators" "^7.11.0" "@babel/plugin-proposal-nullish-coalescing-operator" "^7.10.4" "@babel/plugin-proposal-numeric-separator" "^7.10.4" - "@babel/plugin-proposal-object-rest-spread" "^7.10.4" + "@babel/plugin-proposal-object-rest-spread" "^7.11.0" "@babel/plugin-proposal-optional-catch-binding" "^7.10.4" - "@babel/plugin-proposal-optional-chaining" "^7.10.4" + "@babel/plugin-proposal-optional-chaining" "^7.11.0" "@babel/plugin-proposal-private-methods" "^7.10.4" "@babel/plugin-proposal-unicode-property-regex" "^7.10.4" "@babel/plugin-syntax-async-generators" "^7.8.0" "@babel/plugin-syntax-class-properties" "^7.10.4" "@babel/plugin-syntax-dynamic-import" "^7.8.0" + "@babel/plugin-syntax-export-namespace-from" "^7.8.3" "@babel/plugin-syntax-json-strings" "^7.8.0" + "@babel/plugin-syntax-logical-assignment-operators" "^7.10.4" "@babel/plugin-syntax-nullish-coalescing-operator" "^7.8.0" "@babel/plugin-syntax-numeric-separator" "^7.10.4" "@babel/plugin-syntax-object-rest-spread" "^7.8.0" @@ -1006,14 +1092,14 @@ "@babel/plugin-transform-regenerator" "^7.10.4" "@babel/plugin-transform-reserved-words" "^7.10.4" "@babel/plugin-transform-shorthand-properties" "^7.10.4" - "@babel/plugin-transform-spread" "^7.10.4" + "@babel/plugin-transform-spread" "^7.11.0" "@babel/plugin-transform-sticky-regex" "^7.10.4" "@babel/plugin-transform-template-literals" "^7.10.4" "@babel/plugin-transform-typeof-symbol" "^7.10.4" "@babel/plugin-transform-unicode-escapes" "^7.10.4" "@babel/plugin-transform-unicode-regex" "^7.10.4" "@babel/preset-modules" "^0.1.3" - "@babel/types" "^7.10.4" + "@babel/types" "^7.11.0" browserslist "^4.12.0" core-js-compat "^3.6.2" invariant "^2.2.2" @@ -1039,21 +1125,21 @@ "@babel/helper-plugin-utils" "^7.10.4" "@babel/plugin-transform-typescript" "^7.10.4" -"@babel/register@^7.10.4": - version "7.10.4" - resolved "https://registry.yarnpkg.com/@babel/register/-/register-7.10.4.tgz#53004ba8b04c4af3cbd84508e03ad150669746e4" - integrity sha512-whHmgGiWNVyTVnYTSawtDWhaeYsc+noeU8Rmi+MPnbGhDYmr5QpEDMrQcIA07D2RUv0BlThPcN89XcHCqq/O4g== +"@babel/register@^7.10.5": + version "7.10.5" + resolved "https://registry.yarnpkg.com/@babel/register/-/register-7.10.5.tgz#354f3574895f1307f79efe37a51525e52fd38d89" + integrity sha512-eYHdLv43nyvmPn9bfNfrcC4+iYNwdQ8Pxk1MFJuU/U5LpSYl/PH4dFMazCYZDFVi8ueG3shvO+AQfLrxpYulQw== dependencies: find-cache-dir "^2.0.0" - lodash "^4.17.13" + lodash "^4.17.19" make-dir "^2.1.0" pirates "^4.0.0" source-map-support "^0.5.16" -"@babel/runtime@^7.10.4": - version "7.10.4" - resolved "https://registry.yarnpkg.com/@babel/runtime/-/runtime-7.10.4.tgz#a6724f1a6b8d2f6ea5236dbfe58c7d7ea9c5eb99" - integrity sha512-UpTN5yUJr9b4EX2CnGNWIvER7Ab83ibv0pcvvHc4UOdrBI5jb8bj+32cCwPX6xu0mt2daFNjYhoi+X7beH0RSw== +"@babel/runtime@^7.11.2": + version "7.11.2" + resolved "https://registry.yarnpkg.com/@babel/runtime/-/runtime-7.11.2.tgz#f549c13c754cc40b87644b9fa9f09a6a95fe0736" + integrity sha512-TeWkU52so0mPtDcaCTxNBI/IHiz0pZgr8VEFqXFtZWpYD08ZB6FaSwVAS8MKRQAP3bYKiVjwysOJgMFY28o6Tw== dependencies: regenerator-runtime "^0.13.4" @@ -1112,6 +1198,21 @@ globals "^11.1.0" lodash "^4.17.13" +"@babel/traverse@^7.11.0": + version "7.11.0" + resolved "https://registry.yarnpkg.com/@babel/traverse/-/traverse-7.11.0.tgz#9b996ce1b98f53f7c3e4175115605d56ed07dd24" + integrity sha512-ZB2V+LskoWKNpMq6E5UUCrjtDUh5IOTAyIl0dTjIEoXum/iKWkoIEKIRDnUucO6f+2FzNkE0oD4RLKoPIufDtg== + dependencies: + "@babel/code-frame" "^7.10.4" + "@babel/generator" "^7.11.0" + "@babel/helper-function-name" "^7.10.4" + "@babel/helper-split-export-declaration" "^7.11.0" + "@babel/parser" "^7.11.0" + "@babel/types" "^7.11.0" + debug "^4.1.0" + globals "^11.1.0" + lodash "^4.17.19" + "@babel/traverse@^7.7.0": version "7.10.5" resolved "https://registry.yarnpkg.com/@babel/traverse/-/traverse-7.10.5.tgz#77ce464f5b258be265af618d8fddf0536f20b564" @@ -1154,6 +1255,15 @@ lodash "^4.17.19" to-fast-properties "^2.0.0" +"@babel/types@^7.11.0": + version "7.11.0" + resolved "https://registry.yarnpkg.com/@babel/types/-/types-7.11.0.tgz#2ae6bf1ba9ae8c3c43824e5861269871b206e90d" + integrity sha512-O53yME4ZZI0jO1EVGtF1ePGl0LHirG4P1ibcD80XyzZcKhcMFeCXmh4Xb1ifGBIV233Qg12x4rBfQgA+tmOukA== + dependencies: + "@babel/helper-validator-identifier" "^7.10.4" + lodash "^4.17.19" + to-fast-properties "^2.0.0" + "@istanbuljs/load-nyc-config@^1.0.0": version "1.1.0" resolved "https://registry.yarnpkg.com/@istanbuljs/load-nyc-config/-/load-nyc-config-1.1.0.tgz#fd3db1d59ecf7cf121e80650bb86712f9b55eced" @@ -1234,7 +1344,7 @@ dependencies: "@types/node" "*" -"@types/jwt-decode@^2.2.0": +"@types/jwt-decode@^2.2.1": version "2.2.1" resolved "https://registry.yarnpkg.com/@types/jwt-decode/-/jwt-decode-2.2.1.tgz#afdf5c527fcfccbd4009b5fd02d1e18241f2d2f2" integrity sha512-aWw2YTtAdT7CskFyxEX2K21/zSDStuf/ikI3yBqmwpwJF0pS+/IX5DWv+1UFffZIbruP6cnT9/LAJV1gFwAT1A== @@ -1275,26 +1385,26 @@ dependencies: "@types/node" "*" -"@typescript-eslint/eslint-plugin@^3.6.1": - version "3.6.1" - resolved "https://registry.yarnpkg.com/@typescript-eslint/eslint-plugin/-/eslint-plugin-3.6.1.tgz#5ced8fd2087fbb83a76973dea4a0d39d9cb4a642" - integrity sha512-06lfjo76naNeOMDl+mWG9Fh/a0UHKLGhin+mGaIw72FUMbMGBkdi/FEJmgEDzh4eE73KIYzHWvOCYJ0ak7nrJQ== +"@typescript-eslint/eslint-plugin@^3.9.0": + version "3.9.0" + resolved "https://registry.yarnpkg.com/@typescript-eslint/eslint-plugin/-/eslint-plugin-3.9.0.tgz#0fe529b33d63c9a94f7503ca2bb12c84b9477ff3" + integrity sha512-UD6b4p0/hSe1xdTvRCENSx7iQ+KR6ourlZFfYuPC7FlXEzdHuLPrEmuxZ23b2zW96KJX9Z3w05GE/wNOiEzrVg== dependencies: - "@typescript-eslint/experimental-utils" "3.6.1" + "@typescript-eslint/experimental-utils" "3.9.0" debug "^4.1.1" functional-red-black-tree "^1.0.1" regexpp "^3.0.0" semver "^7.3.2" tsutils "^3.17.1" -"@typescript-eslint/experimental-utils@3.6.1": - version "3.6.1" - resolved "https://registry.yarnpkg.com/@typescript-eslint/experimental-utils/-/experimental-utils-3.6.1.tgz#b5a2738ebbceb3fa90c5b07d50bb1225403c4a54" - integrity sha512-oS+hihzQE5M84ewXrTlVx7eTgc52eu+sVmG7ayLfOhyZmJ8Unvf3osyFQNADHP26yoThFfbxcibbO0d2FjnYhg== +"@typescript-eslint/experimental-utils@3.9.0": + version "3.9.0" + resolved "https://registry.yarnpkg.com/@typescript-eslint/experimental-utils/-/experimental-utils-3.9.0.tgz#3171d8ddba0bf02a8c2034188593630914fcf5ee" + integrity sha512-/vSHUDYizSOhrOJdjYxPNGfb4a3ibO8zd4nUKo/QBFOmxosT3cVUV7KIg8Dwi6TXlr667G7YPqFK9+VSZOorNA== dependencies: "@types/json-schema" "^7.0.3" - "@typescript-eslint/types" "3.6.1" - "@typescript-eslint/typescript-estree" "3.6.1" + "@typescript-eslint/types" "3.9.0" + "@typescript-eslint/typescript-estree" "3.9.0" eslint-scope "^5.0.0" eslint-utils "^2.0.0" @@ -1308,21 +1418,21 @@ eslint-scope "^5.0.0" eslint-utils "^2.0.0" -"@typescript-eslint/parser@^3.6.1": - version "3.6.1" - resolved "https://registry.yarnpkg.com/@typescript-eslint/parser/-/parser-3.6.1.tgz#216e8adf4ee9c629f77c985476a2ea07fb80e1dc" - integrity sha512-SLihQU8RMe77YJ/jGTqOt0lMq7k3hlPVfp7v/cxMnXA9T0bQYoMDfTsNgHXpwSJM1Iq2aAJ8WqekxUwGv5F67Q== +"@typescript-eslint/parser@^3.9.0": + version "3.9.0" + resolved "https://registry.yarnpkg.com/@typescript-eslint/parser/-/parser-3.9.0.tgz#344978a265d9a5c7c8f13e62c78172a4374dabea" + integrity sha512-rDHOKb6uW2jZkHQniUQVZkixQrfsZGUCNWWbKWep4A5hGhN5dLHMUCNAWnC4tXRlHedXkTDptIpxs6e4Pz8UfA== dependencies: "@types/eslint-visitor-keys" "^1.0.0" - "@typescript-eslint/experimental-utils" "3.6.1" - "@typescript-eslint/types" "3.6.1" - "@typescript-eslint/typescript-estree" "3.6.1" + "@typescript-eslint/experimental-utils" "3.9.0" + "@typescript-eslint/types" "3.9.0" + "@typescript-eslint/typescript-estree" "3.9.0" eslint-visitor-keys "^1.1.0" -"@typescript-eslint/types@3.6.1": - version "3.6.1" - resolved "https://registry.yarnpkg.com/@typescript-eslint/types/-/types-3.6.1.tgz#87600fe79a1874235d3cc1cf5c7e1a12eea69eee" - integrity sha512-NPxd5yXG63gx57WDTW1rp0cF3XlNuuFFB5G+Kc48zZ+51ZnQn9yjDEsjTPQ+aWM+V+Z0I4kuTFKjKvgcT1F7xQ== +"@typescript-eslint/types@3.9.0": + version "3.9.0" + resolved "https://registry.yarnpkg.com/@typescript-eslint/types/-/types-3.9.0.tgz#be9d0aa451e1bf3ce99f2e6920659e5b2e6bfe18" + integrity sha512-rb6LDr+dk9RVVXO/NJE8dT1pGlso3voNdEIN8ugm4CWM5w5GimbThCMiMl4da1t5u3YwPWEwOnKAULCZgBtBHg== "@typescript-eslint/typescript-estree@2.32.0": version "2.32.0" @@ -1337,13 +1447,13 @@ semver "^7.3.2" tsutils "^3.17.1" -"@typescript-eslint/typescript-estree@3.6.1": - version "3.6.1" - resolved "https://registry.yarnpkg.com/@typescript-eslint/typescript-estree/-/typescript-estree-3.6.1.tgz#a5c91fcc5497cce7922ff86bc37d5e5891dcdefa" - integrity sha512-G4XRe/ZbCZkL1fy09DPN3U0mR6SayIv1zSeBNquRFRk7CnVLgkC2ZPj8llEMJg5Y8dJ3T76SvTGtceytniaztQ== +"@typescript-eslint/typescript-estree@3.9.0": + version "3.9.0" + resolved "https://registry.yarnpkg.com/@typescript-eslint/typescript-estree/-/typescript-estree-3.9.0.tgz#c6abbb50fa0d715cab46fef67ca6378bf2eaca13" + integrity sha512-N+158NKgN4rOmWVfvKOMoMFV5n8XxAliaKkArm/sOypzQ0bUL8MSnOEBW3VFIeffb/K5ce/cAV0yYhR7U4ALAA== dependencies: - "@typescript-eslint/types" "3.6.1" - "@typescript-eslint/visitor-keys" "3.6.1" + "@typescript-eslint/types" "3.9.0" + "@typescript-eslint/visitor-keys" "3.9.0" debug "^4.1.1" glob "^7.1.6" is-glob "^4.0.1" @@ -1351,10 +1461,10 @@ semver "^7.3.2" tsutils "^3.17.1" -"@typescript-eslint/visitor-keys@3.6.1": - version "3.6.1" - resolved "https://registry.yarnpkg.com/@typescript-eslint/visitor-keys/-/visitor-keys-3.6.1.tgz#5c57a7772f4dd623cfeacc219303e7d46f963b37" - integrity sha512-qC8Olwz5ZyMTZrh4Wl3K4U6tfms0R/mzU4/5W3XeUZptVraGVmbptJbn6h2Ey6Rb3hOs3zWoAUebZk8t47KGiQ== +"@typescript-eslint/visitor-keys@3.9.0": + version "3.9.0" + resolved "https://registry.yarnpkg.com/@typescript-eslint/visitor-keys/-/visitor-keys-3.9.0.tgz#44de8e1b1df67adaf3b94d6b60b80f8faebc8dd3" + integrity sha512-O1qeoGqDbu0EZUC/MZ6F1WHTIzcBVhGqDj3LhTnj65WUA548RXVxUHbYhAW9bZWfb2rnX9QsbbP5nmeJ5Z4+ng== dependencies: eslint-visitor-keys "^1.1.0" @@ -1574,10 +1684,10 @@ acorn@^6.4.1: resolved "https://registry.yarnpkg.com/acorn/-/acorn-6.4.1.tgz#531e58ba3f51b9dacb9a6646ca4debf5b14ca474" integrity sha512-ZVA9k326Nwrj3Cj9jlh3wGFutC2ZornPNARZwsNYqQYgN0EsV2d53w5RN/co65Ohn4sUAUtb1rSUAOD6XN9idA== -acorn@^7.2.0: - version "7.3.1" - resolved "https://registry.yarnpkg.com/acorn/-/acorn-7.3.1.tgz#85010754db53c3fbaf3b9ea3e083aa5c5d147ffd" - integrity sha512-tLc0wSnatxAQHVHUapaHdz72pi9KUyHjq5KyHjGg9Y8Ifdc79pTh2XvI6I1/chZbnM7QtNKzh66ooDogPZSleA== +acorn@^7.3.1: + version "7.4.0" + resolved "https://registry.yarnpkg.com/acorn/-/acorn-7.4.0.tgz#e1ad486e6c54501634c6c397c5c121daa383607c" + integrity sha512-+G7P8jJmCHr+S+cLfQxygbWhXy+8YTVGzAkpEbcLo2mLoL7tij/VG41QSHACSf5QgYRhMZYHuNc6drJaO0Da+w== after@0.8.2: version "0.8.2" @@ -2493,7 +2603,7 @@ chokidar@^2.1.8: optionalDependencies: fsevents "^1.2.7" -chokidar@^3.0.0, chokidar@^3.4.0: +chokidar@^3.0.0: version "3.4.0" resolved "https://registry.yarnpkg.com/chokidar/-/chokidar-3.4.0.tgz#b30611423ce376357c765b9b8f904b9fba3c0be8" integrity sha512-aXAaho2VJtisB/1fg1+3nlLJqGOuewTzQpd/Tz0yTg2R0e4IGtshYvtjowyEumcBv2z+y4+kc75Mz7j5xJskcQ== @@ -2508,6 +2618,21 @@ chokidar@^3.0.0, chokidar@^3.4.0: optionalDependencies: fsevents "~2.1.2" +chokidar@^3.4.1: + version "3.4.2" + resolved "https://registry.yarnpkg.com/chokidar/-/chokidar-3.4.2.tgz#38dc8e658dec3809741eb3ef7bb0a47fe424232d" + integrity sha512-IZHaDeBeI+sZJRX7lGcXsdzgvZqKv6sECqsbErJA4mHWfpRrD8B97kSFN4cQz6nGBGiuFia1MKR4d6c1o8Cv7A== + dependencies: + anymatch "~3.1.1" + braces "~3.0.2" + glob-parent "~5.1.0" + is-binary-path "~2.1.0" + is-glob "~4.0.1" + normalize-path "~3.0.0" + readdirp "~3.4.0" + optionalDependencies: + fsevents "~2.1.2" + chownr@^1.1.1: version "1.1.4" resolved "https://registry.yarnpkg.com/chownr/-/chownr-1.1.4.tgz#6fc9d7b42d32a583596337666e7d08084da2cc6b" @@ -2594,10 +2719,10 @@ clone-response@1.0.2, clone-response@^1.0.2: dependencies: mimic-response "^1.0.0" -codecov@^3.7.1: - version "3.7.1" - resolved "https://registry.yarnpkg.com/codecov/-/codecov-3.7.1.tgz#434cb8d55f18ef01672e5739d3d266696bebc202" - integrity sha512-JHWxyPTkMLLJn9SmKJnwAnvY09kg2Os2+Ux+GG7LwZ9g8gzDDISpIN5wAsH1UBaafA/yGcd3KofMaorE8qd6Lw== +codecov@^3.7.2: + version "3.7.2" + resolved "https://registry.yarnpkg.com/codecov/-/codecov-3.7.2.tgz#998e68c8c1ef4b55cfcf11cd456866d35e13d693" + integrity sha512-fmCjAkTese29DUX3GMIi4EaKGflHa4K51EoMc29g8fBHawdk/+KEq5CWOeXLdd9+AT7o1wO4DIpp/Z1KCqCz1g== dependencies: argv "0.0.2" ignore-walk "3.0.3" @@ -3369,7 +3494,7 @@ engine.io@~3.4.0: engine.io-parser "~2.2.0" ws "^7.1.2" -enhanced-resolve@^4.1.0, enhanced-resolve@^4.1.1: +enhanced-resolve@^4.1.1: version "4.2.0" resolved "https://registry.yarnpkg.com/enhanced-resolve/-/enhanced-resolve-4.2.0.tgz#5d43bda4a0fd447cb0ebbe71bef8deff8805ad0d" integrity sha512-S7eiFb/erugyd1rLb6mQ3Vuq+EXHv5cpCkNqqIkYkBgN2QdFnyCZzFBleqwGEx4lgNGYij81BWnCrFNK7vxvjQ== @@ -3378,6 +3503,15 @@ enhanced-resolve@^4.1.0, enhanced-resolve@^4.1.1: memory-fs "^0.5.0" tapable "^1.0.0" +enhanced-resolve@^4.3.0: + version "4.3.0" + resolved "https://registry.yarnpkg.com/enhanced-resolve/-/enhanced-resolve-4.3.0.tgz#3b806f3bfafc1ec7de69551ef93cca46c1704126" + integrity sha512-3e87LvavsdxyoCfGusJnrZ5G8SLPOFeHSNpZI/ATL9a5leXo2k0w6MKnbqhdBad9qTobSfB20Ld7UmgoNbAZkQ== + dependencies: + graceful-fs "^4.1.2" + memory-fs "^0.5.0" + tapable "^1.0.0" + enquirer@^2.3.5: version "2.3.5" resolved "https://registry.yarnpkg.com/enquirer/-/enquirer-2.3.5.tgz#3ab2b838df0a9d8ab9e7dff235b0e8712ef92381" @@ -3571,27 +3705,27 @@ eslint-scope@^5.0.0, eslint-scope@^5.1.0: esrecurse "^4.1.0" estraverse "^4.1.1" -eslint-utils@^2.0.0: +eslint-utils@^2.0.0, eslint-utils@^2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/eslint-utils/-/eslint-utils-2.1.0.tgz#d2de5e03424e707dc10c74068ddedae708741b27" integrity sha512-w94dQYoauyvlDc43XnGB8lU3Zt713vNChgt4EWwhXAP2XkBvndfxF0AgIqKOOasjPIPzj9JqgwkwbCYD0/V3Zg== dependencies: eslint-visitor-keys "^1.1.0" -eslint-visitor-keys@^1.0.0: +eslint-visitor-keys@^1.0.0, eslint-visitor-keys@^1.3.0: version "1.3.0" resolved "https://registry.yarnpkg.com/eslint-visitor-keys/-/eslint-visitor-keys-1.3.0.tgz#30ebd1ef7c2fdff01c3a4f151044af25fab0523e" integrity sha512-6J72N8UNa462wa/KFODt/PJ3IU60SDpC3QXC1Hjc1BXXpfL2C9R5+AU7jhe0F6GREqVMh4Juu+NY7xn+6dipUQ== -eslint-visitor-keys@^1.1.0, eslint-visitor-keys@^1.2.0: +eslint-visitor-keys@^1.1.0: version "1.2.0" resolved "https://registry.yarnpkg.com/eslint-visitor-keys/-/eslint-visitor-keys-1.2.0.tgz#74415ac884874495f78ec2a97349525344c981fa" integrity sha512-WFb4ihckKil6hu3Dp798xdzSfddwKKU3+nGniKF6HfeW6OLd2OUDEPP7TcHtB5+QXOKg2s6B2DaMPE1Nn/kxKQ== -eslint@^7.3.1: - version "7.3.1" - resolved "https://registry.yarnpkg.com/eslint/-/eslint-7.3.1.tgz#76392bd7e44468d046149ba128d1566c59acbe19" - integrity sha512-cQC/xj9bhWUcyi/RuMbRtC3I0eW8MH0jhRELSvpKYkWep3C6YZ2OkvcvJVUeO6gcunABmzptbXBuDoXsjHmfTA== +eslint@^7.6.0: + version "7.6.0" + resolved "https://registry.yarnpkg.com/eslint/-/eslint-7.6.0.tgz#522d67cfaea09724d96949c70e7a0550614d64d6" + integrity sha512-QlAManNtqr7sozWm5TF4wIH9gmUm2hE3vNRUvyoYAa4y1l5/jxD/PQStEjBMQtCqZmSep8UxrcecI60hOpe61w== dependencies: "@babel/code-frame" "^7.0.0" ajv "^6.10.0" @@ -3601,9 +3735,9 @@ eslint@^7.3.1: doctrine "^3.0.0" enquirer "^2.3.5" eslint-scope "^5.1.0" - eslint-utils "^2.0.0" - eslint-visitor-keys "^1.2.0" - espree "^7.1.0" + eslint-utils "^2.1.0" + eslint-visitor-keys "^1.3.0" + espree "^7.2.0" esquery "^1.2.0" esutils "^2.0.2" file-entry-cache "^5.0.1" @@ -3617,7 +3751,7 @@ eslint@^7.3.1: js-yaml "^3.13.1" json-stable-stringify-without-jsonify "^1.0.1" levn "^0.4.1" - lodash "^4.17.14" + lodash "^4.17.19" minimatch "^3.0.4" natural-compare "^1.4.0" optionator "^0.9.1" @@ -3630,14 +3764,14 @@ eslint@^7.3.1: text-table "^0.2.0" v8-compile-cache "^2.0.3" -espree@^7.1.0: - version "7.1.0" - resolved "https://registry.yarnpkg.com/espree/-/espree-7.1.0.tgz#a9c7f18a752056735bf1ba14cb1b70adc3a5ce1c" - integrity sha512-dcorZSyfmm4WTuTnE5Y7MEN1DyoPYy1ZR783QW1FJoenn7RailyWFsq/UL6ZAAA7uXurN9FIpYyUs3OfiIW+Qw== +espree@^7.2.0: + version "7.2.0" + resolved "https://registry.yarnpkg.com/espree/-/espree-7.2.0.tgz#1c263d5b513dbad0ac30c4991b93ac354e948d69" + integrity sha512-H+cQ3+3JYRMEIOl87e7QdHX70ocly5iW4+dttuR8iYSPr/hXKFb+7dBsZ7+u1adC4VrnPlTkv0+OwuPnDop19g== dependencies: - acorn "^7.2.0" + acorn "^7.3.1" acorn-jsx "^5.2.0" - eslint-visitor-keys "^1.2.0" + eslint-visitor-keys "^1.3.0" esprima@^4.0.0: version "4.0.1" @@ -3851,10 +3985,10 @@ faye-websocket@>=0.9.1: dependencies: websocket-driver ">=0.5.1" -faye@^1.3.0: - version "1.3.0" - resolved "https://registry.yarnpkg.com/faye/-/faye-1.3.0.tgz#a8139ad9c45eef4d5faaa52a23d2b92c38d7254b" - integrity sha512-l+IzAmEsT2OCVeGbLfZBpm8HeHQYVelkqKWNE0LA/k68jhVIT/qzHTXLygURrLpKweqiaTBCtzxxO5JTQ+dnFQ== +faye@^1.4.0: + version "1.4.0" + resolved "https://registry.yarnpkg.com/faye/-/faye-1.4.0.tgz#01d3d26ed5642c1cb203eed358afb1c1444b8669" + integrity sha512-kRrIg4be8VNYhycS2PY//hpBJSzZPr/DBbcy9VWelhZMW3KhyLkQR0HL0k0MNpmVoNFF4EdfMFkNAWjTP65g6w== dependencies: asap "*" csprng "*" @@ -4919,7 +5053,7 @@ is-object@^1.0.1: resolved "https://registry.yarnpkg.com/is-object/-/is-object-1.0.1.tgz#8952688c5ec2ffd6b03ecc85e769e02903083470" integrity sha1-iVJojF7C/9awPsyF52ngKQMINHA= -is-plain-obj@^1.0.0: +is-plain-obj@^1.0.0, is-plain-obj@^1.1.0: version "1.1.0" resolved "https://registry.yarnpkg.com/is-plain-obj/-/is-plain-obj-1.1.0.tgz#71a50c8429dfca773c92a390a4a03b39fcd51d3e" integrity sha1-caUMhCnfync8kqOQpKA7OfzVHT4= @@ -5154,10 +5288,10 @@ jsbn@~0.1.0: resolved "https://registry.yarnpkg.com/jsbn/-/jsbn-0.1.1.tgz#a5e654c2e5a2deb5f201d96cefbca80c0ef2f513" integrity sha1-peZUwuWi3rXyAdls77yoDA7y9RM= -jsdoc@^3.6.4: - version "3.6.4" - resolved "https://registry.yarnpkg.com/jsdoc/-/jsdoc-3.6.4.tgz#246b2832a0ea8b37a441b61745509cfe29e174b6" - integrity sha512-3G9d37VHv7MFdheviDCjUfQoIjdv4TC5zTTf5G9VODLtOnVS6La1eoYBDlbWfsRT3/Xo+j2MIqki2EV12BZfwA== +jsdoc@^3.6.5: + version "3.6.5" + resolved "https://registry.yarnpkg.com/jsdoc/-/jsdoc-3.6.5.tgz#e004372ca6f2dcdf19b3d2ebcd7c725528485502" + integrity sha512-SbY+i9ONuxSK35cgVHaI8O9senTE4CDYAmGSDJ5l3+sfe62Ff4gy96osy6OW84t4K4A8iGnMrlRrsSItSNp3RQ== dependencies: "@babel/parser" "^7.9.4" bluebird "^3.7.2" @@ -5349,10 +5483,10 @@ karma-webpack@^4.0.2: source-map "^0.7.3" webpack-dev-middleware "^3.7.0" -karma@^5.1.0: - version "5.1.0" - resolved "https://registry.yarnpkg.com/karma/-/karma-5.1.0.tgz#deaa5f3939f75d7d78ded33283fa5f9bb67e9a05" - integrity sha512-I3aPbkuIbwuBo6wSog97P5WnnhCgUTsWTu/bEw1vZVQFbXmKO3PK+cfFhZioOgVtJAuQxoyauGNjnwXNHMCxbw== +karma@^5.1.1: + version "5.1.1" + resolved "https://registry.yarnpkg.com/karma/-/karma-5.1.1.tgz#4e472c1e5352d73edbd2090726afdb01d7869d72" + integrity sha512-xAlOr5PMqUbiKXSv5PCniHWV3aiwj6wIZ0gUVcwpTCPVQm/qH2WAMFWxtnpM6KJqhkRWrIpovR4Rb0rn8GtJzQ== dependencies: body-parser "^1.19.0" braces "^3.0.2" @@ -5915,10 +6049,10 @@ mkdirp@^1.0.4: resolved "https://registry.yarnpkg.com/mkdirp/-/mkdirp-1.0.4.tgz#3eb5ed62622756d79a5f0e2a221dfebad75c2f7e" integrity sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw== -mocha@^8.0.1: - version "8.0.1" - resolved "https://registry.yarnpkg.com/mocha/-/mocha-8.0.1.tgz#fe01f0530362df271aa8f99510447bc38b88d8ed" - integrity sha512-vefaXfdYI8+Yo8nPZQQi0QO2o+5q9UIMX1jZ1XMmK3+4+CQjc7+B0hPdUeglXiTlr8IHMVRo63IhO9Mzt6fxOg== +mocha@^8.1.1: + version "8.1.1" + resolved "https://registry.yarnpkg.com/mocha/-/mocha-8.1.1.tgz#1de1ba4e9a2c955d96b84e469d7540848223592d" + integrity sha512-p7FuGlYH8t7gaiodlFreseLxEmxTgvyG9RgPHODFPySNhwUehu8NIb0vdSt3WFckSneswZ0Un5typYcWElk7HQ== dependencies: ansi-colors "4.1.1" browser-stdout "1.3.1" @@ -5936,7 +6070,7 @@ mocha@^8.0.1: ms "2.1.2" object.assign "4.1.0" promise.allsettled "1.0.2" - serialize-javascript "3.0.0" + serialize-javascript "4.0.0" strip-json-comments "3.0.1" supports-color "7.1.0" which "2.0.2" @@ -5944,7 +6078,7 @@ mocha@^8.0.1: workerpool "6.0.0" yargs "13.3.2" yargs-parser "13.1.2" - yargs-unparser "1.6.0" + yargs-unparser "1.6.1" move-concurrently@^1.0.1: version "1.0.1" @@ -6856,10 +6990,10 @@ querystring@0.2.0: resolved "https://registry.yarnpkg.com/querystring/-/querystring-0.2.0.tgz#b209849203bb25df820da756e747005878521620" integrity sha1-sgmEkgO7Jd+CDadW50cAWHhSFiA= -quibble@^0.6.3: - version "0.6.3" - resolved "https://registry.yarnpkg.com/quibble/-/quibble-0.6.3.tgz#750617218feeb8e3ac7af4d01a7675b8c7a4fca6" - integrity sha512-gIOnJ0y7nJk9sWOHwTzqh2M4llaIDBzEOcMdvBd5rIrNTGyOTb44CDJWc85OFEFpkxsnjru2g36LhL0gu7d5ng== +quibble@^0.6.4: + version "0.6.4" + resolved "https://registry.yarnpkg.com/quibble/-/quibble-0.6.4.tgz#a8a4d6a4f3b7f1785a7edacb945082c046601c13" + integrity sha512-hZXvHTiBcpCJ4cQ0FvR7tZJuyAF6k5Q1EZMExjTTY6eKng5wSMMWbithU8hNDQjV8vqYWqxasnf79QUDwX8WlQ== dependencies: lodash "^4.17.14" resolve "^1.11.1" @@ -7342,10 +7476,12 @@ serialize-error@^7.0.0, serialize-error@^7.0.1: dependencies: type-fest "^0.13.1" -serialize-javascript@3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/serialize-javascript/-/serialize-javascript-3.0.0.tgz#492e489a2d77b7b804ad391a5f5d97870952548e" - integrity sha512-skZcHYw2vEX4bw90nAr2iTTsz6x2SrHEnfxgKYmZlvJYBEZrvbKtobJWlQ20zczKb3bsHHXXTYt48zBA7ni9cw== +serialize-javascript@4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/serialize-javascript/-/serialize-javascript-4.0.0.tgz#b525e1238489a5ecfc42afacc3fe99e666f4b1aa" + integrity sha512-GaNA54380uFefWghODBWEGisLZFj00nS5ACs6yHa9nLqlLpVLO8ChDGeKRjZnV4Nh4n0Qi7nhYZD/9fCPzEqkw== + dependencies: + randombytes "^2.1.0" serialize-javascript@^1.7.0: version "1.9.1" @@ -7996,13 +8132,13 @@ test-exclude@^6.0.0: glob "^7.1.4" minimatch "^3.0.4" -testdouble@^3.16.0: - version "3.16.0" - resolved "https://registry.yarnpkg.com/testdouble/-/testdouble-3.16.0.tgz#aa52a6d7510c88143e8b38882012418c6541bd69" - integrity sha512-IGC1I/UaVBHlILSvldEUzf+csYv2O6uQngist4oKNATKbve5mSrTxrR6qkcquh/G+/vuLIyUtqJ5/bPANYjkjA== +testdouble@^3.16.1: + version "3.16.1" + resolved "https://registry.yarnpkg.com/testdouble/-/testdouble-3.16.1.tgz#05e3405b79e81d5e37aec7157cccd52217c97e8b" + integrity sha512-diaNYjFfR8bdMhtwJ9c2KxHa7M8Al7YciU+kteutWIIendmCC61ZyqQBtprsFkb6Cd/rjBr2sEoUJ8bWIVHm6w== dependencies: lodash "^4.17.15" - quibble "^0.6.3" + quibble "^0.6.4" stringify-object-es5 "^2.5.0" theredoc "^1.0.0" @@ -8215,10 +8351,10 @@ typedarray@^0.0.6: resolved "https://registry.yarnpkg.com/typedarray/-/typedarray-0.0.6.tgz#867ac74e3864187b1d3d47d996a78ec5c8830777" integrity sha1-hnrHTjhkGHsdPUfZlqeOxciDB3c= -typescript@^3.9.6: - version "3.9.6" - resolved "https://registry.yarnpkg.com/typescript/-/typescript-3.9.6.tgz#8f3e0198a34c3ae17091b35571d3afd31999365a" - integrity sha512-Pspx3oKAPJtjNwE92YS05HQoY7z2SFyOpHo9MqJor3BXAGNaPUs83CuVp9VISFkSjyRfiTpmKuAYGJB7S7hOxw== +typescript@^3.9.7: + version "3.9.7" + resolved "https://registry.yarnpkg.com/typescript/-/typescript-3.9.7.tgz#98d600a5ebdc38f40cb277522f12dc800e9e25fa" + integrity sha512-BLbiRkiBzAwsjut4x/dsibSTB6yWpwT5qWmC2OfuCg3GgVQCSgMs4vEctYPhsaGtd0AeuuHMkjZ2h2WG8MSzRw== ua-parser-js@0.7.21, ua-parser-js@^0.7.21: version "0.7.21" @@ -8471,15 +8607,15 @@ watchpack-chokidar2@^2.0.0: dependencies: chokidar "^2.1.8" -watchpack@^1.6.1: - version "1.7.2" - resolved "https://registry.yarnpkg.com/watchpack/-/watchpack-1.7.2.tgz#c02e4d4d49913c3e7e122c3325365af9d331e9aa" - integrity sha512-ymVbbQP40MFTp+cNMvpyBpBtygHnPzPkHqoIwRRj/0B8KhqQwV8LaKjtbaxF2lK4vl8zN9wCxS46IFCU5K4W0g== +watchpack@^1.7.4: + version "1.7.4" + resolved "https://registry.yarnpkg.com/watchpack/-/watchpack-1.7.4.tgz#6e9da53b3c80bb2d6508188f5b200410866cd30b" + integrity sha512-aWAgTW4MoSJzZPAicljkO1hsi1oKj/RRq/OJQh2PKI2UKL04c2Bs+MBOB+BBABHTXJpf9mCwHN7ANCvYsvY2sg== dependencies: graceful-fs "^4.1.2" neo-async "^2.5.0" optionalDependencies: - chokidar "^3.4.0" + chokidar "^3.4.1" watchpack-chokidar2 "^2.0.0" webdriver@6.1.17: @@ -8560,10 +8696,10 @@ webpack-sources@^1.4.0, webpack-sources@^1.4.1: source-list-map "^2.0.0" source-map "~0.6.1" -webpack@^4.43.0: - version "4.43.0" - resolved "https://registry.yarnpkg.com/webpack/-/webpack-4.43.0.tgz#c48547b11d563224c561dad1172c8aa0b8a678e6" - integrity sha512-GW1LjnPipFW2Y78OOab8NJlCflB7EFskMih2AHdvjbpKMeDJqEgSx24cXXXiPS65+WSwVyxtDsJH6jGX2czy+g== +webpack@^4.44.1: + version "4.44.1" + resolved "https://registry.yarnpkg.com/webpack/-/webpack-4.44.1.tgz#17e69fff9f321b8f117d1fda714edfc0b939cc21" + integrity sha512-4UOGAohv/VGUNQJstzEywwNxqX417FnjZgZJpJQegddzPmTvph37eBIRbRTfdySXzVtJXLJfbMN3mMYhM6GdmQ== dependencies: "@webassemblyjs/ast" "1.9.0" "@webassemblyjs/helper-module-context" "1.9.0" @@ -8573,7 +8709,7 @@ webpack@^4.43.0: ajv "^6.10.2" ajv-keywords "^3.4.1" chrome-trace-event "^1.0.2" - enhanced-resolve "^4.1.0" + enhanced-resolve "^4.3.0" eslint-scope "^4.0.3" json-parse-better-errors "^1.0.2" loader-runner "^2.4.0" @@ -8586,7 +8722,7 @@ webpack@^4.43.0: schema-utils "^1.0.0" tapable "^1.1.3" terser-webpack-plugin "^1.4.3" - watchpack "^1.6.1" + watchpack "^1.7.4" webpack-sources "^1.4.1" websocket-driver@>=0.5.1: @@ -8746,6 +8882,14 @@ yargs-parser@13.1.2, yargs-parser@^13.1.2: camelcase "^5.0.0" decamelize "^1.2.0" +yargs-parser@^15.0.1: + version "15.0.1" + resolved "https://registry.yarnpkg.com/yargs-parser/-/yargs-parser-15.0.1.tgz#54786af40b820dcb2fb8025b11b4d659d76323b3" + integrity sha512-0OAMV2mAZQrs3FkNpDQcBk1x5HXb8X4twADss4S0Iuk+2dGnLOE/fRHrsYm542GduMveyA77OF4wrNJuanRCWw== + dependencies: + camelcase "^5.0.0" + decamelize "^1.2.0" + yargs-parser@^18.1.1: version "18.1.3" resolved "https://registry.yarnpkg.com/yargs-parser/-/yargs-parser-18.1.3.tgz#be68c4975c6b2abf469236b0c870362fab09a7b0" @@ -8754,16 +8898,18 @@ yargs-parser@^18.1.1: camelcase "^5.0.0" decamelize "^1.2.0" -yargs-unparser@1.6.0: - version "1.6.0" - resolved "https://registry.yarnpkg.com/yargs-unparser/-/yargs-unparser-1.6.0.tgz#ef25c2c769ff6bd09e4b0f9d7c605fb27846ea9f" - integrity sha512-W9tKgmSn0DpSatfri0nx52Joq5hVXgeLiqR/5G0sZNDoLZFOr/xjBUDcShCOGNsBnEMNo1KAMBkTej1Hm62HTw== +yargs-unparser@1.6.1: + version "1.6.1" + resolved "https://registry.yarnpkg.com/yargs-unparser/-/yargs-unparser-1.6.1.tgz#bd4b0ee05b4c94d058929c32cb09e3fce71d3c5f" + integrity sha512-qZV14lK9MWsGCmcr7u5oXGH0dbGqZAIxTDrWXZDo5zUr6b6iUmelNKO6x6R1dQT24AH3LgRxJpr8meWy2unolA== dependencies: + camelcase "^5.3.1" + decamelize "^1.2.0" flat "^4.1.0" - lodash "^4.17.15" - yargs "^13.3.0" + is-plain-obj "^1.1.0" + yargs "^14.2.3" -yargs@13.3.2, yargs@^13.3.0, yargs@^13.3.2: +yargs@13.3.2, yargs@^13.3.2: version "13.3.2" resolved "https://registry.yarnpkg.com/yargs/-/yargs-13.3.2.tgz#ad7ffefec1aa59565ac915f82dccb38a9c31a2dd" integrity sha512-AX3Zw5iPruN5ie6xGRIDgqkT+ZhnRlZMLMHAs8tg7nRruy2Nb+i5o9bwghAogtM08q1dpr2LVoS8KSTMYpWXUw== @@ -8779,6 +8925,23 @@ yargs@13.3.2, yargs@^13.3.0, yargs@^13.3.2: y18n "^4.0.0" yargs-parser "^13.1.2" +yargs@^14.2.3: + version "14.2.3" + resolved "https://registry.yarnpkg.com/yargs/-/yargs-14.2.3.tgz#1a1c3edced1afb2a2fea33604bc6d1d8d688a414" + integrity sha512-ZbotRWhF+lkjijC/VhmOT9wSgyBQ7+zr13+YLkhfsSiTriYsMzkTUFP18pFhWwBeMa5gUc1MzbhrO6/VB7c9Xg== + dependencies: + cliui "^5.0.0" + decamelize "^1.2.0" + find-up "^3.0.0" + get-caller-file "^2.0.1" + require-directory "^2.1.1" + require-main-filename "^2.0.0" + set-blocking "^2.0.0" + string-width "^3.0.0" + which-module "^2.0.0" + y18n "^4.0.0" + yargs-parser "^15.0.1" + yargs@^15.0.2, yargs@^15.3.1: version "15.3.1" resolved "https://registry.yarnpkg.com/yargs/-/yargs-15.3.1.tgz#9505b472763963e54afe60148ad27a330818e98b" From 122a9d8323f5e7033205f4f62c122e6ccad505f7 Mon Sep 17 00:00:00 2001 From: Amin Mahboubi Date: Tue, 11 Aug 2020 17:12:06 +0200 Subject: [PATCH 67/69] move comments outside fn body --- src/batch_operations.ts | 52 ++--- src/client.ts | 507 ++++++++++++++++++++-------------------- src/collections.ts | 190 +++++++-------- src/connect.ts | 44 ++-- src/feed.ts | 266 +++++++++++---------- src/files.ts | 16 +- src/images.ts | 16 +- src/personalization.ts | 76 +++--- src/reaction.ts | 165 +++++++------ src/redirect_url.ts | 22 +- src/signing.ts | 66 +++--- src/user.ts | 18 +- src/utils.ts | 18 +- 13 files changed, 725 insertions(+), 731 deletions(-) diff --git a/src/batch_operations.ts b/src/batch_operations.ts index 6d9d6f11..368794d7 100644 --- a/src/batch_operations.ts +++ b/src/batch_operations.ts @@ -14,20 +14,20 @@ export type UnfollowRelation = BaseFollowRelation & { keep_history?: boolean; }; +/** + * Add one activity to many feeds + * @method addToMany + * @memberof StreamClient.prototype + * @since 2.3.0 + * @param {ActivityType} activity The activity to add + * @param {string[]} feeds Array of feed id in form of `${feedSlug}:${feedId}` + * @return {Promise} + */ function addToMany( this: StreamClient, activity: ActivityType, feeds: string[], ) { - /** - * Add one activity to many feeds - * @method addToMany - * @memberof StreamClient.prototype - * @since 2.3.0 - * @param {ActivityType} activity The activity to add - * @param {string[]} feeds Array of feed id in form of `${feedSlug}:${feedId}` - * @return {Promise} - */ this._throwMissingApiSecret(); return this.post({ @@ -40,16 +40,16 @@ function addToMany( }); } +/** + * Follow multiple feeds with one API call + * @method followMany + * @memberof StreamClient.prototype + * @since 2.3.0 + * @param {FollowRelation[]} follows The follow relations to create: [{ source: string; target: string }] + * @param {number} [activityCopyLimit] How many activities should be copied from the target feed + * @return {Promise} + */ function followMany(this: StreamClient, follows: FollowRelation[], activityCopyLimit?: number) { - /** - * Follow multiple feeds with one API call - * @method followMany - * @memberof StreamClient.prototype - * @since 2.3.0 - * @param {FollowRelation[]} follows The follow relations to create: [{ source: string; target: string }] - * @param {number} [activityCopyLimit] How many activities should be copied from the target feed - * @return {Promise} - */ this._throwMissingApiSecret(); const qs: { activity_copy_limit?: number } = {}; @@ -63,15 +63,15 @@ function followMany(this: StreamClient, follows: FollowRelation[], activityCopyL }); } +/** + * Unfollow multiple feeds with one API call + * @method unfollowMany + * @memberof StreamClient.prototype + * @since 3.15.0 + * @param {UnfollowRelation[]} unfollows The follow relations to remove: [{ source: string; target: string }] + * @return {Promise} + */ function unfollowMany(this: StreamClient, unfollows: UnfollowRelation[]) { - /** - * Unfollow multiple feeds with one API call - * @method unfollowMany - * @memberof StreamClient.prototype - * @since 3.15.0 - * @param {UnfollowRelation[]} unfollows The follow relations to remove: [{ source: string; target: string }] - * @return {Promise} - */ this._throwMissingApiSecret(); return this.post({ diff --git a/src/client.ts b/src/client.ts index a0863268..bc6cc9a4 100644 --- a/src/client.ts +++ b/src/client.ts @@ -170,26 +170,25 @@ export default class StreamClient< unfollowMany?: (this: StreamClient, unfollows: UnfollowRelation[]) => Promise; createRedirectUrl?: (this: StreamClient, targetUrl: string, userId: string, events: unknown[]) => string; + /** + * Initialize a client + * @method initialize + * @memberof StreamClient.prototype + * @param {string} apiKey - the api key + * @param {string} [apiSecret] - the api secret + * @param {string} [appId] - id of the app + * @param {ClientOptions} [options] - additional options + * @param {string} [options.location] - which data center to use + * @param {boolean} [options.expireTokens=false] - whether to use a JWT timestamp field (i.e. iat) + * @param {string} [options.version] - advanced usage, custom api version + * @param {boolean} [options.keepAlive] - axios keepAlive, default to true + * @param {number} [options.timeout] - axios timeout in Ms, default to 10s + * @example initialize is not directly called by via stream.connect, ie: + * stream.connect(apiKey, apiSecret) + * @example secret is optional and only used in server side mode + * stream.connect(apiKey, null, appId); + */ constructor(apiKey: string, apiSecretOrToken: string | null, appId?: string, options: ClientOptions = {}) { - /** - * Initialize a client - * @method initialize - * @memberof StreamClient.prototype - * @param {string} apiKey - the api key - * @param {string} [apiSecret] - the api secret - * @param {string} [appId] - id of the app - * @param {ClientOptions} [options] - additional options - * @param {string} [options.location] - which data center to use - * @param {boolean} [options.expireTokens=false] - whether to use a JWT timestamp field (i.e. iat) - * @param {string} [options.version] - advanced usage, custom api version - * @param {boolean} [options.keepAlive] - axios keepAlive, default to true - * @param {number} [options.timeout] - axios timeout in Ms, default to 10s - * @example initialize is not directly called by via stream.connect, ie: - * stream.connect(apiKey, apiSecret) - * @example secret is optional and only used in server side mode - * stream.connect(apiKey, null, appId); - */ - this.baseUrl = 'https://api.stream-io-api.com/api/'; this.baseAnalyticsUrl = 'https://analytics.stream-io-api.com/analytics/'; this.apiKey = apiKey; @@ -329,31 +328,31 @@ export default class StreamClient< return this.baseUrl; } + /** + * Support for global event callbacks + * This is useful for generic error and loading handling + * @method on + * @memberof StreamClient.prototype + * @param {string} event - Name of the event + * @param {function} callback - Function that is called when the event fires + * @example + * client.on('request', callback); + * client.on('response', callback); + */ on(event: string, callback: HandlerCallback) { - /** - * Support for global event callbacks - * This is useful for generic error and loading handling - * @method on - * @memberof StreamClient.prototype - * @param {string} event - Name of the event - * @param {function} callback - Function that is called when the event fires - * @example - * client.on('request', callback); - * client.on('response', callback); - */ this.handlers[event] = callback; } + /** + * Remove one or more event handlers + * @method off + * @memberof StreamClient.prototype + * @param {string} [key] - Name of the handler + * @example + * client.off() removes all handlers + * client.off(name) removes the specified handler + */ off(key?: string) { - /** - * Remove one or more event handlers - * @method off - * @memberof StreamClient.prototype - * @param {string} [key] - Name of the handler - * @example - * client.off() removes all handlers - * client.off(name) removes the specified handler - */ if (key === undefined) { this.handlers = {}; } else { @@ -361,37 +360,37 @@ export default class StreamClient< } } + /** + * Call the given handler with the arguments + * @method send + * @memberof StreamClient.prototype + * @access private + */ send(key: string, ...args: unknown[]) { - /** - * Call the given handler with the arguments - * @method send - * @memberof StreamClient.prototype - * @access private - */ if (this.handlers[key]) this.handlers[key].apply(this, args); } + /** + * Get the current user agent + * @method userAgent + * @memberof StreamClient.prototype + * @return {string} current user agent + */ userAgent() { - /** - * Get the current user agent - * @method userAgent - * @memberof StreamClient.prototype - * @return {string} current user agent - */ return `stream-javascript-client-${this.node ? 'node' : 'browser'}-${pkg.version}`; } + /** + * Returns a token that allows only read operations + * + * @method getReadOnlyToken + * @memberof StreamClient.prototype + * @param {string} feedSlug - The feed slug to get a read only token for + * @param {string} userId - The user identifier + * @return {string} token + * @example client.getReadOnlyToken('user', '1'); + */ getReadOnlyToken(feedSlug: string, userId: string) { - /** - * Returns a token that allows only read operations - * - * @method getReadOnlyToken - * @memberof StreamClient.prototype - * @param {string} feedSlug - The feed slug to get a read only token for - * @param {string} userId - The user identifier - * @return {string} token - * @example client.getReadOnlyToken('user', '1'); - */ utils.validateFeedSlug(feedSlug); utils.validateUserId(userId); @@ -401,17 +400,17 @@ export default class StreamClient< }); } + /** + * Returns a token that allows read and write operations + * + * @method getReadWriteToken + * @memberof StreamClient.prototype + * @param {string} feedSlug - The feed slug to get a read only token for + * @param {string} userId - The user identifier + * @return {string} token + * @example client.getReadWriteToken('user', '1'); + */ getReadWriteToken(feedSlug: string, userId: string) { - /** - * Returns a token that allows read and write operations - * - * @method getReadWriteToken - * @memberof StreamClient.prototype - * @param {string} feedSlug - The feed slug to get a read only token for - * @param {string} userId - The user identifier - * @return {string} token - * @example client.getReadWriteToken('user', '1'); - */ utils.validateFeedSlug(feedSlug); utils.validateUserId(userId); @@ -421,21 +420,21 @@ export default class StreamClient< }); } + /** + * Returns a feed object for the given feed id and token + * @method feed + * @memberof StreamClient.prototype + * @param {string} feedSlug - The feed slug + * @param {string} [userId] - The user identifier + * @param {string} [token] - The token + * @return {StreamFeed} + * @example client.feed('user', '1'); + */ feed( feedSlug: string, userId?: string | StreamUser, token?: string, ): StreamFeed { - /** - * Returns a feed object for the given feed id and token - * @method feed - * @memberof StreamClient.prototype - * @param {string} feedSlug - The feed slug - * @param {string} [userId] - The user identifier - * @param {string} [token] - The token - * @return {StreamFeed} - * @example client.feed('user', '1'); - */ if (userId instanceof StreamUser) userId = userId.id; if (token === undefined) { @@ -454,16 +453,16 @@ export default class StreamClient< ); } + /** + * Combines the base url with version and the relative url + * @method enrichUrl + * @memberof StreamClient.prototype + * @private + * @param {string} relativeUrl + * @param {string} [serviceName] + * @return {string} + */ enrichUrl(relativeUrl: string, serviceName?: string) { - /** - * Combines the base url with version and the relative url - * @method enrichUrl - * @memberof StreamClient.prototype - * @private - * @param {string} relativeUrl - * @param {string} [serviceName] - * @return {string} - */ return `${this.getBaseUrl(serviceName)}${this.version}/${relativeUrl}`; } @@ -516,15 +515,15 @@ export default class StreamClient< ); } + /** + * Adds the API key and the signature + * @method enrichKwargs + * @private + * @memberof StreamClient.prototype + * @param {AxiosConfig} kwargs + * @return {axios.AxiosRequestConfig} + */ enrichKwargs({ method, signature, ...kwargs }: AxiosConfig & { method: axios.Method }): axios.AxiosRequestConfig { - /** - * Adds the API key and the signature - * @method enrichKwargs - * @private - * @memberof StreamClient.prototype - * @param {AxiosConfig} kwargs - * @return {axios.AxiosRequestConfig} - */ const isJWT = signing.isJWTSignature(signature); return { @@ -546,14 +545,14 @@ export default class StreamClient< }; } + /** + * Get the authorization middleware to use Faye with getstream.io + * @method getFayeAuthorization + * @memberof StreamClient.prototype + * @private + * @return {Faye.Middleware} Faye authorization middleware + */ getFayeAuthorization(): Faye.Middleware { - /** - * Get the authorization middleware to use Faye with getstream.io - * @method getFayeAuthorization - * @memberof StreamClient.prototype - * @private - * @return {Faye.Middleware} Faye authorization middleware - */ return { incoming: (message: Faye.Message, callback: Faye.Callback) => callback(message), outgoing: (message: Faye.Message, callback: Faye.Callback) => { @@ -572,15 +571,15 @@ export default class StreamClient< }; } + /** + * Returns this client's current Faye client + * @method getFayeClient + * @memberof StreamClient.prototype + * @private + * @param {number} timeout + * @return {Faye.Client} Faye client + */ getFayeClient(timeout = 10) { - /** - * Returns this client's current Faye client - * @method getFayeClient - * @memberof StreamClient.prototype - * @private - * @param {number} timeout - * @return {Faye.Client} Faye client - */ if (this.fayeClient === null) { this.fayeClient = new Faye.Client(this.fayeUrl, { timeout }); const authExtension = this.getFayeAuthorization(); @@ -636,60 +635,60 @@ export default class StreamClient< }); } + /** + * Shorthand function for get request + * @method get + * @memberof StreamClient.prototype + * @private + * @param {AxiosConfig} kwargs + * @return {Promise} Promise object + */ get(kwargs: AxiosConfig) { - /** - * Shorthand function for get request - * @method get - * @memberof StreamClient.prototype - * @private - * @param {AxiosConfig} kwargs - * @return {Promise} Promise object - */ return this.doAxiosRequest('GET', kwargs); } + /** + * Shorthand function for post request + * @method post + * @memberof StreamClient.prototype + * @private + * @param {AxiosConfig} kwargs + * @return {Promise} Promise object + */ post(kwargs: AxiosConfig) { - /** - * Shorthand function for post request - * @method post - * @memberof StreamClient.prototype - * @private - * @param {AxiosConfig} kwargs - * @return {Promise} Promise object - */ return this.doAxiosRequest('POST', kwargs); } + /** + * Shorthand function for delete request + * @method delete + * @memberof StreamClient.prototype + * @private + * @param {AxiosConfig} kwargs + * @return {Promise} Promise object + */ delete(kwargs: AxiosConfig) { - /** - * Shorthand function for delete request - * @method delete - * @memberof StreamClient.prototype - * @private - * @param {AxiosConfig} kwargs - * @return {Promise} Promise object - */ return this.doAxiosRequest('DELETE', kwargs); } + /** + * Shorthand function for put request + * @method put + * @memberof StreamClient.prototype + * @private + * @param {AxiosConfig} kwargs + * @return {Promise} Promise object + */ put(kwargs: AxiosConfig) { - /** - * Shorthand function for put request - * @method put - * @memberof StreamClient.prototype - * @private - * @param {AxiosConfig} kwargs - * @return {Promise} Promise object - */ return this.doAxiosRequest('PUT', kwargs); } + /** + * @param {string} userId + * @param {object} extraData + * @return {string} + */ createUserToken(userId: string, extraData = {}) { - /** - * @param {string} userId - * @param {object} extraData - * @return {string} - */ this._throwMissingApiSecret(); return signing.JWTUserSessionToken(this.apiSecret as string, userId, extraData, { @@ -697,13 +696,13 @@ export default class StreamClient< }); } + /** + * Updates all supplied activities on the getstream-io api + * @since 3.1.0 + * @param {UpdateActivity[]} activities list of activities to update + * @return {Promise} + */ updateActivities(activities: UpdateActivity[]) { - /** - * Updates all supplied activities on the getstream-io api - * @since 3.1.0 - * @param {UpdateActivity[]} activities list of activities to update - * @return {Promise} - */ this._throwMissingApiSecret(); if (!(activities instanceof Array)) { @@ -722,18 +721,24 @@ export default class StreamClient< }); } + /** + * Updates one activity on the getstream-io api + * @since 3.1.0 + * @param {UpdateActivity} activity The activity to update + * @return {Promise} + */ updateActivity(activity: UpdateActivity) { - /** - * Updates one activity on the getstream-io api - * @since 3.1.0 - * @param {UpdateActivity} activity The activity to update - * @return {Promise} - */ this._throwMissingApiSecret(); return this.updateActivities([activity]); } + /** + * Retrieve activities by ID or foreign ID and time + * @since 3.19.0 + * @param {object} params object containing either the list of activity IDs as {ids: ['...', ...]} or foreign IDs and time as {foreignIDTimes: [{foreignID: ..., time: ...}, ...]} + * @return {Promise} + */ getActivities({ ids, foreignIDTimes, @@ -743,12 +748,6 @@ export default class StreamClient< ids?: string[]; reactions?: Record; }) { - /** - * Retrieve activities by ID or foreign ID and time - * @since 3.19.0 - * @param {object} params object containing either the list of activity IDs as {ids: ['...', ...]} or foreign IDs and time as {foreignIDTimes: [{foreignID: ..., time: ...}, ...]} - * @return {Promise} - */ const extraParams: { foreign_ids?: string; ids?: string; timestamps?: string } = {}; if (ids) { @@ -838,102 +837,102 @@ export default class StreamClient< }); } + /** + * Update a single activity with partial operations. + * @since 3.20.0 + * @param {ActivityPartialChanges} data object containing either the ID or the foreign ID and time of the activity and the operations to issue as set:{...} and unset:[...]. + * @return {Promise>} + * @example + * client.activityPartialUpdate({ + * id: "54a60c1e-4ee3-494b-a1e3-50c06acb5ed4", + * set: { + * "product.price": 19.99, + * "shares": { + * "facebook": "...", + * "twitter": "...", + * } + * }, + * unset: [ + * "daily_likes", + * "popularity" + * ] + * }) + * @example + * client.activityPartialUpdate({ + * foreignID: "product:123", + * time: "2016-11-10T13:20:00.000000", + * set: { + * ... + * }, + * unset: [ + * ... + * ] + * }) + */ async activityPartialUpdate( data: ActivityPartialChanges, ): Promise> { - /** - * Update a single activity with partial operations. - * @since 3.20.0 - * @param {ActivityPartialChanges} data object containing either the ID or the foreign ID and time of the activity and the operations to issue as set:{...} and unset:[...]. - * @return {Promise>} - * @example - * client.activityPartialUpdate({ - * id: "54a60c1e-4ee3-494b-a1e3-50c06acb5ed4", - * set: { - * "product.price": 19.99, - * "shares": { - * "facebook": "...", - * "twitter": "...", - * } - * }, - * unset: [ - * "daily_likes", - * "popularity" - * ] - * }) - * @example - * client.activityPartialUpdate({ - * foreignID: "product:123", - * time: "2016-11-10T13:20:00.000000", - * set: { - * ... - * }, - * unset: [ - * ... - * ] - * }) - */ const response = await this.activitiesPartialUpdate([data]); const activity = response.activities[0]; delete response.activities; return { ...activity, ...response }; } + /** + * Update multiple activities with partial operations. + * @since v3.20.0 + * @param {ActivityPartialChanges[]} changes array containing the changesets to be applied. Every changeset contains the activity identifier which is either the ID or the pair of of foreign ID and time of the activity. The operations to issue can be set:{...} and unset:[...]. + * @return {Promise<{ activities: Activity[] }>} + * @example + * client.activitiesPartialUpdate([ + * { + * id: "4b39fda2-d6e2-42c9-9abf-5301ef071b12", + * set: { + * "product.price.eur": 12.99, + * "colors": { + * "blue": "#0000ff", + * "green": "#00ff00", + * }, + * }, + * unset: [ "popularity", "size.x2" ], + * }, + * { + * id: "8d2dcad8-1e34-11e9-8b10-9cb6d0925edd", + * set: { + * "product.price.eur": 17.99, + * "colors": { + * "red": "#ff0000", + * "green": "#00ff00", + * }, + * }, + * unset: [ "rating" ], + * }, + * ]) + * @example + * client.activitiesPartialUpdate([ + * { + * foreignID: "product:123", + * time: "2016-11-10T13:20:00.000000", + * set: { + * ... + * }, + * unset: [ + * ... + * ] + * }, + * { + * foreignID: "product:321", + * time: "2016-11-10T13:20:00.000000", + * set: { + * ... + * }, + * unset: [ + * ... + * ] + * }, + * ]) + */ activitiesPartialUpdate(changes: ActivityPartialChanges[]) { - /** - * Update multiple activities with partial operations. - * @since v3.20.0 - * @param {ActivityPartialChanges[]} changes array containing the changesets to be applied. Every changeset contains the activity identifier which is either the ID or the pair of of foreign ID and time of the activity. The operations to issue can be set:{...} and unset:[...]. - * @return {Promise<{ activities: Activity[] }>} - * @example - * client.activitiesPartialUpdate([ - * { - * id: "4b39fda2-d6e2-42c9-9abf-5301ef071b12", - * set: { - * "product.price.eur": 12.99, - * "colors": { - * "blue": "#0000ff", - * "green": "#00ff00", - * }, - * }, - * unset: [ "popularity", "size.x2" ], - * }, - * { - * id: "8d2dcad8-1e34-11e9-8b10-9cb6d0925edd", - * set: { - * "product.price.eur": 17.99, - * "colors": { - * "red": "#ff0000", - * "green": "#00ff00", - * }, - * }, - * unset: [ "rating" ], - * }, - * ]) - * @example - * client.activitiesPartialUpdate([ - * { - * foreignID: "product:123", - * time: "2016-11-10T13:20:00.000000", - * set: { - * ... - * }, - * unset: [ - * ... - * ] - * }, - * { - * foreignID: "product:321", - * time: "2016-11-10T13:20:00.000000", - * set: { - * ... - * }, - * unset: [ - * ... - * ] - * }, - * ]) - */ if (!(changes instanceof Array)) { throw new TypeError('changes should be an Array'); } diff --git a/src/collections.ts b/src/collections.ts index 35f717f7..4c784913 100644 --- a/src/collections.ts +++ b/src/collections.ts @@ -57,57 +57,57 @@ export class CollectionEntry>} + * @example collection.get("0c7db91c-67f9-11e8-bcd9-fe00a9219401") + */ async get() { - /** - * get item from collection and sync data - * @method get - * @memberof CollectionEntry.prototype - * @return {Promise>} - * @example collection.get("0c7db91c-67f9-11e8-bcd9-fe00a9219401") - */ const response = await this.store.get(this.collection, this.id); this.data = response.data; this.full = response; return response; } + /** + * Add item to collection + * @method add + * @memberof CollectionEntry.prototype + * @return {Promise>} + * @example collection.add("cheese101", {"name": "cheese burger","toppings": "cheese"}) + */ async add() { - /** - * Add item to collection - * @method add - * @memberof CollectionEntry.prototype - * @return {Promise>} - * @example collection.add("cheese101", {"name": "cheese burger","toppings": "cheese"}) - */ const response = await this.store.add(this.collection, this.id, this.data as CollectionType); this.data = response.data; this.full = response; return response; } + /** + * Update item in the object storage + * @method update + * @memberof CollectionEntry.prototype + * @return {Promise>} + * @example store.update("0c7db91c-67f9-11e8-bcd9-fe00a9219401", {"name": "cheese burger","toppings": "cheese"}) + * @example store.update("cheese101", {"name": "cheese burger","toppings": "cheese"}) + */ async update() { - /** - * Update item in the object storage - * @method update - * @memberof CollectionEntry.prototype - * @return {Promise>} - * @example store.update("0c7db91c-67f9-11e8-bcd9-fe00a9219401", {"name": "cheese burger","toppings": "cheese"}) - * @example store.update("cheese101", {"name": "cheese burger","toppings": "cheese"}) - */ const response = await this.store.update(this.collection, this.id, this.data as CollectionType); this.data = response.data; this.full = response; return response; } + /** + * Delete item from collection + * @method delete + * @memberof CollectionEntry.prototype + * @return {Promise} + * @example collection.delete("cheese101") + */ async delete() { - /** - * Delete item from collection - * @method delete - * @memberof CollectionEntry.prototype - * @return {Promise} - * @example collection.delete("cheese101") - */ const response = await this.store.delete(this.collection, this.id); this.data = null; this.full = null; @@ -140,16 +140,16 @@ export default class Collections(this, collection, itemId, itemData); } + /** + * get item from collection + * @method get + * @memberof Collections.prototype + * @param {string} collection collection name + * @param {string} itemId id for this entry + * @return {Promise>} + * @example collection.get("food", "0c7db91c-67f9-11e8-bcd9-fe00a9219401") + */ async get(collection: string, itemId: string) { - /** - * get item from collection - * @method get - * @memberof Collections.prototype - * @param {string} collection collection name - * @param {string} itemId id for this entry - * @return {Promise>} - * @example collection.get("food", "0c7db91c-67f9-11e8-bcd9-fe00a9219401") - */ const response = await this.client.get>({ url: this.buildURL(collection, itemId), signature: this.token, @@ -160,17 +160,17 @@ export default class Collections>} + * @example collection.add("food", "cheese101", {"name": "cheese burger","toppings": "cheese"}) + */ async add(collection: string, itemId: string, itemData: CollectionType) { - /** - * Add item to collection - * @method add - * @memberof Collections.prototype - * @param {string} collection collection name - * @param {string} itemId entry id - * @param {CollectionType} itemData ObjectStore data - * @return {Promise>} - * @example collection.add("food", "cheese101", {"name": "cheese burger","toppings": "cheese"}) - */ const response = await this.client.post>({ url: this.buildURL(collection), body: { @@ -185,18 +185,18 @@ export default class Collections>} + * @example store.update("0c7db91c-67f9-11e8-bcd9-fe00a9219401", {"name": "cheese burger","toppings": "cheese"}) + * @example store.update("food", "cheese101", {"name": "cheese burger","toppings": "cheese"}) + */ async update(collection: string, entryId: string, data: CollectionType) { - /** - * Update entry in the collection - * @method update - * @memberof Collections.prototype - * @param {string} collection collection name - * @param {string} entryId Collection object id - * @param {CollectionType} data ObjectStore data - * @return {Promise>} - * @example store.update("0c7db91c-67f9-11e8-bcd9-fe00a9219401", {"name": "cheese burger","toppings": "cheese"}) - * @example store.update("food", "cheese101", {"name": "cheese burger","toppings": "cheese"}) - */ const response = await this.client.put>({ url: this.buildURL(collection, entryId), body: { data }, @@ -208,32 +208,32 @@ export default class Collections} Promise object + * @example collection.delete("food", "cheese101") + */ delete(collection: string, entryId: string) { - /** - * Delete entry from collection - * @method delete - * @memberof Collections.prototype - * @param {string} collection collection name - * @param {string} entryId Collection entry id - * @return {Promise} Promise object - * @example collection.delete("food", "cheese101") - */ return this.client.delete({ url: this.buildURL(collection, entryId), signature: this.token, }); } + /** + * Upsert one or more items within a collection. + * + * @method upsert + * @memberof Collections.prototype + * @param {string} collection collection name + * @param {NewCollectionEntry | NewCollectionEntry[]} data - A single json object or an array of objects + * @return {Promise>} + */ upsert(collection: string, data: NewCollectionEntry | NewCollectionEntry[]) { - /** - * Upsert one or more items within a collection. - * - * @method upsert - * @memberof Collections.prototype - * @param {string} collection collection name - * @param {NewCollectionEntry | NewCollectionEntry[]} data - A single json object or an array of objects - * @return {Promise>} - */ if (!this.client.usingApiSecret) { throw new errors.SiteError('This method can only be used server-side using your API Secret'); } @@ -248,16 +248,16 @@ export default class Collections>} + */ select(collection: string, ids: string | string[]) { - /** - * Select all objects with ids from the collection. - * - * @method select - * @memberof Collections.prototype - * @param {string} collection collection name - * @param {string | string[]} ids - A single object id or an array of ids - * @return {Promise>} - */ if (!this.client.usingApiSecret) { throw new errors.SiteError('This method can only be used server-side using your API Secret'); } @@ -272,16 +272,16 @@ export default class Collections} + */ deleteMany(collection: string, ids: string | string[]) { - /** - * Remove all objects by id from the collection. - * - * @method delete - * @memberof Collections.prototype - * @param {string} collection collection name - * @param {string | string[]} ids - A single object id or an array of ids - * @return {Promise} - */ if (!this.client.usingApiSecret) { throw new errors.SiteError('This method can only be used server-side using your API Secret'); } diff --git a/src/connect.ts b/src/connect.ts index 10e97d05..ff13de6a 100644 --- a/src/connect.ts +++ b/src/connect.ts @@ -1,5 +1,27 @@ import StreamClient, { UnknownRecord, ClientOptions } from './client'; +/** + * Create StreamClient + * @method connect + * @param {string} apiKey API key + * @param {string} [apiSecret] API secret (only use this on the server) + * @param {string} [appId] Application identifier + * @param {ClientOptions} [options] - additional options + * @param {string} [options.location] - which data center to use + * @param {boolean} [options.expireTokens=false] - whether to use a JWT timestamp field (i.e. iat) + * @param {string} [options.version] - advanced usage, custom api version + * @param {boolean} [options.keepAlive] - axios keepAlive, default to true + * @param {number} [options.timeout] - axios timeout in Ms, default to 10s + * @return {StreamClient} StreamClient + * @example Basic usage + * stream.connect(apiKey, apiSecret); + * @example or if you want to be able to subscribe and listen + * stream.connect(apiKey, apiSecret, appId); + * @example or on Heroku + * stream.connect(streamURL); + * @example where streamURL looks like + * "https://thierry:pass@gestream.io/?app=1" + */ export function connect< UserType extends UnknownRecord = UnknownRecord, ActivityType extends UnknownRecord = UnknownRecord, @@ -8,28 +30,6 @@ export function connect< ChildReactionType extends UnknownRecord = UnknownRecord, PersonalizationType extends UnknownRecord = UnknownRecord >(apiKey: string, apiSecret: string | null, appId?: string, options?: ClientOptions) { - /** - * Create StreamClient - * @method connect - * @param {string} apiKey API key - * @param {string} [apiSecret] API secret (only use this on the server) - * @param {string} [appId] Application identifier - * @param {ClientOptions} [options] - additional options - * @param {string} [options.location] - which data center to use - * @param {boolean} [options.expireTokens=false] - whether to use a JWT timestamp field (i.e. iat) - * @param {string} [options.version] - advanced usage, custom api version - * @param {boolean} [options.keepAlive] - axios keepAlive, default to true - * @param {number} [options.timeout] - axios timeout in Ms, default to 10s - * @return {StreamClient} StreamClient - * @example Basic usage - * stream.connect(apiKey, apiSecret); - * @example or if you want to be able to subscribe and listen - * stream.connect(apiKey, apiSecret, appId); - * @example or on Heroku - * stream.connect(streamURL); - * @example where streamURL looks like - * "https://thierry:pass@gestream.io/?app=1" - */ if (typeof process !== 'undefined' && process.env && process.env.STREAM_URL && !apiKey) { const parts = /https:\/\/(\w+):(\w+)@([\w-]*).*\?app_id=(\d+)/.exec(process.env.STREAM_URL) || []; apiKey = parts[1]; diff --git a/src/feed.ts b/src/feed.ts index 539886e8..1c039cb3 100644 --- a/src/feed.ts +++ b/src/feed.ts @@ -229,17 +229,16 @@ export default class StreamFeed< signature: string; notificationChannel: string; + /** + * Initialize a feed object + * @method constructor + * @memberof StreamFeed.prototype + * @param {StreamClient} client - The stream client this feed is constructed from + * @param {string} feedSlug - The feed slug + * @param {string} userId - The user id + * @param {string} [token] - The authentication token + */ constructor(client: StreamClient, feedSlug: string, userId: string, token: string) { - /** - * Initialize a feed object - * @method constructor - * @memberof StreamFeed.prototype - * @param {StreamClient} client - The stream client this feed is constructed from - * @param {string} feedSlug - The feed slug - * @param {string} userId - The user id - * @param {string} [token] - The authentication token - */ - if (!feedSlug || !userId) { throw new errors.FeedError('Please provide a feed slug and user id, ie client.feed("user", "1")'); } @@ -270,15 +269,14 @@ export default class StreamFeed< this.notificationChannel = `site-${this.client.appId}-feed-${this.feedTogether}`; } + /** + * Adds the given activity to the feed + * @method addActivity + * @memberof StreamFeed.prototype + * @param {NewActivity} activity - The activity to add + * @return {Promise>} + */ addActivity(activity: NewActivity) { - /** - * Adds the given activity to the feed - * @method addActivity - * @memberof StreamFeed.prototype - * @param {NewActivity} activity - The activity to add - * @return {Promise>} - */ - activity = utils.replaceStreamObjects(activity); if (!activity.actor && this.client.currentUser) { activity.actor = this.client.currentUser.ref(); @@ -291,16 +289,16 @@ export default class StreamFeed< }); } + /** + * Removes the activity by activityId or foreignId + * @method removeActivity + * @memberof StreamFeed.prototype + * @param {string} activityId Identifier of activity to remove + * @return {Promise} + * @example feed.removeActivity(activityId); + * @example feed.removeActivity({'foreignId': foreignId}); + */ removeActivity(activityId: string | { foreignId: string }) { - /** - * Removes the activity by activityId or foreignId - * @method removeActivity - * @memberof StreamFeed.prototype - * @param {string} activityId Identifier of activity to remove - * @return {Promise} - * @example feed.removeActivity(activityId); - * @example feed.removeActivity({'foreignId': foreignId}); - */ return this.client.delete({ url: `feed/${this.feedUrl}/${(activityId as { foreignId: string }).foreignId || activityId}/`, qs: (activityId as { foreignId: string }).foreignId ? { foreign_id: '1' } : {}, @@ -308,14 +306,14 @@ export default class StreamFeed< }); } + /** + * Adds the given activities to the feed + * @method addActivities + * @memberof StreamFeed.prototype + * @param {NewActivity[]} activities Array of activities to add + * @return {Promise[]>} + */ addActivities(activities: NewActivity[]) { - /** - * Adds the given activities to the feed - * @method addActivities - * @memberof StreamFeed.prototype - * @param {NewActivity[]} activities Array of activities to add - * @return {Promise[]>} - */ return this.client.post[]>({ url: `feed/${this.feedUrl}/`, body: { activities: utils.replaceStreamObjects(activities) }, @@ -323,20 +321,20 @@ export default class StreamFeed< }); } + /** + * Follows the given target feed + * @method follow + * @memberof StreamFeed.prototype + * @param {string} targetSlug Slug of the target feed + * @param {string} targetUserId User identifier of the target feed + * @param {object} [options] Additional options + * @param {number} [options.limit] Limit the amount of activities copied over on follow + * @return {Promise} + * @example feed.follow('user', '1'); + * @example feed.follow('user', '1'); + * @example feed.follow('user', '1', options); + */ follow(targetSlug: string, targetUserId: string | { id: string }, options: { limit?: number } = {}) { - /** - * Follows the given target feed - * @method follow - * @memberof StreamFeed.prototype - * @param {string} targetSlug Slug of the target feed - * @param {string} targetUserId User identifier of the target feed - * @param {object} [options] Additional options - * @param {number} [options.limit] Limit the amount of activities copied over on follow - * @return {Promise} - * @example feed.follow('user', '1'); - * @example feed.follow('user', '1'); - * @example feed.follow('user', '1', options); - */ if (targetUserId instanceof StreamUser) { targetUserId = targetUserId.id; } @@ -353,19 +351,19 @@ export default class StreamFeed< }); } + /** + * Unfollow the given feed + * @method unfollow + * @memberof StreamFeed.prototype + * @param {string} targetSlug Slug of the target feed + * @param {string} targetUserId User identifier of the target feed + * @param {object} [options] + * @param {boolean} [options.keepHistory] when provided the activities from target + * feed will not be kept in the feed + * @return {Promise} + * @example feed.unfollow('user', '2'); + */ unfollow(targetSlug: string, targetUserId: string, options: { keepHistory?: boolean } = {}) { - /** - * Unfollow the given feed - * @method unfollow - * @memberof StreamFeed.prototype - * @param {string} targetSlug Slug of the target feed - * @param {string} targetUserId User identifier of the target feed - * @param {object} [options] - * @param {boolean} [options.keepHistory] when provided the activities from target - * feed will not be kept in the feed - * @return {Promise} - * @example feed.unfollow('user', '2'); - */ const qs: { keep_history?: string } = {}; if (typeof options.keepHistory === 'boolean' && options.keepHistory) qs.keep_history = '1'; @@ -379,18 +377,18 @@ export default class StreamFeed< }); } + /** + * List which feeds this feed is following + * @method following + * @memberof StreamFeed.prototype + * @param {GetFollowOptions} [options] Additional options + * @param {string[]} options.filter array of feed id to filter on + * @param {number} options.limit pagination + * @param {number} options.offset pagination + * @return {Promise} + * @example feed.following({limit:10, filter: ['user:1', 'user:2']}); + */ following(options: GetFollowOptions = {}) { - /** - * List which feeds this feed is following - * @method following - * @memberof StreamFeed.prototype - * @param {GetFollowOptions} [options] Additional options - * @param {string[]} options.filter array of feed id to filter on - * @param {number} options.limit pagination - * @param {number} options.offset pagination - * @return {Promise} - * @example feed.following({limit:10, filter: ['user:1', 'user:2']}); - */ const extraOptions: { filter?: string } = {}; if (options.filter) extraOptions.filter = options.filter.join(','); @@ -401,18 +399,18 @@ export default class StreamFeed< }); } + /** + * List the followers of this feed + * @method followers + * @memberof StreamFeed.prototype + * @param {GetFollowOptions} [options] Additional options + * @param {string[]} options.filter array of feed id to filter on + * @param {number} options.limit pagination + * @param {number} options.offset pagination + * @return {Promise} + * @example feed.followers({limit:10, filter: ['user:1', 'user:2']}); + */ followers(options: GetFollowOptions = {}) { - /** - * List the followers of this feed - * @method followers - * @memberof StreamFeed.prototype - * @param {GetFollowOptions} [options] Additional options - * @param {string[]} options.filter array of feed id to filter on - * @param {number} options.limit pagination - * @param {number} options.offset pagination - * @return {Promise} - * @example feed.followers({limit:10, filter: ['user:1', 'user:2']}); - */ const extraOptions: { filter?: string } = {}; if (options.filter) extraOptions.filter = options.filter.join(','); @@ -423,17 +421,16 @@ export default class StreamFeed< }); } + /** + * Reads the feed + * @method get + * @memberof StreamFeed.prototype + * @param {GetFeedOptions & NotificationFeedOptions} options Additional options + * @return {Promise} + * @example feed.get({limit: 10, id_lte: 'activity-id'}) + * @example feed.get({limit: 10, mark_seen: true}) + */ get(options: GetFeedOptions & NotificationFeedOptions = {}) { - /** - * Reads the feed - * @method get - * @memberof StreamFeed.prototype - * @param {GetFeedOptions & NotificationFeedOptions} options Additional options - * @return {Promise} - * @example feed.get({limit: 10, id_lte: 'activity-id'}) - * @example feed.get({limit: 10, mark_seen: true}) - */ - const extraOptions: { mark_read?: boolean | string; mark_seen?: boolean | string } = {}; if (options.mark_read && (options.mark_read as string[]).join) { @@ -455,19 +452,19 @@ export default class StreamFeed< }); } + /** + * Retrieves one activity from a feed and adds enrichment + * @method getActivityDetail + * @memberof StreamFeed.prototype + * @param {string} activityId Identifier of activity to retrieve + * @param {EnrichOptions} options Additional options + * @return {Promise} + * @example feed.getActivityDetail(activityId) + * @example feed.getActivityDetail(activityId, {withRecentReactions: true}) + * @example feed.getActivityDetail(activityId, {withReactionCounts: true}) + * @example feed.getActivityDetail(activityId, {withOwnReactions: true, withReactionCounts: true}) + */ getActivityDetail(activityId: string, options: EnrichOptions) { - /** - * Retrieves one activity from a feed and adds enrichment - * @method getActivityDetail - * @memberof StreamFeed.prototype - * @param {string} activityId Identifier of activity to retrieve - * @param {EnrichOptions} options Additional options - * @return {Promise} - * @example feed.getActivityDetail(activityId) - * @example feed.getActivityDetail(activityId, {withRecentReactions: true}) - * @example feed.getActivityDetail(activityId, {withReactionCounts: true}) - * @example feed.getActivityDetail(activityId, {withOwnReactions: true, withReactionCounts: true}) - */ return this.get({ id_lte: activityId, id_gte: activityId, @@ -476,29 +473,29 @@ export default class StreamFeed< }); } + /** + * Returns the current faye client object + * @method getFayeClient + * @memberof StreamFeed.prototype + * @access private + * @return {Faye.Client} Faye client + */ getFayeClient() { - /** - * Returns the current faye client object - * @method getFayeClient - * @memberof StreamFeed.prototype - * @access private - * @return {Faye.Client} Faye client - */ return this.client.getFayeClient(); } + /** + * Subscribes to any changes in the feed, return a promise + * @method subscribe + * @memberof StreamFeed.prototype + * @param {function} callback Callback to call on completion + * @return {Promise} + * @example + * feed.subscribe(callback).then(function(){ + * console.log('we are now listening to changes'); + * }); + */ subscribe(callback: Faye.Callback) { - /** - * Subscribes to any changes in the feed, return a promise - * @method subscribe - * @memberof StreamFeed.prototype - * @param {function} callback Callback to call on completion - * @return {Promise} - * @example - * feed.subscribe(callback).then(function(){ - * console.log('we are now listening to changes'); - * }); - */ if (!this.client.appId) { throw new errors.SiteError( 'Missing app id, which is needed to subscribe, use var client = stream.connect(key, secret, appId);', @@ -515,11 +512,11 @@ export default class StreamFeed< return subscription; } + /** + * Cancel updates created via feed.subscribe() + * @return void + */ unsubscribe() { - /** - * Cancel updates created via feed.subscribe() - * @return void - */ const streamSubscription = this.client.subscriptions[`/${this.notificationChannel}`]; if (streamSubscription) { delete this.client.subscriptions[`/${this.notificationChannel}`]; @@ -527,6 +524,15 @@ export default class StreamFeed< } } + /** + * Updates an activity's "to" fields + * @since 3.10.0 + * @param {string} foreignId The foreign_id of the activity to update + * @param {string} time The time of the activity to update + * @param {string[]} newTargets Set the new "to" targets for the activity - will remove old targets + * @param {string[]} added_targets Add these new targets to the activity + * @param {string[]} removedTargets Remove these targets from the activity + */ updateActivityToTargets( foreignId: string, time: string, @@ -534,16 +540,6 @@ export default class StreamFeed< addedTargets?: string[], removedTargets?: string[], ) { - /** - * Updates an activity's "to" fields - * @since 3.10.0 - * @param {string} foreignId The foreign_id of the activity to update - * @param {string} time The time of the activity to update - * @param {string[]} newTargets Set the new "to" targets for the activity - will remove old targets - * @param {string[]} added_targets Add these new targets to the activity - * @param {string[]} removedTargets Remove these targets from the activity - */ - if (!foreignId) throw new Error('Missing `foreign_id` parameter!'); if (!time) throw new Error('Missing `time` parameter!'); diff --git a/src/files.ts b/src/files.ts index d1013c3f..d2785e5d 100644 --- a/src/files.ts +++ b/src/files.ts @@ -11,20 +11,20 @@ export default class StreamFileStore { // React Native does not auto-detect MIME type, you need to pass that via contentType // param. If you don't then Android will refuse to perform the upload + /** + * upload a File instance or a readable stream of data + * @param {File|NodeJS.ReadStream|string} uri - File object or stream or URI + * @param {string} [name] - file name + * @param {string} [contentType] - mime-type + * @param {function} [onUploadProgress] - browser only, Function that is called with upload progress + * @return {Promise} + */ upload( uri: string | File | NodeJS.ReadStream, name?: string, contentType?: string, onUploadProgress?: OnUploadProgress, ) { - /** - * upload a File instance or a readable stream of data - * @param {File|NodeJS.ReadStream|string} uri - File object or stream or URI - * @param {string} [name] - file name - * @param {string} [contentType] - mime-type - * @param {function} [onUploadProgress] - browser only, Function that is called with upload progress - * @return {Promise} - */ return this.client.upload('files/', uri, name, contentType, onUploadProgress); } diff --git a/src/images.ts b/src/images.ts index 2a2ab8a0..02566d6b 100644 --- a/src/images.ts +++ b/src/images.ts @@ -19,20 +19,20 @@ export default class StreamImageStore { // React Native does not auto-detect MIME type, you need to pass that via contentType // param. If you don't then Android will refuse to perform the upload + /** + * upload an Image File instance or a readable stream of data + * @param {File|NodeJS.ReadStream|string} uri - File object or stream or URI + * @param {string} [name] - file name + * @param {string} [contentType] - mime-type + * @param {function} [onUploadProgress] - browser only, Function that is called with upload progress + * @return {Promise} + */ upload( uri: string | File | NodeJS.ReadStream, name?: string, contentType?: string, onUploadProgress?: OnUploadProgress, ) { - /** - * upload an Image File instance or a readable stream of data - * @param {File|NodeJS.ReadStream|string} uri - File object or stream or URI - * @param {string} [name] - file name - * @param {string} [contentType] - mime-type - * @param {function} [onUploadProgress] - browser only, Function that is called with upload progress - * @return {Promise} - */ return this.client.upload('images/', uri, name, contentType, onUploadProgress); } diff --git a/src/personalization.ts b/src/personalization.ts index d6ef1492..2657385c 100644 --- a/src/personalization.ts +++ b/src/personalization.ts @@ -18,28 +18,28 @@ export type PersonalizationAPIResponse { client: StreamClient; + /** + * Initialize the Personalization class + * + * @method constructor + * @memberof Personalization.prototype + * @param {StreamClient} client - The stream client + */ constructor(client: StreamClient) { - /** - * Initialize the Personalization class - * - * @method constructor - * @memberof Personalization.prototype - * @param {StreamClient} client - The stream client - */ this.client = client; } + /** + * Get personalized activities for this feed + * + * @method get + * @memberof Personalization.prototype + * @param {string} resource - personalized resource endpoint i.e "follow_recommendations" + * @param {object} options Additional options + * @return {Promise>} Promise object. Personalized feed + * @example client.personalization.get('follow_recommendations', {foo: 'bar', baz: 'qux'}) + */ get(resource: string, options: Record & { token?: string } = {}) { - /** - * Get personalized activities for this feed - * - * @method get - * @memberof Personalization.prototype - * @param {string} resource - personalized resource endpoint i.e "follow_recommendations" - * @param {object} options Additional options - * @return {Promise>} Promise object. Personalized feed - * @example client.personalization.get('follow_recommendations', {foo: 'bar', baz: 'qux'}) - */ return this.client.get>({ url: `${resource}/`, serviceName: 'personalization', @@ -48,18 +48,18 @@ export default class Personalization>} Promise object. Data that was posted if successful, or an error. + * @example client.personalization.post('follow_recommendations', {foo: 'bar', baz: 'qux'}) + */ post(resource: string, options: Record = {}, data: UnknownRecord = {}) { - /** - * Post data to personalization endpoint - * - * @method post - * @memberof Personalization.prototype - * @param {string} resource - personalized resource endpoint i.e "follow_recommendations" - * @param {object} options - Additional options - * @param {object} data - Data to send in the payload - * @return {Promise>} Promise object. Data that was posted if successful, or an error. - * @example client.personalization.post('follow_recommendations', {foo: 'bar', baz: 'qux'}) - */ return this.client.post>({ url: `${resource}/`, serviceName: 'personalization', @@ -69,17 +69,17 @@ export default class Personalization>} Promise object. Data that was deleted if successful, or an error. + * @example client.personalization.delete('follow_recommendations', {foo: 'bar', baz: 'qux'}) + */ delete(resource: string, options: Record = {}) { - /** - * Delete metadata or activities - * - * @method delete - * @memberof Personalization.prototype - * @param {object} resource - personalized resource endpoint i.e "follow_recommendations" - * @param {object} options - Additional options - * @return {Promise>} Promise object. Data that was deleted if successful, or an error. - * @example client.personalization.delete('follow_recommendations', {foo: 'bar', baz: 'qux'}) - */ return this.client.delete>({ url: `${resource}/`, serviceName: 'personalization', diff --git a/src/reaction.ts b/src/reaction.ts index 47b049db..4e5e7890 100644 --- a/src/reaction.ts +++ b/src/reaction.ts @@ -75,15 +75,15 @@ export default class StreamReaction< client: StreamClient; token: string; + /** + * Initialize a reaction object + * @method constructor + * @memberof StreamReaction.prototype + * @param {StreamClient} client Stream client this feed is constructed from + * @param {string} token JWT token + * @example new StreamReaction(client, "eyJhbGciOiJIUzI1...") + */ constructor(client: StreamClient, token: string) { - /** - * Initialize a reaction object - * @method constructor - * @memberof StreamReaction.prototype - * @param {StreamClient} client Stream client this feed is constructed from - * @param {string} token JWT token - * @example new StreamReaction(client, "eyJhbGciOiJIUzI1...") - */ this.client = client; this.token = token; } @@ -115,6 +115,22 @@ export default class StreamReaction< return targetFeeds.map((elem: TargetFeed) => (typeof elem === 'string' ? elem : (elem as StreamFeed).id)); }; + /** + * add reaction + * @method add + * @memberof StreamReaction.prototype + * @param {string} kind kind of reaction + * @param {string} activity Activity or an ActivityID + * @param {ReactionType} data data related to reaction + * @param {object} [options] + * @param {string} [options.id] id associated with reaction + * @param {string[]} [options.targetFeeds] an array of feeds to which to send an activity with the reaction + * @param {string} [options.userId] useful for adding reaction with server token + * @param {object} [options.targetFeedsExtraData] extra data related to target feeds + * @return {Promise>} + * @example reactions.add("like", "0c7db91c-67f9-11e8-bcd9-fe00a9219401") + * @example reactions.add("comment", "0c7db91c-67f9-11e8-bcd9-fe00a9219401", {"text": "love it!"},) + */ add( kind: string, activity: string | { id: string }, @@ -126,22 +142,6 @@ export default class StreamReaction< targetFeedsExtraData, }: { id?: string; targetFeeds?: TargetFeeds; targetFeedsExtraData?: TargetFeedsExtraData; userId?: string } = {}, ) { - /** - * add reaction - * @method add - * @memberof StreamReaction.prototype - * @param {string} kind kind of reaction - * @param {string} activity Activity or an ActivityID - * @param {ReactionType} data data related to reaction - * @param {object} [options] - * @param {string} [options.id] id associated with reaction - * @param {string[]} [options.targetFeeds] an array of feeds to which to send an activity with the reaction - * @param {string} [options.userId] useful for adding reaction with server token - * @param {object} [options.targetFeedsExtraData] extra data related to target feeds - * @return {Promise>} - * @example reactions.add("like", "0c7db91c-67f9-11e8-bcd9-fe00a9219401") - * @example reactions.add("comment", "0c7db91c-67f9-11e8-bcd9-fe00a9219401", {"text": "love it!"},) - */ const body: ReactionBody = { id, activity_id: activity instanceof Object ? (activity as { id: string }).id : activity, @@ -160,6 +160,21 @@ export default class StreamReaction< }); } + /** + * add child reaction + * @method addChild + * @memberof StreamReaction.prototype + * @param {string} kind kind of reaction + * @param {string} reaction Reaction or a ReactionID + * @param {ChildReactionType} data data related to reaction + * @param {object} [options] + * @param {string[]} [options.targetFeeds] an array of feeds to which to send an activity with the reaction + * @param {string} [options.userId] useful for adding reaction with server token + * @param {object} [options.targetFeedsExtraData] extra data related to target feeds + * @return {Promise>} + * @example reactions.add("like", "0c7db91c-67f9-11e8-bcd9-fe00a9219401") + * @example reactions.add("comment", "0c7db91c-67f9-11e8-bcd9-fe00a9219401", {"text": "love it!"},) + */ addChild( kind: string, reaction: string | { id: string }, @@ -174,21 +189,6 @@ export default class StreamReaction< userId?: string; } = {}, ) { - /** - * add child reaction - * @method addChild - * @memberof StreamReaction.prototype - * @param {string} kind kind of reaction - * @param {string} reaction Reaction or a ReactionID - * @param {ChildReactionType} data data related to reaction - * @param {object} [options] - * @param {string[]} [options.targetFeeds] an array of feeds to which to send an activity with the reaction - * @param {string} [options.userId] useful for adding reaction with server token - * @param {object} [options.targetFeedsExtraData] extra data related to target feeds - * @return {Promise>} - * @example reactions.add("like", "0c7db91c-67f9-11e8-bcd9-fe00a9219401") - * @example reactions.add("comment", "0c7db91c-67f9-11e8-bcd9-fe00a9219401", {"text": "love it!"},) - */ const body: ReactionBody = { parent: reaction instanceof Object ? (reaction as { id: string }).id : reaction, kind, @@ -206,21 +206,35 @@ export default class StreamReaction< }); } + /** + * get reaction + * @method get + * @memberof StreamReaction.prototype + * @param {string} id Reaction Id + * @return {Promise>} + * @example reactions.get("67b3e3b5-b201-4697-96ac-482eb14f88ec") + */ get(id: string) { - /** - * get reaction - * @method get - * @memberof StreamReaction.prototype - * @param {string} id Reaction Id - * @return {Promise>} - * @example reactions.get("67b3e3b5-b201-4697-96ac-482eb14f88ec") - */ return this.client.get>({ url: this.buildURL(id), signature: this.token, }); } + /** + * retrieve reactions by activity_id, user_id or reaction_id (to paginate children reactions), pagination can be done using id_lt, id_lte, id_gt and id_gte parameters + * id_lt and id_lte return reactions order by creation descending starting from the reaction with the ID provided, when id_lte is used + * the reaction with ID equal to the value provided is included. + * id_gt and id_gte return reactions order by creation ascending (oldest to newest) starting from the reaction with the ID provided, when id_gte is used + * the reaction with ID equal to the value provided is included. + * results are limited to 25 at most and are ordered newest to oldest by default. + * @method filter + * @memberof StreamReaction.prototype + * @param {object} conditions Reaction Id {activity_id|user_id|reaction_id:string, kind:string, limit:integer} + * @return {Promise>} + * @example reactions.filter({activity_id: "0c7db91c-67f9-11e8-bcd9-fe00a9219401", kind:"like"}) + * @example reactions.filter({user_id: "john", kinds:"like"}) + */ filter(conditions: { activity_id?: string; id_gt?: string; @@ -233,21 +247,6 @@ export default class StreamReaction< user_id?: string; with_activity_data?: boolean; }) { - /** - * retrieve reactions by activity_id, user_id or reaction_id (to paginate children reactions), pagination can be done using id_lt, id_lte, id_gt and id_gte parameters - * id_lt and id_lte return reactions order by creation descending starting from the reaction with the ID provided, when id_lte is used - * the reaction with ID equal to the value provided is included. - * id_gt and id_gte return reactions order by creation ascending (oldest to newest) starting from the reaction with the ID provided, when id_gte is used - * the reaction with ID equal to the value provided is included. - * results are limited to 25 at most and are ordered newest to oldest by default. - * @method filter - * @memberof StreamReaction.prototype - * @param {object} conditions Reaction Id {activity_id|user_id|reaction_id:string, kind:string, limit:integer} - * @return {Promise>} - * @example reactions.filter({activity_id: "0c7db91c-67f9-11e8-bcd9-fe00a9219401", kind:"like"}) - * @example reactions.filter({user_id: "john", kinds:"like"}) - */ - const { user_id: userId, activity_id: activityId, reaction_id: reactionId, ...qs } = conditions; if (!qs.limit) { qs.limit = 10; @@ -273,6 +272,19 @@ export default class StreamReaction< }); } + /** + * update reaction + * @method update + * @memberof StreamReaction.prototype + * @param {string} id Reaction Id + * @param {ReactionType | ChildReactionType} data Data associated to reaction or childReaction + * @param {object} [options] + * @param {string[]} [options.targetFeeds] Optional feeds to post the activity to. If you sent this before and don't set it here it will be removed. + * @param {object} [options.targetFeedsExtraData] extra data related to target feeds + * @return {Promise>} + * @example reactions.update("67b3e3b5-b201-4697-96ac-482eb14f88ec", "0c7db91c-67f9-11e8-bcd9-fe00a9219401", "like") + * @example reactions.update("67b3e3b5-b201-4697-96ac-482eb14f88ec", "0c7db91c-67f9-11e8-bcd9-fe00a9219401", "comment", {"text": "love it!"},) + */ update( id: string, data: ReactionType | ChildReactionType, @@ -281,19 +293,6 @@ export default class StreamReaction< targetFeedsExtraData, }: { targetFeeds?: string[] | StreamFeed[]; targetFeedsExtraData?: TargetFeedsExtraData } = {}, ) { - /** - * update reaction - * @method update - * @memberof StreamReaction.prototype - * @param {string} id Reaction Id - * @param {ReactionType | ChildReactionType} data Data associated to reaction or childReaction - * @param {object} [options] - * @param {string[]} [options.targetFeeds] Optional feeds to post the activity to. If you sent this before and don't set it here it will be removed. - * @param {object} [options.targetFeedsExtraData] extra data related to target feeds - * @return {Promise>} - * @example reactions.update("67b3e3b5-b201-4697-96ac-482eb14f88ec", "0c7db91c-67f9-11e8-bcd9-fe00a9219401", "like") - * @example reactions.update("67b3e3b5-b201-4697-96ac-482eb14f88ec", "0c7db91c-67f9-11e8-bcd9-fe00a9219401", "comment", {"text": "love it!"},) - */ const body: ReactionBody = { data, target_feeds: this._convertTargetFeeds(targetFeeds), @@ -308,15 +307,15 @@ export default class StreamReaction< }); } + /** + * delete reaction + * @method delete + * @memberof StreamReaction.prototype + * @param {string} id Reaction Id + * @return {Promise} + * @example reactions.delete("67b3e3b5-b201-4697-96ac-482eb14f88ec") + */ delete(id: string) { - /** - * delete reaction - * @method delete - * @memberof StreamReaction.prototype - * @param {string} id Reaction Id - * @return {Promise} - * @example reactions.delete("67b3e3b5-b201-4697-96ac-482eb14f88ec") - */ return this.client.delete({ url: this.buildURL(id), signature: this.token, diff --git a/src/redirect_url.ts b/src/redirect_url.ts index b4740c42..3548f361 100644 --- a/src/redirect_url.ts +++ b/src/redirect_url.ts @@ -7,18 +7,18 @@ import utils from './utils'; import signing from './signing'; // TODO: userId is skipped here +/** + * Creates a redirect url for tracking the given events in the context of + * an email using Stream's analytics platform. Learn more at + * getstream.io/personalization + * @method createRedirectUrl + * @memberof StreamClient.prototype + * @param {string} targetUrl Target url + * @param {string} userId User id to track + * @param {array} events List of events to track + * @return {string} The redirect url + */ export default function createRedirectUrl(this: StreamClient, targetUrl: string, userId: string, events: unknown[]) { - /** - * Creates a redirect url for tracking the given events in the context of - * an email using Stream's analytics platform. Learn more at - * getstream.io/personalization - * @method createRedirectUrl - * @memberof StreamClient.prototype - * @param {string} targetUrl Target url - * @param {string} userId User id to track - * @param {array} events List of events to track - * @return {string} The redirect url - */ const uri = Url.parse(targetUrl); if (!(uri.host || (uri.hostname && uri.port))) { diff --git a/src/signing.ts b/src/signing.ts index 77bf1685..f77cf66e 100644 --- a/src/signing.ts +++ b/src/signing.ts @@ -45,26 +45,26 @@ function headerFromJWS(jwsSig: string) { return safeJsonParse(decodeBase64Url(encodedHeader)); } +/** + * Creates the JWT token for feedId, resource and action using the apiSecret + * @method JWTScopeToken + * @memberof signing + * @private + * @param {string} apiSecret - API Secret key + * @param {string} resource - JWT payload resource + * @param {string} action - JWT payload action + * @param {object} [options] - Optional additional options + * @param {string} [options.feedId] - JWT payload feed identifier + * @param {string} [options.userId] - JWT payload user identifier + * @param {boolean} [options.expireTokens] - JWT noTimestamp + * @return {string} JWT Token + */ function JWTScopeToken( apiSecret: string, resource: string, action: string, options: { expireTokens?: boolean; feedId?: string; userId?: string } = {}, ) { - /** - * Creates the JWT token for feedId, resource and action using the apiSecret - * @method JWTScopeToken - * @memberof signing - * @private - * @param {string} apiSecret - API Secret key - * @param {string} resource - JWT payload resource - * @param {string} action - JWT payload action - * @param {object} [options] - Optional additional options - * @param {string} [options.feedId] - JWT payload feed identifier - * @param {string} [options.userId] - JWT payload user identifier - * @param {boolean} [options.expireTokens] - JWT noTimestamp - * @return {string} JWT Token - */ const noTimestamp = options.expireTokens ? !options.expireTokens : true; const payload: { action: string; resource: string; feed_id?: string; user_id?: string } = { resource, action }; if (options.feedId) payload.feed_id = options.feedId; @@ -73,23 +73,23 @@ function JWTScopeToken( return jwt.sign(payload, apiSecret, { algorithm: 'HS256', noTimestamp }); } +/** + * Creates the JWT token that can be used for a UserSession + * @method JWTUserSessionToken + * @memberof signing + * @private + * @param {string} apiSecret - API Secret key + * @param {string} userId - The user_id key in the JWT payload + * @param {object} [extraData] - Extra that should be part of the JWT token + * @param {object} [jwtOptions] - Options that can be past to jwt.sign + * @return {string} JWT Token + */ function JWTUserSessionToken( apiSecret: string, userId: string, extraData: Record = {}, jwtOptions: jwt.SignOptions = {}, ) { - /** - * Creates the JWT token that can be used for a UserSession - * @method JWTUserSessionToken - * @memberof signing - * @private - * @param {string} apiSecret - API Secret key - * @param {string} userId - The user_id key in the JWT payload - * @param {object} [extraData] - Extra that should be part of the JWT token - * @param {object} [jwtOptions] - Options that can be past to jwt.sign - * @return {string} JWT Token - */ if (typeof userId !== 'string') { throw new TypeError('userId should be a string'); } @@ -100,15 +100,15 @@ function JWTUserSessionToken( return jwt.sign(payload, apiSecret, opts); } +/** + * check if token is a valid JWT token + * @method isJWTSignature + * @memberof signing + * @private + * @param {string} signature - Signature to check + * @return {boolean} + */ function isJWTSignature(signature: string | null) { - /** - * check if token is a valid JWT token - * @method isJWTSignature - * @memberof signing - * @private - * @param {string} signature - Signature to check - * @return {boolean} - */ if (signature == null || signature.length === 0) { return false; } diff --git a/src/user.ts b/src/user.ts index ea8428c9..19d3f53a 100644 --- a/src/user.ts +++ b/src/user.ts @@ -18,16 +18,16 @@ export default class StreamUser full?: UserAPIResponse; private url: string; + /** + * Initialize a user session object + * @method constructor + * @memberof StreamUser.prototype + * @param {StreamClient} client Stream client this collection is constructed from + * @param {string} userId The ID of the user + * @param {string} userAuthToken JWT token + * @example new StreamUser(client, "123", "eyJhbGciOiJIUzI1...") + */ constructor(client: StreamClient, userId: string, userAuthToken: string) { - /** - * Initialize a user session object - * @method constructor - * @memberof StreamUser.prototype - * @param {StreamClient} client Stream client this collection is constructed from - * @param {string} userId The ID of the user - * @param {string} userAuthToken JWT token - * @example new StreamUser(client, "123", "eyJhbGciOiJIUzI1...") - */ this.client = client; this.id = userId; this.data = undefined; diff --git a/src/utils.ts b/src/utils.ts index e2af1a4f..be23d3cc 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -5,10 +5,10 @@ import * as errors from './errors'; const validFeedSlugRe = /^[\w]+$/; const validUserIdRe = /^[\w-]+$/; +/* + * Validate that the feedSlug matches \w + */ function validateFeedSlug(feedSlug: string) { - /* - * Validate that the feedSlug matches \w - */ if (!validFeedSlugRe.test(feedSlug)) { throw new errors.FeedError(`Invalid feedSlug, please use letters, numbers or _: ${feedSlug}`); } @@ -16,10 +16,10 @@ function validateFeedSlug(feedSlug: string) { return feedSlug; } +/* + * Validate the userId matches \w + */ function validateUserId(userId: string) { - /* - * Validate the userId matches \w - */ if (!validUserIdRe.test(userId)) { throw new errors.FeedError(`Invalid userId, please use letters, numbers, - or _: ${userId}`); } @@ -35,10 +35,10 @@ function isReadableStream(obj: NodeJS.ReadStream): obj is NodeJS.ReadStream { return obj !== null && typeof obj === 'object' && typeof (obj as NodeJS.ReadStream)._read === 'function'; } +/* + * Validate that the feedId matches the spec user:1 + */ function validateFeedId(feedId: string) { - /* - * Validate that the feedId matches the spec user:1 - */ const parts = feedId.split(':'); if (parts.length !== 2) { throw new errors.FeedError(`Invalid feedId, expected something like user:1 got ${feedId}`); From 617fc4584b568d0f43a6cbff21f1df0f87956dd0 Mon Sep 17 00:00:00 2001 From: Amin Mahboubi Date: Tue, 11 Aug 2020 17:15:28 +0200 Subject: [PATCH 68/69] remove jsdoc dep and cmd --- .jsdoc | 14 ------ package.json | 2 - yarn.lock | 122 ++------------------------------------------------- 3 files changed, 3 insertions(+), 135 deletions(-) delete mode 100644 .jsdoc diff --git a/.jsdoc b/.jsdoc deleted file mode 100644 index e89bd3b0..00000000 --- a/.jsdoc +++ /dev/null @@ -1,14 +0,0 @@ -{ - "source" : { - "include": ["./src"], - "exclude": ["node_modules","dist","test"] - }, - "plugins": [], - "opts": { - "recurse": true, - "template": "templates/default", - "destination": "./docs/", - "package": "./package.json", - "readme": "./README.md" - } -} diff --git a/package.json b/package.json index 9433c1c6..4a9d331c 100644 --- a/package.json +++ b/package.json @@ -28,7 +28,6 @@ "test-cloud": "mocha --require ./babel-register.js test/integration/cloud --timeout 40000", "test-cloud-local": "LOCAL=true mocha --require ./babel-register.js test/integration/cloud --timeout 40000 -i --grep 'Files|Images'", "test-browser": "karma start karma.config.js", - "generate-docs": "jsdoc -c .jsdoc", "coverage": "nyc yarn run test-unit-node && nyc report --reporter=text-lcov | codecov --pipe", "prepare": "yarn run build", "preversion": "yarn run test-unit-node", @@ -83,7 +82,6 @@ "eslint-plugin-typescript-sort-keys": "^1.3.0", "expect.js": "^0.3.1", "husky": "^4.2.5", - "jsdoc": "^3.6.5", "json-loader": "~0.5.7", "karma": "^5.1.1", "karma-chrome-launcher": "^3.1.0", diff --git a/yarn.lock b/yarn.lock index 81cb3df8..b347f29f 100644 --- a/yarn.lock +++ b/yarn.lock @@ -520,7 +520,7 @@ resolve "^1.13.1" v8flags "^3.1.1" -"@babel/parser@^7.10.1", "@babel/parser@^7.10.2", "@babel/parser@^7.9.4": +"@babel/parser@^7.10.1", "@babel/parser@^7.10.2": version "7.10.2" resolved "https://registry.yarnpkg.com/@babel/parser/-/parser-7.10.2.tgz#871807f10442b92ff97e4783b9b54f6a0ca812d0" integrity sha512-PApSXlNMJyB4JiGVhCOlzKIif+TKFTvu0aQAhnTvfP/z3vVSN6ZypH5bfUNwFXXjRQtUEBNFd2PtmCmG2Py3qQ== @@ -2168,7 +2168,7 @@ blob@0.0.5: resolved "https://registry.yarnpkg.com/blob/-/blob-0.0.5.tgz#d680eeef25f8cd91ad533f5b01eed48e64caf683" integrity sha512-gaqbzQPqOoamawKg0LGVd7SzLgXS+JH61oWprSLH+P+abTczqJbhTR8CmJ2u9/bUYNmHTGJx/UEmn6doAvvuig== -bluebird@^3.5.5, bluebird@^3.7.2: +bluebird@^3.5.5: version "3.7.2" resolved "https://registry.yarnpkg.com/bluebird/-/bluebird-3.7.2.tgz#9f229c15be272454ffa973ace0dbee79a1b0c36f" integrity sha512-XpNj6GDQzdfW+r2Wnn7xiSAd7TM3jzkxGXBGTtWKuSXv1xUV+azxAm8jdWZN06QTQk+2N2XB9jRDkvbmQmcRtg== @@ -2500,13 +2500,6 @@ caseless@~0.12.0: resolved "https://registry.yarnpkg.com/caseless/-/caseless-0.12.0.tgz#1b681c21ff84033c826543090689420d187151dc" integrity sha1-G2gcIf+EAzyCZUMJBolCDRhxUdw= -catharsis@^0.8.11: - version "0.8.11" - resolved "https://registry.yarnpkg.com/catharsis/-/catharsis-0.8.11.tgz#d0eb3d2b82b7da7a3ce2efb1a7b00becc6643468" - integrity sha512-a+xUyMV7hD1BrDQA/3iPV7oc+6W26BgVJO05PGEoatMyIuPScQKsde6i3YorWX1qs+AZjnJ18NqdKoCtKiNh1g== - dependencies: - lodash "^4.17.14" - caw@^2.0.1: version "2.0.1" resolved "https://registry.yarnpkg.com/caw/-/caw-2.0.1.tgz#6c3ca071fc194720883c2dc5da9b074bfc7e9e95" @@ -3524,11 +3517,6 @@ ent@~2.2.0: resolved "https://registry.yarnpkg.com/ent/-/ent-2.2.0.tgz#e964219325a21d05f44466a2f686ed6ce5f5dd1d" integrity sha1-6WQhkyWiHQX0RGai9obtbOX13R0= -entities@~2.0.0: - version "2.0.3" - resolved "https://registry.yarnpkg.com/entities/-/entities-2.0.3.tgz#5c487e5742ab93c15abb5da22759b8590ec03b7f" - integrity sha512-MyoZ0jgnLvB2X3Lg5HqpFmn1kybDiIfEQmKzTb5apr51Rb+T3KdmMiqa70T+bhGnyv7bQ6WMj2QMHpGMmlrUYQ== - errno@^0.1.3, errno@~0.1.7: version "0.1.7" resolved "https://registry.yarnpkg.com/errno/-/errno-0.1.7.tgz#4684d71779ad39af177e3f007996f7c67c852618" @@ -3602,11 +3590,6 @@ escape-string-regexp@1.0.5, escape-string-regexp@^1.0.2, escape-string-regexp@^1 resolved "https://registry.yarnpkg.com/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz#1b61c0562190a8dff6ae3bb2cf0200ca130b86d4" integrity sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ= -escape-string-regexp@^2.0.0: - version "2.0.0" - resolved "https://registry.yarnpkg.com/escape-string-regexp/-/escape-string-regexp-2.0.0.tgz#a30304e99daa32e23b2fd20f51babd07cffca344" - integrity sha512-UpzcLCXolUWcNu5HtVMHYdXJjArjsF9C0aNnquZYY4uW/Vu0miy5YoWvbV345HauVvcAUnpRuhMMcqTcGOY2+w== - escape-string-regexp@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz#14ba83a5d373e3d311e5afca29cf5bfad965bf34" @@ -4508,7 +4491,7 @@ got@^8.3.1: url-parse-lax "^3.0.0" url-to-options "^1.0.1" -graceful-fs@^4.1.10, graceful-fs@^4.1.11, graceful-fs@^4.1.15, graceful-fs@^4.1.2, graceful-fs@^4.1.6, graceful-fs@^4.1.9, graceful-fs@^4.2.0, graceful-fs@^4.2.4: +graceful-fs@^4.1.10, graceful-fs@^4.1.11, graceful-fs@^4.1.15, graceful-fs@^4.1.2, graceful-fs@^4.1.6, graceful-fs@^4.2.0, graceful-fs@^4.2.4: version "4.2.4" resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-4.2.4.tgz#2256bde14d3632958c465ebc96dc467ca07a29fb" integrity sha512-WjKPNJF79dtJAVniUlGGWHYGz2jWxT6VhN/4m1NdkbZ2nOsEF+cI1Edgql5zCRhs/VsQYRvrXctxktVXZUkixw== @@ -5276,38 +5259,11 @@ js-yaml@^3.13.1: argparse "^1.0.7" esprima "^4.0.0" -js2xmlparser@^4.0.1: - version "4.0.1" - resolved "https://registry.yarnpkg.com/js2xmlparser/-/js2xmlparser-4.0.1.tgz#670ef71bc5661f089cc90481b99a05a1227ae3bd" - integrity sha512-KrPTolcw6RocpYjdC7pL7v62e55q7qOMHvLX1UCLc5AAS8qeJ6nukarEJAF2KL2PZxlbGueEbINqZR2bDe/gUw== - dependencies: - xmlcreate "^2.0.3" - jsbn@~0.1.0: version "0.1.1" resolved "https://registry.yarnpkg.com/jsbn/-/jsbn-0.1.1.tgz#a5e654c2e5a2deb5f201d96cefbca80c0ef2f513" integrity sha1-peZUwuWi3rXyAdls77yoDA7y9RM= -jsdoc@^3.6.5: - version "3.6.5" - resolved "https://registry.yarnpkg.com/jsdoc/-/jsdoc-3.6.5.tgz#e004372ca6f2dcdf19b3d2ebcd7c725528485502" - integrity sha512-SbY+i9ONuxSK35cgVHaI8O9senTE4CDYAmGSDJ5l3+sfe62Ff4gy96osy6OW84t4K4A8iGnMrlRrsSItSNp3RQ== - dependencies: - "@babel/parser" "^7.9.4" - bluebird "^3.7.2" - catharsis "^0.8.11" - escape-string-regexp "^2.0.0" - js2xmlparser "^4.0.1" - klaw "^3.0.0" - markdown-it "^10.0.0" - markdown-it-anchor "^5.2.7" - marked "^0.8.2" - mkdirp "^1.0.4" - requizzle "^0.2.3" - strip-json-comments "^3.1.0" - taffydb "2.6.2" - underscore "~1.10.2" - jsesc@^2.5.1: version "2.5.2" resolved "https://registry.yarnpkg.com/jsesc/-/jsesc-2.5.2.tgz#80564d2e483dacf6e8ef209650a67df3f0c283a4" @@ -5551,13 +5507,6 @@ kind-of@^6.0.0, kind-of@^6.0.2: resolved "https://registry.yarnpkg.com/kind-of/-/kind-of-6.0.3.tgz#07c05034a6c349fa06e24fa35aa76db4580ce4dd" integrity sha512-dcS1ul+9tmeD95T+x28/ehLgd9mENa3LsvDTtzm3vyBEO7RPptvAD+t44WVXaUjTBRcrpFeFlC8WCruUR456hw== -klaw@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/klaw/-/klaw-3.0.0.tgz#b11bec9cf2492f06756d6e809ab73a2910259146" - integrity sha512-0Fo5oir+O9jnXu5EefYbVK+mHMBeEVEy2cmctR1O1NECcCkPRreJKrS6Qt/j3KC2C148Dfo9i3pCmCMsdqGr0g== - dependencies: - graceful-fs "^4.1.9" - lazystream@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/lazystream/-/lazystream-1.0.0.tgz#f6995fe0f820392f61396be89462407bb77168e4" @@ -5598,13 +5547,6 @@ lines-and-columns@^1.1.6: resolved "https://registry.yarnpkg.com/lines-and-columns/-/lines-and-columns-1.1.6.tgz#1c00c743b433cd0a4e80758f7b64a57440d9ff00" integrity sha1-HADHQ7QzzQpOgHWPe2SldEDZ/wA= -linkify-it@^2.0.0: - version "2.2.0" - resolved "https://registry.yarnpkg.com/linkify-it/-/linkify-it-2.2.0.tgz#e3b54697e78bf915c70a38acd78fd09e0058b1cf" - integrity sha512-GnAl/knGn+i1U/wjBz3akz2stz+HrHLsxMwHQGofCDfPvlf+gDKN58UtfmUquTY4/MXeE2x7k19KQmeoZi94Iw== - dependencies: - uc.micro "^1.0.1" - load-json-file@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/load-json-file/-/load-json-file-2.0.0.tgz#7947e42149af80d696cbf797bcaabcfe1fe29ca8" @@ -5859,27 +5801,6 @@ map-visit@^1.0.0: dependencies: object-visit "^1.0.0" -markdown-it-anchor@^5.2.7: - version "5.3.0" - resolved "https://registry.yarnpkg.com/markdown-it-anchor/-/markdown-it-anchor-5.3.0.tgz#d549acd64856a8ecd1bea58365ef385effbac744" - integrity sha512-/V1MnLL/rgJ3jkMWo84UR+K+jF1cxNG1a+KwqeXqTIJ+jtA8aWSHuigx8lTzauiIjBDbwF3NcWQMotd0Dm39jA== - -markdown-it@^10.0.0: - version "10.0.0" - resolved "https://registry.yarnpkg.com/markdown-it/-/markdown-it-10.0.0.tgz#abfc64f141b1722d663402044e43927f1f50a8dc" - integrity sha512-YWOP1j7UbDNz+TumYP1kpwnP0aEa711cJjrAQrzd0UXlbJfc5aAq0F/PZHjiioqDC1NKgvIMX+o+9Bk7yuM2dg== - dependencies: - argparse "^1.0.7" - entities "~2.0.0" - linkify-it "^2.0.0" - mdurl "^1.0.1" - uc.micro "^1.0.5" - -marked@^0.8.2: - version "0.8.2" - resolved "https://registry.yarnpkg.com/marked/-/marked-0.8.2.tgz#4faad28d26ede351a7a1aaa5fec67915c869e355" - integrity sha512-EGwzEeCcLniFX51DhTpmTom+dSA/MG/OBUDjnWtHbEnjAH180VzUeAw+oE4+Zv+CoYBWyRlYOTR0N8SO9R1PVw== - marky@^1.2.0: version "1.2.1" resolved "https://registry.yarnpkg.com/marky/-/marky-1.2.1.tgz#a3fcf82ffd357756b8b8affec9fdbf3a30dc1b02" @@ -5901,11 +5822,6 @@ md5.js@^1.3.4: inherits "^2.0.1" safe-buffer "^5.1.2" -mdurl@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/mdurl/-/mdurl-1.0.1.tgz#fe85b2ec75a59037f2adfec100fd6c601761152e" - integrity sha1-/oWy7HWlkDfyrf7BAP1sYBdhFS4= - media-typer@0.3.0: version "0.3.0" resolved "https://registry.yarnpkg.com/media-typer/-/media-typer-0.3.0.tgz#8710d7af0aa626f8fffa1ce00168545263255748" @@ -6044,11 +5960,6 @@ mkdirp@^0.5.1, mkdirp@^0.5.3: dependencies: minimist "^1.2.5" -mkdirp@^1.0.4: - version "1.0.4" - resolved "https://registry.yarnpkg.com/mkdirp/-/mkdirp-1.0.4.tgz#3eb5ed62622756d79a5f0e2a221dfebad75c2f7e" - integrity sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw== - mocha@^8.1.1: version "8.1.1" resolved "https://registry.yarnpkg.com/mocha/-/mocha-8.1.1.tgz#1de1ba4e9a2c955d96b84e469d7540848223592d" @@ -7220,13 +7131,6 @@ requires-port@^1.0.0: resolved "https://registry.yarnpkg.com/requires-port/-/requires-port-1.0.0.tgz#925d2601d39ac485e091cf0da5c6e694dc3dcaff" integrity sha1-kl0mAdOaxIXgkc8NpcbmlNw9yv8= -requizzle@^0.2.3: - version "0.2.3" - resolved "https://registry.yarnpkg.com/requizzle/-/requizzle-0.2.3.tgz#4675c90aacafb2c036bd39ba2daa4a1cb777fded" - integrity sha512-YanoyJjykPxGHii0fZP0uUPEXpvqfBDxWV7s6GKAiiOsiqhX6vHNyW3Qzdmqp/iq/ExbhaGbVrjB4ruEVSM4GQ== - dependencies: - lodash "^4.17.14" - resolve-alpn@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/resolve-alpn/-/resolve-alpn-1.0.0.tgz#745ad60b3d6aff4b4a48e01b8c0bdc70959e0e8c" @@ -8044,11 +7948,6 @@ table@^5.2.3: slice-ansi "^2.1.0" string-width "^3.0.0" -taffydb@2.6.2: - version "2.6.2" - resolved "https://registry.yarnpkg.com/taffydb/-/taffydb-2.6.2.tgz#7cbcb64b5a141b6a2efc2c5d2c67b4e150b2a268" - integrity sha1-fLy2S1oUG2ou/CxdLGe04VCyomg= - tapable@^1.0.0, tapable@^1.1.3: version "1.1.3" resolved "https://registry.yarnpkg.com/tapable/-/tapable-1.1.3.tgz#a1fccc06b58db61fd7a45da2da44f5f3a3e67ba2" @@ -8361,11 +8260,6 @@ ua-parser-js@0.7.21, ua-parser-js@^0.7.21: resolved "https://registry.yarnpkg.com/ua-parser-js/-/ua-parser-js-0.7.21.tgz#853cf9ce93f642f67174273cc34565ae6f308777" integrity sha512-+O8/qh/Qj8CgC6eYBVBykMrNtp5Gebn4dlGD/kKXVkJNDwyrAwSIqwz8CDf+tsAIWVycKcku6gIXJ0qwx/ZXaQ== -uc.micro@^1.0.1, uc.micro@^1.0.5: - version "1.0.6" - resolved "https://registry.yarnpkg.com/uc.micro/-/uc.micro-1.0.6.tgz#9c411a802a409a91fc6cf74081baba34b24499ac" - integrity sha512-8Y75pvTYkLJW2hWQHXxoqRgV7qb9B+9vFEtidML+7koHUFapnVJAZ6cKs+Qjz5Aw3aZWHMC6u0wJE3At+nSGwA== - uglify-js@^3.6.0: version "3.9.4" resolved "https://registry.yarnpkg.com/uglify-js/-/uglify-js-3.9.4.tgz#867402377e043c1fc7b102253a22b64e5862401b" @@ -8396,11 +8290,6 @@ unbzip2-stream@^1.0.9, unbzip2-stream@^1.3.3: buffer "^5.2.1" through "^2.3.8" -underscore@~1.10.2: - version "1.10.2" - resolved "https://registry.yarnpkg.com/underscore/-/underscore-1.10.2.tgz#73d6aa3668f3188e4adb0f1943bd12cfd7efaaaf" - integrity sha512-N4P+Q/BuyuEKFJ43B9gYuOj4TQUHXX+j2FqguVOpjkssLUUrnJofCcBccJSCoeturDoZU6GorDTHSvUDlSQbTg== - unicode-canonical-property-names-ecmascript@^1.0.4: version "1.0.4" resolved "https://registry.yarnpkg.com/unicode-canonical-property-names-ecmascript/-/unicode-canonical-property-names-ecmascript-1.0.4.tgz#2619800c4c825800efdd8343af7dd9933cbe2818" @@ -8839,11 +8728,6 @@ ws@~6.1.0: dependencies: async-limiter "~1.0.0" -xmlcreate@^2.0.3: - version "2.0.3" - resolved "https://registry.yarnpkg.com/xmlcreate/-/xmlcreate-2.0.3.tgz#df9ecd518fd3890ab3548e1b811d040614993497" - integrity sha512-HgS+X6zAztGa9zIK3Y3LXuJes33Lz9x+YyTxgrkIdabu2vqcGOWwdfCpf1hWLRrd553wd4QCDf6BBO6FfdsRiQ== - xmlhttprequest-ssl@~1.5.4: version "1.5.5" resolved "https://registry.yarnpkg.com/xmlhttprequest-ssl/-/xmlhttprequest-ssl-1.5.5.tgz#c2876b06168aadc40e57d97e81191ac8f4398b3e" From 85f26d2a4978240fdabfe5c21bf917e4616c2553 Mon Sep 17 00:00:00 2001 From: Amin Mahboubi Date: Tue, 11 Aug 2020 18:16:25 +0200 Subject: [PATCH 69/69] add TODO comment to package import --- src/client.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/client.ts b/src/client.ts index bc6cc9a4..33cfdaaa 100644 --- a/src/client.ts +++ b/src/client.ts @@ -26,7 +26,7 @@ import StreamFeed, { GetFeedOptions, } from './feed'; -// no import since typescript json loader shifts the final output structure +// TODO: no import since typescript json loader shifts the final output structure // eslint-disable-next-line @typescript-eslint/no-var-requires const pkg = require('../package.json');