diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 94701801da..7e3c9ccc69 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -9,6 +9,7 @@ /types/absolute/ @AyaMorisawa /types/abstract-leveldown/ @MeirionHughes @danwbyrne /types/acc-wizard/ @cyrilschumacher +/types/accept/ @feinoujc /types/accept-language-parser/ @kampfgnom /types/accepts/ @bomret @brikou /types/accounting/ @gerich-home @chrisleck @@ -159,7 +160,7 @@ /types/ansi-escapes/ @jacobbubu /types/ansi-regex/ @mvachhar /types/ansi-styles/ @brynbellomy @plylrnsdy -/types/ansicolors/ @rogierschouten +/types/ansicolors/ @balupton /types/antlr4/ @mcchatman8009 /types/antlr4-autosuggest/ @jonfreedman /types/any-db/ @rogierschouten @@ -175,6 +176,7 @@ /types/apollo-codegen/ @bradleyayers @kostspielig /types/apollo-upload-client/ @Slessi /types/apostrophe/ @afholderman +/types/app-module-path/ @darkwebdev /types/app-root-dir/ @chenyang-biu /types/app-root-path/ @shantmarouti /types/appdmg/ @unindented @@ -212,7 +214,7 @@ /types/asenv/ @remisery /types/asn1js/ @microshine /types/aspnet-identity-pw/ @jt000 -/types/assert/ @nicoabie +/types/assert/ @nicoabie @LinusU /types/assert-equal-jsx/ @seryl /types/assert-plus/ @KostyaTretyak /types/assertsharp/ @brunolm @@ -231,6 +233,7 @@ /types/atlaskit__inline-edit/ @lstanden /types/atlaskit__layer/ @lstanden /types/atlaskit__single-select/ @lstanden +/types/atlaskit__tree/ @benhjames /types/atlassian-crowd-client/ @mtgto /types/atmosphere.js/ @toedter @Mory1879 @Scipion /types/atob/ @johngeorgewright @@ -254,6 +257,7 @@ /types/autoprefixer/ @odnamrataizem @murt /types/autosize/ @kingdango @keika299 @NeekSandhu /types/autosuggest-highlight/ @senukartur +/types/await-timeout/ @szhu /types/awesomplete/ @webbiesdk @bmdixon @tbekolay @chrislopresto /types/aws-iot-device-sdk/ @niik @mlamp /types/aws-lambda/ @skarum @tobyhede @buggy @y13i @wwwy3y3 @OrthoDex @MichaelMarner @daniel-cottone @kostya-misura @coderbyheart @palmithor @daniloraisi @simonbuchan @Haydabase @repl-chris @aneilbaboo @jeznag @louislarry @dpapukchiev @ohookins @trevor-leach @jagregory @@ -279,20 +283,19 @@ /types/babel__code-frame/ @mohsen1 @ForbesLindesay /types/babel__core/ @yortus @marvinhagemeister @mgroenhoff /types/babel__generator/ @yortus @johnnyestilles @mgroenhoff -/types/babel__parser/ @yortus @marvinhagemeister @mgroenhoff /types/babel__template/ @yortus @marvinhagemeister @mgroenhoff /types/babel__traverse/ @yortus @marvinhagemeister @rpetrich @mgroenhoff /types/babelify/ @TeamworkGuy2 @marvinhagemeister /types/babylon/ @yortus @marvinhagemeister /types/babylon-walk/ @czbuchi /types/babyparse/ @cdiddy77 -/types/backbone/ @borisyankov @nvivo @kenjiru +/types/backbone/ @borisyankov @nvivo @kenjiru @jjoekoullas /types/backbone-associations/ @craigbrett17 /types/backbone-fetch-cache/ @delphinus35 /types/backbone-relational/ @eirikhm /types/backbone.layoutmanager/ @hejiang2000 /types/backbone.localstorage/ @lgrignon -/types/backbone.marionette/ @zhamid @nvivo @sventschui @razorness @confususs +/types/backbone.marionette/ @zhamid @nvivo @sventschui @razorness @confususs @jjoekoullas /types/backbone.paginator/ @Nyamazing /types/backbone.radio/ @alphaleonis /types/backgrid/ @jlujan @@ -301,6 +304,7 @@ /types/backoff/ @BendingBender /types/baconjs/ @alexander-matsievsky @gekkio /types/bagpipes/ @micmro +/types/baidu-app/ @taoqf /types/barbellweights/ @evelijn /types/barcode/ @pvomhoff /types/bardjs/ @TepigMC @@ -329,7 +333,7 @@ /types/better-curry/ @pocesar /types/better-queue/ @maozedong /types/better-scroll/ @stoneChen @cnjack -/types/better-sqlite3/ @Morfent @matrumz +/types/better-sqlite3/ @Morfent @matrumz @sant123 /types/bezier-easing/ @ptlis /types/bezier-js/ @danmarshall @Epskampie /types/bgiframe/ @sumegizoltan @@ -340,7 +344,7 @@ /types/bignum/ @Patman64 /types/bigscreen/ @dduugg /types/bin-pack/ @orentrutner -/types/binary-parser/ @riggs @dolanmiu +/types/binary-parser/ @riggs @dolanmiu @yuhr /types/bind-ponyfill/ @skysteve /types/bindings/ @unindented /types/bintrees/ @CjS77 @@ -352,7 +356,7 @@ /types/bitcoinjs-lib/ @mhegazy @dlebrecht @rbuckton @micksatana @youssefgh @kento1218 /types/bitcore-lib/ @lautarodragan /types/bittorrent-protocol/ @feross @tlaziuk -/types/bitwise-xor/ @rogierschouten +/types/bitwise-xor/ @rogierschouten @BendingBender /types/bl/ @Bartvds @reconbot /types/blacklist/ @mhegazy /types/blazy/ @julienpa @@ -425,6 +429,7 @@ /types/browser-resolve/ @marionebl /types/browser-sync/ @joeskeen @aznnomness /types/browserify/ @AndrewGaspar @jvilk @leonard-thieu @LinusU +/types/browserslist/ @davecardwell /types/bs58/ @chrootsu /types/bson/ @horiuchi @CaselIT /types/btoa/ @johngeorgewright @@ -438,7 +443,7 @@ /types/bufferstream/ @Bartvds /types/builtin-modules/ @ajafff /types/bull/v2/ @bgrieder @JProgrammer -/types/bull/ @bgrieder @JProgrammer @marshall007 @weeco @blaugold @iamolegga @koblas @bondz @wuha-team @aleccool213 @danmana +/types/bull/ @bgrieder @JProgrammer @marshall007 @weeco @blaugold @iamolegga @koblas @bondz @wuha-team @aleccool213 @danmana @kjellmorten @pc-jedi /types/bump-regex/ @silkentrance /types/bunnymq/ @cyrilschumacher /types/bunyan/ @amikhalev @@ -457,6 +462,7 @@ /types/bytewise/ @danwbyrne /types/c3/ @mcliment @gerinjacob @denyo @dmitryshindin @timn /types/cache-manager/ @GausSim +/types/cached-path-relative/ @TeamworkGuy2 /types/cal-heatmap/ @RetroChrisB /types/caller/ @ignocide /types/callsite/ @newclear @@ -468,6 +474,7 @@ /types/camo/ @lucasmciruzzi /types/cancan/ @Vincent-Pang /types/caniuse-api/ @davecardwell +/types/caniuse-lite/ @mutech /types/cannon/ @clark-stevenson @Gelio /types/canvas-confetti/ @matracey /types/canvas-gauges/ @Mikhus @@ -482,10 +489,12 @@ /types/cassandra-driver/ @Svjard @pc-jedi /types/catbox/v7/ @jasonswearingen @AJamesPhillips /types/catbox/ @jasonswearingen @AJamesPhillips @saboya +/types/catbox-memory/ @SimonSchick /types/catbox-redis/ @SimonSchick /types/cbor/ @pushplay /types/ccap/ @taoqf /types/cesium/ @Zuzon @hnipps @szechyjs @golyalpha +/types/cfn-response/ @ivoisbelongtous /types/chai/v2/ @Bartvds @AGBrown /types/chai/ @jedmao @Bartvds @AGBrown @olivr70 @mwistrand @joshuakgoldberg @shaunluttin @Naktibalda @micksatana @ErikSchierboom /types/chai-arrays/ @clementprevot @@ -520,7 +529,7 @@ /types/check-types/ @idchlife /types/checkstyle-formatter/ @mhegazy /types/checksum/ @rogierschouten -/types/cheerio/ @blittle @wmaurer @umarniz @LiJinyao @chennakrishna8 +/types/cheerio/ @blittle @wmaurer @umarniz @LiJinyao @chennakrishna8 @AzSiAz /types/chess.js/ @JacobFischer /types/chessboardjs/ @sliverb @davidmpaz /types/chmodr/ @BendingBender @@ -538,7 +547,8 @@ /types/circuit-breaker-js/ @DeTeam /types/circular-json/ @jpevarnek /types/ckeditor/v2/ @wittwert -/types/ckeditor/ @wittwert @stuartlong +/types/ckeditor/ @wittwert @stuartlong @viktorpegy +/types/ckeditor__ckeditor5-utils/ @denisname /types/clamp-js/ @Hikariii /types/clamp-js-main/ @sinziananicolae /types/classnames/ @adidahiya @JKillian @seansfkelley @mradamczyk @marvinhagemeister @@ -552,6 +562,7 @@ /types/clearbladejs-server/ @ClearBlade /types/cleave.js/ @clentfort @jasongi-at-sportsbet @sashashakun /types/cli/ @kayahr +/types/cli-box/ @athasach /types/cli-color/ @ChaosinaCan /types/cli-interact/ @ffflorian /types/cli-progress/ @mhegazy @@ -579,7 +590,7 @@ /types/co-body/ @geoffreak /types/co-views/ @devlee @geoffreak /types/code/ @prashaantt -/types/codemirror/ @mihailik @nrbernard @Pr1st0n @rileymiller +/types/codemirror/ @mihailik @nrbernard @Pr1st0n @rileymiller @toddself /types/codependency/ @morphatic /types/coffeeify/ @tkQubo /types/coinbase/ @rogierschouten @@ -598,9 +609,10 @@ /types/com.darktalker.cordova.screenshot/ @akarienta /types/com.wikitude.phonegap.wikitudeplugin/ @zbarbuto /types/combine-source-map/ @TeamworkGuy2 -/types/combined-stream/ @felixge @tlaziuk +/types/combined-stream/ @felixge @tlaziuk @konpikwastaken /types/combokeys/ @iclanton /types/cometd/ @derekcicerone @unindented @alxHenry +/types/command-exists/ @BendingBender /types/command-line-args/v4/ @CzBuCHi @75lb /types/command-line-args/ @75lb /types/command-line-commands/ @CzBuCHi @@ -610,9 +622,10 @@ /types/commercetools__enzyme-extensions/ @screendriver /types/common-errors/ @icopp /types/common-prefix/ @seangenabe -/types/common-tags/ @zuzusik @tzupengwang +/types/common-tags/ @zuzusik @tzupengwang @BendingBender /types/commondir/ @leonard-thieu /types/commonmark/ @nicojs @leonard-thieu +/types/compare-func/ @fennibay /types/compare-version/ @jpevarnek /types/compare-versions/ @LogvinovLeon /types/complex/ @AyaMorisawa @pavasich @@ -662,7 +675,7 @@ /types/convert-layout/ @xeningem /types/convert-source-map/ @AndrewGaspar @mgroenhoff @TeamworkGuy2 /types/convict/ @Nemo157 @vesse @elyscape @vanthiyathevan -/types/cookie/ @pine613 +/types/cookie/ @pine /types/cookie-parser/ @santialbo @BendingBender /types/cookie-session/ @borislavjivkov /types/cookie-signature/ @lith-light-g @@ -706,7 +719,8 @@ /types/countdown/ @gjuchault /types/counterpart/ @santiagodoldan /types/countries-and-timezones/ @zero51 -/types/country-list/ @iRoachie +/types/country-list/v1/ @iRoachie +/types/country-list/ @iRoachie @Kimahriman /types/country-select-js/ @humrochagf /types/countup.js/ @shermendev /types/coverup/ @bevalorous @@ -717,6 +731,8 @@ /types/cradle/ @panuhorsmalahti /types/crc/ @YuJianrong /types/create-error/ @tkrotoff +/types/create-hash/ @BendingBender +/types/create-hmac/ @BendingBender /types/create-react-class/ @jgoz /types/create-subscription/ @Asana @vsiao /types/createjs/ @evilangelist @gyohk @@ -731,20 +747,24 @@ /types/crossfilter/ @schmuli @iebaker @nordfjord /types/crossroads/ @diullei /types/crpc/ @0xdeafcafe +/types/crumb/ @lenovouser @SimonSchick /types/cryptiles/ @awendland /types/crypto-js/ @misak113 /types/crypto-random-string/ @MrManny /types/cryptojs/ @giabao +/types/cryptr/ @rrogowski /types/cson/ @stpettersens +/types/cson-parser/ @lenovouser /types/csprng/ @winksaville /types/csrf/ @markis /types/css/ @ilich /types/css-font-loading-module/ @slikts /types/css-modules/ @NeekSandhu /types/css-to-style/ @bengry +/types/css-tree/ @erik-kallen /types/cssbeautify/ @rictic /types/cssnano/ @odnamrataizem -/types/csso/ @screendriver +/types/csso/ @screendriver @erik-kallen /types/csurf/ @horiuchi /types/csv-parse/ @davidm77 @obi-jan-kenobi /types/csv-stringify/ @rogierschouten @arjenvanderende @@ -777,7 +797,7 @@ /types/d3-delaunay/ @BTOdell /types/d3-dispatch/ @tomwanzek @gustavderdrache @borisyankov @denisname /types/d3-drag/ @tomwanzek @gustavderdrache @borisyankov -/types/d3-dsv/ @tomwanzek @gustavderdrache @borisyankov +/types/d3-dsv/ @tomwanzek @gustavderdrache @borisyankov @denisname /types/d3-ease/ @tomwanzek @gustavderdrache @borisyankov /types/d3-fetch/ @ledragon /types/d3-force/ @tomwanzek @gustavderdrache @borisyankov @@ -843,7 +863,8 @@ /types/dd-trace/ @ColinBradley @alloy /types/deasync/ @Sicilica /types/debessmann/ @vkorehov -/types/debounce/ @denis-sokolov @joshuakgoldberg +/types/debounce/ @denis-sokolov @joshuakgoldberg @wcarson +/types/debounce-promise/ @whtsky /types/debug/ @swook @galtalmor @zamb3zi @brasten /types/decamelize/ @samverschueren /types/decay/ @enaeseth @@ -876,10 +897,13 @@ /types/depd/ @danny8002 @BendingBender /types/dependency-tree/ @joscha /types/deployjava/ @cyrilschumacher +/types/deprecate/ @Toilal +/types/deps-sort/ @TeamworkGuy2 /types/derhuerst__cli-on-key/ @jacobbubu /types/destroy/ @BendingBender /types/destroy-on-hwm/ @BendingBender -/types/detect-browser/ @rogierschouten +/types/detect-browser/ @rogierschouten @carusology +/types/detect-character-encoding/ @BendingBender /types/detect-hover/ @thomastilkema /types/detect-indent/v0/ @Bartvds /types/detect-indent/ @Bartvds @BendingBender @@ -901,17 +925,21 @@ /types/di-lite/ @dcrusader /types/diacritics/ @otociulis /types/dialogflow/ @dyladan +/types/dicer/ @GoupilRobin @BendingBender /types/diff/ @vvakame @szdc @moc-yuto /types/diff2html/ @rtfpessoa +/types/diffie-hellman/ @BendingBender /types/digibyte/ @lautarodragan @werewolfe +/types/dinero.js/ @BendingBender /types/dir-resolve/ @andy-ms /types/discontinuous-range/ @OiCMudkips +/types/discord-rpc/ @jasonhaxstuff /types/discourse-sso/ @championswimmer /types/dispatchr/ @Ragg- /types/disposable-email-domains/ @geoffreak /types/dnssd/ @angelmerino @Maxr1998 /types/doccookies/ @jonegerton -/types/dockerode/ @seikho @nlaplante @isac322 @lazarusx @meisenzahl @thegecko +/types/dockerode/ @seikho @nlaplante @isac322 @lazarusx @meisenzahl @thegecko @CameronDiver /types/docopt/ @giggio /types/doctrine/ @rictic /types/document-promises/ @NotWoods @@ -923,6 +951,7 @@ /types/dom-clipboard-api/ @43081j /types/dom-inputevent/ @diagramatics /types/dom-loaded/ @ltetzlaff +/types/dom-mediacapture-record/ @eliasmeire /types/dom-to-image/ @JipSterk /types/dom4/ @adidahiya @giladgray /types/domo/ @Steve-Fenton @@ -937,7 +966,7 @@ /types/dotdir-regex/ @mrmlnc /types/dotdotdot/ @milanjaros /types/dotenv/v2/ @jussikinnula @borekb @enaeseth -/types/dotenv/ @jussikinnula @borekb @enaeseth +/types/dotenv/ @jussikinnula @borekb @enaeseth @maxbeatty /types/dotenv-safe/ @krenor /types/dotenv-webpack/ @karol-majewski /types/dotfile-regex/ @mrmlnc @@ -984,7 +1013,7 @@ /types/easy-xapi/ @DeadAlready /types/easy-xapi-utils/ @DeadAlready /types/ebongarde-root/ @Ebongarde -/types/echarts/ @xieisabug @AntiMoron @liveangela @Ovilia +/types/echarts/ @xieisabug @AntiMoron @liveangela @Ovilia @iRON5 /types/ecma-proposal-math-extensions/ @ksm2 /types/ecurve/ @mhegazy /types/ed25519/ @erikma @@ -1018,7 +1047,7 @@ /types/electron-winstaller/ @shiftkey @unindented /types/elegant-spinner/ @danwbyrne /types/element-ready/ @BendingBender -/types/element-resize-detector/ @saranshkataria +/types/element-resize-detector/ @saranshkataria @franklixuefei /types/element-resize-event/ @rogierschouten @plgregoire /types/elementtree/ @dwieeb /types/elliptic/ @danwbyrne @@ -1062,6 +1091,7 @@ /types/emoji-regex/ @iKBAHT /types/emojione/ @dbrgn /types/empower/ @vvakame +/types/empty-dir/ @BendingBender /types/emscripten/ @zakki @periklis /types/encoding-down/ @MeirionHughes @danwbyrne /types/end-of-stream/ @strax @@ -1079,6 +1109,7 @@ /types/enzyme-adapter-react-15/ @tkrotoff /types/enzyme-adapter-react-15.4/ @nali /types/enzyme-adapter-react-16/ @tkrotoff +/types/enzyme-async-helpers/ @kimehrenpohl /types/enzyme-redux/ @knegusen /types/enzyme-to-json/ @joscha /types/eonasdan-bootstrap-datetimepicker/ @ToastHawaii @@ -1137,17 +1168,21 @@ /types/exit/ @Bartvds /types/exit-hook/ @BendingBender /types/exorcist/ @TeamworkGuy2 +/types/expand-tilde/ @carnesen /types/expect/ @jmreidy @merrywhether /types/expect-puppeteer/ @JoshuaKGoldberg @tkrotoff /types/expect.js/ @teppeis /types/expectations/ @vvakame /types/expired-storage/ @intolerance +/types/expirymanager/ @DanielRose /types/expo/v23/ @KonstantinKai /types/expo/v24/ @KonstantinKai @martynaskadisa @janaagaard75 @ssanchezmarc @fhelwanger /types/expo/v25/ @KonstantinKai @martynaskadisa @janaagaard75 @ssanchezmarc @fhelwanger @umidbekkarimov /types/expo/v26/ @KonstantinKai @martynaskadisa @janaagaard75 @ssanchezmarc @fhelwanger @umidbekkarimov @tinaroh /types/expo/v27/ @KonstantinKai @martynaskadisa @janaagaard75 @ssanchezmarc @fhelwanger @umidbekkarimov @moshfeu @prokopcm @tinaroh @binki @mo -/types/expo/ @KonstantinKai @martynaskadisa @janaagaard75 @ssanchezmarc @fhelwanger @umidbekkarimov @moshfeu @prokopcm @tinaroh @binki @mo +/types/expo/v30/ @KonstantinKai @martynaskadisa @janaagaard75 @ssanchezmarc @fhelwanger @umidbekkarimov @moshfeu @prokopcm @tinaroh @binki @mo +/types/expo/ @KonstantinKai @martynaskadisa @janaagaard75 @ssanchezmarc @fhelwanger @umidbekkarimov @moshfeu @prokopcm @tinaroh @binki @mo @levansuper @ihmpavel +/types/expo-localization/ @burtek /types/expo__status-bar-height/ @dawnmist /types/expo__vector-icons/ @incleaf /types/express/ @borisyankov @@ -1188,6 +1223,7 @@ /types/express-redis-cache/ @ajliv /types/express-route-fs/ @kripod /types/express-routemap/ @icopp +/types/express-routes-versioning/ @weffe /types/express-sanitized/ @cjbarth /types/express-serve-static-core/ @borisyankov @19majkel94 @kacepe @micksatana @samijaber /types/express-session/ @horiuchi @jacobbogers @builtinnya @ry7n @@ -1195,6 +1231,8 @@ /types/express-socket.io-session/ @AylaJK /types/express-to-koa/ @xiaohanzhang /types/express-unless/ @wokim +/types/express-version-request/ @weffe +/types/express-version-route/ @weffe /types/express-wechat-access/ @simmons8616 /types/express-winston/ @bricka /types/express-ws/ @ajliv @@ -1226,11 +1264,11 @@ /types/fancy-log/ @pine /types/fancybox/ @borisyankov /types/farbtastic/ @EnableSoftware -/types/fast-diff/ @djrenren /types/fast-levenshtein/ @mizunashi-mana /types/fast-list/ @BendingBender /types/fast-stats/ @rogierschouten /types/fastclick/ @shinnn +/types/fastify-accepts/ @leomelzer /types/fastify-cors/ @jannikkeye /types/fastify-jwt/ @jannikkeye /types/fastify-multipart/ @jannikkeye @@ -1283,13 +1321,15 @@ /types/finalhandler/ @chrootsu /types/finch/ @DavidSichau /types/find/ @andypyrope +/types/find-package-json/ @BendingBender /types/find-parent-dir/ @ikatyang /types/find-process/ @buaban /types/find-project-root/ @ikatyang /types/find-root/ @Alorel /types/find-up/ @BendingBender -/types/find-versions/ @LogvinovLeon +/types/find-versions/ @LogvinovLeon @carnesen /types/findup-sync/ @Bartvds @ngbrown +/types/fined/ @BendingBender /types/fingerprintjs/ @zaneli /types/fingerprintjs2/ @curtstate /types/firebase-client/ @fpsscarecrow @@ -1301,7 +1341,9 @@ /types/first-mate/ @GlenCFL /types/fixed-data-table/ @pepaar @stephenjelfs /types/fixed-data-table-2/ @ilivit +/types/flagged-respawn/ @BendingBender /types/flat/ @chrootsu +/types/fleximap/ @DanielRose /types/flexslider/ @diullei /types/flickity/ @clmcgrath @wagich /types/flight/ @jonathanhedren @@ -1309,6 +1351,7 @@ /types/flipsnap/ @kubosho @gsino @mayuki /types/float-regex/ @wanganjun /types/flot/ @burlandm @Anticom @admiralsmaster +/types/flowdoc/ @animify /types/flowjs/ @ryan10132 /types/fluent-ffmpeg/ @tcaesvk @DingWeizhe @mabidina /types/flush-write-stream/ @djcsdy @@ -1374,6 +1417,7 @@ /types/fusioncharts/ @rohitkr @shivarajkv /types/fuzzaldrin/ @mhegazy /types/fuzzaldrin-plus/ @jeancroy @jkillian @reyronald +/types/fuzzy-search/ @alex-deas @BendingBender /types/fuzzyset/ @lgrignon @narainsagar /types/fuzzyset.js/ @lgrignon @narainsagar /types/fxn/ @charrondev @@ -1547,6 +1591,7 @@ /types/getos/ @BendingBender /types/gettext.js/ @jucrouzet /types/gh-pages/ @DanielRosenwasser +/types/ghauth/ @Leko /types/gifffer/ @gatimus /types/gijgo/ @atatanasov /types/giraffe/ @darthapo @@ -1555,11 +1600,17 @@ /types/git-config/ @stpettersens /types/git-remote-origin-url/ @janslow /types/git-rev-sync/ @khoi-fish +/types/git-root-dir/ @ffflorian /types/git-url-parse/ @ajafff +/types/gitconfiglocal/ @ffflorian /types/github-url-to-object/ @ajafff /types/github-username-regex/ @BehindTheMath -/types/gitlab/ @yanqing6628780 @Arylo /types/gl-matrix/ @mattijskneppers @tatchx @nbabanov @auzmartist @surtr-isaz +/types/gl-react/ @jussikinnula +/types/gl-react-dom/ @jussikinnula +/types/gl-react-expo/ @jussikinnula +/types/gl-react-headless/ @jussikinnula +/types/gl-react-native/ @jussikinnula /types/gl-shader/ @MathiasPaumgarten /types/gl-texture2d/ @MathiasPaumgarten /types/gldatepicker/ @qcz @@ -1585,12 +1636,12 @@ /types/google-apps-script-oauth2/ @dhayab /types/google-cloud__datastore/ @beaulac @ogawa0071 @ThomasdenH /types/google-cloud__pubsub/ @pheromonez @LunaPg @msiviero -/types/google-cloud__storage/ @blove @nbperry @welkie @ogawa0071 /types/google-earth/ @icholy /types/google-images/ @dolanmiu /types/google-libphonenumber/ @leonyu @winfinit /types/google-map-react/ @honzabrecka /types/google-maps/ @DeividasBakanas @GiedriusGrabauskas +/types/google-maps-react/ @gburgett @jpowell /types/google-protobuf/ @marcuslongmuir /types/google-translate-api/ @maple3142 /types/google.analytics/ @tyler-murphy @@ -1598,7 +1649,7 @@ /types/google.fonts/ @danmarshall /types/google.geolocation/ @vbortone /types/google.picker/ @grapswiz -/types/google.visualization/ @danludwig @gmoore-sjcorg @danmana @mlcheng @IvanBisultanov @glebm +/types/google.visualization/ @danludwig @gmoore-sjcorg @danmana @mlcheng @IvanBisultanov @glebm @shrujalshah28 /types/google__maps/ @indrimuska /types/googlemaps/ @cgwrench @nertzy @xaolas @mrmcnerd @martincostello @svenkreiss @bolatovumar @gauthierm /types/googlemaps.infobubble/ @Dashue @@ -1616,6 +1667,7 @@ /types/graphql-date/ @enaeseth /types/graphql-deduplicator/ @lfades /types/graphql-depth-limit/ @eritikass +/types/graphql-fields/ @feinoujc /types/graphql-iso-date/ @jwaldrip /types/graphql-list-fields/ @filipows /types/graphql-query-complexity/ @abhikmitra @@ -1678,6 +1730,7 @@ /types/gulp-jasmine/ @andypyrope /types/gulp-jasmine-browser/ @tkrotoff /types/gulp-json-editor/ @peterjuras +/types/gulp-json-validator/ @pe8ter /types/gulp-jsonmin/ @romain-faust /types/gulp-jsonminify/ @pine /types/gulp-jspm/ @peterjuras @@ -1722,12 +1775,14 @@ /types/halogen/ @steller /types/hammerjs/ @milkisevil @codler /types/handlebars/ @borisyankov @evil-shrike +/types/handlebars-helpers/ @Toilal /types/hapi/v8/ @jasonswearingen /types/hapi/v12/ @jasonswearingen /types/hapi/v15/ @jasonswearingen /types/hapi/v16/ @jasonswearingen @AJamesPhillips /types/hapi/ @rafaelsouzaf @jhsimms @SimonSchick /types/hapi-auth-basic/ @AJamesPhillips @saboya +/types/hapi-auth-cookie/ @lenovouser @SimonSchick @Mutmatt /types/hapi-auth-jwt2/v7/ @warrenseymour /types/hapi-auth-jwt2/ @warrenseymour @SimonSchick /types/hapi-decorators/ @kenhowardpdx @@ -1764,6 +1819,7 @@ /types/hexo-fs/ @segayuu /types/hexo-log/ @segayuu /types/hexo-util/ @segayuu +/types/hibp/ @lenovouser /types/highcharts/ @damianog @baltie @AlbertOzimek @hanssens /types/highcharts-ng/ @scatcher /types/highland/ @Bartvds @hgwood @iwllyu @alvis @notbobthebuilder @@ -1821,6 +1877,7 @@ /types/humanparser/ @MichalPodeszwa /types/humps/ @nikeee /types/hyco-ws/ @mrcabellom +/types/hyper-aws4/ @bambutz /types/hyperscript/ @spacejack @jmfirth /types/hypertext-application-language/ @maks3w /types/hystrixjs/ @igorsechyn @@ -1867,7 +1924,7 @@ /types/images/ @DingWeizhe /types/imagesloaded/ @coldacid @apexskier /types/imap/ @psnider -/types/imap-simple/ @pushplay +/types/imap-simple/ @pushplay @iaarnio /types/imgur-rest-api/ @lukewestby /types/imperium/ @gaetansenn /types/impress/ @borisyankov @@ -1881,7 +1938,7 @@ /types/inflected/ @dsci /types/inflection/ @shiwano /types/inherits/ @chrootsu -/types/ini/ @marcinporebski +/types/ini/ @marcinporebski @carnesen /types/iniparser/ @chrootsu /types/init-package-json/ @kfarnung /types/inline-css/ @philipisapain @@ -1890,33 +1947,38 @@ /types/inquirer-npm-name/ @manuth /types/insert-module-globals/ @leonard-thieu /types/insight/ @vvakame +/types/instabug-reactnative/ @pengcao1 /types/integer/ @Morfent /types/intercom-client/ @jineshshah36 @peping /types/intercom-web/ @fongandrew @salbahra @onatm /types/intercomjs/ @spencerwi /types/internal-ip/ @BendingBender +/types/interpret/ @BendingBender /types/intl/ @RagibHasin /types/intl-locales-supported/ @Slessi /types/intl-messageformat/ @mhegazy /types/intl-relativeformat/ @mohsen1 -/types/intl-tel-input/ @fdnhkj @leonard-thieu +/types/intl-tel-input/v13/ @fdnhkj @leonard-thieu +/types/intl-tel-input/ @fdnhkj @leonard-thieu @molnarm /types/into-stream/ @BendingBender /types/intrinsic-scale/ @shalomdotnet /types/intro.js/ @anahkiasen /types/invariant/ @bennett000 /types/inversify-devtools/ @inversify +/types/iobroker/ @AlCalzone /types/ion-rangeslider/v1/ @dduugg @Karel-van-de-Plassche /types/ion-rangeslider/ @Karel-van-de-Plassche /types/ioredis/v3/ @plantain-00 @chrisleck @aliarham11 @br8h @shaharmor @palindrom615 @reconbot -/types/ioredis/ @plantain-00 @chrisleck @aliarham11 @br8h @shaharmor @palindrom615 @reconbot @funthing @iamolegga +/types/ioredis/ @plantain-00 @chrisleck @aliarham11 @br8h @shaharmor @palindrom615 @reconbot @funthing @iamolegga @tingwai-to /types/iota.lib.js/ @fogsh /types/ip/ @codeanimal /types/ip-address/ @icopp @danwbyrne /types/ip-regex/ @unindented /types/ipcheck/ @bengry /types/irc/ @phillips1012 +/types/iri/ @BendingBender /types/iron/ @simonschick @rafaelsouzaf -/types/is/ @cabralRodrigo +/types/is/ @cabralRodrigo @gricey432 /types/is-absolute-url/ @mhegazy /types/is-alphanumerical/ @vutran /types/is-archive/ @mhegazy @@ -1936,10 +1998,12 @@ /types/is-my-json-valid/ @kruncher /types/is-negated-glob/ @ajafff /types/is-number/ @harryshipton +/types/is-obj/ @forivall /types/is-object/ @wbhob /types/is-path-cwd/ @DanielRosenwasser /types/is-path-in-cwd/ @mhegazy /types/is-promise/ @DanielRosenwasser +/types/is-regexp/ @forivall /types/is-relative-url/ @mhegazy /types/is-root/ @mhegazy /types/is-root-path/ @mhegazy @@ -1975,7 +2039,9 @@ /types/jade/ @panuhorsmalahti /types/jalaali-js/ @alitaheri /types/japanese-holidays/ @syamatoo -/types/jasmine/ @borisyankov @theodorejb @davidparsson @gmoothart @lukas-zech-software @Engineer2B +/types/jasmine/v1/ @borisyankov +/types/jasmine/v2/ @borisyankov @theodorejb @davidparsson @gmoothart @lukas-zech-software @Engineer2B @cyungmann +/types/jasmine/ @borisyankov @theodorejb @davidparsson @gmoothart @lukas-zech-software @Engineer2B @cyungmann @Roaders /types/jasmine-ajax/ @lgrignon /types/jasmine-data-provider/ @tlaziuk /types/jasmine-data_driven_tests/ @AnthonyMacKinnon @@ -1991,7 +2057,7 @@ /types/jasminewd2/ @sjelin @gkalpak /types/java/ @jimlloyd @hrl7 @darti /types/java-applet/ @cyrilschumacher -/types/javascript-astar/ @ptlis +/types/javascript-astar/ @ptlis @lazerwalker /types/javascript-bignum/ @sandersn /types/javascript-obfuscator/ @sanex3339 /types/javascript-state-machine/ @borisyankov @mdocter @MrBigDog2U @samael65535 @taoqf @@ -2021,10 +2087,11 @@ /types/jexl/ @m-tomczyk /types/jfs/ @tlaziuk /types/jira-client/ @KOPTE3 @orta +/types/jju/ @ecraig12345 @rlidwka /types/jjv/ @Nemo157 /types/jjve/ @Nemo157 /types/jmespath/ @pushplay -/types/johnny-five/ @nakakura @ujvzolee @workshop2 +/types/johnny-five/ @nakakura @ujvzolee @workshop2 @xtrimsystems /types/joi/v6/ @Bartvds @laurence-myers @cglantschnig @DavidBR-SW /types/joi/v10/ @Bartvds @laurence-myers @cglantschnig @DavidBR-SW @GaelMagnan @ralekna @schfkt @rokoroku @aconanlai /types/joi/v13/ @Bartvds @laurence-myers @cglantschnig @DavidBR-SW @GaelMagnan @ralekna @schfkt @rokoroku @dankraus @wanganjun @rafaelkallis @aconanlai @zaphoyd @thewillg @SimonSchick @@ -2173,7 +2240,7 @@ /types/js-sha512/ @nicojs /types/js-string-escape/ @viralpickaxe /types/js-to-java/ @skyitachi -/types/js-url/ @pine613 +/types/js-url/ @pine /types/js-yaml/ @Bartvds @sclausen /types/js.spec/ @mattbishop /types/jsbn/ @Evgenus @al2xed @@ -2201,6 +2268,7 @@ /types/json-rpc-random-id/ @micahriggan /types/json-rpc-ws/ @npenin @mlamp /types/json-schema/ @bcherny @cyrilletuzi @lucianbuzzo @rolandjitsu +/types/json-server/ @jeremyben /types/json-socket/ @svi3c /types/json-stable-stringify/ @mhfrantz /types/json-stringify-safe/ @BendingBender @@ -2208,6 +2276,7 @@ /types/json2md/ @MartynasZilinskas /types/json3/ @NN--- /types/json5/ @Esemesek +/types/json_ml/ @pluma /types/jsonata/ @nick121212 /types/jsoneditor/ @alejo90 @errietta /types/jsoneditor-for-react/ @joshuakgoldberg @@ -2225,7 +2294,7 @@ /types/jsonwebtoken/ @SomaticIT @danielheim @brikou @vpk @rlgod /types/jsonwebtoken-promisified/ @SomaticIT @danielheim @brikou @aneilbaboo /types/jspath/ @dex4er -/types/jspdf/ @amberjs +/types/jspdf/ @amberjs @lleios @jemerald /types/jsqrcode/ @lordazzi /types/jsrender/ @zakki /types/jsreport-core/ @taoqf @@ -2253,6 +2322,7 @@ /types/jui-grid/ @easylogic /types/just-debounce-it/ @azizhk /types/just-extend/ @pe8ter +/types/just-pick/ @pe8ter /types/jweixin/ @taoqf @gomydodo /types/jwplayer/ @martinduparc @kutomer @philippguertler @danielmcgraw @bpdsw /types/jws/ @JustinBeckwith @@ -2268,7 +2338,7 @@ /types/karma/ @tkrotoff @43081j @devoto13 /types/karma-chai/ @JayAndCatchFire /types/karma-chai-sinon/ @vasek17 -/types/karma-coverage/ @tkrotoff +/types/karma-coverage/ @tkrotoff @devoto13 /types/karma-fixture/ @evictor @afshawnlotfi /types/karma-jasmine/ @michelsalib /types/karma-viewport/ @karak @@ -2276,9 +2346,11 @@ /types/katex/ @mrand01 /types/kcors/ @Xstoudi @izayoiko /types/kdbush/ @DenisCarriere @chrfrasco +/types/kdbxweb/ @Roang-zero1 /types/keen-tracking/ @rui-ferreira /types/kefir/ @AyaMorisawa @HitoriSensei /types/kendo-ui/ @telerik +/types/kerberos/ @velezsarain /types/keyboardjs/ @vbortone @piranha771 @teoxoy /types/keycloak-connect/ @gstamac /types/keygrip/ @jkeylu @@ -2293,10 +2365,10 @@ /types/klaw/ @mceachen /types/klaw-sync/ @shiftkey /types/kms-json/ @sunnyone -/types/knex/ @tkQubo @MeLlamoPablo @mastermatt @micksatana @shreyjain1994 +/types/knex/ @tkQubo @MeLlamoPablo @mastermatt @micksatana @shreyjain1994 @joelshepherd /types/knex-postgis/ @vesse /types/knockback/ @borisyankov -/types/knockout/ @borisyankov @Igorbek @moonpyk @EnableSoftware @BenjaminEckardt @ffMathy @ltlombardi +/types/knockout/ @borisyankov @Igorbek @moonpyk @EnableSoftware @BenjaminEckardt @ffMathy @ltlombardi @Retsam /types/knockout-amd-helpers/ @DavidSichau /types/knockout-secure-binding/ @pine613 /types/knockout-transformations/ @johnnyreilly @Nemo157 @@ -2317,7 +2389,8 @@ /types/koa/ @DavidCai1993 @jkeylu @brikou /types/koa-basic-auth/ @Tobias4872 /types/koa-better-body/ @danwbyrne -/types/koa-bodyparser/ @hellopao @anup-2s +/types/koa-bodyparser/ @hellopao @anup-2s @hirochachacha +/types/koa-bouncer/ @maruware /types/koa-bunyan-logger/ @sjmcdowall /types/koa-cache-control/ @pe8ter /types/koa-compose/ @jkeylu @@ -2332,9 +2405,10 @@ /types/koa-hbs/ @jcbmln @mudkipme /types/koa-helmet/ @me /types/koa-html-minifier/ @romain-faust -/types/koa-joi-router/ @wingsbob @move-zig +/types/koa-joi-router/ @wingsbob @move-zig @hirochachacha /types/koa-json/ @brooklyndev /types/koa-json-error/ @mudkipme +/types/koa-log/ @havenchyk /types/koa-logger/ @geoffreak @tlaziuk /types/koa-logger-winston/ @stevehipwell /types/koa-morgan/ @vesse @@ -2343,14 +2417,16 @@ /types/koa-passport/ @horiuchi @tlaziuk @brendtumi /types/koa-pino-logger/ @khell /types/koa-pug/ @Xstoudi +/types/koa-qs/ @RemyJeancolas /types/koa-range/ @strax /types/koa-ratelimit/ @OutdatedVersion +/types/koa-ratelimit-lru/ @danwbyrne /types/koa-redis/ @nsimmons /types/koa-redis-cache/ @dimamukhin /types/koa-requestid/ @sjmcdowall /types/koa-response-time/ @thorsedeke @sjmcdowall /types/koa-route/ @migstopheles @jacogr -/types/koa-router/ @hellopao @schfkt @JounQin @romain-faust +/types/koa-router/ @hellopao @schfkt @JounQin @romain-faust @Guillaume-Mayer @falinor /types/koa-send/ @pe8ter @tlaziuk /types/koa-session/ @kerol2r20 @tlaziuk /types/koa-session-minimal/ @longztian @@ -2358,6 +2434,7 @@ /types/koa-static/ @hellopao @tlaziuk /types/koa-static-cache/ @JounQin /types/koa-static-server/ @wulunyi +/types/koa-useragent/ @rvboris /types/koa-views/ @brooklyndev /types/koa-webpack/ @malj @leebenson @miZyind @tlaziuk /types/koa-websocket/ @moimael @jacogr @zdila @Kroisse @@ -2387,6 +2464,7 @@ /types/lazy-value/ @ikatyang /types/lazy.js/ @Bartvds @miso440 /types/lazypipe/ @tomc974 +/types/ldap-filters/ @pluma /types/ldapjs/ @cvillemure @peterkooijmans /types/leadfoot/ @theintern /types/leaflet/v0/ @rgripper @@ -2441,6 +2519,7 @@ /types/libxmljs/ @fdecampredon @ComFreek /types/libxslt/ @alejo90 /types/license-checker/ @rogierschouten @unindented +/types/liftoff/ @BendingBender /types/lil-uuid/ @Pr1st0n /types/lime-js/ @arthur-xavier /types/line-by-line/ @etomsen @@ -2450,6 +2529,8 @@ /types/lingui__macro/ @huan086 /types/lingui__react/ @huan086 /types/linkify-it/ @praxxis +/types/linkifyjs/ @szhu +/types/list-stream/ @IanStorm /types/listr/ @durad /types/lls/ @borislavjivkov /types/load-json-file/ @SamVerschueren @@ -2767,6 +2848,7 @@ /types/lokijs/ @TeamworkGuy2 @thomasconner /types/lolex/ @Nemo157 @joshuakgoldberg @rogierschouten /types/long/ @peterkooijmans +/types/looks-same/ @xcatliu /types/loopback/ @kattsushi @enko @sequoia @drmikecrowe @karimsa /types/loopback-boot/ @kattsushi /types/lorem-ipsum/ @durad @@ -2778,12 +2860,12 @@ /types/lozad/ @plantain-00 /types/lru-cache/ @Bartvds @BendingBender /types/lscache/ @Chris-Martinezz -/types/ltx/ @PJakcson +/types/ltx/ @PJakcson @BendingBender /types/luaparse/ @stpettersens /types/lunr/v0/ @sebastian-lenz /types/lunr/ @seantanly /types/lusca/ @crutchcorn -/types/luxon/ @colbydehart @FourwingsY @jsiebern +/types/luxon/ @colbydehart @FourwingsY @jsiebern @mastermatt /types/lwip/ @AyaMorisawa /types/lz-string/ @M0ns1gn0r /types/lzma-native/ @leshow @@ -2793,19 +2875,21 @@ /types/mailcheck/ @pocesar /types/maildev/ @cyrilschumacher @zbarbuto /types/mailgen/ @vothanhkiet @jordanfarrer -/types/mailgun-js/ @sampsonjoliver +/types/mailgun-js/ @sampsonjoliver @andipaetzold /types/mailparser/ @psnider /types/main-bower-files/ @k-kagurazaka /types/make-dir/ @ikatyang @BendingBender /types/maker.js/ @danmarshall /types/makeup-expander/ @darkwebdev /types/makeup-floating-label/ @darkwebdev +/types/makeup-keyboard-trap/ @darkwebdev +/types/makeup-prevent-scroll-keys/ @darkwebdev /types/makeup-screenreader-trap/ @darkwebdev /types/mali-compose/ @danwbyrne /types/mali-onerror/ @danwbyrne /types/mandrill-api/ @pocesar /types/map-obj/ @BendingBender -/types/mapbox/ @anahkiasen +/types/mapbox/ @anahkiasen @Fluccioni /types/mapbox-gl/ @dobrud @patrickr /types/mapbox-gl-leaflet/ @agorshkov23 /types/mapbox__geo-viewport/ @fnberta @@ -2822,7 +2906,7 @@ /types/markdown-it-lazy-headers/ @knom /types/markdown-pdf/ @MonsieurMan /types/markdownlint/ @ark120202 -/types/marked/ @worr @BendingBender @CrossR +/types/marked/ @worr @BendingBender @CrossR @mwickett /types/marker-animate-unobtrusive/ @viskin /types/markerclustererplus/ @enanox @mxl /types/markitup/ @drillbits @@ -2868,12 +2952,13 @@ /types/materialize-css/ @huww98 @MaximBalaganskiy @MonizDave @broccoliarchy /types/math3d/ @laszlojakab @jimsmart /types/mathjax/ @rolandzwaga -/types/mathjs/ @siavol @andnp @bradbesserman +/types/mathjs/ @siavol @andnp @bradbesserman @pawkrol /types/matter-js/ @piranha771 @hasparus -/types/maxmind/ @geoffreak +/types/mcrypt/ @pluma /types/mcustomscrollbar/ @flurg /types/md5/ @arcdev1 @jprogrammer /types/md5-file/ @BamButz +/types/mdast/ @lujun2 /types/mdns/ @reppners /types/mdurl/ @rokt33r /types/media-typer/ @BendingBender @@ -2892,6 +2977,7 @@ /types/memwatch-next/ @cyrilschumacher /types/meow/ @KnisterPeter @praxxis @bitjson /types/merge-descriptors/ @danny8002 +/types/merge-env/ @BendingBender /types/merge-stream/ @k-kagurazaka @tomxtobin @daniel-zazula @djcsdy /types/merge2/ @tkrotoff @smac89 /types/merkle/ @kerol2r20 @@ -2945,12 +3031,12 @@ /types/mixpanel/ @hjellek @Manduro /types/mixto/ @vvakame /types/mjml/ @aahoughton @marpstar +/types/mjml-react/ @henrinormak /types/mkdirp/ @Bartvds @mrmlnc /types/mkdirp-promise/ @pluma /types/mkpath/ @optical /types/ml-levenberg-marquardt/ @m93a /types/mobx-apollo/ @pselden -/types/mobx-cookie/ @t49tran /types/mobx-devtools-mst/ @pluma /types/mocha/ @kazimanzurrashid @otiai10 @jt000 @enlight @cspotcode @1999 /types/mocha-each/ @magnostherobot @@ -2964,6 +3050,7 @@ /types/mock-require/ @gDelgado14 /types/mockdate/ @brunolm /types/mockery/ @jt000 +/types/mockingoose/ @hirochachacha /types/modernizr/ @borisyankov @theodorejb @leonyu @lucax88x @nhardy /types/modesl/ @neeschit /types/module-alias/ @KevinRamharak @@ -2982,7 +3069,7 @@ /types/money-math/ @taoqf /types/mongo-sanitize/ @CedricCazin /types/mongodb/v2/ @CaselIT @alanmarcell @bitjson @dante-101 @mcortesi -/types/mongodb/ @CaselIT @alanmarcell @bitjson @dante-101 @mcortesi @EnricoPicci @AJCStriker @julien-c @daprahamian @denys-bushulyak @BastienAr @sindbach @geraldinelemeur @jishi @various89 @angela-1 @lirbank @hector7 @floric +/types/mongodb/ @CaselIT @alanmarcell @bitjson @dante-101 @mcortesi @EnricoPicci @AJCStriker @julien-c @daprahamian @denys-bushulyak @BastienAr @sindbach @geraldinelemeur @jishi @various89 @angela-1 @lirbank @hector7 @floric @erikc5000 /types/mongodb-memory-server/ @dmitryrogozhny /types/mongodb-uri/ @mernxl /types/mongoose/v4/ @simonxca @horiuchi @sindrenm @lukasz-zak @@ -3040,6 +3127,7 @@ /types/murmurhash3js/ @dlee-nvisia /types/musicmetadata/ @Xstoudi /types/mustache/ @markashleybell @manuth +/types/mustache-express/ @BendingBender /types/mutexify/ @maistho /types/mv/ @nenadalm /types/mysql/ @wjohnsto @kacepe @kpping @jdmunro @@ -3078,6 +3166,8 @@ /types/nes/ @NoHomey @saboya /types/nested-error-stacks/ @woutervh- /types/net-keepalive/ @hertzg +/types/netease-captcha/ @norubidium +/types/netlify-identity-widget/ @nkprince007 /types/netmask/ @mhfrantz /types/network-interfaces/ @anderswestberg /types/new-relic-browser/ @renehamburger @piotrkubisa @@ -3112,7 +3202,8 @@ /types/ngtoaster/ @btesser /types/ngwysiwyg/ @patrick-mackay /types/nightmare/ @horiuchi @samyang-au @Bleser92 -/types/nightwatch/ @rkavalap @schlesiger +/types/nightwatch/ @rkavalap @schlesiger @ClaytonAstrom +/types/nise/ @a-tarasyuk /types/nivo-slider/ @AndersonFriaca /types/noble/ @swook @shantanubhadoria @lukel99 @bioball @keton @thegecko /types/nock/ @bonnici @horiuchi @afharo @mastermatt @damour @paambaati @@ -3123,7 +3214,7 @@ /types/node/v7/ @Microsoft @DefinitelyTyped @parambirs @tellnes @WilcoBakker @eps1lon @KSXGitHub @Archcry /types/node/v8/ @Microsoft @DefinitelyTyped @parambirs @tellnes @WilcoBakker @octo-sniffle @smac89 @Flarna @mwiktorczyk @wwwy3y3 @DeividasBakanas @kjin @alvis @eps1lon @Hannes-Magnusson-CK @jkomyno @hoo29 @n-e @brunoscheufler @KSXGitHub @islishude @r3nya /types/node/v9/ @Microsoft @DefinitelyTyped @parambirs @tellnes @WilcoBakker @octo-sniffle @smac89 @Flarna @mwiktorczyk @wwwy3y3 @DeividasBakanas @kjin @alvis @eps1lon @Hannes-Magnusson-CK @jkomyno @ajafff @hoo29 @n-e @brunoscheufler @mohsen1 @KSXGitHub @a-tarasyuk @islishude @r3nya @eyqs -/types/node/ @Microsoft @DefinitelyTyped @jkomyno @a-tarasyuk @alvis @r3nya @brunoscheufler @smac89 @tellnes @DeividasBakanas @eyqs @Flarna @Hannes-Magnusson-CK @KSXGitHub @hoo29 @kjin @ajafff @islishude @mwiktorczyk @matthieusieben @mohsen1 @n-e @octo-sniffle @parambirs @eps1lon @SimonSchick @ThomasdenH @WilcoBakker @wwwy3y3 @ZaneHannanAU @jeremiergz +/types/node/ @Microsoft @DefinitelyTyped @jkomyno @a-tarasyuk @alvis @r3nya @brunoscheufler @smac89 @tellnes @DeividasBakanas @eyqs @Flarna @Hannes-Magnusson-CK @KSXGitHub @hoo29 @kjin @ajafff @islishude @mwiktorczyk @matthieusieben @mohsen1 @n-e @octo-sniffle @parambirs @eps1lon @SimonSchick @ThomasdenH @WilcoBakker @wwwy3y3 @ZaneHannanAU @jeremiergz @samuela /types/node-7z/ @erkie /types/node-array-ext/ @Beng89 /types/node-cache/ @chrootsu @dthunell @useltmann @@ -3137,7 +3228,7 @@ /types/node-emoji/ @jonestristand @styu /types/node-fetch/ @torstenwerner @nikcorg /types/node-fibers/ @caryhaynie -/types/node-forge/ @westy92 @flynetworks @a-k-g @rafal2228 @beenotung @joeflateau +/types/node-forge/ @westy92 @flynetworks @a-k-g @rafal2228 @beenotung @joeflateau @Apologiz @timhwang21 /types/node-gcm/ @horiuchi /types/node-geocoder/ @rosek86 /types/node-getopt/ @kcauchy @@ -3212,7 +3303,7 @@ /types/ns-api/ @Archcry /types/nslog/ @unindented /types/nsqjs/ @cezaryrk -/types/nuka-carousel/ @Romic @altaudio +/types/nuka-carousel/ @Romic @altaudio @matt-sungwook /types/number-is-nan/ @mhegazy /types/number-to-words/ @frederickfogerty /types/numeral/ @vbortone @BehindTheMath @klujanrosas @@ -3226,8 +3317,9 @@ /types/nwmatcher/ @woutervh- /types/o.js/ @IceOnFire @bradzacher @janhommes @jcchalte /types/oauth/ @nonAlgebraic @EduardoAC +/types/oauth-shim/ @BendingBender /types/oauth.js/ @nobuoka -/types/oauth2-server/ @vangorra @cirick @d-fischer +/types/oauth2-server/ @vangorra @cirick @d-fischer @rvitorsantos /types/oauth2orize/ @wokim @heycalmdown @stevehipwell /types/obelisk.js/ @bdrupieski /types/obj-file-parser/ @benc-uk @@ -3248,6 +3340,7 @@ /types/observe-js/ @herrmanno /types/oclazyload/ @rolandzwaga /types/odata/ @janhommes @jcchalte +/types/oembed-parser/ @BendingBender /types/ofe/ @Morfent /types/office-js/ @OfficeDev @LanceEA @Zlatkovsky @kbrandl @Rick-Kirkham @AlexJerabek @ElizabethSamuel-MSFT /types/office-runtime/ @Zlatkovsky @mscharlock @@ -3271,17 +3364,18 @@ /types/opener/ @tikurahul /types/openfin/v17/ @chrisbarker /types/openfin/v29/ @chrisbarker @rdepena -/types/openfin/ @chrisbarker @rdepena @whyn07m3 +/types/openfin/v34/ @chrisbarker @rdepena @whyn07m3 +/types/openfin/ @chrisbarker @rdepena @whyn07m3 @licui3936 /types/openjscad/ @danmarshall /types/openlayers/v2/ @bolhovsky /types/openlayers/v3/ @osechet @matthiasdailey-ccri /types/openlayers/ @osechet @wb14123 @ailrun @mylen @iamthechad @danmana @yairtawil @pierremarc @hauke96 @gberaudo -/types/openpgp/ @errietta @damonpam +/types/openpgp/ @errietta @damonpam @po5i /types/openstack-wrapper/ @sanjaymadane /types/opentok/ @westy92 @CatGuardian /types/opentype.js/ @danmarshall @edzis /types/opn/ @shinnn @SomaticIT @tlent -/types/opossum/ @quinnlangille @lance +/types/opossum/ @quinnlangille @merufm @lance /types/optics-agent/ @crevil /types/optimist/ @soywiz @chbrown /types/optimize-css-assets-webpack-plugin/ @odnamrataizem @@ -3310,7 +3404,7 @@ /types/p-cancelable/ @BendingBender /types/p-catch-if/ @LinusU /types/p-debounce/ @BendingBender -/types/p-defer/ @SamVerschueren +/types/p-defer/ @SamVerschueren @BendingBender /types/p-do-whilst/ @BendingBender /types/p-each-series/ @BendingBender /types/p-event/ @BendingBender @@ -3326,6 +3420,7 @@ /types/p-one/ @BendingBender /types/p-progress/ @icopp /types/p-props/ @BendingBender +/types/p-queue/v2/ @BendingBender @evanshortiss /types/p-queue/ @BendingBender @evanshortiss /types/p-reduce/ @BendingBender /types/p-reflect/ @BendingBender @@ -3337,6 +3432,7 @@ /types/p-throttle/ @BendingBender /types/p-timeout/ @BendingBender /types/p-try/ @BendingBender @LinusU +/types/p-wait-for/v1/ @BendingBender /types/p-wait-for/ @BendingBender /types/p-whilst/ @BendingBender /types/p2/ @clark-stevenson @@ -3358,7 +3454,8 @@ /types/parity-pmd/ @leovujanic @jewbre /types/parity-pmr/ @leovujanic /types/parity-poe/ @leovujanic -/types/parse/ @dpoetzsch @jaeggerr @flavionegrao @wesleygrimes @owsas +/types/parse/v1/ @dpoetzsch @jaeggerr @flavionegrao @wesleygrimes @owsas +/types/parse/ @dpoetzsch @jaeggerr @flavionegrao @wesleygrimes @owsas @agoldis /types/parse-git-config/ @leonard-thieu @deltaidea /types/parse-github-url/ @ajafff /types/parse-glob/ @glen-84 @@ -3382,9 +3479,10 @@ /types/parsimmon/ @Bartvds @mizunashi-mana @bcherny @bvanreeven @leonard-thieu @MrJohz /types/passport/ @horiuchi @enaeseth @theigor @tlaziuk @danielpa9708 /types/passport-anonymous/ @0x6368656174 -/types/passport-auth0/ @johnbendi @iamvishnusankar +/types/passport-auth0/ @johnbendi @iamvishnusankar @duncanhall /types/passport-azure-ad/ @ShekharNain /types/passport-beam/ @AtlasDev +/types/passport-bnet/ @ivan94 /types/passport-cognito/ @mbutsykin /types/passport-discord/ @kzay /types/passport-facebook/ @staticfunction @lucasmacosta @@ -3403,7 +3501,7 @@ /types/passport-oauth2/ @pasieronen @WangZishi @EduardoAC /types/passport-oauth2-client-password/ @akaNightmare /types/passport-remember-me-extended/ @AylaJK -/types/passport-saml/ @cjbarth @dassennato +/types/passport-saml/ @cjbarth @dassennato @ksamborski /types/passport-steam/ @kzay /types/passport-strategy/ @liorm /types/passport-twitter/ @staticfunction @@ -3425,6 +3523,7 @@ /types/paypal-rest-sdk/ @trainerbill /types/pbf/ @cschwarz /types/pbkdf2/ @timonegk +/types/pdf2image/ @taoqf /types/pdfjs-dist/ @jbaldwin /types/pdfkit/ @erichillah /types/pdfmake/ @m1llen1um @radziksh @evolkmann @@ -3467,13 +3566,13 @@ /types/picturefill/ @alaz /types/pidusage/ @cyrilschumacher @mx601595686 /types/pify/ @samverschueren @mad-mike @c7hm4r -/types/pigpio/ @manerfan +/types/pigpio/ @manerfan @erikma /types/pigpio-dht/ @erikma /types/pikaday/ @MidnightDesign @wake42 @mezoistvan /types/pikaday-time/ @Sayan751 /types/pinkyswear/ @chances /types/pino/v3/ @psnider -/types/pino/ @psnider @BendingBender @screendriver @paambaati @alferpal +/types/pino/ @psnider @BendingBender @screendriver @paambaati @alferpal @mortiy /types/pino-http/ @screendriver /types/pino-multi-stream/ @JakeGinnivan /types/pinterest-sdk/ @adamburmister @@ -3483,6 +3582,7 @@ /types/pixi.js/ @clark-stevenson /types/pkg-conf/ @jorgegonzalez /types/pkg-dir/ @NK-WEB-Git +/types/pkg-up/ @forivall /types/pkijs/ @microshine /types/platform/ @JakeH /types/playcanvas/ @Neoflash1979 @@ -3503,6 +3603,12 @@ /types/podcast/ @nikeee /types/podium/ @AJamesPhillips /types/point-in-polygon/ @dyst5422 @kogai +/types/pollyjs__adapter/ @feinoujc +/types/pollyjs__adapter-fetch/ @feinoujc +/types/pollyjs__core/ @feinoujc +/types/pollyjs__persister/ @feinoujc +/types/pollyjs__persister-fs/ @feinoujc +/types/pollyjs__utils/ @feinoujc /types/polyfill-service/ @Alorel /types/polylabel/ @DenisCarriere /types/polyline/ @Kern0 @@ -3513,7 +3619,11 @@ /types/postal/ @lokeshpeta @myitcv /types/postcss-calc/ @huan086 /types/postcss-icss-values/ @huan086 +/types/postcss-modules-extract-imports/ @huan086 +/types/postcss-modules-local-by-default/ @huan086 /types/postcss-modules-resolve-imports/ @huan086 +/types/postcss-modules-scope/ @huan086 +/types/postcss-url/ @lenovouser /types/postman-collection/ @kbuzby /types/postmark/ @benbayard @jineshshah36 /types/pouch-redux-middleware/ @charrondev @@ -3563,21 +3673,23 @@ /types/promise-ftp/ @coolreader18 /types/promise-ftp-common/ @coolreader18 /types/promise-map-limit/ @kohlmannj +/types/promise-memoize/ @forivall /types/promise-pg/ @coldacid -/types/promise-polyfill/ @skysteve +/types/promise-polyfill/ @skysteve @djcsdy /types/promise-pool/ @vilic /types/promise-queue/ @LachlanStuart /types/promise-retry/ @shirakaba /types/promise-sftp/ @coolreader18 /types/promise-timeout/ @Aankhen /types/promise.prototype.finally/ @slavik57 @BendingBender +/types/promised-ldap/ @pluma /types/promised-temp/ @rokadias /types/promisify-node/ @borekb /types/promisify-supertest/ @aleung /types/prompt-sync/ @MugeSo /types/prompt-sync-history/ @MugeSo /types/promptly/ @danrspencer -/types/prompts/ @Berkays +/types/prompts/ @Berkays @danielpa9708 /types/prop-types/ @DovydasNavickas @ferdaber /types/proper-lockfile/ @qlonik /types/properties-reader/ @Goldsmith42 @@ -3610,12 +3722,13 @@ /types/ptomasroos__react-native-multi-slider/ @Slessi /types/pty.js/ @enlight /types/public-ip/ @BendingBender -/types/pubnub/ @bitbankinc @rollymaduk @vitosamson +/types/pubnub/ @bitbankinc @rollymaduk @vitosamson @FlorianDr /types/pubsub-js/ @borisyankov /types/pug/ @TonyPythoneer @19majkel94 /types/pulltorefreshjs/ @DanielRosenwasser @humpedli /types/pump/ @tlaziuk /types/pumpify/ @JustinBeckwith @aoberoi +/types/punycode/ @yavanosta /types/pupa/ @nju33 /types/puppeteer/v0/ @marvinhagemeister @cdeutsch /types/puppeteer/ @marvinhagemeister @cdeutsch @ksm2 @SimonSchick @@ -3651,13 +3764,22 @@ /types/qwest/ @lindsayevans /types/r-script/ @NaridaL /types/rabbit.js/ @wokim +/types/rabbitmq-schema/ @rulezzz1987 /types/radium/ @alexgorbatchev @nupplaphil @asvetliakov /types/radius/ @codeanimal +/types/radix64/ @huan086 /types/ramda/ @donnut @tycho01 @mdekrey @mrdziuban @sbking @afharo @teves-castro @1M0reBug @hojberg @samsonkeung @angeloocana @raynerd @googol @moshensky @ethanresnick @leighman @CaptJakk @deftomat @deptno @blimusiek @biern @rayhaneh @rgm @drewwyatt +/types/random-boolean/ @BendingBender +/types/random-float/ @BendingBender +/types/random-int/ @BendingBender +/types/random-item/ @BendingBender /types/random-js/ @pistacchio /types/random-number/ @OpenByteDev +/types/random-obj-key/ @BendingBender +/types/random-obj-prop/ @BendingBender /types/random-seed/ @endel /types/random-string/ @stpettersens +/types/randombytes/ @BendingBender /types/randomcolor/ @feitzi @BradyLiles /types/range-parser/ @tlaziuk /types/rangyinputs/ @ersimont @@ -3681,9 +3803,11 @@ /types/raygun4js/ @xt0rted @BenjaminHarding @UberMouse /types/rbac-a/ @tlaziuk /types/rc/ @DanielRosenwasser +/types/rc-progress/ @jussikinnula /types/rc-select/ @DenisTirilis /types/rc-slider/ @mantasmarcinkus @mattoni @paustint @j-fro @Deanna2 /types/rc-time-picker/ @Hoff97 +/types/rc-tooltip/ @rhysd @ahstro @vsaarinen /types/rc-tree/ @johnnyreilly @Methuselah96 /types/rcloader/ @panuhorsmalahti /types/rdf-data-model/ @rubensworks @@ -3692,7 +3816,7 @@ /types/re-base/ @jordandrako /types/reach__router/ @kingdaro /types/react/v15/ @bbenezech @pzavolinsky @digiguru @ericanderson @tkrotoff @DovydasNavickas @onigoetz -/types/react/ @johnnyreilly @bbenezech @pzavolinsky @digiguru @ericanderson @tkrotoff @DovydasNavickas @onigoetz @theruther4d @guilhermehubner @ferdaber @jrakotoharisoa @pascaloliv @hotell @franklixuefei +/types/react/ @johnnyreilly @bbenezech @pzavolinsky @digiguru @ericanderson @tkrotoff @DovydasNavickas @onigoetz @theruther4d @guilhermehubner @ferdaber @jrakotoharisoa @pascaloliv @hotell @franklixuefei @Kovensky /types/react-adal/ @dkorolev1 /types/react-albus/ @sseppola @conradreuter @kuirak /types/react-alert/v2/ @ssyrell @@ -3708,7 +3832,8 @@ /types/react-avatar-editor/ @diogocorrea @gabsprates /types/react-beautiful-dnd/ @varHarrie @bradleyayers @paustint @marknelissen /types/react-better-password/ @mhuynh1 -/types/react-big-calendar/ @piotrwitek @paustint @pikpok @eps1lon @strongpauly +/types/react-big-calendar/ @piotrwitek @paustint @pikpok @eps1lon @strongpauly @janb87 +/types/react-blessed/ @me /types/react-body-classname/ @mhegazy /types/react-bootstrap/ @walkerburgin @vsiao @danilojrr @Batbold-Gansukh @octatone @chengsieuly @mretolaza @katbusch @vitosamson @LKay @aaronbeall @jrakotoharisoa @r3nya @t49tran /types/react-bootstrap-date-picker/ @LKay @ssi-hu-antal-bodnar @@ -3720,6 +3845,7 @@ /types/react-breadcrumbs-dynamic/ @mitsuruog /types/react-broadcast/ @kandros /types/react-burger-menu/ @radziksh +/types/react-cache/ @skovy /types/react-calendar-heatmap/ @9renpoto /types/react-calendar-timeline/ @radziksh @acemac /types/react-cartographer/ @trevonmckay @@ -3738,6 +3864,7 @@ /types/react-countup/ @danielbrodin /types/react-credit-cards/ @vstrimaitis @olefrank /types/react-cropper/ @stepancar +/types/react-css-collapse/ @dford07 /types/react-css-modules/ @KostyaEsmukov @skirsdeda /types/react-css-transition-replace/ @LKay /types/react-currency-formatter/ @pastushenkoy @Jeka-Vasiliev @@ -3748,7 +3875,7 @@ /types/react-data-grid/ @SupernaviX @KieranPeat @martinnov92 @baso53 /types/react-datagrid/ @stephenjelfs /types/react-date-range/ @Junbong -/types/react-datepicker/ @radziksh @andrewBalekha @smrq @Rogach @royxue @KoalaHuman @seansfkelley +/types/react-datepicker/ @radziksh @andrewBalekha @smrq @Rogach @royxue @KoalaHuman @seansfkelley @justingrant @jakeboone02 /types/react-daterange-picker/ @uncovertruth @MartynasZilinskas @donaldtf @vladflorescu94 /types/react-dates/ @ArturAmpilogov @NathanNZ /types/react-daum-postcode/ @Sa-ryong @@ -3775,7 +3902,7 @@ /types/react-file-reader-input/ @dmitryrogozhny @alitaheri /types/react-flag-icon-css/ @jonfreedman /types/react-flags-select/ @senukartur -/types/react-flatpickr/ @begincalendar +/types/react-flatpickr/ @begincalendar @snaveevans /types/react-flex/ @pushplay /types/react-flexr/ @pushplay /types/react-fontawesome/ @timurrustamov @dublicator @vincaslt @gavingregory @@ -3814,17 +3941,17 @@ /types/react-infinite/ @rhysd /types/react-infinite-calendar/ @christianchown /types/react-infinite-scroll-component/ @sroy3 @burtek @davidkevork @JoshuaScript -/types/react-infinite-scroller/ @Lapanti @psrebniak @WrathZA +/types/react-infinite-scroller/ @Lapanti @psrebniak @WrathZA @daggerjames /types/react-input-autosize/ @jsonunger @franklixuefei /types/react-input-calendar/ @stepancar /types/react-input-mask/v1/ @apare /types/react-input-mask/ @apare @dima7a14 /types/react-instantsearch/ @gburgett @jpowell -/types/react-instantsearch-core/ @gburgett @jpowell +/types/react-instantsearch-core/ @gburgett @jpowell @davidfurlong /types/react-instantsearch-dom/ @gburgett @jpowell /types/react-instantsearch-native/ @gburgett @jpowell /types/react-intl/v1/ @bgrieder -/types/react-intl/ @bgrieder @cdroulers @gyzerok @tillwolff @LKay @bhouser @kristerkari @formatlos @lukyth +/types/react-intl/ @bgrieder @cdroulers @gyzerok @tillwolff @LKay @bhouser @kristerkari @formatlos @lukyth @obedm503 /types/react-intl-redux/ @LKay /types/react-is/ @AviVahl @christianchown /types/react-is-deprecated/ @seansfkelley @@ -3838,6 +3965,7 @@ /types/react-lazyload/ @m0a /types/react-lazylog/ @benjaminRomano /types/react-leaflet/ @danzel @davschne @yuit +/types/react-leaflet-markercluster/ @Kimahriman /types/react-lifecycle-component/ @pixelshaded /types/react-list/ @buptyyf @tomshen /types/react-loadable/ @Kovensky @odensc @ianks @tlaziuk @iMobs @@ -3865,16 +3993,18 @@ /types/react-native-communications/ @huhuanming @PaitoAnderson /types/react-native-custom-tabs/ @philnova /types/react-native-datepicker/ @jacobbaskin -/types/react-native-dialog/ @MrLuje +/types/react-native-dialog/ @MrLuje @stackbuilders @ibarrae /types/react-native-dialogflow/ @jasonmerino /types/react-native-doc-viewer/ @iRoachie /types/react-native-document-picker/ @plantain-00 +/types/react-native-draggable-flatlist/ @stackbuilders @ibarrae /types/react-native-drawer/ @jnbt @suniahk /types/react-native-drawer-layout/ @jmfirth /types/react-native-elevated-view/ @fhelwanger /types/react-native-fabric/ @josephroque /types/react-native-fbsdk/ @ifiokjr /types/react-native-fetch-blob/ @MNBuyskih +/types/react-native-flip-card/ @imjakechapman /types/react-native-fs/ @pocesar @josephroque /types/react-native-google-signin/ @j-fro @bm-software @christianchown @echentw /types/react-native-htmlview/ @ifiokjr @@ -3903,6 +4033,7 @@ /types/react-native-referrer/ @christianchown /types/react-native-restart/ @christianchown /types/react-native-safari-view/ @mrand01 +/types/react-native-safe-area/ @pvinis /types/react-native-scaled-image/ @Jaeger25 /types/react-native-scrollable-tab-view/ @CaiHuan @egorshulga /types/react-native-sensor-manager/ @SahinVardar @@ -3927,7 +4058,7 @@ /types/react-native-version-number/ @VincentLanglet /types/react-native-video/ @huhuanming /types/react-navigation/v1/ @huhuanming @mhcgrq @fangpenlin @petejkim @iRoachie @phanalpha @charlesfamu @timwangdev @bang88 @svbutko @levito @YourGamesBeOver @ArmandoAssuncao @cliedeman @Slessi -/types/react-navigation/ @huhuanming @mhcgrq @fangpenlin @petejkim @iRoachie @phanalpha @charlesfamu @timwangdev @bang88 @svbutko @levito @YourGamesBeOver @ArmandoAssuncao @cliedeman @Slessi @magrinj @TizioFittizio @stigi @LinusU @jshosomichi @jakebooyah @brunoro @DenisFrezzato @mickaelw @maxdavidson @jkillian +/types/react-navigation/ @huhuanming @mhcgrq @fangpenlin @petejkim @iRoachie @phanalpha @charlesfamu @timwangdev @bang88 @svbutko @levito @YourGamesBeOver @ArmandoAssuncao @cliedeman @magrinj @TizioFittizio @stigi @LinusU @jshosomichi @jakebooyah @brunoro @DenisFrezzato @mickaelw @maxdavidson @alechill @builtbyproxy @jkillian @jeroenvervaeke @chagasaway /types/react-navigation-material-bottom-tabs/ @iRoachie /types/react-no-ssr/ @rafalfilipek /types/react-notification-system/ @GiedriusGrabauskas @DeividasBakanas @LKay @sztobar @@ -3941,7 +4072,8 @@ /types/react-overlays/ @aaronbeall @vitosamson /types/react-owl-carousel/ @tbounsiar @igorissen @KennethanCeyer /types/react-paginate/v4/ @deevus @wouterhardeman @pegel03 @archy-bold -/types/react-paginate/ @deevus @wouterhardeman @pegel03 @archy-bold @yasupeke +/types/react-paginate/v5/ @deevus @wouterhardeman @pegel03 @archy-bold @yasupeke +/types/react-paginate/ @deevus @wouterhardeman @pegel03 @archy-bold @yasupeke @sugarshin /types/react-places-autocomplete/ @guilhermehubner @r3nya /types/react-plotly.js/ @jonfreedman /types/react-pointable/ @istefo @mdibyo @@ -3955,7 +4087,7 @@ /types/react-recaptcha/ @mhegazy @zzanol /types/react-reconciler/ @Methuselah96 /types/react-redux/v5/ @tkqubo @thasner @kenzierocks @clayne11 @tansongyang @nicholasboll @mdibyo @pdeva -/types/react-redux/ @tkqubo @kenzierocks @clayne11 @tansongyang @nicholasboll @mdibyo @pdeva @kallikrein @val1984 @jrakotoharisoa @apapirovski +/types/react-redux/ @tkqubo @kenzierocks @clayne11 @tansongyang @nicholasboll @mdibyo @pdeva @kallikrein @val1984 @jrakotoharisoa @apapirovski @surgeboris /types/react-redux-epic/ @forabi /types/react-redux-i18n/ @clementdevos /types/react-redux-toastr/ @Smiche @artyomsv @kulmajaba @@ -3970,7 +4102,7 @@ /types/react-router/v3/ @sergey-buturlakin @mrk21 @vasek17 @ngbrown @awendland @KostyaEsmukov @johnnyreilly @LKay @DovydasNavickas @ssorallen @gillchristian @nulladdict /types/react-router/ @sergey-buturlakin @mrk21 @vasek17 @ngbrown @awendland @KostyaEsmukov @johnnyreilly @LKay @DovydasNavickas @tkrotoff @huy-nguyen @grmiade @DaIgeb @egorshulga @neuoy @rraina @pret-a-porter @t49tran @8enSmith /types/react-router-bootstrap/ @vlesierse @LKay @olmobrutall -/types/react-router-config/ @lith-light-g @johnnyreilly +/types/react-router-config/ @lith-light-g @johnnyreilly @NullMDR /types/react-router-dom/ @tkrotoff @huy-nguyen @p-jackson @johnnyreilly /types/react-router-hash-link/ @zoompie /types/react-router-native/ @ezintz @fhelwanger @@ -3989,7 +4121,7 @@ /types/react-show-more/ @naortor /types/react-side-effect/ @remojansen @0xcaff /types/react-sidebar/ @jeroenvervaeke -/types/react-sketchapp/ @ricokahler @DomiR +/types/react-sketchapp/ @ricokahler @DomiR @saschazar21 /types/react-slick/ @andrewBalekha @GiedriusGrabauskas @r3nya /types/react-slider/ @jsonunger /types/react-smooth-scrollbar/ @asvetliakov @@ -4000,12 +4132,13 @@ /types/react-sparklines/ @henrinormak /types/react-spinkit/v1/ @tkqubo @mleko @pelotom /types/react-spinkit/ @tkqubo @mleko @pelotom @zzanol +/types/react-splitter-layout/ @snaptags /types/react-star-rating-component/ @marpstar /types/react-sticky/ @curtisw0 @ajhyndman /types/react-sticky-box/ @koss-lebedev /types/react-sticky-el/ @jbraithwaite /types/react-stickynode/ @tstirrat -/types/react-stripe-elements/ @dan-j @santiagodoldan @sonnysangha @9y5 @thchia +/types/react-stripe-elements/ @dan-j @santiagodoldan @sonnysangha @9y5 @thchia @yhnavein /types/react-svg-inline/ @kiyopikko /types/react-svg-pan-zoom/ @huy-nguyen /types/react-swf/ @stepancar @@ -4013,7 +4146,7 @@ /types/react-swipeable/ @GiedriusGrabauskas @mctep @horiuchi /types/react-swipeable-views/ @mxl @DeividasBakanas /types/react-syntax-highlighter/ @NoHomey @ajgamble-milner -/types/react-table/ @royxue @psakalo @Havret @andys8 +/types/react-table/ @royxue @psakalo @Havret @andys8 @Gelio /types/react-table-filter/ @gjsln /types/react-tabs/ @danez @Equationist /types/react-tag-autocomplete/ @jlismore @@ -4043,9 +4176,9 @@ /types/react-user-tour/ @ccancellieri /types/react-vertical-timeline-component/ @stephane-monnot /types/react-virtual-keyboard/ @bsurai -/types/react-virtualized/ @kaoDev @guntherjh @wasd171 @szabolcsx @kraenhansen @Stevearzh @mgoszcz2 @brandonhall +/types/react-virtualized/ @kaoDev @guntherjh @wasd171 @szabolcsx @kraenhansen @Stevearzh @mgoszcz2 @brandonhall @sbusch /types/react-virtualized-select/ @seansfkelley -/types/react-visibility-sensor/ @JRasmusBm +/types/react-visibility-sensor/ @JRasmusBm @gcangussu /types/react-webcam/ @squat /types/react-weui/ @tairan /types/react-widgets/ @rogierschouten @sanyatuning @frodehansen2 @r3nya @MBillemaz @georg94 @@ -4068,14 +4201,15 @@ /types/readline-sync/ @jonestristand /types/readline-transform/ @dex4er /types/reapop/ @Barrokgl -/types/rebass/ @ryee-dev +/types/rebass/ @ryee-dev @jamesmckenzie /types/rebass__grid/ @antonvasin @vittorio @lhache @lavoaster /types/recaptcha2/ @l-jonas /types/recase/ @18steps -/types/recharts/ @mthmulders @rapmue @royxue @ZheyangSong @richbai90 @caspeco-dan @pkeuter @jrsaunde @paulmelnikow @crusectrl @apalugniok +/types/recharts/ @mthmulders @rapmue @royxue @ZheyangSong @richbai90 @caspeco-dan @pkeuter @jrsaunde @paulmelnikow @crusectrl @apalugniok @RobertStigsson /types/recharts-scale/ @johnnyreilly +/types/rechoir/ @BendingBender /types/recluster/ @dex4er -/types/recompose/ @iskandersierra @mrapogee @clayne11 @Pajn @lucasterra @brian-lives-outdoors +/types/recompose/ @iskandersierra @clayne11 @Pajn @lucasterra @brian-lives-outdoors @TiuSh /types/reconnect-core/ @thw0rted /types/reconnectingwebsocket/ @nguarracino /types/recorder-js/ @higuri @@ -4084,7 +4218,7 @@ /types/redis/ @soywiz @CodeAnimal @MugeSo @UppaJung @Rokt33r @43081j @barnski @1pete /types/redis-errors/ @43081j /types/redis-mock/ @BendingBender -/types/redis-rate-limiter/ @westy92 +/types/redis-rate-limiter/ @westy92 @nodify-at /types/redis-scripto/ @westy92 /types/redlock/v2/ @chrootsu /types/redlock/ @chrootsu @BendingBender @@ -4102,7 +4236,7 @@ /types/redux-devtools-dock-monitor/ @mc-petry /types/redux-devtools-log-monitor/ @mc-petry /types/redux-doghouse/ @BendingBender -/types/redux-first-router/ @Valbrand @viggyfresh @janb87 @corydeppen @jscinoz @surgeboris +/types/redux-first-router/ @Valbrand @viggyfresh @janb87 @corydeppen @jscinoz @surgeboris @geirsagberg /types/redux-first-router-link/ @janb87 /types/redux-first-router-restore-scroll/ @icopp /types/redux-first-routing/ @tlaziuk @@ -4111,7 +4245,7 @@ /types/redux-form/ @carsonf @aikoven @LKay @bancek @alsiola @tehbi4 @huwmartin @ethanresnick @reggino @maddijoyce @smifun /types/redux-immutable/v3/ @oizie @sebald @gavingregory /types/redux-immutable/ @oizie @sebald @gavingregory @lukyth -/types/redux-immutable-state-invariant/ @remojansen @highflying +/types/redux-immutable-state-invariant/ @remojansen @highflying @mihai-dinculescu /types/redux-infinite-scroll/ @silkyfray /types/redux-injectable-store/ @unindented /types/redux-localstorage/ @LKay @@ -4129,7 +4263,8 @@ /types/redux-promise-middleware/ @ianks /types/redux-recycle/ @LKay /types/redux-router/ @stepancar -/types/redux-saga-tester/ @BenLorantfy +/types/redux-saga-tester/ @BenLorantfy @lawsumisu +/types/redux-sentry-middleware/ @dolezel /types/redux-shortcuts/ @tstirrat /types/redux-socket.io/ @snakeego /types/redux-storage/ @asvetliakov @@ -4212,8 +4347,10 @@ /types/riot-route/ @karak /types/riotcontrol/ @chrootsu /types/riotjs/ @vvakame +/types/ripemd160/ @BendingBender /types/rison/ @impworks /types/rivets/ @TrevorDev @matjanos +/types/rmc-drawer/ @Hoff97 /types/rmfr/ @pluma /types/roads/ @dancespiele /types/roads-server/ @dancespiele @@ -4221,8 +4358,9 @@ /types/roll/ @icopp /types/rolling-rate-limiter/ @l-jonas /types/rollup-plugin-json/ @asmockler @hotell +/types/roman-numerals/ @pluma /types/ronomon__crypto-async/ @BendingBender -/types/rosie/ @abner @subvertallchris @abukurov +/types/rosie/ @abner @subvertallchris @abukurov @adam187 /types/roslib/ @Pro @skycoop @dgorobopec /types/rot-js/ @atiaxi /types/round-to/ @seangenabe @@ -4278,11 +4416,18 @@ /types/sanitize-filename/ @Nemo157 /types/sanitize-html/ @rogierschouten @afshin @BehindTheMath @biermeester @WillGibson @sirMerr /types/sap__xsenv/ @mad-mike +/types/sasl-anonymous/ @BendingBender +/types/saslmechanisms/ @BendingBender +/types/sass/ @lenovouser /types/sass-graph/ @marvinhagemeister /types/sass-webpack-plugin/ @AepKill /types/sat/ @omni360 /types/satnav/ @DotNetNerd /types/saywhen/ @SeanSobey +/types/sc-auth/ @DanielRose +/types/sc-broker/ @DanielRose +/types/sc-broker-cluster/ @DanielRose +/types/sc-channel/ @DanielRose /types/scalike/ @ryoppy /types/schedule/ @Methuselah96 /types/scheduler/ @Methuselah96 @@ -4367,7 +4512,9 @@ /types/session-file-store/ @blendsdk @rokt33r /types/set-cookie-parser/ @nickp10 /types/set-value/ @DanielRosenwasser +/types/setasap/ @djcsdy /types/settings/ @shreyjain1994 +/types/sha.js/ @BendingBender /types/sha1/ @arcdev1 /types/sha256/ @nhardy /types/shallow-equals/ @rsolomon @@ -4391,6 +4538,7 @@ /types/shot/ @AJamesPhillips @SimonSchick /types/should-sinon/ @Arylo /types/showdown/ @cbowdon @tan9 @arielsaldana +/types/shpjs/ @littlebtc /types/shrink-ray/ @forabi /types/shuffle-seed/ @LeartS /types/siema/ @Irmiz @0x6368656174 @samnau @@ -4407,7 +4555,7 @@ /types/simple-lru/ @NN--- /types/simple-mock/ @leonyu /types/simple-oauth2/v1/ @mad-mike @troy-lamerton @netux -/types/simple-oauth2/ @mad-mike @troy-lamerton @netux +/types/simple-oauth2/ @mad-mike @troy-lamerton @netux @LinusU /types/simple-peer/ @tlaziuk /types/simple-url-cache/ @a-lucas /types/simple-websocket/ @dex4er @@ -4420,7 +4568,7 @@ /types/sindresorhus__df/ @whatknight /types/single-line-log/ @ffflorian /types/single-spa-react/ @Garrett-Smith-iq -/types/sinon/ @mrbigdog2u @rationull @lumaxis @nicojs @43081j @joshuakgoldberg @gjednaszewski +/types/sinon/ @mrbigdog2u @rationull @lumaxis @nicojs @43081j @joshuakgoldberg @gjednaszewski @johnjesse /types/sinon-as-promised/ @igrayson /types/sinon-chai/v2/ @kazimanzurrashid @jedmao /types/sinon-chai/ @kazimanzurrashid @jedmao @elpdpt @@ -4437,7 +4585,7 @@ /types/sjcl/ @Evgenus /types/skatejs/ @Hotell /types/ski/ @AyaMorisawa -/types/skyway/ @nakakura +/types/skyway/ @nakakura @izmhr /types/slack-mock/ @kkalavantavanich /types/slack-node/ @geoffreak /types/slack-winston/ @BlueHatbRit @@ -4448,18 +4596,21 @@ /types/slate-html-serializer/ @YangusKhan /types/slate-irc/ @elisee /types/slate-plain-serializer/ @YangusKhan @mkiefel -/types/slate-react/ @andykent @majelbstoat @JanLoebel @PatrickSachs @YangusKhan @isubasti @sgreav +/types/slate-react/ @andykent @majelbstoat @JanLoebel @PatrickSachs @YangusKhan @isubasti @sgreav @Kornil /types/sleep/ @rajarz +/types/slice-ansi/ @dwieeb /types/slickgrid/ @jbaldwin /types/slideout/ @ToastHawaii /types/slimerjs/ @alexwall /types/slocket/ @BendingBender /types/slug/ @mhegazy /types/smart-fox-server/ @ChanceM +/types/smooth-scroll/ @andreiho /types/smoothscroll-polyfill/ @kryops /types/smtp-server/v1/ @markisme @Taisiias /types/smtp-server/ @markisme @Taisiias @dex4er /types/smtpapi/ @a-morales +/types/snakecase-keys/ @BendingBender /types/snappy/ @reconbot /types/snapsvg/ @lhk @mattanja @kant2002 /types/snazzy-info-window/ @milosd92 @@ -4474,6 +4625,9 @@ /types/socket.io-parser/ @plantain-00 /types/socket.io-redis/ @nupplaphil @seeLuck /types/socket.io.users/ @kataras +/types/socketcluster/ @DanielRose +/types/socketcluster-client/ @DanielRose +/types/socketcluster-server/ @DanielRose /types/socketio-jwt/ @ehallander9591 /types/socketio-jwt-auth/ @codeanimal /types/socketio-wildcard/ @BendingBender @@ -4485,6 +4639,7 @@ /types/solution-center-communicator/ @dami-gg /types/sonic-boom/ @alferpal /types/sort-array/ @mrmlnc +/types/sort-object-keys/ @forivall /types/sortablejs/ @Maw-Fox @maartenstaa /types/soundmanager2/ @elton2048 /types/soupbintcp/ @jewbre @@ -4502,7 +4657,7 @@ /types/spdy/ @tony19 /types/speakeasy/ @legendecas @mrOlorin @xeoneux /types/speakingurl/ @Goldsmith42 -/types/spectacle/ @zmaybury +/types/spectacle/ @zmaybury @kale-stew /types/spectrum/ @M-Zuber @Ailrun /types/split/ @marcinporebski /types/split.js/ @icholy @@ -4514,6 +4669,7 @@ /types/sprintf/ @soywiz @BendingBender /types/sprintf-js/ @jasonswearingen @BendingBender @cdagli /types/sql-bricks/ @adn05 @paleo +/types/sql-template/ @q42jaap /types/sql.js/ @Hozuki /types/sqlanywhere/ @pkeuter /types/sqlite3/ @nmalaguti @dpyro @BehindTheMath @@ -4521,8 +4677,8 @@ /types/squirejs/ @bradleyayers /types/srp/ @Patman64 /types/ssh-key-decrypt/ @BendingBender -/types/ssh2/ @tkQubo @rbuckton @wrboyce -/types/ssh2-sftp-client/ @igrayson @ascariandrea @kartik2406 +/types/ssh2/ @tkQubo @rbuckton @wrboyce @lucasmotta +/types/ssh2-sftp-client/ @igrayson @ascariandrea @kartik2406 @viamuli /types/ssh2-streams/ @rbuckton /types/sshpk/ @mabels /types/stack-mapper/ @rogierschouten @@ -4552,9 +4708,9 @@ /types/sticky-cluster/ @paustint /types/stompit/ @DanielRose /types/stompjs/ @jimic @Dr4k4n -/types/stoppable/ @EricByers +/types/stoppable/ @EricByers @jplusje /types/storage-helper/ @ajafff -/types/store/ @vbortone @harry0000 @Ky6uk +/types/store/ @vbortone @harry0000 @Ky6uk @igl00 /types/storybook-addon-jsx/ @jameslnewell /types/storybook-readme/ @lonyele /types/storybook__addon-a11y/ @hyunseob @@ -4566,10 +4722,10 @@ /types/storybook__addon-knobs/ @joscha @martynaskadisa @amacleay /types/storybook__addon-links/ @joscha @jessepinho /types/storybook__addon-notes/ @joscha @amacleay -/types/storybook__addon-options/ @joscha @simonhn @amacleay +/types/storybook__addon-options/ @joscha @simonhn @amacleay @gaetanmaisse @adam187 /types/storybook__addon-storyshots/ @bradleyayers -/types/storybook__react/ @joscha @wapgear -/types/storybook__react-native/ @joscha @wapgear @alechill @iRoachie +/types/storybook__react/ @joscha @wapgear @dandean +/types/storybook__react-native/ @joscha @wapgear @alechill @iRoachie @ceyhuno /types/storybook__vue/ @pntgupta /types/stream-array/ @Tyler-Murphy /types/stream-buffers/ @Jason3S @@ -4584,6 +4740,7 @@ /types/stream-to-array/v0/ @Bartvds /types/stream-to-array/ @Bartvds @BendingBender /types/stream-to-promise/ @Alorel +/types/stream-to-string/ @BendingBender /types/streaming-json-stringify/ @BendingBender /types/streamjs/ @erosb /types/streamtest/ @lummish @@ -4606,7 +4763,7 @@ /types/stripe-checkout/ @cgwrench /types/stripe-v2/ @ejsmith @amritk @adamcmiel @jleider @galuszkak /types/stripe-v3/ @ejsmith @amritk @adamcmiel @jleider @galuszkak -/types/stripejs/ @RobinvanTienhoven +/types/stripejs/ @RobinvanTienhoven @mattferderer /types/strong-cluster-control/ @shuntksh /types/strong-error-handler/ @blankstar85 /types/strong-log-transformer/ @azasypkin @@ -4614,7 +4771,7 @@ /types/strophe.js/ @DavidKDeutsch /types/structured-source/ @azu /types/styled-components/v3/ @Igorbek @Igmat -/types/styled-components/ @Igorbek @Igmat @lavoaster +/types/styled-components/ @Igorbek @Igmat @lavoaster @Kovensky /types/styled-jsx/ @R1ZZU /types/styled-react-modal/ @Lavoaster /types/styled-system/ @maxdeviant @phobon @zephraph @damassi @alloy @maoueh @lavoaster @jschuler @@ -4634,7 +4791,7 @@ /types/sumo-logger/ @forabi @clementallen /types/suncalc/ @horiuchi /types/superagent/v2/ @varju @NicoZelaya @mxl -/types/superagent/ @NicoZelaya @mxl @paplorinc @shreyjain1994 @zopf @beeequeue +/types/superagent/ @NicoZelaya @mxl @paplorinc @shreyjain1994 @zopf @beeequeue @lukaselmer /types/superagent-bunyan/ @bricka /types/superagent-no-cache/ @mxl /types/superagent-prefix/ @mxl @@ -4658,7 +4815,7 @@ /types/sw-precache/ @JounQin /types/sw-precache-webpack-plugin/ @JounQin /types/swag/ @shiwano -/types/swagger-express-middleware/ @alexandreroba +/types/swagger-express-middleware/ @alexandreroba @tromgy /types/swagger-express-mw/ @micmro /types/swagger-express-validator/ @pinguet62 /types/swagger-hapi/ @micmro @@ -4690,8 +4847,9 @@ /types/tabbable/ @mokkan /types/table/ @evanshortiss @mrmlnc /types/tableau/ @protip +/types/tableify/ @forivall /types/tabris-plugin-firebase/ @eclipsesource -/types/tabtab/ @vojtechhabarta +/types/tabtab/ @vojtechhabarta @kamontat /types/tabulator/ @euginio /types/tail/ @spacejack /types/tapable/v0/ @e-cloud @@ -4721,7 +4879,7 @@ /types/tether-drop/ @adidahiya /types/tether-shepherd/ @mtgibbs /types/text-buffer/ @GlenCFL -/types/text-encoding/ @pine613 @mohsen1 @nwmqpa +/types/text-encoding/ @pine @mohsen1 @nwmqpa /types/text-encoding-utf-8/ @trxcllnt /types/text-table/ @saadq /types/textarea-caret/ @shiftkey @@ -4732,7 +4890,8 @@ /types/theming/ @eps1lon /types/theo/ @petekp /types/thepiratebay/ @jsorrell -/types/three/ @gyohk @florentpoujol @SereznoKot @omni360 @ivoisbelongtous @piranha771 @qszhusightp @nakakura @s093294 @Pro @efokschaner @PsychoSTS @dhritzkiv @apurvaojas @NotWoods @sethk @elk941 @Methuselah96 @Dukuo @JulianSSS @devilsparta +/types/three/ @gyohk @florentpoujol @SereznoKot @omni360 @ivoisbelongtous @piranha771 @qszhusightp @nakakura @s093294 @Pro @efokschaner @PsychoSTS @dhritzkiv @apurvaojas @NotWoods @sethk @elk941 @Methuselah96 @Dukuo @JulianSSS @devilsparta @KonstantinLukaschenko +/types/three-tds-loader/ @KonstantinLukaschenko @sschoensee /types/thrift/ @kamek-pf @kevin-greene-ck @jessezhang91 /types/throng/ @cyrilschumacher @tatethurston /types/throttle/ @BendingBender @@ -4742,6 +4901,7 @@ /types/through2/ @Bartvds @jedmao @valotas @TeamworkGuy2 @Alorel /types/through2-concurrent/ @Alorel /types/through2-map/ @LucasHill +/types/tildify/ @BendingBender /types/tile-reduce/ @DenisCarriere /types/tilebelt/ @DenisCarriere /types/time-span/ @BendingBender @mdvorscak @@ -4749,6 +4909,8 @@ /types/timelinejs3/ @MikeMatusz /types/timer-machine/ @dolanmiu /types/timezone-js/ @bonnici +/types/timing-safe-equal/ @BendingBender +/types/timsort/ @Vunovati /types/tinajs__tina/ @Jimexist /types/tinajs__tina-redux/ @Jimexist /types/tinder/ @pingec @@ -4773,7 +4935,7 @@ /types/toastr/ @borisyankov /types/tocktimer/ @evanshortiss /types/tokgen/ @l-jonas -/types/toobusy-js/ @atd-schubert +/types/toobusy-js/ @atd-schubert @BendingBender /types/tooltipster/ @stephenlautier @pjmagee @VorobeY1326 @leonard-thieu @janhi @joeskeen /types/topojson/ @ricardo-mello @chenzhutian @denisname /types/topojson-client/ @denisname @ricardo-mello @@ -4787,7 +4949,7 @@ /types/tough-cookie/ @leonard-thieu @LiJinyao @no2chem /types/tough-cookie-filestore/ @friedow /types/traceback/ @misak113 -/types/tracking/ @pimterry +/types/tracking/ @pimterry @bratter /types/transducers-js/ @colinkahn @dphilipson @NaridaL /types/transducers.js/ @dphilipson /types/transliteration/ @tony19 @@ -4806,13 +4968,14 @@ /types/tspromise/ @soywiz /types/ttf2woff2/ @ThomasdenH /types/tunnel/ @BendingBender -/types/tus-js-client/ @kevhiggins +/types/tus-js-client/ @kevhiggins @Acconut /types/tv4/ @Bartvds @psnider /types/tween.js/ @Amos47 @sunetos @jzarnikov @alexburner /types/tweenjs/ @evilangelist @jcyuan /types/tweezer.js/ @praxxis /types/twig/ @soywiz @enko /types/twilio/ @nickiannone @ashleybrener +/types/twilio-common/ @gatimus /types/twilio-video/ @minddocdev @darioblanco /types/twit/ @Volox @sapphiredev @abraham @siwalikm @plhery /types/twitch-ext/ @beheh @@ -4857,7 +5020,9 @@ /types/uniqid/ @idchlife /types/unique-hash-stream/ @BendingBender /types/unique-random/ @Kuniwak -/types/unist/ @bizen241 +/types/unique-random-array/ @BendingBender +/types/unist/ @bizen241 @lujun2 @hrajchert @wooorm @rokt33r +/types/unist-util-is/ @rokt33r /types/unity-webapi/ @jmvrbanac /types/universal-analytics/ @Bartvds @DarkerTV /types/universal-cookie/ @tomi @@ -4905,6 +5070,7 @@ /types/uuid-validate/ @HiromiShikata /types/uws/ @plantain-00 @orblazer /types/v-chart-plugin/ @natemara +/types/v8flags/ @BendingBender /types/valdr/ @ilbertz /types/valdr-message/ @ilbertz /types/valerie/ @conficient @@ -4920,7 +5086,6 @@ /types/vast-client/ @jgainfort /types/vec3/ @xstoudi /types/vectorious/ @erikgerrits -/types/vega/ @pelotom /types/velocity-animate/ @smrq /types/verror/ @svi3c @max4t /types/vertx3-eventbus-client/ @oddeirik @@ -4928,7 +5093,8 @@ /types/vexdb/ @MayorMonty /types/vexflow/ @rquiring @sebastianhaas @bohoffi @sschmidTU /types/vfile/ @bizen241 @rokt33r -/types/vfile-location/ @ikatyang +/types/vfile-location/ @ikatyang @rokt33r +/types/vfile-message/ @rokt33r /types/victory/ @asvetliakov @snerks @Havret @alredyExist /types/video.js/ @vbortone @scleriot @SWBennett06 @IgelCampus @giofreitas @gjanblaszczyk @sroucheray @AkxeOne @meikidd /types/viewability-helper/ @lironzluf @@ -4944,7 +5110,7 @@ /types/vinyl-paths/ @tkQubo /types/virtual-dom/ @chbrown /types/virtual-keyboard/ @bsurai -/types/vis/ @MichaelBitard @macleodbroad-wf @adripanico @seveves @kaktus40 @mmaitre314 @supercargo @takato1314 @alex-kachura @dcop @avrahamcool +/types/vis/ @MichaelBitard @macleodbroad-wf @adripanico @seveves @kaktus40 @mmaitre314 @supercargo @takato1314 @alex-kachura @dcop @avrahamcool @divideby /types/vision/v4/ @jasonswearingen @AJamesPhillips /types/vision/ @jasonswearingen @AJamesPhillips @lenovouser /types/vitalsigns/ @cyrilschumacher @@ -4963,7 +5129,8 @@ /types/vue-scrollto/ @vincekovacs /types/vue-select/ @silh /types/vue2-datepicker/ @ChristianStornowski -/types/vuex-i18n/ @jaeggerr @noamkfir +/types/vuelidate/ @janesser +/types/vuex-i18n/ @jaeggerr @noamkfir @barahliush /types/w2ui/ @Ptival /types/w3c-generic-sensor/ @kenchris /types/w3c-image-capture/ @cosium @@ -4984,17 +5151,19 @@ /types/watson-developer-cloud/ @waldo000000 @Naktibalda /types/wavesurfer.js/ @higuri /types/waypoints/ @dominikbulaj @Koloto @evil-shrike +/types/wcag-contrast/ @plantain-00 /types/wcwidth/ @rokt33r /types/weak/ @int0h /types/weapp-api/ @vargeek /types/web-animations-js/ @kritollm /types/web-bluetooth/ @urish /types/web-push/ @paullessing +/types/web-resource-inliner/ @BendingBender /types/web3/ @simon-jentzsch @nitzantomer @zurbo @yxliang01 @phra @naddison36 @icaroharry @linusnorton @jpeletier @anneau @matrushka @andrevmatos @levino @zlumer @archangel-irk @sogasg @donamk @dkent600 @nerddan /types/web3-eth-abi/ @LogvinovLeon /types/web3-provider-engine/ @LogvinovLeon /types/webappsec-credential-management/ @iainmcgin -/types/webassembly-js-api/ @periklis +/types/webassembly-js-api/ @periklis @chicoxyzzy /types/webassembly-web-api/ @jhenninger /types/webcl/ @NCARalph /types/webcomponents.js/ @adidahiya @@ -5061,6 +5230,7 @@ /types/wicg-mediasession/ @jucrouzet /types/wif/ @danwbyrne /types/wiiu/ @mzsm +/types/wikidata-sdk/ @kamontat /types/window-or-global/ @vvakame /types/window-size/ @pmkary /types/windows-1251/ @RomanGolovanov @@ -5113,7 +5283,8 @@ /types/xmldom/ @tkqubo /types/xmlpoke/ @garthk /types/xmltojson/ @traviscrowe -/types/xmpp__jid/ @PJakcson +/types/xmpp__jid/ @PJakcson @BendingBender +/types/xmpp__xml/ @BendingBender /types/xregexp/ @Bartvds @jfahrenkrug @sigo /types/xrm/v7/ @daryllabar /types/xrm/v8/ @6ix4our @mattngan @markusmauch @daryllabar @clownwilleatme @mariusagur @@ -5137,7 +5308,8 @@ /types/yayson/ @Codesleuth /types/yazl/ @taoqf @seangenabe /types/ydn-db/ @yathit @gabrielmaldi -/types/yeoman-generator/ @armorik83 @janslow @ikatyang +/types/yeoman-assert/ @Toilal +/types/yeoman-generator/ @armorik83 @janslow @ikatyang @tasadar2 /types/yeoman-test/ @ikatyang /types/yesql/ @Sumolari /types/yoctodelay/ @seangenabe @@ -5146,10 +5318,10 @@ /types/yog2-kernel/ @ssddi456 /types/yoga-layout/ @tnobody /types/yosay/ @armorik83 -/types/youtube/ @DazWilkin @JoshuaKGoldberg @eliotfallon213 @terrymun +/types/youtube/ @DazWilkin @JoshuaKGoldberg @eliotfallon213 @terrymun @paulhobbel /types/youtube-dl/ @bsurai /types/yui/ @giabao -/types/yup/ @dhardtke @vtserman @MoretonBayRC @sseppola @YashdalfTheGray +/types/yup/ @dhardtke @vtserman @MoretonBayRC @sseppola @YashdalfTheGray @vincentjames501 /types/z-schema/ @pgonzal /types/zapier-platform-core/ @bradleyayers /types/zeit__next-typescript/ @icopp @@ -5172,5 +5344,6 @@ /types/zmq/ @davemckeown /types/zookeeper/ @xialeistudio /types/zopflipng-bin/ @hikoma +/types/zrender/ @iRON5 /types/zui/ @yuanxu /types/zxcvbn/ @mtraynham diff --git a/README.md b/README.md index eba170c493..a9be0471a1 100644 --- a/README.md +++ b/README.md @@ -169,8 +169,14 @@ If a package was never on DefinitelyTyped, it does not need to be added to `notN #### Lint -To lint a package, just add a `tslint.json` to that package containing `{ "extends": "dtslint/dt.json" }`. All new packages must be linted. -If a `tslint.json` turns rules off, this is because that hasn't been fixed yet. For example: +All new packages must be linted. To lint a package, add a `tslint.json` to that package containing +```js +{ + "extends": "dtslint/dt.json" +} +``` + +This should be the only content in a finished project's `tslint.json` file. If a `tslint.json` turns rules off, this is because that hasn't been fixed yet. For example: ```js { diff --git a/notNeededPackages.json b/notNeededPackages.json index 53ff6a7124..c64738aa8d 100644 --- a/notNeededPackages.json +++ b/notNeededPackages.json @@ -642,6 +642,12 @@ "sourceRepoURL": "https://github.com/jdalrymple/node-gitlab", "asOfVersion": "2.0.0" }, + { + "libraryName": "Google Cloud Storage", + "typingsPackageName": "google-cloud__storage", + "sourceRepoURL": "https://github.com/googleapis/nodejs-storage", + "asOfVersion": "2.3.0" + }, { "libraryName": "graphene-pk11", "typingsPackageName": "graphene-pk11", diff --git a/package.json b/package.json index 09fe064d48..caf101cbc6 100644 --- a/package.json +++ b/package.json @@ -22,6 +22,6 @@ }, "devDependencies": { "dtslint": "github:Microsoft/dtslint#production", - "types-publisher": "Microsoft/types-publisher#production" + "types-publisher": "github:Microsoft/types-publisher#production" } } diff --git a/types/accept/accept-tests.ts b/types/accept/accept-tests.ts new file mode 100644 index 0000000000..011216ede4 --- /dev/null +++ b/types/accept/accept-tests.ts @@ -0,0 +1,29 @@ +import * as accept from 'accept'; + +accept.charsets("iso-8859-5, unicode-1-1;q=0.8"); // charset === "iso-8859-5" +accept.charset("iso-8859-5, unicode-1-1;q=0.8", ["unicode-1-1"]); // charset === "unicode-1-1" + +accept.encoding("gzip, deflate, sdch"); // encoding === "gzip" +accept.encoding("gzip, deflate, sdch", ["deflate", "identity"]); + +const encodings = accept.encodings("compress;q=0.5, gzip;q=1.0"); // encodings === ["gzip", "compress", "identity"] +encodings.lastIndexOf(''); + +accept.language("en;q=0.7, en-GB;q=0.8"); +accept.language("en;q=0.7, en-GB;q=0.8", ["en-gb"]); // language === "en-GB" +const languages = accept.languages("da, en;q=0.7, en-GB;q=0.8"); // languages === ["da", "en-GB", "en"] +languages.lastIndexOf(''); + +const mediaTypes = accept.mediaTypes("text/plain, application/json;q=0.5, text/html, */*;q=0.1"); +// mediaTypes === ["text/plain", "text/html", "application/json", "*/*"] +mediaTypes.lastIndexOf(''); +const headers = { + accept: 'text/plain, application/json;q=0.5, text/html, */*;q=0.1', + 'accept-language': 'da, en;q=0.7, en-GB;q=0.8' +}; + +const all = accept.parseAll(headers); +all.charsets.length; +all.encodings.length; +all.languages.length; +all.mediaTypes.length; diff --git a/types/accept/index.d.ts b/types/accept/index.d.ts new file mode 100644 index 0000000000..b067ea4306 --- /dev/null +++ b/types/accept/index.d.ts @@ -0,0 +1,21 @@ +// Type definitions for accept 3.1 +// Project: https://github.com/hapijs/accept#readme +// Definitions by: feinoujc +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +export function charset(charsetHeader?: string, preferences?: string[]): string; +export function charsets(charsetHeader?: string): string[]; +export function encoding(encodingHeader?: string, preferences?: string[]): string; +export function encodings(encodingHeader?: string): string[]; +export function language(languageHeader?: string, preferences?: string[]): string; +export function languages(languageHeader?: string): string[]; +export function mediaTypes(mediaTypeHeader?: string): string[]; +export function parseAll( + headers: Record +): { + charsets: string[]; + encodings: string[]; + languages: string[]; + mediaTypes: string[]; +}; diff --git a/types/accept/tsconfig.json b/types/accept/tsconfig.json new file mode 100644 index 0000000000..cb192697d5 --- /dev/null +++ b/types/accept/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "accept-tests.ts" + ] +} diff --git a/types/accept/tslint.json b/types/accept/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/accept/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/ace/index.d.ts b/types/ace/index.d.ts index 7faa5da4f8..cd20b57f05 100644 --- a/types/ace/index.d.ts +++ b/types/ace/index.d.ts @@ -1223,7 +1223,7 @@ declare namespace AceAjax { /** * Returns `true` if the current `textInput` is in focus. **/ - isFocused(): void; + isFocused(): boolean; /** * Blurs the current `textInput`. diff --git a/types/alt/index.d.ts b/types/alt/index.d.ts index 9094642e70..c95e1653b0 100644 --- a/types/alt/index.d.ts +++ b/types/alt/index.d.ts @@ -54,7 +54,7 @@ declare namespace AltJS { export type Source = {[name:string]: () => SourceModel}; export interface SourceModel { - local(state:any, ...args: any[]):any; + local?(state:any, ...args: any[]):any; remote(state:any, ...args: any[]):Promise; shouldFetch?(fetchFn:(...args:Array) => boolean):void; loading?:(args:any) => void; diff --git a/types/amqp-connection-manager/index.d.ts b/types/amqp-connection-manager/index.d.ts index ab69aadeb1..e2907b67ee 100644 --- a/types/amqp-connection-manager/index.d.ts +++ b/types/amqp-connection-manager/index.d.ts @@ -136,7 +136,16 @@ export interface ChannelWrapper extends EventEmitter { * Setup functions should, ideally, not throw errors, but if they do then the ChannelWrapper will emit an 'error' event. * @param func */ - addSetup(func: SetupFunc): Promise; + addSetup(func: SetupFunc): Promise; + + /** + * Remove a setup function added with `addSetup`. If there is currently a + * connection, `teardown(channel, [cb])` will be run immediately, and the + * returned Promise will not resolve until it completes. + * @param func + * @param [tearDown] + */ + removeSetup(func: SetupFunc, tearDown?: SetupFunc): Promise; /** * @see amqplib diff --git a/types/angular-agility/tslint.json b/types/angular-agility/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/angular-agility/tslint.json +++ b/types/angular-agility/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/angular-locker/tslint.json b/types/angular-locker/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/angular-locker/tslint.json +++ b/types/angular-locker/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/angular-material/index.d.ts b/types/angular-material/index.d.ts index db74c97d10..9202829175 100644 --- a/types/angular-material/index.d.ts +++ b/types/angular-material/index.d.ts @@ -153,6 +153,10 @@ declare module 'angular' { defaultFontSet(name: string): IIconProvider; } + interface IInkRippleProvider { + disableInkRipple(): void; + } + type IMedia = (media: string) => boolean; interface ISidenavObject { diff --git a/types/angular-odata-resources/tslint.json b/types/angular-odata-resources/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/angular-odata-resources/tslint.json +++ b/types/angular-odata-resources/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/angular-ui-tree/tslint.json b/types/angular-ui-tree/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/angular-ui-tree/tslint.json +++ b/types/angular-ui-tree/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/angular/test/jquery3-merging-tests.ts b/types/angular/test/jquery3-merging-tests.ts index 507c58b67e..da61a6f0bc 100644 --- a/types/angular/test/jquery3-merging-tests.ts +++ b/types/angular/test/jquery3-merging-tests.ts @@ -94,8 +94,6 @@ function JQuery() { } function bind() { - interface I1 { kind: 'I1'; } - // $ExpectType JQuery $('p').bind('myEvent', 'myData', function(event) { // TODO: $ExpectType HTMLElement @@ -104,14 +102,6 @@ function JQuery() { event; }); - // $ExpectType JQuery - $('p').bind('myEvent', 'myData', function(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; - }); - // $ExpectType JQuery $('p').bind('myEvent', function(event) { // TODO: $ExpectType HTMLElement @@ -120,14 +110,6 @@ function JQuery() { event; }); - // $ExpectType JQuery - $('p').bind('myEvent', function(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; - }); - // $ExpectType JQuery $('p').bind('myEvent', false); @@ -139,12 +121,6 @@ function JQuery() { this; // TODO: $ExpectType Event event; - }, - myEvent3(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; } }); @@ -164,27 +140,15 @@ function JQuery() { } function off() { - function defaultContext_defaultData(this: HTMLElement, event: JQueryEventObject) { } + function defaultData(this: HTMLElement, event: JQueryEventObject) { } - function defaultContext_customData(this: HTMLElement, event: JQueryEventObject) { } - - function customContext_defaultData(this: I1, event: JQueryEventObject) { } - - function customContext_customData(this: I1, event: JQueryEventObject) { } - - interface I1 { kind: 'I1'; } + function customData(this: HTMLElement, event: JQueryEventObject) { } // $ExpectType JQuery - $('table').off('myEvent', 'td', defaultContext_defaultData); + $('table').off('myEvent', 'td', defaultData); // $ExpectType JQuery - $('table').off('myEvent', 'td', defaultContext_customData); - - // $ExpectType JQuery - $('table').off('myEvent', 'td', customContext_defaultData); - - // $ExpectType JQuery - $('table').off('myEvent', 'td', customContext_customData); + $('table').off('myEvent', 'td', customData); // $ExpectType JQuery $('table').off('myEvent', 'td', false); @@ -193,16 +157,10 @@ function JQuery() { $('table').off('myEvent', 'td'); // $ExpectType JQuery - $('table').off('myEvent', defaultContext_defaultData); + $('table').off('myEvent', defaultData); // $ExpectType JQuery - $('table').off('myEvent', defaultContext_customData); - - // $ExpectType JQuery - $('table').off('myEvent', customContext_defaultData); - - // $ExpectType JQuery - $('table').off('myEvent', customContext_customData); + $('table').off('myEvent', customData); // $ExpectType JQuery $('table').off('myEvent', false); @@ -213,19 +171,15 @@ function JQuery() { // $ExpectType JQuery $('table').off({ myEvent1: false, - defaultContext_defaultData, - defaultContext_customData, - customContext_defaultData, - customContext_customData + defaultData, + customData }, 'td'); // $ExpectType JQuery $('table').off({ myEvent1: false, - defaultContext_defaultData, - defaultContext_customData, - customContext_defaultData, - customContext_customData + defaultData, + customData }); // $ExpectType JQuery @@ -236,8 +190,6 @@ function JQuery() { } function on() { - interface I1 { kind: 'I1'; } - // $ExpectType JQuery $('table').on('myEvent', 'td', 'myData', function(event) { // TODO: $ExpectType HTMLElement @@ -246,14 +198,6 @@ function JQuery() { event; }); - // $ExpectType JQuery - $('table').on('myEvent', 'td', 'myData', function(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; - }); - // $ExpectType JQuery $('table').on('myEvent', null, 'myData', function(event) { // TODO: $ExpectType HTMLElement @@ -262,14 +206,6 @@ function JQuery() { event; }); - // $ExpectType JQuery - $('table').on('myEvent', null, 'myData', function(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; - }); - // $ExpectType JQuery $('table').on('myEvent', 'td', function(event) { // TODO: $ExpectType HTMLElement @@ -278,14 +214,6 @@ function JQuery() { event; }); - // $ExpectType JQuery - $('table').on('myEvent', 'td', function(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; - }); - // $ExpectType JQuery $('table').on('myEvent', 'td', false); @@ -297,14 +225,6 @@ function JQuery() { event; }); - // $ExpectType JQuery - $('table').on('myEvent', 3, function(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; - }); - // $ExpectType JQuery $('table').on('myEvent', function(event) { // TODO: $ExpectType HTMLElement @@ -313,14 +233,6 @@ function JQuery() { event; }); - // $ExpectType JQuery - $('table').on('myEvent', function(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; - }); - // $ExpectType JQuery $('table').on('myEvent', false); @@ -332,12 +244,6 @@ function JQuery() { this; // TODO: $ExpectType Event event; - }, - myEvent3(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; } }, 'td', 'myData'); @@ -349,12 +255,6 @@ function JQuery() { this; // TODO: $ExpectType Event event; - }, - myEvent3(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; } }, null, 'myData'); @@ -366,12 +266,6 @@ function JQuery() { this; // TODO: $ExpectType Event event; - }, - myEvent3(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; } }, 'td'); @@ -383,12 +277,6 @@ function JQuery() { this; // TODO: $ExpectType Event event; - }, - myEvent3(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; } }, 3); @@ -400,19 +288,11 @@ function JQuery() { this; // TODO: $ExpectType Event event; - }, - myEvent3(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; } }); } function one() { - interface I1 { kind: 'I1'; } - // $ExpectType JQuery $('table').one('myEvent', 'td', 'myData', function(event) { // TODO: $ExpectType HTMLElement @@ -421,14 +301,6 @@ function JQuery() { event; }); - // $ExpectType JQuery - $('table').one('myEvent', 'td', 'myData', function(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; - }); - // $ExpectType JQuery $('table').one('myEvent', null, 'myData', function(event) { // TODO: $ExpectType HTMLElement @@ -437,14 +309,6 @@ function JQuery() { event; }); - // $ExpectType JQuery - $('table').one('myEvent', null, 'myData', function(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; - }); - // $ExpectType JQuery $('table').one('myEvent', 'td', function(event) { // TODO: $ExpectType HTMLElement @@ -453,14 +317,6 @@ function JQuery() { event; }); - // $ExpectType JQuery - $('table').one('myEvent', 'td', function(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; - }); - // $ExpectType JQuery $('table').one('myEvent', 'td', false); @@ -472,14 +328,6 @@ function JQuery() { event; }); - // $ExpectType JQuery - $('table').one('myEvent', 3, function(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; - }); - // $ExpectType JQuery $('table').one('myEvent', function(event) { // TODO: $ExpectType HTMLElement @@ -488,14 +336,6 @@ function JQuery() { event; }); - // $ExpectType JQuery - $('table').one('myEvent', function(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; - }); - // $ExpectType JQuery $('table').one('myEvent', false); @@ -507,12 +347,6 @@ function JQuery() { this; // TODO: $ExpectType Event event; - }, - myEvent3(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; } }, 'td', 'myData'); @@ -524,12 +358,6 @@ function JQuery() { this; // TODO: $ExpectType Event event; - }, - myEvent3(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; } }, null, 'myData'); @@ -541,12 +369,6 @@ function JQuery() { this; // TODO: $ExpectType Event event; - }, - myEvent3(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; } }, 'td'); @@ -558,12 +380,6 @@ function JQuery() { this; // TODO: $ExpectType Event event; - }, - myEvent3(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; } }, 3); @@ -575,12 +391,6 @@ function JQuery() { this; // TODO: $ExpectType Event event; - }, - myEvent3(this: I1, event) { - // $ExpectType I1 - this; - // TODO: $ExpectType Event - event; } }); } diff --git a/types/angularfire/tslint.json b/types/angularfire/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/angularfire/tslint.json +++ b/types/angularfire/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/ansicolors/index.d.ts b/types/ansicolors/index.d.ts index 6750283895..dd1a872e57 100644 --- a/types/ansicolors/index.d.ts +++ b/types/ansicolors/index.d.ts @@ -1,8 +1,45 @@ // Type definitions for ansicolors // Project: https://github.com/thlorenz/ansicolors -// Definitions by: rogierschouten +// Definitions by: Benjamin Arthur Lupton // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare var colors: { [index: string]: (s: string) => string; }; -export = colors; +interface Colors extends String { + (value: string): string + white: this + black: this + blue: this + cyan: this + green: this + magenta: this + red: this + yellow: this + brightBlack: this + brightRed: this + brightGreen: this + brightYellow: this + brightBlue: this + brightMagenta: this + brightCyan: this + brightWhite: this + bgBlack: this + bgRed: this + bgGreen: this + bgYellow: this + bgBlue: this + bgMagenta: this + bgCyan: this + bgWhite: this + bgBrightBlack: this + bgBrightRed: this + bgBrightGreen: this + bgBrightYellow: this + bgBrightBlue: this + bgBrightMagenta: this + bgBrightCyan: this + bgBrightWhite: this + open: this + close: this + colors: this +} +declare const colors: Colors +export default colors diff --git a/types/applicationinsights-js/index.d.ts b/types/applicationinsights-js/index.d.ts index b86dc23634..002a950637 100644 --- a/types/applicationinsights-js/index.d.ts +++ b/types/applicationinsights-js/index.d.ts @@ -670,14 +670,16 @@ declare module Microsoft.ApplicationInsights { context: ITelemetryContext; queue: Array<() => void>; /** - * Starts timing how long the user views a page or other item. Call this when the page opens. - * This method doesn't send any telemetry. Call {@link stopTrackTelemetry} to log the page when it closes. + * Starts the timer for tracking a page load time. Use this instead of `trackPageView` if you want to control when the page view timer starts and stops, + * but don't want to calculate the duration yourself. This method doesn't send any telemetry. Call `stopTrackPage` to log the end of the page view + * and send the event. * @param name A string that idenfities this item, unique within this HTML document. Defaults to the document title. */ startTrackPage(name?: string): any; /** - * Logs how long a page or other item was visible, after {@link startTrackPage}. Call this when the page closes. - * @param name The string you used as the name in startTrackPage. Defaults to the document title. + * Stops the timer that was started by calling `startTrackPage` and sends the pageview load time telemetry with the specified properties and measurements. + * The duration of the page view will be the time between calling `startTrackPage` and `stopTrackPage`. + * @param name The string you used as the name in `startTrackPage`. Defaults to the document title. * @param url String - a relative or absolute URL that identifies the page or other item. Defaults to the window location. * @param properties map[string, string] - additional data used to filter pages and metrics in the portal. Defaults to empty. * @param measurements map[string, number] - metrics associated with this page, displayed in Metrics Explorer on the portal. Defaults to empty. @@ -689,7 +691,7 @@ declare module Microsoft.ApplicationInsights { measurements?: { [name: string]: number }): any; /** * Logs that a page or other item was viewed. - * @param name The string you used as the name in startTrackPage. Defaults to the document title. + * @param name The string you used as the name in `startTrackPage`. Defaults to the document title. * @param url String - a relative or absolute URL that identifies the page or other item. Defaults to the window location. * @param properties map[string, string] - additional data used to filter pages and metrics in the portal. Defaults to empty. * @param measurements map[string, number] - metrics associated with this page, displayed in Metrics Explorer on the portal. Defaults to empty. @@ -701,13 +703,13 @@ declare module Microsoft.ApplicationInsights { properties?: { [name: string]: string }, measurements?: { [name: string]: number }, duration?: number): any; /** - * Start timing an extended event. Call {@link stopTrackEvent} to log the event when it ends. + * Start timing an extended event. Call `stopTrackEvent` to log the event when it ends. * @param name A string that identifies this event uniquely within the document. */ startTrackEvent(name: string): any; /** - * Log an extended event that you started timing with {@link startTrackEvent}. - * @param name The string you used to identify this event in startTrackEvent. + * Log an extended event that you started timing with `startTrackEvent`. + * @param name The string you used to identify this event in `startTrackEvent`. * @param properties map[string, string] - additional data used to filter events and metrics in the portal. Defaults to empty. * @param measurements map[string, number] - metrics associated with this event, displayed in Metrics Explorer on the portal. Defaults to empty. */ diff --git a/types/assert/assert-tests.ts b/types/assert/assert-tests.ts index 22248c18bd..3f795f0552 100644 --- a/types/assert/assert-tests.ts +++ b/types/assert/assert-tests.ts @@ -5,6 +5,7 @@ assert(true, "it's working"); assert.ok(true, "inner functions work as well"); assert.throws(() => {}); +assert.throws(() => {}, /Regex test/); assert.throws(() => {}, () => {}, "works wonderfully"); assert['fail'](true, true, "works like a charm"); diff --git a/types/assert/index.d.ts b/types/assert/index.d.ts index d79805f5af..f04158bbd3 100644 --- a/types/assert/index.d.ts +++ b/types/assert/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for commonjs-assert 1.4 // Project: https://github.com/browserify/commonjs-assert // Definitions by: Nico Gallinal +// Linus Unnebäck // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare function assert(value: any, message?: string): void; @@ -23,10 +24,10 @@ declare namespace assert { function notStrictEqual(actual: any, expected: any, message?: string): void; function throws(block: () => void, message?: string): void; - function throws(block: () => void, error: () => void | ((err: any) => boolean) | RegExp, message?: string): void; + function throws(block: () => void, error: (() => void) | ((err: any) => boolean) | RegExp, message?: string): void; function doesNotThrow(block: () => void, message?: string): void; - function doesNotThrow(block: () => void, error: () => void | ((err: any) => boolean) | RegExp, message?: string): void; + function doesNotThrow(block: () => void, error: (() => void) | ((err: any) => boolean) | RegExp, message?: string): void; function ifError(value: any): void; diff --git a/types/atlaskit__tree/atlaskit__tree-tests.tsx b/types/atlaskit__tree/atlaskit__tree-tests.tsx new file mode 100644 index 0000000000..b99647a7c6 --- /dev/null +++ b/types/atlaskit__tree/atlaskit__tree-tests.tsx @@ -0,0 +1,42 @@ +import Tree from "@atlaskit/tree"; + +import * as React from "react"; +import { render } from "react-dom"; + +declare const container: Element; + +render( +
} + onExpand={() => {}} + onCollapse={() => {}} + onDragStart={() => {}} + onDragEnd={() => {}} + offsetPerLevel={20} + isDragEnabled + isNestingEnabled + />, + container +); + +// Check that default props work too. +render(
} />, container); diff --git a/types/atlaskit__tree/index.d.ts b/types/atlaskit__tree/index.d.ts new file mode 100644 index 0000000000..4d6a952b76 --- /dev/null +++ b/types/atlaskit__tree/index.d.ts @@ -0,0 +1,153 @@ +// Type definitions for @atlaskit/tree 4.1 +// Project: https://bitbucket.org/atlassian/atlaskit-mk-2/ +// Definitions by: Ben James +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 3.0 + +import { Component, ReactNode } from "react"; + +import { + DraggingStyle, + DraggableProvidedDragHandleProps, + DraggableStateSnapshot, + NotDraggingStyle +} from "react-beautiful-dnd"; + +export type ItemId = any; + +export type Path = number[]; + +export interface TreeData { + rootId: ItemId; + items: { [key: string]: TreeItem; [key: number]: TreeItem }; +} + +export type TreeItemData = any; + +export interface TreeItem { + id: ItemId; + children: ItemId[]; + hasChildren?: boolean; + isExpanded?: boolean; + isChildrenLoading?: boolean; + data?: TreeItemData; +} + +export interface TreeSourcePosition { + parentId: ItemId; + index: number; +} + +export interface TreeDestinationPosition { + parentId: ItemId; + index?: number; +} + +type Omit = Pick>; + +interface TreeDraggingStyle extends Omit { + paddingLeft: number; + transition: "none" | string; +} + +type TreeDraggableStyle = NotDraggingStyle | TreeDraggingStyle; + +interface TreeDraggableProps { + // Props that can be spread onto the element directly + // inline style + style?: TreeDraggableStyle; + // used for shared global styles + "data-react-beautiful-dnd-draggable": string; +} + +interface TreeDraggableProvided { + draggableProps: TreeDraggableProps; + // will be null if the draggable is disabled + dragHandleProps?: DraggableProvidedDragHandleProps; + // The following props will be removed once we move to react 16 + innerRef: (element?: HTMLElement) => void; +} + +export interface RenderItemParams { + item: TreeItem; + depth: number; + onExpand: (itemId: ItemId) => void; + onCollapse: (itemId: ItemId) => void; + provided: TreeDraggableProvided; + snapshot: DraggableStateSnapshot; +} + +interface TreeItemMutation { + id?: ItemId; + children?: ItemId[]; + hasChildren?: boolean; + isExpanded?: boolean; + isChildrenLoading?: boolean; + data?: TreeItemData; +} + +export function mutateTree( + tree: TreeData, + itemId: ItemId, + mutation: TreeItemMutation +): TreeData; + +export function moveItemOnTree( + tree: TreeData, + from: TreeSourcePosition, + to: TreeDestinationPosition +): TreeData; + +interface TreeProps { + /** The tree data structure. */ + tree: TreeData; + /** Function that will be called when a parent item needs to be expanded. */ + onExpand: (itemId: ItemId, path: Path) => void; + /** Function that will be called when a parent item needs to be collapsed. */ + onCollapse: (itemId: ItemId, path: Path) => void; + /** Function that will be called when the user starts dragging. */ + onDragStart: (itemId: ItemId) => void; + /** Function that will be called when the user finishes dragging. */ + onDragEnd: ( + sourcePosition: TreeSourcePosition, + destinationPosition: TreeDestinationPosition | undefined + ) => void; + /** Function that will be called to render a single item. */ + renderItem: (itemProps: RenderItemParams) => ReactNode; + /** Number of pixel is used to scaffold the tree by the consumer. */ + offsetPerLevel: number; + /** Boolean to turn on drag&drop re-ordering on the tree */ + isDragEnabled: boolean; + /** Boolean to turn on hovering while dragging */ + isNestingEnabled: boolean; +} + +interface FlattenedItem { + item: TreeItem; + path: Path; +} + +type FlattenedTree = FlattenedItem[]; + +interface TreeState { + /** The flattened tree data structure transformed from props.tree */ + flattenedTree: FlattenedTree; + // Id of the currently dragged item + draggedItemId: ItemId; +} + +declare class Tree extends Component { + static defaultProps: { + tree: { children: [] }; + onExpand: () => void; + onCollapse: () => void; + onDragStart: () => void; + onDragEnd: () => void; + renderItem: () => void; + offsetPerLevel: 35; + isDragEnabled: false; + isNestingEnabled: false; + }; +} + +export default Tree; diff --git a/types/atlaskit__tree/tsconfig.json b/types/atlaskit__tree/tsconfig.json new file mode 100644 index 0000000000..b6d581fa0d --- /dev/null +++ b/types/atlaskit__tree/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6", "dom"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "jsx": "react", + "paths": { + "@atlaskit/tree": ["atlaskit__tree"] + } + }, + "files": ["index.d.ts", "atlaskit__tree-tests.tsx"] +} diff --git a/types/atlaskit__tree/tslint.json b/types/atlaskit__tree/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/atlaskit__tree/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/backbone/index.d.ts b/types/backbone/index.d.ts index ca36541735..a881284c8f 100644 --- a/types/backbone/index.d.ts +++ b/types/backbone/index.d.ts @@ -92,7 +92,7 @@ declare namespace Backbone { } interface EventsHash { - [selector: string]: string | {(eventObject: JQueryEventObject): void}; + [selector: string]: string | {(eventObject: JQuery.TriggeredEvent): void}; } export const Events: Events; diff --git a/types/better-sqlite3/better-sqlite3-tests.ts b/types/better-sqlite3/better-sqlite3-tests.ts index 7272d88f7e..81e96861d2 100644 --- a/types/better-sqlite3/better-sqlite3-tests.ts +++ b/types/better-sqlite3/better-sqlite3-tests.ts @@ -6,7 +6,6 @@ const result: Database.RunResult = { changes: 1, lastInsertRowid: 1 }; const options: Database.Options = { fileMustExist: true, memory: true, readonly: true }; const registrationOptions: Database.RegistrationOptions = { deterministic: true, - name: '', safeIntegers: true, varargs: true }; @@ -15,26 +14,49 @@ let db = Database('.'); db = new Database('.', { memory: true }); db.exec('CREATE TABLE test (id INTEGER PRIMARY KEY NOT NULL, name TEXT NOT NULL);'); db.exec('INSERT INTO test(name) VALUES("name");'); -db.pragma('data_version', true); +db.pragma('data_version', { simple: true }); db.checkpoint(); db.checkpoint('main'); -db.register(() => { }); -db.register({ name: 'noop', deterministic: true, varargs: true }, () => { }); +db.function('noop', () => { }); +db.function('noop', { deterministic: true, varargs: true }, () => { }); +db.aggregate('add', { + start: 0, + step: (t, n) => t + n, + deterministic: true, + varargs: true +}); +db.aggregate('getAverage', { + start: () => [], + step: (array, nextValue) => { + array.push(nextValue); + }, + result: array => array.reduce((t: any, v: any) => t + v) / array.length, +}); +db.aggregate('addAll', { + start: 0, + step: (total, nextValue) => total + nextValue, + inverse: (total, droppedValue) => total - droppedValue, + result: total => Math.round(total), +}); db.defaultSafeIntegers(); db.defaultSafeIntegers(true); const stmt = db.prepare('SELECT * FROM test WHERE name == ?;'); stmt.get(['name']); stmt.all({ name: 'name' }); -stmt.each('name', (row: { name: string }) => { }); -stmt.each((row: { name: string }) => { }); +for (const row of stmt.iterate('name')) { +} stmt.pluck(); stmt.pluck(true); +stmt.expand(); +stmt.expand(true); stmt.bind('name'); stmt.safeIntegers(); stmt.safeIntegers(true); -const trans = db.transaction(['INSERT INTO test(name) VALUES(?);']); -trans.run('name'); -trans.bind('name'); -trans.run(); +const trans = db.transaction((param) => stmt.all(param)); +trans('name'); +trans.default('name'); +trans.deferred('name'); +trans.immediate('name'); +trans.exclusive('name'); diff --git a/types/better-sqlite3/index.d.ts b/types/better-sqlite3/index.d.ts index 5a4859e21f..32383e1337 100644 --- a/types/better-sqlite3/index.d.ts +++ b/types/better-sqlite3/index.d.ts @@ -3,35 +3,32 @@ // Definitions by: Ben Davies // Mathew Rumsey // Santiago Aguilar +// Alessandro Vergani // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped import Integer = require("integer"); -declare class Statement { +interface Statement { database: Database; source: string; - returnsData: boolean; - constructor(db: Database, sources: string[]); + reader: boolean; run(...params: any[]): Database.RunResult; get(...params: any[]): any; all(...params: any[]): any[]; - each(params: any, cb: (row: any) => void): void; - each(cb: (row: any) => void): void; - each(...params: any[]): void; + iterate(...params: any[]): IterableIterator; pluck(toggleState?: boolean): this; + expand(toggleState?: boolean): this; bind(...params: any[]): this; safeIntegers(toggleState?: boolean): this; } -declare class Transaction { - database: Database; - source: string; - constructor(db: Database, sources: string[]); - - run(...params: any[]): Database.RunResult; - bind(...params: any[]): this; - safeIntegers(toggleState?: boolean): this; +interface Transaction { + (...params: any[]): any; + default(...params: any[]): any; + deferred(...params: any[]): any; + immediate(...params: any[]): any; + exclusive(...params: any[]): any; } interface Database { @@ -42,15 +39,14 @@ interface Database { inTransaction: boolean; prepare(source: string): Statement; - transaction(sources: string[]): Transaction; + transaction(fn: (...params: any[]) => any): Transaction; exec(source: string): this; - pragma(source: string, simplify?: boolean): any; + pragma(source: string, options?: Database.PragmaOptions): any; checkpoint(databaseName?: string): this; - register(cb: (...params: any[]) => any): this; - register( - options: Database.RegistrationOptions, - cb: (...params: any[]) => any - ): this; + function(name: string, cb: (...params: any[]) => any): this; + function(name: string, options: Database.RegistrationOptions, cb: (...params: any[]) => any): this; + aggregate(name: string, options: Database.AggregateOptions): this; + loadExtension(path: string): this; close(): this; defaultSafeIntegers(toggleState?: boolean): this; } @@ -81,14 +77,25 @@ declare namespace Database { memory?: boolean; readonly?: boolean; fileMustExist?: boolean; + timeout?: number; + } + + interface PragmaOptions { + simple?: boolean; } interface RegistrationOptions { - name?: string; varargs?: boolean; deterministic?: boolean; safeIntegers?: boolean; } + + interface AggregateOptions extends RegistrationOptions { + start?: any; + step: (total: any, next: any) => any; + inverse?: (total: any, dropped: any) => any; + result?: (total: any) => any; + } } declare const Database: DatabaseConstructor; diff --git a/types/better-sqlite3/tsconfig.json b/types/better-sqlite3/tsconfig.json index 30a480355b..19cd56ac36 100644 --- a/types/better-sqlite3/tsconfig.json +++ b/types/better-sqlite3/tsconfig.json @@ -1,6 +1,7 @@ { "compilerOptions": { "module": "commonjs", + "target": "es6", "lib": [ "es6" ], @@ -20,4 +21,4 @@ "index.d.ts", "better-sqlite3-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/bin-version/bin-version-tests.ts b/types/bin-version/bin-version-tests.ts new file mode 100644 index 0000000000..7decda3e66 --- /dev/null +++ b/types/bin-version/bin-version-tests.ts @@ -0,0 +1,6 @@ +import binVersion = require('bin-version'); + +// $ExpectType Promise +binVersion('curl'); +// $ExpectType Promise +binVersion('openssl', { args: ['version'] }); diff --git a/types/bin-version/index.d.ts b/types/bin-version/index.d.ts new file mode 100644 index 0000000000..3db592bec7 --- /dev/null +++ b/types/bin-version/index.d.ts @@ -0,0 +1,14 @@ +// Type definitions for bin-version 3.0 +// Project: https://github.com/sindresorhus/bin-version#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = binVersion; + +declare function binVersion(binary: string, options?: binVersion.Options): Promise; + +declare namespace binVersion { + interface Options { + args?: string[]; + } +} diff --git a/types/bin-version/tsconfig.json b/types/bin-version/tsconfig.json new file mode 100644 index 0000000000..e89af3fdb8 --- /dev/null +++ b/types/bin-version/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "bin-version-tests.ts" + ] +} diff --git a/types/bin-version/tslint.json b/types/bin-version/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/bin-version/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/binary-parser/binary-parser-tests.ts b/types/binary-parser/binary-parser-tests.ts index d0d09e5ef7..9eca89211c 100644 --- a/types/binary-parser/binary-parser-tests.ts +++ b/types/binary-parser/binary-parser-tests.ts @@ -93,3 +93,28 @@ const parser5 = new Parser() length: '4', formatter: (arr) => { } }); + +const parser6 = new Parser() + .nest("nested", { + type: new Parser() + .array("points", { + type: new Parser() + .uint8("x") + .uint8("y"), + length: 2 + }) + }) + .choice("optional", { + tag: "nested.points[0].x", + choices: { + 1: new Parser() + .uint8("number") + } + }); + +const result = parser6.parse(Buffer.from([0x01, 0x02, 0x03, 0x04, 0x05])); + +// See the inferred static types on the IntelliSense. +result.nested.points[0].x; +result.nested.points[1].y; +result.optional.number; diff --git a/types/binary-parser/index.d.ts b/types/binary-parser/index.d.ts index 657996bd8d..b16f433e55 100644 --- a/types/binary-parser/index.d.ts +++ b/types/binary-parser/index.d.ts @@ -1,88 +1,117 @@ // Type definitions for binary-parser 1.3 // Project: https://github.com/keichi/binary-parser -// Definitions by: Benjamin Riggs , Dolan Miu +// Definitions by: Benjamin Riggs , +// Dolan Miu , +// Yu Shimura // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 /// -export interface Parser { - parse(buffer: Buffer, callback?: (err?: Error, result?: any) => void): Parser.Parsed; +export interface Parser { + parse(buffer: Buffer, callback?: (err?: Error, result?: any) => void): Parser.Parsed; create(constructorFunction: ObjectConstructor): Parser; - int8(name: string, options?: Parser.Options): Parser; - uint8(name: string, options?: Parser.Options): Parser; + int8(name: N, options?: Parser.Options): Parser.Next; + uint8(name: N, options?: Parser.Options): Parser.Next; - int16(name: string, options?: Parser.Options): Parser; - uint16(name: string, options?: Parser.Options): Parser; - int16le(name: string, options?: Parser.Options): Parser; - int16be(name: string, options?: Parser.Options): Parser; - uint16le(name: string, options?: Parser.Options): Parser; - uint16be(name: string, options?: Parser.Options): Parser; + int16(name: N, options?: Parser.Options): Parser.Next; + uint16(name: N, options?: Parser.Options): Parser.Next; + int16le(name: N, options?: Parser.Options): Parser.Next; + int16be(name: N, options?: Parser.Options): Parser.Next; + uint16le(name: N, options?: Parser.Options): Parser.Next; + uint16be(name: N, options?: Parser.Options): Parser.Next; - int32(name: string, options?: Parser.Options): Parser; - uint32(name: string, options?: Parser.Options): Parser; - int32le(name: string, options?: Parser.Options): Parser; - int32be(name: string, options?: Parser.Options): Parser; - uint32le(name: string, options?: Parser.Options): Parser; - uint32be(name: string, options?: Parser.Options): Parser; + int32(name: N, options?: Parser.Options): Parser.Next; + uint32(name: N, options?: Parser.Options): Parser.Next; + int32le(name: N, options?: Parser.Options): Parser.Next; + int32be(name: N, options?: Parser.Options): Parser.Next; + uint32le(name: N, options?: Parser.Options): Parser.Next; + uint32be(name: N, options?: Parser.Options): Parser.Next; - bit1(name: string, options?: Parser.Options): Parser; - bit2(name: string, options?: Parser.Options): Parser; - bit3(name: string, options?: Parser.Options): Parser; - bit4(name: string, options?: Parser.Options): Parser; - bit5(name: string, options?: Parser.Options): Parser; - bit6(name: string, options?: Parser.Options): Parser; - bit7(name: string, options?: Parser.Options): Parser; - bit8(name: string, options?: Parser.Options): Parser; - bit9(name: string, options?: Parser.Options): Parser; - bit10(name: string, options?: Parser.Options): Parser; - bit11(name: string, options?: Parser.Options): Parser; - bit12(name: string, options?: Parser.Options): Parser; - bit13(name: string, options?: Parser.Options): Parser; - bit14(name: string, options?: Parser.Options): Parser; - bit15(name: string, options?: Parser.Options): Parser; - bit16(name: string, options?: Parser.Options): Parser; - bit17(name: string, options?: Parser.Options): Parser; - bit18(name: string, options?: Parser.Options): Parser; - bit19(name: string, options?: Parser.Options): Parser; - bit20(name: string, options?: Parser.Options): Parser; - bit21(name: string, options?: Parser.Options): Parser; - bit22(name: string, options?: Parser.Options): Parser; - bit23(name: string, options?: Parser.Options): Parser; - bit24(name: string, options?: Parser.Options): Parser; - bit25(name: string, options?: Parser.Options): Parser; - bit26(name: string, options?: Parser.Options): Parser; - bit27(name: string, options?: Parser.Options): Parser; - bit28(name: string, options?: Parser.Options): Parser; - bit29(name: string, options?: Parser.Options): Parser; - bit30(name: string, options?: Parser.Options): Parser; - bit31(name: string, options?: Parser.Options): Parser; - bit32(name: string, options?: Parser.Options): Parser; + bit1(name: N, options?: Parser.Options): Parser.Next; + bit2(name: N, options?: Parser.Options): Parser.Next; + bit3(name: N, options?: Parser.Options): Parser.Next; + bit4(name: N, options?: Parser.Options): Parser.Next; + bit5(name: N, options?: Parser.Options): Parser.Next; + bit6(name: N, options?: Parser.Options): Parser.Next; + bit7(name: N, options?: Parser.Options): Parser.Next; + bit8(name: N, options?: Parser.Options): Parser.Next; + bit9(name: N, options?: Parser.Options): Parser.Next; + bit10(name: N, options?: Parser.Options): Parser.Next; + bit11(name: N, options?: Parser.Options): Parser.Next; + bit12(name: N, options?: Parser.Options): Parser.Next; + bit13(name: N, options?: Parser.Options): Parser.Next; + bit14(name: N, options?: Parser.Options): Parser.Next; + bit15(name: N, options?: Parser.Options): Parser.Next; + bit16(name: N, options?: Parser.Options): Parser.Next; + bit17(name: N, options?: Parser.Options): Parser.Next; + bit18(name: N, options?: Parser.Options): Parser.Next; + bit19(name: N, options?: Parser.Options): Parser.Next; + bit20(name: N, options?: Parser.Options): Parser.Next; + bit21(name: N, options?: Parser.Options): Parser.Next; + bit22(name: N, options?: Parser.Options): Parser.Next; + bit23(name: N, options?: Parser.Options): Parser.Next; + bit24(name: N, options?: Parser.Options): Parser.Next; + bit25(name: N, options?: Parser.Options): Parser.Next; + bit26(name: N, options?: Parser.Options): Parser.Next; + bit27(name: N, options?: Parser.Options): Parser.Next; + bit28(name: N, options?: Parser.Options): Parser.Next; + bit29(name: N, options?: Parser.Options): Parser.Next; + bit30(name: N, options?: Parser.Options): Parser.Next; + bit31(name: N, options?: Parser.Options): Parser.Next; + bit32(name: N, options?: Parser.Options): Parser.Next; - float(name: string, options?: Parser.Options): Parser; - floatle(name: string, options?: Parser.Options): Parser; - floatbe(name: string, options?: Parser.Options): Parser; + float(name: N, options?: Parser.Options): Parser.Next; + floatle(name: N, options?: Parser.Options): Parser.Next; + floatbe(name: N, options?: Parser.Options): Parser.Next; - double(name: string, options?: Parser.Options): Parser; - doublele(name: string, options?: Parser.Options): Parser; - doublebe(name: string, options?: Parser.Options): Parser; + double(name: N, options?: Parser.Options): Parser.Next; + doublele(name: N, options?: Parser.Options): Parser.Next; + doublebe(name: N, options?: Parser.Options): Parser.Next; - string(name: string, options?: Parser.StringOptions): Parser; + string(name: N, options?: Parser.StringOptions): Parser.Next; - buffer(name: string, options: Parser.BufferOptions): Parser; + buffer(name: N, options: Parser.BufferOptions): Parser.Next; - array(name: string, options: Parser.ArrayOptions): Parser; + array(name: N, options: Q): Parser.Next + ? O extends undefined ? Array<{}> : O[] + : T extends string + ? number[] + : never + : never + >; - choice(name: string, options: Parser.ChoiceOptions): Parser; + choice(name: N, options: Q): Parser.Next + ? O extends undefined ? {} : O + : T extends string ? any : never + : never + : never + >; - nest(name: string, options: Parser.NestOptions): Parser; + nest(name: N, options: Q): Parser.Next + ? O extends undefined ? {} : O + : never + : never + >; - skip(length: number): Parser; + skip(length: number): Parser; - endianess(endianess: Parser.Endianness): Parser; /* [sic] */ + endianess(endianess: Parser.Endianness): Parser; /* [sic] */ - namely(alias: string): Parser; + namely(alias: string): Parser; compile(): void; @@ -96,10 +125,8 @@ export interface ParserConstructor { export const Parser: ParserConstructor; export namespace Parser { - type Data = number | string | Array | Parsed | Buffer; - interface Parsed { - [name: string]: Data; - } + type Data = number | string | Array> | Parser | Buffer; + type Parsed = O extends undefined ? {} : O; interface Options { formatter?: ((value: Data) => any); @@ -108,7 +135,7 @@ export namespace Parser { interface StringOptions extends Options { encoding?: string; - length?: number | string | ((this: Parsed) => number); + length?: number | string | ((this: Parser) => number); zeroTerminated?: boolean; greedy?: boolean; stripNull?: boolean; @@ -116,32 +143,34 @@ export namespace Parser { interface BufferOptions extends Options { clone?: boolean; - length?: number | string | ((this: Parsed) => number); + length?: number | string | ((this: Parser) => number); readUntil?: string | ((item: number, buffer: Buffer) => boolean); } interface ArrayOptions extends Options { - type: string | Parser; - length?: number | string | ((this: Parsed) => number); - lengthInBytes?: number | string | ((this: Parsed) => number); + type: string | Parser; + length?: number | string | ((this: Parser) => number); + lengthInBytes?: number | string | ((this: Parser) => number); readUntil?: string | ((item: number, buffer: Buffer) => boolean); } interface ChoiceOptions extends Options { - tag: string | ((this: Parsed) => number); - choices: { [item: number]: Parser | string }; - defaultChoice?: Parser | string; + tag: string | ((this: Parser) => number); + choices: { [item: number]: Parser | string }; + defaultChoice?: Parser | string; } interface NestOptions extends Options { - type: Parser | string; + type: Parser; } type Endianness = 'little' | 'big'; - interface Context { - [name: string]: Parsed; - } + type Valid = + O extends undefined ? P : O & P; + + type Next = + Parser>; } diff --git a/types/bluebird/index.d.ts b/types/bluebird/index.d.ts index 091dbe6e7a..24c2b79a32 100644 --- a/types/bluebird/index.d.ts +++ b/types/bluebird/index.d.ts @@ -35,7 +35,8 @@ * THE SOFTWARE. */ -type CatchFilter = (new (...args: any[]) => E) | ((error: E) => boolean) | (object & E); +type Constructor = new (...args: any[]) => E; +type CatchFilter = ((error: E) => boolean) | (object & E); type IterableItem = R extends Iterable ? U : never; type IterableOrNever = Extract>; type Resolvable = R | PromiseLike; @@ -85,69 +86,74 @@ declare class Bluebird implements PromiseLike, Bluebird.Inspection { * * Alias `.caught();` for compatibility with earlier ECMAScript version. */ - catch( - filter1: CatchFilter, - filter2: CatchFilter, - filter3: CatchFilter, - filter4: CatchFilter, - filter5: CatchFilter, - onReject: (error: E1 | E2 | E3 | E4 | E5) => Resolvable, - ): Bluebird; catch( - filter1: CatchFilter, - filter2: CatchFilter, - filter3: CatchFilter, - filter4: CatchFilter, - filter5: CatchFilter, + filter1: Constructor, + filter2: Constructor, + filter3: Constructor, + filter4: Constructor, + filter5: Constructor, onReject: (error: E1 | E2 | E3 | E4 | E5) => Resolvable, ): Bluebird; - catch( - filter1: CatchFilter, - filter2: CatchFilter, - filter3: CatchFilter, - filter4: CatchFilter, - onReject: (error: E1 | E2 | E3 | E4) => Resolvable, - ): Bluebird; + catch( + filter1: Constructor | CatchFilter, + filter2: Constructor | CatchFilter, + filter3: Constructor | CatchFilter, + filter4: Constructor | CatchFilter, + filter5: Constructor | CatchFilter, + onReject: (error: E1 | E2 | E3 | E4 | E5) => Resolvable, + ): Bluebird; catch( - filter1: CatchFilter, - filter2: CatchFilter, - filter3: CatchFilter, - filter4: CatchFilter, + filter1: Constructor, + filter2: Constructor, + filter3: Constructor, + filter4: Constructor, + onReject: (error: E1 | E2 | E3 | E4) => Resolvable, + ): Bluebird; + + catch( + filter1: Constructor | CatchFilter, + filter2: Constructor | CatchFilter, + filter3: Constructor | CatchFilter, + filter4: Constructor | CatchFilter, onReject: (error: E1 | E2 | E3 | E4) => Resolvable, ): Bluebird; - catch( - filter1: CatchFilter, - filter2: CatchFilter, - filter3: CatchFilter, - onReject: (error: E1 | E2 | E3) => Resolvable, - ): Bluebird; catch( - filter1: CatchFilter, - filter2: CatchFilter, - filter3: CatchFilter, + filter1: Constructor, + filter2: Constructor, + filter3: Constructor, + onReject: (error: E1 | E2 | E3) => Resolvable, + ): Bluebird; + + catch( + filter1: Constructor | CatchFilter, + filter2: Constructor | CatchFilter, + filter3: Constructor | CatchFilter, onReject: (error: E1 | E2 | E3) => Resolvable, ): Bluebird; - catch( - filter1: CatchFilter, - filter2: CatchFilter, - onReject: (error: E1 | E2) => Resolvable, - ): Bluebird; catch( - filter1: CatchFilter, - filter2: CatchFilter, + filter1: Constructor, + filter2: Constructor, + onReject: (error: E1 | E2) => Resolvable, + ): Bluebird; + + catch( + filter1: Constructor | CatchFilter, + filter2: Constructor | CatchFilter, onReject: (error: E1 | E2) => Resolvable, ): Bluebird; - catch( - filter1: CatchFilter, - onReject: (error: E1) => Resolvable, - ): Bluebird; catch( - filter1: CatchFilter, + filter1: Constructor, + onReject: (error: E1) => Resolvable, + ): Bluebird; + + catch( + // tslint:disable-next-line:unified-signatures + filter1: Constructor | CatchFilter, onReject: (error: E1) => Resolvable, ): Bluebird; @@ -201,33 +207,64 @@ declare class Bluebird implements PromiseLike, Bluebird.Inspection { tapCatch(onReject: (error?: any) => Resolvable): Bluebird; tapCatch( - filter1: CatchFilter, - filter2: CatchFilter, - filter3: CatchFilter, - filter4: CatchFilter, - filter5: CatchFilter, + filter1: Constructor, + filter2: Constructor, + filter3: Constructor, + filter4: Constructor, + filter5: Constructor, + onReject: (error: E1 | E2 | E3 | E4 | E5) => Resolvable, + ): Bluebird; + tapCatch( + filter1: Constructor | CatchFilter, + filter2: Constructor | CatchFilter, + filter3: Constructor | CatchFilter, + filter4: Constructor | CatchFilter, + filter5: Constructor | CatchFilter, onReject: (error: E1 | E2 | E3 | E4 | E5) => Resolvable, ): Bluebird; tapCatch( - filter1: CatchFilter, - filter2: CatchFilter, - filter3: CatchFilter, - filter4: CatchFilter, + filter1: Constructor, + filter2: Constructor, + filter3: Constructor, + filter4: Constructor, + onReject: (error: E1 | E2 | E3 | E4) => Resolvable, + ): Bluebird; + tapCatch( + filter1: Constructor | CatchFilter, + filter2: Constructor | CatchFilter, + filter3: Constructor | CatchFilter, + filter4: Constructor | CatchFilter, onReject: (error: E1 | E2 | E3 | E4) => Resolvable, ): Bluebird; tapCatch( - filter1: CatchFilter, - filter2: CatchFilter, - filter3: CatchFilter, + filter1: Constructor, + filter2: Constructor, + filter3: Constructor, + onReject: (error: E1 | E2 | E3) => Resolvable, + ): Bluebird; + tapCatch( + filter1: Constructor | CatchFilter, + filter2: Constructor | CatchFilter, + filter3: Constructor | CatchFilter, onReject: (error: E1 | E2 | E3) => Resolvable, ): Bluebird; tapCatch( - filter1: CatchFilter, - filter2: CatchFilter, + filter1: Constructor, + filter2: Constructor, + onReject: (error: E1 | E2) => Resolvable, + ): Bluebird; + tapCatch( + filter1: Constructor | CatchFilter, + filter2: Constructor | CatchFilter, onReject: (error: E1 | E2) => Resolvable, ): Bluebird; tapCatch( - filter1: CatchFilter, + filter1: Constructor, + onReject: (error: E1) => Resolvable, + ): Bluebird; + tapCatch( + // tslint:disable-next-line:unified-signatures + filter1: Constructor | CatchFilter, onReject: (error: E1) => Resolvable, ): Bluebird; @@ -376,33 +413,64 @@ declare class Bluebird implements PromiseLike, Bluebird.Inspection { // No need to be specific about Error types in these overrides, since there's no handler function catchReturn( - filter1: CatchFilter, - filter2: CatchFilter, - filter3: CatchFilter, - filter4: CatchFilter, - filter5: CatchFilter, + filter1: Constructor, + filter2: Constructor, + filter3: Constructor, + filter4: Constructor, + filter5: Constructor, value: U, ): Bluebird; catchReturn( - filter1: CatchFilter, - filter2: CatchFilter, - filter3: CatchFilter, - filter4: CatchFilter, + filter1: Constructor | CatchFilter, + filter2: Constructor | CatchFilter, + filter3: Constructor | CatchFilter, + filter4: Constructor | CatchFilter, + filter5: Constructor | CatchFilter, value: U, ): Bluebird; catchReturn( - filter1: CatchFilter, - filter2: CatchFilter, - filter3: CatchFilter, + filter1: Constructor, + filter2: Constructor, + filter3: Constructor, + filter4: Constructor, value: U, ): Bluebird; catchReturn( - filter1: CatchFilter, - filter2: CatchFilter, + filter1: Constructor | CatchFilter, + filter2: Constructor | CatchFilter, + filter3: Constructor | CatchFilter, + filter4: Constructor | CatchFilter, value: U, ): Bluebird; catchReturn( - filter1: CatchFilter, + filter1: Constructor, + filter2: Constructor, + filter3: Constructor, + value: U, + ): Bluebird; + catchReturn( + filter1: Constructor | CatchFilter, + filter2: Constructor | CatchFilter, + filter3: Constructor | CatchFilter, + value: U, + ): Bluebird; + catchReturn( + filter1: Constructor, + filter2: Constructor, + value: U, + ): Bluebird; + catchReturn( + filter1: Constructor | CatchFilter, + filter2: Constructor | CatchFilter, + value: U, + ): Bluebird; + catchReturn( + filter1: Constructor, + value: U, + ): Bluebird; + catchReturn( + // tslint:disable-next-line:unified-signatures + filter1: Constructor | CatchFilter, value: U, ): Bluebird; @@ -420,33 +488,64 @@ declare class Bluebird implements PromiseLike, Bluebird.Inspection { // No need to be specific about Error types in these overrides, since there's no handler function catchThrow( - filter1: CatchFilter, - filter2: CatchFilter, - filter3: CatchFilter, - filter4: CatchFilter, - filter5: CatchFilter, + filter1: Constructor, + filter2: Constructor, + filter3: Constructor, + filter4: Constructor, + filter5: Constructor, reason: Error, ): Bluebird; catchThrow( - filter1: CatchFilter, - filter2: CatchFilter, - filter3: CatchFilter, - filter4: CatchFilter, + filter1: Constructor | CatchFilter, + filter2: Constructor | CatchFilter, + filter3: Constructor | CatchFilter, + filter4: Constructor | CatchFilter, + filter5: Constructor | CatchFilter, reason: Error, ): Bluebird; catchThrow( - filter1: CatchFilter, - filter2: CatchFilter, - filter3: CatchFilter, + filter1: Constructor, + filter2: Constructor, + filter3: Constructor, + filter4: Constructor, reason: Error, ): Bluebird; catchThrow( - filter1: CatchFilter, - filter2: CatchFilter, + filter1: Constructor | CatchFilter, + filter2: Constructor | CatchFilter, + filter3: Constructor | CatchFilter, + filter4: Constructor | CatchFilter, reason: Error, ): Bluebird; catchThrow( - filter1: CatchFilter, + filter1: Constructor, + filter2: Constructor, + filter3: Constructor, + reason: Error, + ): Bluebird; + catchThrow( + filter1: Constructor | CatchFilter, + filter2: Constructor | CatchFilter, + filter3: Constructor | CatchFilter, + reason: Error, + ): Bluebird; + catchThrow( + filter1: Constructor, + filter2: Constructor, + reason: Error, + ): Bluebird; + catchThrow( + filter1: Constructor | CatchFilter, + filter2: Constructor | CatchFilter, + reason: Error, + ): Bluebird; + catchThrow( + filter1: Constructor, + reason: Error, + ): Bluebird; + catchThrow( + // tslint:disable-next-line:unified-signatures + filter1: Constructor | CatchFilter, reason: Error, ): Bluebird; diff --git a/types/bootstrap-slider/bootstrap-slider-tests.ts b/types/bootstrap-slider/bootstrap-slider-tests.ts index 9b2a1a2014..d3ffdeedeb 100644 --- a/types/bootstrap-slider/bootstrap-slider-tests.ts +++ b/types/bootstrap-slider/bootstrap-slider-tests.ts @@ -42,7 +42,7 @@ $(() => { $('#ex7').slider(); - $('#ex7-enabled').click(function(this: HTMLInputElement) { + $('#ex7-enabled').click(function() { if (this.checked) { // With JQuery $('#ex7').slider('enable'); diff --git a/types/bootstrap-slider/tslint.json b/types/bootstrap-slider/tslint.json index f93cf8562a..1c36270d47 100644 --- a/types/bootstrap-slider/tslint.json +++ b/types/bootstrap-slider/tslint.json @@ -1,3 +1,6 @@ { - "extends": "dtslint/dt.json" + "extends": "dtslint/dt.json", + "rules": { + "no-angle-bracket-type-assertion": false + } } diff --git a/types/bootstrap/index.d.ts b/types/bootstrap/index.d.ts index 8a815bccd5..9744731237 100755 --- a/types/bootstrap/index.d.ts +++ b/types/bootstrap/index.d.ts @@ -322,7 +322,7 @@ export interface TooltipOption { // Events // -------------------------------------------------------------------------------------- -export interface CarouselEventHandler extends JQuery.Event { +export interface CarouselEventHandler extends JQuery.TriggeredEvent { /** * The direction in which the carousel is sliding. */ @@ -339,6 +339,10 @@ export interface CarouselEventHandler extends JQuery.Event extends JQuery.TriggeredEvent { + relatedTarget: HTMLElement; +} + export type AlertEvent = "close.bs.alert" | "closed.bs.alert"; export type CarouselEvent = "slide.bs.carousel" | "slid.bs.carousel"; export type CollapseEvent = "show.bs.collapse" | "shown.bs.collapse" | "hide.bs.collapse" | "hidden.bs.collapse"; @@ -383,9 +387,10 @@ declare global { tooltip(options?: TooltipOption): this; on(events: CarouselEvent, handler: JQuery.EventHandlerBase>): this; + on(events: TapEvent, handler: JQuery.EventHandlerBase>): this; on(events: AlertEvent | CollapseEvent | DropdownEvent | ModalEvent | - PopoverEvent | ScrollspyEvent | TapEvent | TooltipEvent, + PopoverEvent | ScrollspyEvent | TooltipEvent, handler: JQuery.EventHandler): this; } } diff --git a/types/bull/index.d.ts b/types/bull/index.d.ts index c08048f1d7..2d18e0a800 100644 --- a/types/bull/index.d.ts +++ b/types/bull/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for bull 3.4 +// Type definitions for bull 3.5 // Project: https://github.com/OptimalBits/bull // Definitions by: Bruno Grieder // Cameron Crothers @@ -17,7 +17,6 @@ // TypeScript Version: 2.8 import * as Redis from "ioredis"; -import * as Promise from "bluebird"; /** * This is the Queue constructor. diff --git a/types/cached-path-relative/cached-path-relative-tests.ts b/types/cached-path-relative/cached-path-relative-tests.ts new file mode 100644 index 0000000000..22e6af97df --- /dev/null +++ b/types/cached-path-relative/cached-path-relative-tests.ts @@ -0,0 +1,7 @@ +import cachedPathRelative = require("cached-path-relative"); + +function browserifyTest() { + const file = "file.txt"; + const m1: string = cachedPathRelative("./", file).replace(/\\/g, '/'); + return m1; +} diff --git a/types/cached-path-relative/index.d.ts b/types/cached-path-relative/index.d.ts new file mode 100644 index 0000000000..b2af5ea81c --- /dev/null +++ b/types/cached-path-relative/index.d.ts @@ -0,0 +1,13 @@ +// Type definitions for cached-path-relative 1.0 +// Project: https://github.com/ashaffer/cached-path-relative +// Definitions by: TeamworkGuy2 +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * Memoize the results of the path.relative function. path.relative can be an expensive operation + * if it happens a lot, and its results shouldn't change for the same arguments. + * Use it just like your normal path.relative, but it's memoized. + */ +declare function cachedPathRelative(from: string, to: string): string; + +export = cachedPathRelative; diff --git a/types/cached-path-relative/tsconfig.json b/types/cached-path-relative/tsconfig.json new file mode 100644 index 0000000000..e69970c325 --- /dev/null +++ b/types/cached-path-relative/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "cached-path-relative-tests.ts" + ] +} \ No newline at end of file diff --git a/types/cached-path-relative/tslint.json b/types/cached-path-relative/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/cached-path-relative/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/caniuse-lite/caniuse-lite-tests.ts b/types/caniuse-lite/caniuse-lite-tests.ts new file mode 100644 index 0000000000..38b09230de --- /dev/null +++ b/types/caniuse-lite/caniuse-lite-tests.ts @@ -0,0 +1,48 @@ +import { + agents, features, feature, Agent, Feature, PackedFeature, StatsByAgentID, SupportStatusByVersion, SupportStatus +} from "caniuse-lite"; + +const chrome: Agent | undefined = agents.chrome; +if (chrome !== undefined) { + const browser: string = chrome.browser; + const prefix: string = chrome.prefix; + const prefixExceptions: any = chrome.prefix_exceptions; + const usageGlobal: { [version: string]: number | undefined } = chrome.usage_global; + const releaseDate: { [version: string]: number | undefined } = chrome.release_date; + const versions: Array = chrome.versions; + consume(browser, prefix, prefixExceptions, usageGlobal, releaseDate, versions); +} + +const unpackedFeatures = Object.keys(features).map((id: string) => { + const packed: PackedFeature = features[id]; + const unpacked: Feature = feature(packed); + + const status: string = unpacked.status; + const title: string = unpacked.title; + const stats: StatsByAgentID = unpacked.stats; + Object.keys(stats).forEach((agentID: string) => { + const byVersion: SupportStatusByVersion = stats[agentID]; + Object.keys(byVersion).forEach(version => { + const supportStatus: SupportStatus = byVersion[version]; + consume(supportStatus); + }); + + const supportStatusByVersion: SupportStatusByVersion = stats[agentID]; + const agent: Agent = agents[agentID]!; + return { + feature: unpacked, + agent, + versions: Object.keys(supportStatusByVersion).map(version => { + return { + version, + releaseDate: agent.release_date[version], + [`feature_${id}`]: supportStatusByVersion[version] + }; + }) + }; + }); +}); + +function consume(...anything: any[]): void { + // ... +} diff --git a/types/caniuse-lite/index.d.ts b/types/caniuse-lite/index.d.ts new file mode 100644 index 0000000000..ce4f91a35f --- /dev/null +++ b/types/caniuse-lite/index.d.ts @@ -0,0 +1,159 @@ +// Type definitions for caniuse-lite 1.0 +// Project: https://github.com/ben-eb/caniuse-lite#readme +// Definitions by: Michael Utech +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +/** + * Information about user agents (browsers, platforms) indexed by their ID. + */ +export const agents: AgentsByID; + +/** + * Features index by their ID. The feature ID is a human readable identifier. The + * associated value is a packed version of information about the feature that + * can be unpacked using the function `feature(packed)` + */ +export const features: { [featureID: string]: PackedFeature; }; + +/** + * @param packedFeature a packed feature obtained from `features[key]` for some valid key. + * @return the unpacked information as `Feature`. + */ +export function feature(packedFeature: PackedFeature): Feature; + +/** + * @param packedRegion a packed version of regional usage data by agent OD. + * @return the unpacked usage data indexed by agent ID and then version. + */ +export function region(packedRegion: PackedRegion): { [agentID: string]: UsageByVersion }; + +/** + * Agents indexed by their ID. . + */ +export type AgentsByID = Readonly<{ [id: string]: Readonly | undefined }>; + +/** + * Feature support status by version indexed by agent ID. + */ +export type StatsByAgentID = Readonly<{ [agentID: string]: SupportStatusByVersion }>; + +/** + * Feature support status indexed by an agent's versions. + */ +export type SupportStatusByVersion = Readonly<{ [version: string]: SupportStatus }>; + +/** + * Usage (percentage/market share) indexed by an agent's versions. + */ +export type UsageByVersion = Readonly<{ [version: string]: number | undefined }>; + +/** + * The standardization status of a feature: + * * ls - WHATWG living standard + * * rec - W3C recommendation + * * pr - W3C proposed recommendation + * * cr - W3C candidate recommendation + * * wd - W3C working draft + * * other - Non-W3C, but reputable + * * unoff - Unofficial + */ +export type FeatureStatus = "ls" | "rec" | "pr" | "cr" | "wd" | "other" | "unoff" | string; + +/** + * Encoded support status: + * * `n` - not supported + * * `p` - not supported, polyfill available + * * `u` - unknown + * * `a x` - partially supported, vendor prefix + * * `a` - partially supported + * * `y x` - fully supported, vendor prefix + * * `y` - fully supported + * + * The support status can additionally have one or more footnote references as `#`, f.e. + * `a x #1 #3`. + */ +export type SupportStatus = 'n' | 'p' | 'u' | "a x" | 'a' | "y x" | 'y' | string; + +/** + * Provides information about the Agent. + */ +export interface Agent { + /** + * Global agent usage by version + */ + usage_global: UsageByVersion; + + /** + * The agents vendor prefix + */ + prefix: string; + + /** + * Version matrix. See [caniuse](https://caniuse.com) + */ + versions: [ // Tuple of 70 version slots: + string|null, string|null, string|null, string|null, string|null, + string|null, string|null, string|null, string|null, string|null, + string|null, string|null, string|null, string|null, string|null, + string|null, string|null, string|null, string|null, string|null, + string|null, string|null, string|null, string|null, string|null, + string|null, string|null, string|null, string|null, string|null, + string|null, string|null, string|null, string|null, string|null, + string|null, string|null, string|null, string|null, string|null, + string|null, string|null, string|null, string|null, string|null, + string|null, string|null, string|null, string|null, string|null, + string|null, string|null, string|null, string|null, string|null, + string|null, string|null, string|null, string|null, string|null, + string|null, string|null, string|null, string|null, string|null, + string|null, string|null, string|null, string|null, string|null ]; + + /** + * The agent's name + */ + browser: string; + + /** + * Release dates as seconds since epoch by version. + */ + release_date: { [version: string]: number | undefined }; + + /** + * Exceptions to vendor prefix use. + */ + prefix_exceptions?: { [version: string]: string | undefined }; +} + +/** + * Specifies a feature and its support status in all known agent versions. + */ +export interface Feature { + /** + * Specification status of the feature. + */ + status: FeatureStatus; + + /** + * Descriptive title of the feature. + */ + title: string; + + /** + * Agent support matrix for this feature. + */ + stats: StatsByAgentID; +} + +/** + * A space optimized version of Feature that can be unpacked using `feature(PackedFeature)`. + */ +export interface PackedFeature { + [encodedKey: string]: any; +} + +/** + * A space optimized version of Region that can be unpacked using `region(PackedFeature)`. + */ +export interface PackedRegion { + [encodedKey: string]: any; +} diff --git a/types/caniuse-lite/tsconfig.json b/types/caniuse-lite/tsconfig.json new file mode 100644 index 0000000000..adcea4d555 --- /dev/null +++ b/types/caniuse-lite/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "caniuse-lite-tests.ts" + ] +} diff --git a/types/caniuse-lite/tslint.json b/types/caniuse-lite/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/caniuse-lite/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/cfn-response/cfn-response-tests.ts b/types/cfn-response/cfn-response-tests.ts new file mode 100644 index 0000000000..b9633c17aa --- /dev/null +++ b/types/cfn-response/cfn-response-tests.ts @@ -0,0 +1,12 @@ +import * as cfn from "cfn-response"; +import { CloudFormationCustomResourceEvent, Context } from "aws-lambda"; + +declare const event: CloudFormationCustomResourceEvent; +declare const context: Context; + +// $ExpectType void +cfn.send(event, context, cfn.SUCCESS, { sample: 123 }, "abc"); +// $ExpectType void +cfn.send(event, context, "SUCCESS"); +// $ExpectError +cfn.send(event, context, "", {}); diff --git a/types/cfn-response/index.d.ts b/types/cfn-response/index.d.ts new file mode 100644 index 0000000000..54cb63dfef --- /dev/null +++ b/types/cfn-response/index.d.ts @@ -0,0 +1,19 @@ +// Type definitions for cfn-response 1.0 +// Project: https://github.com/LukeMizuhashi/cfn-response +// Definitions by: Ivo Murrell +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import { CloudFormationCustomResourceEvent, Context } from "aws-lambda"; + +export type ResponseStatus = "SUCCESS" | "FAILED"; +export const SUCCESS: ResponseStatus; +export const FAILED: ResponseStatus; + +export function send( + event: CloudFormationCustomResourceEvent, + context: Context, + responseStatus: ResponseStatus, + responseData?: object, + physicalResourceId?: string +): void; diff --git a/types/cfn-response/tsconfig.json b/types/cfn-response/tsconfig.json new file mode 100644 index 0000000000..0aff9f9071 --- /dev/null +++ b/types/cfn-response/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "cfn-response-tests.ts" + ] +} diff --git a/types/cfn-response/tslint.json b/types/cfn-response/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/cfn-response/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/chart.js/chart.js-tests.ts b/types/chart.js/chart.js-tests.ts index 705392baed..fd5ed53e80 100644 --- a/types/chart.js/chart.js-tests.ts +++ b/types/chart.js/chart.js-tests.ts @@ -9,7 +9,9 @@ const plugin = { } }; -const chart: Chart = new Chart(new CanvasRenderingContext2D(), { +const ctx = new CanvasRenderingContext2D(); + +const chart: Chart = new Chart(ctx, { type: "bar", plugins: [plugin, plugin], data: { @@ -17,6 +19,8 @@ const chart: Chart = new Chart(new CanvasRenderingContext2D(), { datasets: [ { backgroundColor: "#000000", + hoverBackgroundColor: ctx.createLinearGradient(0, 0, 0, 100), + hoverBorderColor: ctx.createLinearGradient(0, 0, 0, 100), borderWidth: 1, label: "test", data: [1, null, 3] diff --git a/types/chart.js/index.d.ts b/types/chart.js/index.d.ts index 884ddaa760..2803def896 100644 --- a/types/chart.js/index.d.ts +++ b/types/chart.js/index.d.ts @@ -554,8 +554,8 @@ declare namespace Chart { borderSkipped?: PositionType; data?: Array | ChartPoint[]; fill?: boolean | number | string; - hoverBackgroundColor?: string | string[]; - hoverBorderColor?: string | string[]; + hoverBackgroundColor?: ChartColor | ChartColor[]; + hoverBorderColor?: ChartColor | ChartColor[]; hoverBorderWidth?: number | number[]; label?: string; lineTension?: number; diff --git a/types/chromecast-caf-receiver/cast.framework.breaks.d.ts b/types/chromecast-caf-receiver/cast.framework.breaks.d.ts index 21adf13fb0..bce1d6b71d 100644 --- a/types/chromecast-caf-receiver/cast.framework.breaks.d.ts +++ b/types/chromecast-caf-receiver/cast.framework.breaks.d.ts @@ -1,92 +1,89 @@ import { Break, BreakClip } from "./cast.framework.messages"; -export = cast.framework.breaks; +export as namespace breaks +export class BreakSeekData { + constructor(seekFrom: number, seekTo: number, breaks: Break[]); -declare namespace cast.framework.breaks { - class BreakSeekData { - constructor(seekFrom: number, seekTo: number, breaks: Break[]); + /** + * List of breaks + */ + breaks: Break[]; - /** - * List of breaks - */ - breaks: Break[]; + /** + * Current playback time + */ + seekFrom: number; - /** - * Current playback time - */ - seekFrom: number; + /** + * The time to seek to + */ + seekTo: number; +} - /** - * The time to seek to - */ - seekTo: number; - } +/** Provide context information for break clip load interceptor. */ +export class BreakClipLoadInterceptorContext { + constructor(brk: Break); - /** Provide context information for break clip load interceptor. */ - class BreakClipLoadInterceptorContext { - constructor(brk: Break); + /** + * The container break for the break clip + */ + break: Break; +} - /** - * The container break for the break clip - */ - break: Break; - } +/** Interface to manage breaks */ +export interface BreakManager { + /** + * Get current media break by id. + */ + getBreakById(id: string): Break; - /** Interface to manage breaks */ - interface BreakManager { - /** - * Get current media break by id. - */ - getBreakById(id: string): Break; + /** + * Get current media break clip by id + */ + getBreakClipById(id: string): BreakClip; - /** - * Get current media break clip by id - */ - getBreakClipById(id: string): BreakClip; + /** Get current media break clips. */ + getBreakClips(): BreakClip[]; - /** Get current media break clips. */ - getBreakClips(): BreakClip[]; + /** Get current media breaks. */ + getBreaks(): Break[]; - /** Get current media breaks. */ - getBreaks(): Break[]; + /** Returns true if watched breaks should be played. */ + getPlayWatchedBreak(): boolean; - /** Returns true if watched breaks should be played. */ - getPlayWatchedBreak(): boolean; + /** + * Provide an interceptor to allow developer to insert more break clips or modify current break clip before a break is started. + * If interceptor is null it will reset the interceptor to default one. + * By default VAST fetching and parsing logic in default interceptor. + * So if customized interceptor is set by developer; + * the VAST logic will be overridden and developers should implement their own VAST fetching and parsing logic in the provided interceptor. + */ + setBreakClipLoadInterceptor( + interceptor: ( + breakClip: BreakClip, + breakClipLoaderContext?: BreakClipLoadInterceptorContext + ) => void + ): void; - /** - * Provide an interceptor to allow developer to insert more break clips or modify current break clip before a break is started. - * If interceptor is null it will reset the interceptor to default one. - * By default VAST fetching and parsing logic in default interceptor. - * So if customized interceptor is set by developer; - * the VAST logic will be overridden and developers should implement their own VAST fetching and parsing logic in the provided interceptor. - */ - setBreakClipLoadInterceptor( - interceptor: ( - breakClip: BreakClip, - breakClipLoaderContext?: BreakClipLoadInterceptorContext - ) => void - ): void; + /** + * Provide an interceptor for developer to specify what breaks they want to play after seek. + */ + setBreakSeekInterceptor( + seekInterceptor: (breakSeekData: BreakSeekData) => void + ): void; - /** - * Provide an interceptor for developer to specify what breaks they want to play after seek. - */ - setBreakSeekInterceptor( - seekInterceptor: (breakSeekData: BreakSeekData) => void - ): void; + /** + * Set a flag to control if the watched client stitching break should be played. + */ + setPlayWatchedBreak(playWatchedBreak: boolean): void; - /** - * Set a flag to control if the watched client stitching break should be played. - */ - setPlayWatchedBreak(playWatchedBreak: boolean): void; - - /** - * Provide an interceptor to modify VAST tracking URL before it is being sent to server. - * The input of the interceptor is a string of the tracking URL. - * The interceptor can either return a modified string of URL or a Promise of modified string of URL. - * The interceptor can also return null if you want to send the tracking URL by your own code instead of by CAF. - */ - setVastTrackingInterceptor( - interceptor?: (trackingUrl: string) => void - ): void; - } + /** + * Provide an interceptor to modify VAST tracking URL before it is being sent to server. + * The input of the interceptor is a string of the tracking URL. + * The interceptor can either return a modified string of URL or a Promise of modified string of URL. + * The interceptor can also return null if you want to send the tracking URL by your own code instead of by CAF. + */ + setVastTrackingInterceptor( + interceptor?: (trackingUrl: string) => void + ): void; } diff --git a/types/chromecast-caf-receiver/cast.framework.d.ts b/types/chromecast-caf-receiver/cast.framework.d.ts index 28b0c69e2d..13d2e52ce0 100644 --- a/types/chromecast-caf-receiver/cast.framework.d.ts +++ b/types/chromecast-caf-receiver/cast.framework.d.ts @@ -1,783 +1,764 @@ -import { EventType } from "./cast.framework.events"; -import { - PlayerState, - PlayStringId, - ErrorType, - ErrorReason, - IdleReason, - MessageType, - Track, - TextTrackStyle, - QueueItem, - LoadRequestData, - QueueData, - Break, - LiveSeekableRange, - MediaInformation, - ErrorData, - RequestData -} from "./cast.framework.messages"; -import { BreakManager } from "./cast.framework.breaks"; -import { EventHandler, RequestHandler, BinaryHandler } from "./index"; -import { - EventType as SystemEventType, - ApplicationData, - Sender, - StandbyState, - SystemState -} from "./cast.framework.system"; +import * as breaks from "./cast.framework.breaks"; +import * as events from "./cast.framework.events"; +import * as messages from "./cast.framework.messages"; +import * as system from "./cast.framework.system"; +import * as ui from "./cast.framework.ui"; -export = cast.framework; -type HTMLMediaElement = any; -declare namespace cast.framework { - type LoggerLevel = - | "DEBUG" - | "VERBOSE" - | "INFO" - | "WARNING" - | "ERROR" - | "NONE"; +export import breaks = breaks; +export import events = events; +export import ui = ui; +export import system = system; +export import messages = messages; - type ContentProtection = "NONE" | "CLEARKEY" | "PLAYREADY" | "WIDEVINE"; +export type HTMLMediaElement = any; +export as namespace framework +export type LoggerLevel = + | "DEBUG" + | "VERBOSE" + | "INFO" + | "WARNING" + | "ERROR" + | "NONE"; + +export type ContentProtection = "NONE" | "CLEARKEY" | "PLAYREADY" | "WIDEVINE"; + +/** + * Manages text tracks. + */ +export class TextTracksManager { + constructor(params?: any); /** - * Manages text tracks. + * Adds text tracks to the list. */ - class TextTracksManager { - constructor(params?: any); - - /** - * Adds text tracks to the list. - */ - addTracks(tracks: Track[]): void; - - /** - * Creates a text track. - */ - createTrack(): Track; - - /** - * Gets all active text ids. - */ - getActiveIds(): number[]; - - /** - * Gets all active text tracks. - */ - getActiveTracks(): Track[]; - - /** - * Returns the current text track style. - */ - getTextTracksStyle(): TextTrackStyle; - - /** - * Gets text track by id. - */ - getTrackById(id: number): Track; - - /** - * Returns all text tracks. - */ - getTracks(): Track[]; - - /** - * Gets text tracks by language. - */ - getTracksByLanguage(language: string): Track[]; - - /** - * Sets text tracks to be active by id. - */ - setActiveByIds(newIds: number[]): void; - - /** - * Sets text tracks to be active by language. - */ - setActiveByLanguage(language: string): void; - - /** - * Sets text track style. - */ - setTextTrackStyle(style: TextTrackStyle): void; - } + addTracks(tracks: messages.Track[]): void; /** - * QueueManager exposes several queue manipulation APIs to developers. + * Creates a text track. */ - class QueueManager { - constructor(params?: any); - - /** - * Returns the current queue item. - */ - getCurrentItem(): QueueItem; - - /** - * Returns the index of the current queue item. - */ - getCurrentItemIndex(): number; - - /** - * Returns the queue items. - */ - getItems(): QueueItem[]; - - /** - * Inserts items into the queue. - */ - insertItems(items: QueueItem[], insertBefore?: number): void; - - /** - * Removes items from the queue. - */ - removeItems(itemIds: number[]): void; - - /** - * Sets whether to limit the number of queue items to be reported in Media Status (default is true). - */ - setQueueStatusLimit(limitQueueItemsInStatus: boolean): void; - - /** - * Updates existing queue items by matching itemId. - */ - updateItems(items: QueueItem[]): void; - } + createTrack(): messages.Track; /** - * Base implementation of a queue. + * Gets all active text ids. */ - class QueueBase { - /** - * Fetches a window of items using the specified item id as reference; called by the receiver MediaManager when it needs more queue items; - * often as a request from senders. If only one of nextCount and prevCount is non-zero; fetchItems should only return items after or before - * the reference item; if both nextCount and prevCount are non-zero; a window of items including the reference item should be returned. - */ - fetchItems( - itemId: number, - nextCount: number, - prevCount: number - ): QueueItem[] | Promise; - - /** - * Initializes the queue with the requestData. This is called when a new LOAD request comes in to the receiver. - * If this returns or resolves to null; our default queueing implementation will create a queue based on queueData.items or the single media - * in the load request data. - */ - initialize( - requestData: LoadRequestData - ): QueueData | Promise; - - /** - * Returns next items after the reference item; often the end of the current queue; called by the receiver MediaManager. - */ - nextItems(itemId?: number): QueueItem[] | Promise; - - /** - * Sets the current item with the itemId; called by the receiver MediaManager when it changes the current playing item. - */ - onCurrentItemIdChanged(itemId: number): void; - - /** - * A callback for informing the following items have been inserted into the receiver queue in this session. - * A cloud based implementation can optionally choose to update its queue based on the new information. - */ - onItemsInserted(items: QueueItem[], insertBefore?: number): void; - - /** - * A callback for informing the following items have been removed from the receiver queue in this session. - * A cloud based implementation can optionally choose to update its queue based on the new information. - */ - onItemsRemoved(itemIds: number[]): void; - - /** - * Returns previous items before the reference item; often at the beginning of the queue; called by the receiver MediaManager. - */ - prevItems(itemId?: number): QueueItem[] | Promise; - - /** - * Shuffles the queue and returns new queue items. Returns null if the operation is not supported. - */ - shuffle(): QueueItem[] | Promise; - } + getActiveIds(): number[]; /** - * Controls and monitors media playback. + * Gets all active text tracks. */ - class PlayerManager { - constructor(params?: any); - - /** - * Adds an event listener for player event. - */ - addEventListener: ( - eventType: EventType | EventType[], - eventListener: EventHandler - ) => void; - - /** - * Sends a media status message to all senders (broadcast). Applications use this to send a custom state change. - */ - broadcastStatus( - includeMedia?: boolean, - requestId?: number, - customData?: any, - includeQueueItems?: boolean - ): void; - - getAudioTracksManager(): AudioTracksManager; - - /** - * Returns current time in sec in currently-playing break clip. - */ - getBreakClipCurrentTimeSec(): number; - - /** - * Returns duration in sec of currently-playing break clip. - */ - getBreakClipDurationSec(): number; - - /** - * Obtain the breaks (Ads) manager. - */ - getBreakManager(): BreakManager; - - /** - * Returns list of breaks. - */ - getBreaks(): Break[]; - - /** - * Gets current time in sec of current media. - */ - getCurrentTimeSec(): number; - - /** - * Gets duration in sec of currently playing media. - */ - getDurationSec(): number; - - /** - * Returns live seekable range with start and end time in seconds. The values are media time based. - */ - getLiveSeekableRange(): LiveSeekableRange; - - /** - * Gets media information of current media. - */ - getMediaInformation(): MediaInformation; - - /** - * Returns playback configuration. - */ - getPlaybackConfig(): PlaybackConfig; - - /** - * Returns current playback rate. - */ - getPlaybackRate(): number; - - /** - * Gets player state. - */ - getPlayerState(): PlayerState; - - /** - * Get the preferred playback rate. (Can be used on shutdown event to save latest preferred playback rate to a persistent storage; - * so it can be used in next session in the cast options). - */ - getPreferredPlaybackRate(): number; - - /** - * Get the preferred text track language. - */ - getPreferredTextLanguage(): string; - - /** - * Obtain QueueManager API. - */ - getQueueManager(): QueueManager; - - getTextTracksManager(): TextTracksManager; - - /** - * Loads media. - */ - load(loadRequest: LoadRequestData): Promise; - - /** - * Pauses currently playing media. - */ - pause(): void; - - /** - * Plays currently paused media. - */ - play(): void; - - /** - * Requests a text string to be played back locally on the receiver device. - */ - playString(stringId: PlayStringId, args?: string[]): Promise; - - /** - * Request Google Assistant to refresh the credentials. Only works if the original credentials came from the assistant. - */ - refreshCredentials(): Promise; - - /** - * Removes the event listener added for given player event. If event listener is not added; it will be ignored. - */ - removeEventListener( - eventType: EventType | EventType[], - eventListener: EventHandler - ): void; - - /** - * Seeks in current media. - */ - seek(seekTime: number): void; - - /** - * Sends an error to a specific sender - */ - sendError( - senderId: string, - requestId: number, - type: ErrorType, - reason?: ErrorReason, - customData?: any - ): void; - - /** - * Send local media request. - */ - sendLocalMediaRequest(request: RequestData): void; - - /** - * Sends a media status message to a specific sender. - */ - sendStatus( - senderId: string, - requestId: number, - includeMedia?: boolean, - customData?: any, - includeQueueItems?: boolean - ): void; - - /** - * Sets the IDLE reason. This allows applications that want to force the IDLE state to indicate the reason that made the player going to IDLE state - * (a custom error; for example). The idle reason will be sent in the next status message. NOTE: Most applications do not need to set this value; - * it is only needed if they want to make the player go to IDLE in special circumstances and the default idleReason does not reflect their intended - * behavior. - */ - setIdleReason(idleReason: IdleReason): void; - - /** - * Sets MediaElement to use. If Promise of MediaElement is set; media begins playback after Promise is resolved. - */ - setMediaElement(mediaElement: HTMLMediaElement): void; - - /** - * Sets media information. - */ - setMediaInformation( - mediaInformation: MediaInformation, - opt_broadcast?: boolean - ): void; - - /** - * Sets a handler to return or modify PlaybackConfig; for a specific load request. The handler paramaters are the load request data - * and default playback config for the receiver (provided in the context options). The handler should returns a modified playback config; - * or null to prevent the media from playing. The return value can be a promise to allow waiting for data from the server. - */ - setMediaPlaybackInfoHandler( - handler: ( - loadRequestData: LoadRequestData, - playbackConfig: PlaybackConfig - ) => void - ): void; - - /** - * Sets a handler to return the media url for a load request. This handler can be used to avoid having the media content url published as part - * of the media status. By default the media contentId is used as the content url. - */ - setMediaUrlResolver( - resolver: (loadRequestData: LoadRequestData) => void - ): void; - - /** - * Provide an interceptor of incoming and outgoing messages. - * The interceptor can update the request data; and return updated data; a promise of - * updated data if need to get more data from the server; or null if the request should not be handled. - * Note that if load message interceptor is provided; and no interceptor is provided for preload - - * the load interceptor will be called for preload messages. - */ - setMessageInterceptor( - type: MessageType, - interceptor: (requestData: RequestData) => Promise - ): void; - - /** - * Sets playback configuration on the PlayerManager. - */ - setPlaybackConfig(playbackConfig: PlaybackConfig): void; - - /** - * Set the preferred playback rate for follow up load or media items. The preferred playback rate will be updated automatically to the latest - * playback rate that was provided by a load request or explicit set of playback rate. - */ - setPreferredPlaybackRate(preferredPlaybackRate: number): void; - - /** - * Set the preferred text track language. The preferred text track language will be updated automatically to the latest enabled language - * by a load request or explicit change to text tracks. (Should be called only in idle state; and Will only apply to next loaded media). - */ - setPreferredTextLanguage(preferredTextLanguage: string): void; - - /** - * Stops currently playing media. - */ - stop(): void; - } + getActiveTracks(): messages.Track[]; /** - * Configuration to customize playback behavior. + * Returns the current text track style. */ - class PlaybackConfig { - /** - * Duration of buffered media in seconds to start buffering. - */ - autoPauseDuration?: number; + getTextTracksStyle(): messages.TextTrackStyle; - /** - * Duration of buffered media in seconds to start/resume playback after auto-paused due to buffering. - */ - autoResumeDuration?: number; - - /** - * Minimum number of buffered segments to start/resume playback. - */ - autoResumeNumberOfSegments?: number; - - /** - * A function to customize request to get a caption segment. - */ - captionsRequestHandler?: RequestHandler; - - /** - * Initial bandwidth in bits in per second. - */ - initialBandwidth?: number; - - /** - * Custom license data. - */ - licenseCustomData?: string; - - /** - * Handler to process license data. The handler is passed the license data; and returns the modified license data. - */ - licenseHandler?: BinaryHandler; - - /** - * A function to customize request to get a license. - */ - licenseRequestHandler?: RequestHandler; - - /** - * Url for acquiring the license. - */ - licenseUrl?: string; - - /** - * Handler to process manifest data. The handler is passed the manifest; and returns the modified manifest. - */ - manifestHandler?: (manifest: string) => string; - - /** - * A function to customize request to get a manifest. - */ - manifestRequestHandler?: RequestHandler; - - /** - * Preferred protection system to use for decrypting content. - */ - protectionSystem: ContentProtection; - - /** - * Handler to process segment data. The handler is passed the segment data; and returns the modified segment data. - */ - segmentHandler?: BinaryHandler; - - /** - * A function to customize request information to get a media segment. - */ - segmentRequestHandler?: RequestHandler; - - /** - * Maximum number of times to retry a network request for a segment. - */ - segmentRequestRetryLimit?: number; - } /** - * HTTP(s) Request/Response information. + * Gets text track by id. */ - class NetworkRequestInfo { - /** - * The content of the request. Can be used to modify license request body. - */ - content: Uint8Array; + getTrackById(id: number): messages.Track; - /** - * An object containing properties that you would like to send in the header. - */ - headers: any; + /** + * Returns all text tracks. + */ + getTracks(): messages.Track[]; - /** - * The URL requested. - */ - url: string; + /** + * Gets text tracks by language. + */ + getTracksByLanguage(language: string): messages.Track[]; - /** - * Indicates whether CORS Access-Control requests should be made using credentials such as cookies or authorization headers. - */ - withCredentials: boolean; - } - /** Cast receiver context options. All options are optionals. */ - class CastReceiverOptions { - /** - * Optional map of custom messages namespaces to initialize and their types. - * Custom messages namespaces need to be initiated before the application started; - * so it is best to provide the namespaces in the receiver options. - * (The default type of a message bus is JSON; if not provided here). - */ - customNamespaces?: any; + /** + * Sets text tracks to be active by id. + */ + setActiveByIds(newIds: number[]): void; - /** - * Sender id used for local requests. Default value is 'local'. - */ - localSenderId?: string; + /** + * Sets text tracks to be active by language. + */ + setActiveByLanguage(language: string): void; - /** - * Maximum time in seconds before closing an idle sender connection. - * Setting this value enables a heartbeat message to keep the connection alive. - * Used to detect unresponsive senders faster than typical TCP timeouts. - * The minimum value is 5 seconds; there is no upper bound enforced but practically it's minutes before platform TCP timeouts come into play. - * Default value is 10 seconds. - */ - maxInactivity?: number; - - /** - * Optional media element to play content with. Default behavior is to use the first found media element in the page. - */ - mediaElement?: HTMLMediaElement; - - /** - * Optional playback configuration. - */ - playbackConfig?: PlaybackConfig; - - /** - * If this is true; the watched client stitching break will also be played. - */ - playWatchedBreak?: boolean; - - /** - * Preferred value for player playback rate. It is used if playback rate value is not provided in the load request. - */ - preferredPlaybackRate?: number; - - /** - * Preferred text track language. It is used if no active track is provided in the load request. - */ - preferredTextLanguage?: string; - - /** - * Optional queue implementation. - */ - queue?: QueueBase; - - /** - * Text that represents the application status. - * It should meet internationalization rules as may be displayed by the sender application. - */ - statusText?: string; - - /** - * A bitmask of media commands supported by the application. - * LOAD; PLAY; STOP; GET_STATUS must always be supported. - * If this value is not provided; then PAUSE; SEEK; STREAM_VOLUME; STREAM_MUTE are assumed to be supported too. - */ - supportedCommands?: number; - - /** - * Indicate that MPL should be used for DASH content. - */ - useLegacyDashSupport?: boolean; - - /** - * An integer used as an internal version number. - * This number is used only to distinguish between receiver releases and higher numbers do not necessarily have to represent newer releases. - */ - versionCode?: number; - } - - /** Manages loading of underlying libraries and initializes underlying cast receiver SDK. */ - class CastReceiverContext { - /** Returns the CastReceiverContext singleton instance. */ - static getInstance(): CastReceiverContext; - - constructor(params: any); - - /** - * Sets message listener on custom message channel. - */ - addCustomMessageListener( - namespace: string, - listener: EventHandler - ): void; - - /** - * Add listener to cast system events. - */ - addEventListener( - type: SystemEventType | SystemEventType[], - handler: EventHandler - ): void; - - /** - * Checks if the given media params of video or audio streams are supported by the platform. - */ - canDisplayType( - mimeType: string, - codecs?: string, - width?: number, - height?: number, - framerate?: number - ): boolean; - - /** - * Provides application information once the system is ready; otherwise it will be null. - */ - getApplicationData(): ApplicationData; - - /** - * Provides device capabilities information once the system is ready; otherwise it will be null. - * If an empty object is returned; the device does not expose any capabilities information. - */ - getDeviceCapabilities(): any; - - /** - * Get Player instance that can control and monitor media playback. - */ - getPlayerManager(): PlayerManager; - - /** - * Get a sender by sender id - */ - getSender(senderId: string): Sender; - - /** - * Gets a list of currently-connected senders. - */ - getSenders(): Sender[]; - - /** - * Reports if the cast application's HDMI input is in standby. - */ - getStandbyState(): StandbyState; - - /** - * Provides application information about the system state. - */ - getSystemState(): SystemState; - - /** - * Reports if the cast application is the HDMI active input. - */ - getVisibilityState(): any; - - /** - * When the application calls start; the system will send the ready event to indicate - * that the application information is ready and the application can send messages as soon as there is one sender connected. - */ - isSystemReady(): boolean; - - /** - * Start loading player js. This can be used to start loading the players js code in early stage of starting the receiver before calling start. - * This function is a no-op if players were already loaded (start was called). - */ - loadPlayerLibraries(useLegacyDashSupport?: boolean): void; - - /** - * Remove a message listener on custom message channel. - */ - removeCustomMessageListener( - namespace: string, - listener: EventHandler - ): void; - - /** - * Remove listener to cast system events. - */ - removeEventListener(type: EventType, handler: EventHandler): void; - - /** - * Sends a message to a specific sender. - */ - sendCustomMessage( - namespace: string, - senderId: string, - message: any - ): void; - - /** - * This function should be called in response to the feedbackstarted event if the application - * add debug state information to log in the feedback report. - * It takes in a parameter ‘message’ that is a string that represents the debug information that the application wants to log. - */ - sendFeedbackMessage(feedbackMessage: string): void; - - /** - * Sets the application state. The application should call this when its state changes. - * If undefined or set to an empty string; the value of the Application Name established during application - * registration is used for the application state by default. - */ - setApplicationState(statusText: string): void; - - /** - * Sets the receiver inactivity timeout. - * It is recommended to set the maximum inactivity value when calling Start and not changing it. - * This API is just provided for development/debugging purposes. - */ - setInactivityTimeout(maxInactivity: number): void; - - /** - * Sets the log verbosity level. - */ - setLoggerLevel(level: LoggerLevel): void; - - /** - * Initializes system manager and media manager; so that receiver app can receive requests from senders. - */ - start(options?: CastReceiverOptions): CastReceiverContext; - - /** - * Shutdown receiver application. - */ - stop(): void; - } - - /** Manages audio tracks. */ - class AudioTracksManager { - constructor(params: any); - getActiveId(): number; - getActiveTrack(): Track; - getTrackById(id: number): Track; - getTracks(): Track[]; - getTracksByLanguage(language: string): Track[]; - setActiveById(id: number): void; - setActiveByLanguage(language: string): void; - } + /** + * Sets text track style. + */ + setTextTrackStyle(style: messages.TextTrackStyle): void; +} + +/** + * QueueManager exposes several queue manipulation APIs to developers. + */ +export class QueueManager { + constructor(params?: any); + + /** + * Returns the current queue item. + */ + getCurrentItem(): messages.QueueItem; + + /** + * Returns the index of the current queue item. + */ + getCurrentItemIndex(): number; + + /** + * Returns the queue items. + */ + getItems(): messages.QueueItem[]; + + /** + * Inserts items into the queue. + */ + insertItems(items: messages.QueueItem[], insertBefore?: number): void; + + /** + * Removes items from the queue. + */ + removeItems(itemIds: number[]): void; + + /** + * Sets whether to limit the number of queue items to be reported in Media Status (default is true). + */ + setQueueStatusLimit(limitQueueItemsInStatus: boolean): void; + + /** + * Updates existing queue items by matching itemId. + */ + updateItems(items: messages.QueueItem[]): void; +} + +/** + * Base implementation of a queue. + */ +export class QueueBase { + /** + * Fetches a window of items using the specified item id as reference; called by the receiver MediaManager when it needs more queue items; + * often as a request from senders. If only one of nextCount and prevCount is non-zero; fetchItems should only return items after or before + * the reference item; if both nextCount and prevCount are non-zero; a window of items including the reference item should be returned. + */ + fetchItems( + itemId: number, + nextCount: number, + prevCount: number + ): messages.QueueItem[] | Promise; + + /** + * Initializes the queue with the requestData. This is called when a new LOAD request comes in to the receiver. + * If this returns or resolves to null; our default queueing implementation will create a queue based on queueData.items or the single media + * in the load request data. + */ + initialize( + requestData: messages.LoadRequestData + ): messages.QueueData | Promise; + + /** + * Returns next items after the reference item; often the end of the current queue; called by the receiver MediaManager. + */ + nextItems(itemId?: number): messages.QueueItem[] | Promise; + + /** + * Sets the current item with the itemId; called by the receiver MediaManager when it changes the current playing item. + */ + onCurrentItemIdChanged(itemId: number): void; + + /** + * A callback for informing the following items have been inserted into the receiver queue in this session. + * A cloud based implementation can optionally choose to update its queue based on the new information. + */ + onItemsInserted(items: messages.QueueItem[], insertBefore?: number): void; + + /** + * A callback for informing the following items have been removed from the receiver queue in this session. + * A cloud based implementation can optionally choose to update its queue based on the new information. + */ + onItemsRemoved(itemIds: number[]): void; + + /** + * Returns previous items before the reference item; often at the beginning of the queue; called by the receiver MediaManager. + */ + prevItems(itemId?: number): messages.QueueItem[] | Promise; + + /** + * Shuffles the queue and returns new queue items. Returns null if the operation is not supported. + */ + shuffle(): messages.QueueItem[] | Promise; +} + +/** + * Controls and monitors media playback. + */ +export class PlayerManager { + constructor(params?: any); + + /** + * Adds an event listener for player event. + */ + addEventListener: ( + eventType: events.EventType | events.EventType[], + eventListener: EventHandler + ) => void; + + /** + * Sends a media status message to all senders (broadcast). Applications use this to send a custom state change. + */ + broadcastStatus( + includeMedia?: boolean, + requestId?: number, + customData?: any, + includeQueueItems?: boolean + ): void; + + getAudioTracksManager(): AudioTracksManager; + + /** + * Returns current time in sec in currently-playing break clip. + */ + getBreakClipCurrentTimeSec(): number; + + /** + * Returns duration in sec of currently-playing break clip. + */ + getBreakClipDurationSec(): number; + + /** + * Obtain the breaks (Ads) manager. + */ + getBreakManager(): breaks.BreakManager; + + /** + * Returns list of breaks. + */ + getBreaks(): messages.Break[]; + + /** + * Gets current time in sec of current media. + */ + getCurrentTimeSec(): number; + + /** + * Gets duration in sec of currently playing media. + */ + getDurationSec(): number; + + /** + * Returns live seekable range with start and end time in seconds. The values are media time based. + */ + getLiveSeekableRange(): messages.LiveSeekableRange; + + /** + * Gets media information of current media. + */ + getMediaInformation(): messages.MediaInformation; + + /** + * Returns playback configuration. + */ + getPlaybackConfig(): PlaybackConfig; + + /** + * Returns current playback rate. + */ + getPlaybackRate(): number; + + /** + * Gets player state. + */ + getPlayerState(): messages.PlayerState; + + /** + * Get the preferred playback rate. (Can be used on shutdown event to save latest preferred playback rate to a persistent storage; + * so it can be used in next session in the cast options). + */ + getPreferredPlaybackRate(): number; + + /** + * Get the preferred text track language. + */ + getPreferredTextLanguage(): string; + + /** + * Obtain QueueManager API. + */ + getQueueManager(): QueueManager; + + getTextTracksManager(): TextTracksManager; + + /** + * Loads media. + */ + load(loadRequest: messages.LoadRequestData): Promise; + + /** + * Pauses currently playing media. + */ + pause(): void; + + /** + * Plays currently paused media. + */ + play(): void; + + /** + * Requests a text string to be played back locally on the receiver device. + */ + playString(stringId: messages.PlayStringId, args?: string[]): Promise; + + /** + * Request Google Assistant to refresh the credentials. Only works if the original credentials came from the assistant. + */ + refreshCredentials(): Promise; + + /** + * Removes the event listener added for given player event. If event listener is not added; it will be ignored. + */ + removeEventListener( + eventType: events.EventType | events.EventType[], + eventListener: EventHandler + ): void; + + /** + * Seeks in current media. + */ + seek(seekTime: number): void; + + /** + * Sends an error to a specific sender + */ + sendError( + senderId: string, + requestId: number, + type: messages.ErrorType, + reason?: messages.ErrorReason, + customData?: any + ): void; + + /** + * Send local media request. + */ + sendLocalMediaRequest(request: messages.RequestData): void; + + /** + * Sends a media status message to a specific sender. + */ + sendStatus( + senderId: string, + requestId: number, + includeMedia?: boolean, + customData?: any, + includeQueueItems?: boolean + ): void; + + /** + * Sets the IDLE reason. This allows applications that want to force the IDLE state to indicate the reason that made the player going to IDLE state + * (a custom error; for example). The idle reason will be sent in the next status message. NOTE: Most applications do not need to set this value; + * it is only needed if they want to make the player go to IDLE in special circumstances and the default idleReason does not reflect their intended + * behavior. + */ + setIdleReason(idleReason: messages.IdleReason): void; + + /** + * Sets MediaElement to use. If Promise of MediaElement is set; media begins playback after Promise is resolved. + */ + setMediaElement(mediaElement: HTMLMediaElement): void; + + /** + * Sets media information. + */ + setMediaInformation( + mediaInformation: messages.MediaInformation, + opt_broadcast?: boolean + ): void; + + /** + * Sets a handler to return or modify PlaybackConfig; for a specific load request. The handler paramaters are the load request data + * and default playback config for the receiver (provided in the context options). The handler should returns a modified playback config; + * or null to prevent the media from playing. The return value can be a promise to allow waiting for data from the server. + */ + setMediaPlaybackInfoHandler( + handler: ( + loadRequestData: messages.LoadRequestData, + playbackConfig: PlaybackConfig + ) => void + ): void; + + /** + * Sets a handler to return the media url for a load request. This handler can be used to avoid having the media content url published as part + * of the media status. By default the media contentId is used as the content url. + */ + setMediaUrlResolver( + resolver: (loadRequestData: messages.LoadRequestData) => void + ): void; + + /** + * Provide an interceptor of incoming and outgoing messages. + * The interceptor can update the request data; and return updated data; a promise of + * updated data if need to get more data from the server; or null if the request should not be handled. + * Note that if load message interceptor is provided; and no interceptor is provided for preload - + * the load interceptor will be called for preload messages. + */ + setMessageInterceptor( + type: messages.MessageType, + interceptor: (requestData: messages.RequestData) => Promise + ): void; + + /** + * Sets playback configuration on the PlayerManager. + */ + setPlaybackConfig(playbackConfig: PlaybackConfig): void; + + /** + * Set the preferred playback rate for follow up load or media items. The preferred playback rate will be updated automatically to the latest + * playback rate that was provided by a load request or explicit set of playback rate. + */ + setPreferredPlaybackRate(preferredPlaybackRate: number): void; + + /** + * Set the preferred text track language. The preferred text track language will be updated automatically to the latest enabled language + * by a load request or explicit change to text tracks. (Should be called only in idle state; and Will only apply to next loaded media). + */ + setPreferredTextLanguage(preferredTextLanguage: string): void; + + /** + * Stops currently playing media. + */ + stop(): void; +} + +/** + * Configuration to customize playback behavior. + */ +export class PlaybackConfig { + /** + * Duration of buffered media in seconds to start buffering. + */ + autoPauseDuration?: number; + + /** + * Duration of buffered media in seconds to start/resume playback after auto-paused due to buffering. + */ + autoResumeDuration?: number; + + /** + * Minimum number of buffered segments to start/resume playback. + */ + autoResumeNumberOfSegments?: number; + + /** + * A function to customize request to get a caption segment. + */ + captionsRequestHandler?: RequestHandler; + + /** + * Initial bandwidth in bits in per second. + */ + initialBandwidth?: number; + + /** + * Custom license data. + */ + licenseCustomData?: string; + + /** + * Handler to process license data. The handler is passed the license data; and returns the modified license data. + */ + licenseHandler?: BinaryHandler; + + /** + * A function to customize request to get a license. + */ + licenseRequestHandler?: RequestHandler; + + /** + * Url for acquiring the license. + */ + licenseUrl?: string; + + /** + * Handler to process manifest data. The handler is passed the manifest; and returns the modified manifest. + */ + manifestHandler?: (manifest: string) => string; + + /** + * A function to customize request to get a manifest. + */ + manifestRequestHandler?: RequestHandler; + + /** + * Preferred protection system to use for decrypting content. + */ + protectionSystem: ContentProtection; + + /** + * Handler to process segment data. The handler is passed the segment data; and returns the modified segment data. + */ + segmentHandler?: BinaryHandler; + + /** + * A function to customize request information to get a media segment. + */ + segmentRequestHandler?: RequestHandler; + + /** + * Maximum number of times to retry a network request for a segment. + */ + segmentRequestRetryLimit?: number; +} +/** + * HTTP(s) Request/Response information. + */ +export class NetworkRequestInfo { + /** + * The content of the request. Can be used to modify license request body. + */ + content: Uint8Array; + + /** + * An object containing properties that you would like to send in the header. + */ + headers: any; + + /** + * The URL requested. + */ + url: string; + + /** + * Indicates whether CORS Access-Control requests should be made using credentials such as cookies or authorization headers. + */ + withCredentials: boolean; +} +/** Cast receiver context options. All options are optionals. */ +export class CastReceiverOptions { + /** + * Optional map of custom messages namespaces to initialize and their types. + * Custom messages namespaces need to be initiated before the application started; + * so it is best to provide the namespaces in the receiver options. + * (The default type of a message bus is JSON; if not provided here). + */ + customNamespaces?: any; + + /** + * Sender id used for local requests. Default value is 'local'. + */ + localSenderId?: string; + + /** + * Maximum time in seconds before closing an idle sender connection. + * Setting this value enables a heartbeat message to keep the connection alive. + * Used to detect unresponsive senders faster than typical TCP timeouts. + * The minimum value is 5 seconds; there is no upper bound enforced but practically it's minutes before platform TCP timeouts come into play. + * Default value is 10 seconds. + */ + maxInactivity?: number; + + /** + * Optional media element to play content with. Default behavior is to use the first found media element in the page. + */ + mediaElement?: HTMLMediaElement; + + /** + * Optional playback configuration. + */ + playbackConfig?: PlaybackConfig; + + /** + * If this is true; the watched client stitching break will also be played. + */ + playWatchedBreak?: boolean; + + /** + * Preferred value for player playback rate. It is used if playback rate value is not provided in the load request. + */ + preferredPlaybackRate?: number; + + /** + * Preferred text track language. It is used if no active track is provided in the load request. + */ + preferredTextLanguage?: string; + + /** + * Optional queue implementation. + */ + queue?: QueueBase; + + /** + * Text that represents the application status. + * It should meet internationalization rules as may be displayed by the sender application. + */ + statusText?: string; + + /** + * A bitmask of media commands supported by the application. + * LOAD; PLAY; STOP; GET_STATUS must always be supported. + * If this value is not provided; then PAUSE; SEEK; STREAM_VOLUME; STREAM_MUTE are assumed to be supported too. + */ + supportedCommands?: number; + + /** + * Indicate that MPL should be used for DASH content. + */ + useLegacyDashSupport?: boolean; + + /** + * An integer used as an internal version number. + * This number is used only to distinguish between receiver releases and higher numbers do not necessarily have to represent newer releases. + */ + versionCode?: number; +} + +/** Manages loading of underlying libraries and initializes underlying cast receiver SDK. */ +export class CastReceiverContext { + /** Returns the CastReceiverContext singleton instance. */ + static getInstance(): CastReceiverContext; + + constructor(params: any); + + /** + * Sets message listener on custom message channel. + */ + addCustomMessageListener( + namespace: string, + listener: EventHandler + ): void; + + /** + * Add listener to cast system events. + */ + addEventListener( + type: system.EventType | system.EventType[], + handler: EventHandler + ): void; + + /** + * Checks if the given media params of video or audio streams are supported by the platform. + */ + canDisplayType( + mimeType: string, + codecs?: string, + width?: number, + height?: number, + framerate?: number + ): boolean; + + /** + * Provides application information once the system is ready; otherwise it will be null. + */ + getApplicationData(): system.ApplicationData; + + /** + * Provides device capabilities information once the system is ready; otherwise it will be null. + * If an empty object is returned; the device does not expose any capabilities information. + */ + getDeviceCapabilities(): any; + + /** + * Get Player instance that can control and monitor media playback. + */ + getPlayerManager(): PlayerManager; + + /** + * Get a sender by sender id + */ + getSender(senderId: string): system.Sender; + + /** + * Gets a list of currently-connected senders. + */ + getSenders(): system.Sender[]; + + /** + * Reports if the cast application's HDMI input is in standby. + */ + getStandbyState(): system.StandbyState; + + /** + * Provides application information about the system state. + */ + getSystemState(): system.SystemState; + + /** + * Reports if the cast application is the HDMI active input. + */ + getVisibilityState(): any; + + /** + * When the application calls start; the system will send the ready event to indicate + * that the application information is ready and the application can send messages as soon as there is one sender connected. + */ + isSystemReady(): boolean; + + /** + * Start loading player js. This can be used to start loading the players js code in early stage of starting the receiver before calling start. + * This function is a no-op if players were already loaded (start was called). + */ + loadPlayerLibraries(useLegacyDashSupport?: boolean): void; + + /** + * Remove a message listener on custom message channel. + */ + removeCustomMessageListener( + namespace: string, + listener: EventHandler + ): void; + + /** + * Remove listener to cast system events. + */ + removeEventListener(type: system.EventType, handler: EventHandler): void; + + /** + * Sends a message to a specific sender. + */ + sendCustomMessage( + namespace: string, + senderId: string, + message: any + ): void; + + /** + * This function should be called in response to the feedbackstarted event if the application + * add debug state information to log in the feedback report. + * It takes in a parameter ‘message’ that is a string that represents the debug information that the application wants to log. + */ + sendFeedbackMessage(feedbackMessage: string): void; + + /** + * Sets the application state. The application should call this when its state changes. + * If undefined or set to an empty string; the value of the Application Name established during application + * registration is used for the application state by default. + */ + setApplicationState(statusText: string): void; + + /** + * Sets the receiver inactivity timeout. + * It is recommended to set the maximum inactivity value when calling Start and not changing it. + * This API is just provided for development/debugging purposes. + */ + setInactivityTimeout(maxInactivity: number): void; + + /** + * Sets the log verbosity level. + */ + setLoggerLevel(level: LoggerLevel): void; + + /** + * Initializes system manager and media manager; so that receiver app can receive requests from senders. + */ + start(options?: CastReceiverOptions): CastReceiverContext; + + /** + * Shutdown receiver application. + */ + stop(): void; +} + +/** Manages audio tracks. */ +export class AudioTracksManager { + constructor(params: any); + getActiveId(): number; + getActiveTrack(): messages.Track; + getTrackById(id: number): messages.Track; + getTracks(): messages.Track[]; + getTracksByLanguage(language: string): messages.Track[]; + setActiveById(id: number): void; + setActiveByLanguage(language: string): void; } diff --git a/types/chromecast-caf-receiver/cast.framework.events.d.ts b/types/chromecast-caf-receiver/cast.framework.events.d.ts index 03b70ca459..468ed98158 100644 --- a/types/chromecast-caf-receiver/cast.framework.events.d.ts +++ b/types/chromecast-caf-receiver/cast.framework.events.d.ts @@ -4,423 +4,421 @@ import { Track, MediaStatus } from "./cast.framework.messages"; -export = cast.framework.events; -declare namespace cast.framework.events { - type EventType = - | "ALL" - | "ABORT" - | "CAN_PLAY" - | "CAN_PLAY_THROUGH" - | "DURATION_CHANGE" - | "EMPTIED" - | "ENDED" - | "LOADED_DATA" - | "LOADED_METADATA" - | "LOAD_START" - | "PAUSE" - | "PLAY" - | "PLAYING" - | "PROGRESS" - | "RATE_CHANGE" - | "SEEKED" - | "SEEKING" - | "STALLED" - | "TIME_UPDATE" - | "SUSPEND" - | "WAITING" - | "BITRATE_CHANGED" - | "BREAK_STARTED" - | "BREAK_ENDED" - | "BREAK_CLIP_LOADING" - | "BREAK_CLIP_STARTED" - | "BREAK_CLIP_ENDED" - | "BUFFERING" - | "CACHE_LOADED" - | "CACHE_HIT" - | "CACHE_INSERTED" - | "CLIP_STARTED" - | "CLIP_ENDED" - | "EMSG" - | "ERROR" - | "ID3" - | "MEDIA_STATUS" - | "MEDIA_FINISHED" - | "PLAYER_PRELOADING" - | "PLAYER_PRELOADING_CANCELLED" - | "PLAYER_LOAD_COMPLETE" - | "PLAYER_LOADING" - | "SEGMENT_DOWNLOADED" - | "REQUEST_SEEK" - | "REQUEST_LOAD" - | "REQUEST_STOP" - | "REQUEST_PAUSE" - | "REQUEST_PLAY" - | "REQUEST_PLAY_AGAIN" - | "REQUEST_PLAYBACK_RATE_CHANGE" - | "REQUEST_SKIP_AD" - | "REQUEST_VOLUME_CHANGE" - | "REQUEST_EDIT_TRACKS_INFO" - | "REQUEST_EDIT_AUDIO_TRACKS" - | "REQUEST_SET_CREDENTIALS" - | "REQUEST_LOAD_BY_ENTITY" - | "REQUEST_USER_ACTION" - | "REQUEST_DISPLAY_STATUS" - | "REQUEST_CUSTOM_COMMAND" - | "REQUEST_FOCUS_STATE" - | "REQUEST_QUEUE_LOAD" - | "REQUEST_QUEUE_INSERT" - | "REQUEST_QUEUE_UPDATE" - | "REQUEST_QUEUE_REMOVE" - | "REQUEST_QUEUE_REORDER" - | "REQUEST_QUEUE_GET_ITEM_RANGE" - | "REQUEST_QUEUE_GET_ITEMS" - | "REQUEST_QUEUE_GET_ITEM_IDS" - | "REQUEST_PRECACHE"; +export as namespace events +export type EventType = + | "ALL" + | "ABORT" + | "CAN_PLAY" + | "CAN_PLAY_THROUGH" + | "DURATION_CHANGE" + | "EMPTIED" + | "ENDED" + | "LOADED_DATA" + | "LOADED_METADATA" + | "LOAD_START" + | "PAUSE" + | "PLAY" + | "PLAYING" + | "PROGRESS" + | "RATE_CHANGE" + | "SEEKED" + | "SEEKING" + | "STALLED" + | "TIME_UPDATE" + | "SUSPEND" + | "WAITING" + | "BITRATE_CHANGED" + | "BREAK_STARTED" + | "BREAK_ENDED" + | "BREAK_CLIP_LOADING" + | "BREAK_CLIP_STARTED" + | "BREAK_CLIP_ENDED" + | "BUFFERING" + | "CACHE_LOADED" + | "CACHE_HIT" + | "CACHE_INSERTED" + | "CLIP_STARTED" + | "CLIP_ENDED" + | "EMSG" + | "ERROR" + | "ID3" + | "MEDIA_STATUS" + | "MEDIA_FINISHED" + | "PLAYER_PRELOADING" + | "PLAYER_PRELOADING_CANCELLED" + | "PLAYER_LOAD_COMPLETE" + | "PLAYER_LOADING" + | "SEGMENT_DOWNLOADED" + | "REQUEST_SEEK" + | "REQUEST_LOAD" + | "REQUEST_STOP" + | "REQUEST_PAUSE" + | "REQUEST_PLAY" + | "REQUEST_PLAY_AGAIN" + | "REQUEST_PLAYBACK_RATE_CHANGE" + | "REQUEST_SKIP_AD" + | "REQUEST_VOLUME_CHANGE" + | "REQUEST_EDIT_TRACKS_INFO" + | "REQUEST_EDIT_AUDIO_TRACKS" + | "REQUEST_SET_CREDENTIALS" + | "REQUEST_LOAD_BY_ENTITY" + | "REQUEST_USER_ACTION" + | "REQUEST_DISPLAY_STATUS" + | "REQUEST_CUSTOM_COMMAND" + | "REQUEST_FOCUS_STATE" + | "REQUEST_QUEUE_LOAD" + | "REQUEST_QUEUE_INSERT" + | "REQUEST_QUEUE_UPDATE" + | "REQUEST_QUEUE_REMOVE" + | "REQUEST_QUEUE_REORDER" + | "REQUEST_QUEUE_GET_ITEM_RANGE" + | "REQUEST_QUEUE_GET_ITEMS" + | "REQUEST_QUEUE_GET_ITEM_IDS" + | "REQUEST_PRECACHE"; - type DetailedErrorCode = - | "MEDIA_UNKNOWN" - | "MEDIA_ABORTED" - | "MEDIA_DECODE" - | "MEDIA_NETWORK" - | "MEDIA_SRC_NOT_SUPPORTED" - | "SOURCE_BUFFER_FAILURE" - | "MEDIAKEYS_UNKNOWN" - | "MEDIAKEYS_NETWORK" - | "MEDIAKEYS_UNSUPPORTED" - | "MEDIAKEYS_WEBCRYPTO" - | "NETWORK_UNKNOWN" - | "SEGMENT_NETWORK" - | "HLS_NETWORK_MASTER_PLAYLIST" - | "HLS_NETWORK_PLAYLIST" - | "HLS_NETWORK_NO_KEY_RESPONSE" - | "HLS_NETWORK_KEY_LOAD" - | "HLS_NETWORK_INVALID_SEGMENT" - | "HLS_SEGMENT_PARSING" - | "DASH_NETWORK" - | "DASH_NO_INIT" - | "SMOOTH_NETWORK" - | "SMOOTH_NO_MEDIA_DATA" - | "MANIFEST_UNKNOWN" - | "HLS_MANIFEST_MASTER" - | "HLS_MANIFEST_PLAYLIST" - | "DASH_MANIFEST_UNKNOWN" - | "DASH_MANIFEST_NO_PERIODS" - | "DASH_MANIFEST_NO_MIMETYPE" - | "DASH_INVALID_SEGMENT_INFO" - | "SMOOTH_MANIFEST" - | "SEGMENT_UNKNOWN" - | "TEXT_UNKNOWN" - | "APP" - | "BREAK_CLIP_LOADING_ERROR" - | "BREAK_SEEK_INTERCEPTOR_ERROR" - | "IMAGE_ERROR" - | "LOAD_INTERRUPTED" - | "GENERIC"; +export type DetailedErrorCode = + | "MEDIA_UNKNOWN" + | "MEDIA_ABORTED" + | "MEDIA_DECODE" + | "MEDIA_NETWORK" + | "MEDIA_SRC_NOT_SUPPORTED" + | "SOURCE_BUFFER_FAILURE" + | "MEDIAKEYS_UNKNOWN" + | "MEDIAKEYS_NETWORK" + | "MEDIAKEYS_UNSUPPORTED" + | "MEDIAKEYS_WEBCRYPTO" + | "NETWORK_UNKNOWN" + | "SEGMENT_NETWORK" + | "HLS_NETWORK_MASTER_PLAYLIST" + | "HLS_NETWORK_PLAYLIST" + | "HLS_NETWORK_NO_KEY_RESPONSE" + | "HLS_NETWORK_KEY_LOAD" + | "HLS_NETWORK_INVALID_SEGMENT" + | "HLS_SEGMENT_PARSING" + | "DASH_NETWORK" + | "DASH_NO_INIT" + | "SMOOTH_NETWORK" + | "SMOOTH_NO_MEDIA_DATA" + | "MANIFEST_UNKNOWN" + | "HLS_MANIFEST_MASTER" + | "HLS_MANIFEST_PLAYLIST" + | "DASH_MANIFEST_UNKNOWN" + | "DASH_MANIFEST_NO_PERIODS" + | "DASH_MANIFEST_NO_MIMETYPE" + | "DASH_INVALID_SEGMENT_INFO" + | "SMOOTH_MANIFEST" + | "SEGMENT_UNKNOWN" + | "TEXT_UNKNOWN" + | "APP" + | "BREAK_CLIP_LOADING_ERROR" + | "BREAK_SEEK_INTERCEPTOR_ERROR" + | "IMAGE_ERROR" + | "LOAD_INTERRUPTED" + | "GENERIC"; - type EndedReason = - | "END_OF_STREAM" - | "ERROR" - | "STOPPED" - | "INTERRUPTED" - | "SKIPPED" - | "BREAK_SWITCH"; +export type EndedReason = + | "END_OF_STREAM" + | "ERROR" + | "STOPPED" + | "INTERRUPTED" + | "SKIPPED" + | "BREAK_SWITCH"; + +/** + * Event data for @see{@link EventType.SEGMENT_DOWNLOADED} event. + */ +export class SegmentDownloadedEvent extends Event { + constructor(downloadTime?: number, size?: number); /** - * Event data for @see{@link EventType.SEGMENT_DOWNLOADED} event. + * The time it took to download the segment; in milliseconds. */ - class SegmentDownloadedEvent extends Event { - constructor(downloadTime?: number, size?: number); - - /** - * The time it took to download the segment; in milliseconds. - */ - downloadTime?: number; - - /** - * The number of bytes in the segment. - */ - size?: number; - } + downloadTime?: number; /** - * Event data for all events that represent requests made to the receiver. + * The number of bytes in the segment. */ - class RequestEvent extends Event { - constructor( - type: EventType, - requestData?: RequestData, - senderId?: string - ); + size?: number; +} + +/** + * Event data for all events that represent requests made to the receiver. + */ +export class RequestEvent extends Event { + constructor( + type: EventType, + requestData?: RequestData, + senderId?: string + ); - /** - * The data that was sent with the request. - */ - requestData?: RequestData; + /** + * The data that was sent with the request. + */ + requestData?: RequestData; + + /** + * The sender id the request came from. + */ + senderId?: string; +} + +/** + * Event data superexport class for all events dispatched by @see{@link PlayerManager} + */ +export class Event { + constructor(type: EventType); + + /** + * Type of the event. + */ + type: EventType; +} +/** + * Event data for @see{@link EventType.MEDIA_STATUS} event. + */ +export class MediaStatusEvent extends Event { + constructor(type: EventType, mediaStatus?: MediaStatus); + + /** + * The media status that was sent. + */ + mediaStatus?: MediaStatus; +} +/** + * Event data for pause events forwarded from the MediaElement. + */ +export class MediaPauseEvent extends Event { + constructor(currentMediaTime?: number, ended?: boolean); + + /** + * Indicate if the media ended (indicates the pause was fired due to stream reached the end). + */ + ended?: boolean; +} +/** + * Event data for @see{@link EventType.MEDIA_FINISHED} event. + */ +export class MediaFinishedEvent extends Event { + constructor(currentMediaTime?: number, endedReason?: EndedReason); + + /** + * The time when the media finished (in seconds). For an item in a queue; this value represents the time in the currently playing queue item ( where 0 means the queue item has just started). + */ + currentTime?: number; + + /** + * The reason the media finished. + */ + endedReason?: EndedReason; +} +/** + * Event data for all events forwarded from the MediaElement. + */ +export class MediaElementEvent extends Event { + constructor(type: EventType, currentMediaTime?: number); + + /** + * The time in the currently playing clip when the event was fired (in seconds). Undefined if playback has not started yet. + */ + currentMediaTime?: number; +} +/** + * Event data for all events pertaining to processing a load / preload request. made to the player. + */ +export class LoadEvent extends Event { + constructor(type: EventType, media?: MediaInformation); + + /** + * Information about the media being loaded. + */ + media: MediaInformation; +} +/** + * Event data for @see{@link EventType.INBAND_TRACK_ADDED} event. + */ +export class InbandTrackAddedEvent { + constructor(track: Track); + + /** + * Added track. + */ + track: Track; +} + +/** Event data for @see{@link EventType.ID3} event. */ +export class Id3Event extends Event { + constructor(segmentData: Uint8Array); + + /** + * The segment data. + */ + segmentData: Uint8Array; +} +/** + * Event data for @see{@link EventType.EMSG} event. + */ +export class EmsgEvent extends Event { + constructor(emsgData: any); + + /** + * The time that the event ends (in presentation time). Undefined if using legacy Dash support. + */ + endTime: any; + + /** + * The duration of the event (in units of timescale). Undefined if using legacy Dash support. + */ + eventDuration: any; + + /** + * A field identifying this instance of the message. Undefined if using legacy Dash support. + */ + id: any; + + /** + * Body of the message. Undefined if using legacy Dash support. + */ + messageData: any; + + /** + * The offset that the event starts; relative to the start of the segment this is contained in (in units of timescale). Undefined if using legacy Dash support. + */ + presentationTimeDelta: any; - /** - * The sender id the request came from. - */ - senderId?: string; - } + /** + * Identifies the message scheme. Undefined if using legacy Dash support. + */ + schemeIdUri: any; /** - * Event data superclass for all events dispatched by @see{@link PlayerManager} + * The segment data. This is only defined if using legacy Dash support. */ - class Event { - constructor(type: EventType); + segmentData: any; - /** - * Type of the event. - */ - type: EventType; - } /** - * Event data for @see{@link EventType.MEDIA_STATUS} event. + * The time that the event starts (in presentation time). Undefined if using legacy Dash support. */ - class MediaStatusEvent extends Event { - constructor(type: EventType, mediaStatus?: MediaStatus); + startTime: any; - /** - * The media status that was sent. - */ - mediaStatus?: MediaStatus; - } /** - * Event data for pause events forwarded from the MediaElement. + * Provides the timescale; in ticks per second. Undefined if using legacy Dash support. */ - class MediaPauseEvent extends Event { - constructor(currentMediaTime?: number, ended?: boolean); + timescale: any; - /** - * Indicate if the media ended (indicates the pause was fired due to stream reached the end). - */ - ended?: boolean; - } - /** - * Event data for @see{@link EventType.MEDIA_FINISHED} event. - */ - class MediaFinishedEvent extends Event { - constructor(currentMediaTime?: number, endedReason?: EndedReason); - - /** - * The time when the media finished (in seconds). For an item in a queue; this value represents the time in the currently playing queue item ( where 0 means the queue item has just started). - */ - currentTime?: number; - - /** - * The reason the media finished. - */ - endedReason?: EndedReason; - } - /** - * Event data for all events forwarded from the MediaElement. - */ - class MediaElementEvent extends Event { - constructor(type: EventType, currentMediaTime?: number); - - /** - * The time in the currently playing clip when the event was fired (in seconds). Undefined if playback has not started yet. - */ - currentMediaTime?: number; - } - /** - * Event data for all events pertaining to processing a load / preload request. made to the player. - */ - class LoadEvent extends Event { - constructor(type: EventType, media?: MediaInformation); - - /** - * Information about the media being loaded. - */ - media: MediaInformation; - } /** - * Event data for @see{@link EventType.INBAND_TRACK_ADDED} event. - */ - class InbandTrackAddedEvent { - constructor(track: Track); + * Specifies the value for the event. Undefined if using legacy Dash support. + */ + value: any; +} +/** + * Event data for @see{@link EventType.CLIP_ENDED} event. + */ +export class ClipEndedEvent extends Event { + constructor(currentMediaTime: number, endedReason?: EndedReason); - /** - * Added track. - */ - track: Track; - } - - /** Event data for @see{@link EventType.ID3} event. */ - class Id3Event extends Event { - constructor(segmentData: Uint8Array); + /** + * The time in media (in seconds) when clip ended. + */ + currentMediaTime: number; - /** - * The segment data. - */ - segmentData: Uint8Array; - } /** - * Event data for @see{@link EventType.EMSG} event. + * The reason the clip ended. */ - class EmsgEvent extends Event { - constructor(emsgData: any); + endedReason?: EndedReason; +} + +/** + * Event data for @see{@link EventType.CACHE_LOADED} event. + */ +export class CacheLoadedEvent extends Event { + constructor(media?: MediaInformation); + + /** + * Information about the media being cached. + */ + media: MediaInformation; +} + +export class CacheItemEvent extends Event { + constructor(type: EventType, url: string); + + /** + * The URL of data fetched from cache + */ + url: string; +} + +export class BufferingEvent extends Event { + constructor(isBuffering: boolean); + + /** + * True if the player is entering a buffering state. + */ + isBuffering: boolean; +} + +export class BreaksEvent extends Event { + constructor( + type: EventType, + currentMediaTime?: number, + index?: number, + total?: number, + whenSkippable?: number, + endedReason?: EndedReason, + breakClipId?: string, + breakId?: string + ); + + /** + * The break's id. Refer to Break.id + */ + breakId?: string; + + /** + * The break clip's id. Refer to BreakClip.id + */ + breakClipId?: string; + + /** + * The time in the currently playing media when the break event occurred. + */ + currentMediaTime?: number; + + /** + * The reason the break clip ended. + */ + endedReason?: EndedReason; + + /** + * Index of break clip; which starts from 1. + */ + index: number; + + /** + * Total number of break clips. + */ + total: number; + + /** + * When to skip current break clip in sec; after break clip begins to play. + */ + whenSkippable?: number; +} + +/** + * Event data for @see {@link EventType.BITRATE_CHANGED} event. + */ +export class BitrateChangedEvent { + constructor(totalBitrate?: number); + + /** The bitrate of the media (audio and video) in bits per second. */ + totalBitrate: number; +} + +export class ErrorEvent extends Event { + constructor(detailedErrorCode: DetailedErrorCode, error?: any); - /** - * The time that the event ends (in presentation time). Undefined if using legacy Dash support. - */ - endTime: any; - - /** - * The duration of the event (in units of timescale). Undefined if using legacy Dash support. - */ - eventDuration: any; - - /** - * A field identifying this instance of the message. Undefined if using legacy Dash support. - */ - id: any; - - /** - * Body of the message. Undefined if using legacy Dash support. - */ - messageData: any; - - /** - * The offset that the event starts; relative to the start of the segment this is contained in (in units of timescale). Undefined if using legacy Dash support. - */ - presentationTimeDelta: any; - - /** - * Identifies the message scheme. Undefined if using legacy Dash support. - */ - schemeIdUri: any; - - /** - * The segment data. This is only defined if using legacy Dash support. - */ - segmentData: any; - - /** - * The time that the event starts (in presentation time). Undefined if using legacy Dash support. - */ - startTime: any; - - /** - * Provides the timescale; in ticks per second. Undefined if using legacy Dash support. - */ - timescale: any; - - /** - * Specifies the value for the event. Undefined if using legacy Dash support. - */ - value: any; - } - /** - * Event data for @see{@link EventType.CLIP_ENDED} event. - */ - class ClipEndedEvent extends Event { - constructor(currentMediaTime: number, endedReason?: EndedReason); - - /** - * The time in media (in seconds) when clip ended. - */ - currentMediaTime: number; - - /** - * The reason the clip ended. - */ - endedReason?: EndedReason; - } - - /** - * Event data for @see{@link EventType.CACHE_LOADED} event. - */ - class CacheLoadedEvent extends Event { - constructor(media?: MediaInformation); - - /** - * Information about the media being cached. - */ - media: MediaInformation; - } - - class CacheItemEvent extends Event { - constructor(type: EventType, url: string); - - /** - * The URL of data fetched from cache - */ - url: string; - } - - class BufferingEvent extends Event { - constructor(isBuffering: boolean); - - /** - * True if the player is entering a buffering state. - */ - isBuffering: boolean; - } - - class BreaksEvent extends Event { - constructor( - type: EventType, - currentMediaTime?: number, - index?: number, - total?: number, - whenSkippable?: number, - endedReason?: EndedReason, - breakClipId?: string, - breakId?: string - ); - - /** - * The break's id. Refer to Break.id - */ - breakId?: string; - - /** - * The break clip's id. Refer to BreakClip.id - */ - breakClipId?: string; - - /** - * The time in the currently playing media when the break event occurred. - */ - currentMediaTime?: number; - - /** - * The reason the break clip ended. - */ - endedReason?: EndedReason; - - /** - * Index of break clip; which starts from 1. - */ - index: number; - - /** - * Total number of break clips. - */ - total: number; - - /** - * When to skip current break clip in sec; after break clip begins to play. - */ - whenSkippable?: number; - } - - /** - * Event data for @see {@link EventType.BITRATE_CHANGED} event. - */ - class BitrateChangedEvent { - constructor(totalBitrate?: number); - - /** The bitrate of the media (audio and video) in bits per second. */ - totalBitrate: number; - } - - class ErrorEvent extends Event { - constructor(detailedErrorCode: DetailedErrorCode, error?: any); - - detailedErrorCode: DetailedErrorCode; - error?: any; - } + detailedErrorCode: DetailedErrorCode; + error?: any; } diff --git a/types/chromecast-caf-receiver/cast.framework.messages.d.ts b/types/chromecast-caf-receiver/cast.framework.messages.d.ts index d6dda6d145..c3dc4a405f 100644 --- a/types/chromecast-caf-receiver/cast.framework.messages.d.ts +++ b/types/chromecast-caf-receiver/cast.framework.messages.d.ts @@ -1,1900 +1,1898 @@ import { Event, DetailedErrorCode } from "./cast.framework.events"; -export = cast.framework.messages; -declare namespace cast.framework.messages { - type UserAction = - | "LIKE" - | "DISLIKE" - | "FOLLOW" - | "UNFOLLOW" - | "FLAG" - | "SKIP_AD"; - - type UserActionContext = - | "UNKNOWN_CONTEXT" - | "ALBUM" - | "ARTIST" - | "PLAYLIST" - | "EPISODE" - | "SERIES" - | "MOVIE" - | "CHANNEL" - | "TEAM" - | "PLAYER" - | "COACH"; - - type TextTrackType = - | "SUBTITLES" - | "CAPTIONS" - | "DESCRIPTIONS" - | "CHAPTERS" - | "METADATA"; - - type TextTrackWindowType = "NONE" | "NORMAL" | "ROUNDED_CORNERS"; - - type TrackType = "TEXT" | "AUDIO" | "VIDEO"; - - type TextTrackFontGenericFamily = - | "SANS_SERIF" - | "MONOSPACED_SANS_SERIF" - | "SERIF" - | "MONOSPACED_SERIF" - | "CASUAL" - | "CURSIVE" - | "SMALL_CAPITALS"; - - type TextTrackFontStyle = "NORMAL" | "BOLD" | "BOLD_ITALIC" | "ITALIC"; - - type TextTrackEdgeType = - | "NONE" - | "OUTLINE" - | "DROP_SHADOW" - | "RAISED" - | "DEPRESSED"; - - type Command = - | "PAUSE" - | "SEEK" - | "STREAM_VOLUME" - | "STREAM_MUTE" - | "ALL_BASIC_MEDIA" - | "QUEUE_NEXT" - | "QUEUE_PREV" - | "QUEUE_SHUFFLE" - | "SKIP_AD"; - - type SeekResumeState = "PLAYBACK_START" | "PLAYBACK_PAUSE"; - - type StreamingProtocolType = - | "UNKNOWN" - | "MPEG_DASH" - | "HLS" - | "SMOOTH_STREAMING"; - - type StreamType = "BUFFERED" | "LIVE" | "NONE"; - - type FocusState = "IN_FOCUS" | "NOT_IN_FOCUS"; - - type ExtendedPlayerState = "LOADING"; - - type ErrorType = - | "INVALID_PLAYER_STATE" - | "LOAD_FAILED" - | "LOAD_CANCELLED" - | "INVALID_REQUEST" - | "ERROR"; - - type ErrorReason = - | "INVALID_COMMAND" - | "INVALID_PARAMS" - | "INVALID_MEDIA_SESSION_ID" - | "SKIP_LIMIT_REACHED" - | "NOT_SUPPORTED" - | "LANGUAGE_NOT_SUPPORTED" - | "END_OF_QUEUE" - | "APP_ERROR" - | "AUTHENTICATION_EXPIRED" - | "PREMIUM_ACCOUNT_REQUIRED" - | "CONCURRENT_STREAM_LIMIT" - | "PARENTAL_CONTROL_RESTRICTED" - | "NOT_AVAILABLE_IN_REGION" - | "CONTENT_ALREADY_PLAYING" - | "INVALID_REQUEST" - | "GENERIC_LOAD_ERROR"; - - type RepeatMode = - | "REPEAT_OFF" - | "REPEAT_ALL" - | "REPEAT_SINGLE" - | "REPEAT_ALL_AND_SHUFFLE"; - - type IdleReason = "CANCELLED" | "INTERRUPTED" | "FINISHED" | "ERROR"; - - type HlsSegmentFormat = "AAC" | "AC3" | "MP3" | "TS" | "TS_AAC"; - - type HdrType = "SDR" | "HDR" | "DV"; - - type PlayStringId = - | "FREE_TRIAL_ABOUT_TO_EXPIRE" - | "SUBSCRIPTION_ABOUT_TO_EXPIRE" - | "STREAM_HIJACKED"; - - type GetStatusOptions = "NO_METADATA" | "NO_QUEUE_ITEMS"; - - type MessageType = - | "MEDIA_STATUS" - | "CLOUD_STATUS" - | "QUEUE_CHANGE" - | "QUEUE_ITEMS" - | "QUEUE_ITEM_IDS" - | "GET_STATUS" - | "LOAD" - | "PAUSE" - | "STOP" - | "PLAY" - | "SKIP_AD" - | "PLAY_AGAIN" - | "SEEK" - | "SET_PLAYBACK_RATE" - | "SET_VOLUME" - | "EDIT_TRACKS_INFO" - | "EDIT_AUDIO_TRACKS" - | "PRECACHE" - | "PRELOAD" - | "QUEUE_LOAD" - | "QUEUE_INSERT" - | "QUEUE_UPDATE" - | "QUEUE_REMOVE" - | "QUEUE_REORDER" - | "QUEUE_NEXT" - | "QUEUE_PREV" - | "QUEUE_GET_ITEM_RANGE" - | "QUEUE_GET_ITEMS" - | "QUEUE_GET_ITEM_IDS" - | "QUEUE_SHUFFLE" - | "SET_CREDENTIALS" - | "LOAD_BY_ENTITY" - | "USER_ACTION" - | "DISPLAY_STATUS" - | "FOCUS_STATE" - | "CUSTOM_COMMAND"; - - type PlayerState = "IDLE" | "PLAYING" | "PAUSED" | "BUFFERING"; - - type QueueChangeType = - | "INSERT" - | "REMOVE" - | "ITEMS_CHANGE" - | "UPDATE" - | "NO_CHANGE"; - - type QueueType = - | "ALBUM" - | "PLAYLIST" - | "AUDIOBOOK" - | "RADIO_STATION" - | "PODCAST_SERIES" - | "TV_SERIES" - | "VIDEO_PLAYLIST" - | "LIVE_TV" - | "MOVIE"; - - type MetadataType = - | "GENERIC" - | "MOVIE" - | "TV_SHOW" - | "MUSIC_TRACK" - | "PHOTO"; - - /** - * RefreshCredentials request data. - */ - interface RefreshCredentialsRequestData { - [key: string]: any; - } - - /** - * Media event SET_VOLUME request data. - */ - interface VolumeRequestData extends RequestData { - /** - * The media stream volume - */ - volume?: Volume; - } - - /** - * Represents the volume of a media session stream. - */ - interface Volume { - /** - * Value from 0 to 1 that represents the current stream volume level. - */ - level?: number; - - /** - * Whether the stream is muted. - */ - muted?: boolean; - } - - /** - * Video information such as video resolution and High Dynamic Range (HDR). - */ - class VideoInformation { - constructor(width: number, height: number, hdrType: HdrType); - - width: number; - - height: number; - - hdrType: HdrType; - } - - /** - * VAST ad request configuration. - */ - interface VastAdsRequest { - /** - * Specifies a VAST document to be used as the ads response instead of making a - * request via an ad tag url. - * This can be useful for debugging and other situations where a VAST response is - * already available. - */ - adsResponse?: string; - - /** - * URL for VAST file. - */ - adTagUrl?: string; - } - - /** - * UserAction request data. - */ - interface UserActionRequestData { - /** - * Optional request source. - * It contain the assistent query that initiate the request. - */ - source?: string; - - /** - * User action to be handled by the application. - */ - userAction?: UserAction; - - /** - * Optional context information for the user action. - */ - userActionContext?: UserActionContext; - } - - /** - * A TV episode media description. - */ - interface TvShowMediaMetadata { - /** - * TV episode number. A positive integer. - */ - episode?: number; - - /** - * @deprecated use episode instead - */ - episodeNumber?: number; - - /** - * @deprecated use episode instead - */ - episodeTitle?: string; - - /** - * Content images. Examples would include cover art or a thumbnail of - * the currently playing media. - */ - images?: Image[]; - - /** - * ISO 8601 date when the episode originally aired; e.g. 2014-02-10. - */ - originalAirdate?: string; - - /** - * @deprecated use originalAirdate instead. - */ - releaseYear?: number; - - /** - * TV episode season. A positive integer. - */ - season?: number; - - /** - * @deprecated use season instead. - */ - seasonNumber?: number; - - /** - * TV series title. - */ - seriesTitle?: string; - - /** - * TV episode title. - */ - title?: string; - } - /** - * Describes track metadata information. - */ - class Track { - constructor(trackId: number, trackType: TrackType); - - /** - * Custom data set by the receiver application. - */ - customData?: string; - - /** - * Language tag as per RFC 5646 (If subtype is “SUBTITLES” it is mandatory). - */ - language?: string; - - /** - * A descriptive; human readable name for the track. For example "Spanish". - */ - name?: string; - - /** - * For text tracks; the type of text track. - */ - subtype?: string; - - /** - * It can be the url of the track or any other identifier that allows the receiver - * to find the content (when the track is not inband or included in the manifest). - * For example it can be the url of a vtt file. - */ - trackContentId?: string; - - /** - * It represents the MIME type of the track content. For example if the track - * is a vtt file it will be ‘text/vtt’. This field is needed for out of band tracks; - * so it is usually provided if a trackContentId has also been provided. - * It is not mandatory if the receiver has a way to identify the content from - * the trackContentId; but recommended. - * The track content type; if provided; must be consistent with the track type. - */ - trackContentType?: string; - - /** - * Unique identifier of the track within the context of a MediaInformation object. - */ - trackId?: number; - - /** - * The type of track. - */ - type: TrackType; - } - /** - * Describes style information for a text track. - */ - interface TextTrackStyle { - /** - * The background 32 bit RGBA color. The alpha channel should be used for transparent backgrounds. - */ - backgroundColor?: string; - - /** - * Custom data set by the receiver application. - */ - customData?: any; - - /** - * RGBA color for the edge; this value will be ignored if edgeType is NONE. - */ - edgeColor?: string; - - edgeType?: TextTrackEdgeType; - - /** - * If the font is not available in the receiver the fontGenericFamily will be used. - */ - fontFamily?: string; - - /** - * The text track generic family. - */ - fontGenericFamily?: TextTrackFontGenericFamily; - - /** - * The font scaling factor for the text track (the default is 1). - */ - fontScale?: number; - - /** - * The text track font style. - */ - fontStyle?: TextTrackFontStyle; - - /** - * The foreground 32 bit RGBA color. - */ - foregroundColor?: string; - - /** - * 32 bit RGBA color for the window. This value will be ignored if windowType is NONE. - */ - windowColor?: string; - - /** - * Rounded corner radius absolute value in pixels (px). This value will be ignored - * if windowType is not ROUNDED_CORNERS. - */ - windowRoundedCornerRadius?: number; - - /** - * The window concept is defined in CEA-608 and CEA-708. In WebVTT is called a region. - */ - windowType?: TextTrackWindowType; - } - - /** - * Media event playback rate request data. - */ - interface SetPlaybackRateRequestData extends RequestData { - /** - * New playback rate (>0). - */ - playbackRate?: number; - - /** - * New playback rate relative to current playback rate. - * New rate will be the result of multiplying the current rate with the value. - * For example a value of 1.1 will increase rate by 10%. - * (Only used if the playbackRate value is not provided). - */ - relativePlaybackRate?: number; - } - - /** - * SetCredentials request data. - */ - interface SetCredentialsRequestData { - /** - * Credentials to use by receiver. - */ - credentials?: string; - - /** - * If it is a response for refresh credentials; it will indicate the request id - * of the refresh credentials request. - */ - forRequestId?: number; - - /** - * Optional request source. It contain the assistent query that initiate the request. - */ - source?: string; - } - - /** - * Media event SEEK request data. - */ - interface SeekRequestData extends RequestData { - /** - * Seconds since beginning of content. - */ - currentTime?: number; - - /** - * Seconds relative to the current playback position. If this field is defined; - * the currentTime field will be ignored. - */ - relativeTime?: number; - - /** - * The playback state after a SEEK request. - */ - resumeState?: SeekResumeState; - } - - /** - * Provides seekable range in seconds. - */ - class SeekableRange { - constructor(start?: number, end?: number); - - /** - * End of the seekable range in seconds. - */ - end?: number; - - /** - * Start of the seekable range in seconds. - */ - start?: number; - } - - /** - * Media event request data. - */ - class RequestData { - constructor(type: MessageType); - - /** - * Application-specific data for this request. - * It enables the sender and receiver to easily extend the media protocol - * without having to use a new namespace with custom messages. - */ - customData?: any; - - /** - * Id of the media session that the request applies to. - */ - mediaSessionId?: number; - - /** - * Id of the request; used to correlate request/response. - */ - requestId: number; - } - - /** - * Media event UPDATE queue request data. - */ - interface QueueUpdateRequestData { - /** - * ID of the current media Item after the deletion - * (if not provided; the currentItem value will be the same as before the deletion; - * if it does not exist because it has been deleted; the currentItem will point to - * the next logical item in the list). - */ - currentItemId?: number; - - /** - * Seconds since the beginning of content to start playback of the current item. - * If provided; this value will take precedence over the startTime value provided - * at the QueueItem level but only the first time the item is played. - * This is to cover the common case where the user jumps to the middle of an - * item so the currentTime does not apply to the item permanently like the - * QueueItem startTime does. It avoids having to reset the startTime dynamically - * (that may not be possible if the phone has gone to sleep). - */ - currentTime?: number; - - /** - * List of queue items to be updated. No reordering will happen; the items will - * retain the existing order. - */ - items?: QueueItem[]; - - /** - * Skip/Go back number of items with respect to the position of currentItem - * (it can be negative). If it is out of boundaries; the currentItem will be the - * next logical item in the queue wrapping around the boundaries. - * The new currentItem position will follow the rules of the queue repeat behavior. - */ - jump?: number; - - /** - * Behavior of the queue when all items have been played. - */ - repeatMode?: RepeatMode; - - /** - * Shuffle the queue items when the update is processed. - * After the queue items are shuffled; the item at the currentItem position will - * be loaded. - */ - shuffle?: boolean; - } - - /** - * Media event queue REORDER request data. - */ - class QueueReorderRequestData extends RequestData { - constructor(itemIds: number[]); - - /** - * ID of the current media Item after the deletion (if not provided; - * the currentItem value will be the same as before the deletion; - * if it does not exist because it has been deleted; - * the currentItem will point to the next logical item in the list). - */ - currentItemId?: number; - - /** - * Seconds since the beginning of content to start playback of the current item. - * If provided; this value will take precedence over the startTime value provided - * at the QueueItem level but only the first time the item is played. - * This is to cover the common case where the user jumps to the middle of an - * item so the currentTime does not apply to the item permanently like - * the QueueItem startTime does. It avoids having to reset the startTime dynamically - * (that may not be possible if the phone has gone to sleep). - */ - currentTime?: number; - - /** - * ID of the item that will be located immediately after the reordered list. - * If the ID is not found or it is not provided; - * the reordered list will be appended at the end of the existing list. - */ - insertBefore?: number; - - /** - * IDs of the items to be reordered; in the new order. - * Items not provided will keep their existing order. - * The provided list will be inserted at the position determined by insertBefore. - * For example: - * If insertBefore is not specified Existing queue: “A”;”D”;”G”;”H”;”B”;”E” itemIds: - * “D”;”H”;”B” New Order: “A”;”G”;”E”;“D”;”H”;”B” - * If insertBefore is “A” Existing queue: “A”;”D”;”G”;”H”;”B” itemIds: - * “D”;”H”;”B” New Order: “D”;”H”;”B”;“A”;”G”;”E” - * If insertBefore is “G” Existing queue: “A”;”D”;”G”;”H”;”B” itemIds: - * “D”;”H”;”B” New Order: “A”;“D”;”H”;”B”;”G”;”E” - */ - itemIds: number[]; - } - - /** - * Media event queue REMOVE request data. - */ - class QueueRemoveRequestData extends RequestData { - constructor(itemIds: number[]); - - /** - * ID of the current media Item after the deletion - * (if not provided; the currentItem value will be the same as before the deletion; - * if it does not exist because it has been deleted; - * the currentItem will point to the next logical item in the list). - */ - currentItemId?: number; - - /** - * Seconds since the beginning of content to start playback of the current item. - * If provided; this value will take precedence over the startTime value provided - * at the QueueItem level but only the first time the item is played. - * This is to cover the common case where the user jumps to the middle of an - * item so the currentTime does not apply to the item permanently like the - * QueueItem startTime does. It avoids having to reset the startTime dynamically - * (that may not be possible if the phone has gone to sleep). - */ - currentTime?: number; - - /** - * IDs of queue items to be deleted. - */ - itemIds?: number[]; - } - /** - * Media event queue LOAD request data. - */ - class QueueLoadRequestData extends RequestData { - constructor(items: QueueItem[]); - - /** - * Seconds (since the beginning of content) to start playback of the first item to - * be played. If provided; this value will take precedence over the - * startTime value provided at the QueueItem level but only the first - * time the item is played. This is to cover the common case where the user - * casts the item that was playing locally so the currentTime does not apply - * to the item permanently like the QueueItem startTime does. - * It avoids having to reset the startTime dynamically - * (that may not be possible if the phone has gone to sleep). - */ - currentTime?: number; - - /** - * Behavior of the queue when all items have been played. - */ - items: QueueItem[]; - - /** - * Id of the request; used to correlate request/response. - */ - repeatMode?: RepeatMode; - - /** - * The index of the item in the items array that must be the first currentItem - * (the item that will be played first). Note this is the index of the array - * (starts at 0) and not the itemId (as it is not known until the queue is created). - * If repeatMode is REPEAT_OFF playback will end when the last item in the array is - * played (elements before the startIndex will not be played). - * This may be useful for continuation scenarios where the user was already - * using the sender app and in the middle decides to cast. - * In this way the sender app does not need to map between the local and remote queue - * positions or saves one extra QUEUE_UPDATE request. - */ - startIndex?: number; - } - - /** - * Queue item information. Application developers may need to create a QueueItem to - * insert a queue element using InsertQueueItems. In this case they should not - * provide an itemId (as the actual itemId will be assigned when the item is inserted - * in the queue). This prevents ID collisions with items added from a sender app. - */ - class QueueItem { - constructor(opt_itemId?: number); - - /** - * Array of Track trackIds that are active. If the array is not provided; - * the default tracks will be active. - */ - activeTrackIds?: number[]; - - /** - * If the autoplay parameter is not specified or is true; the media player - * will begin playing the element in the queue when the item becomes the currentItem. - */ - autoplay?: boolean; - - /** - * The application can define any extra queue item information needed. - */ - customData?: any; - - /** - * Unique identifier of the item in the queue. - * The attribute is optional because for LOAD or INSERT should not be provided - * (as it will be assigned by the receiver when an item is first created/inserted). - */ - itemId?: number; - - /** - * Metadata (including contentId) of the playlist element. - */ - media?: MediaInformation; - - /** - * Playback duration of the item; if it is larger than the actual duration - - * startTime it will be ignored (default behavior). - * It can be negative; in such case the duration will be the actual asset - * duration minus the duration provided. - * It can be used for photo slideshows to control the duration the item should - * be presented or for live events to control the duration that the program - * should be played. It may be useful for autoplay scenarios to avoid displaying all - * the credits after an episode has ended. - */ - playbackDuration?: number; - - /** - * This parameter is a hint for the receiver to preload this media - * item before it is played. It allows for a smooth transition between items - * played from the queue. The time is expressed in seconds; relative to - * the beginning of this item playback (usually the end of the previous item playback). - * Only positive values are valid. For example; if the value is 10 seconds; this item - * will be preloaded 10 seconds before the previous item has finished. - * The receiver will try to honor this value but will not guarantee it; - * for example if the value is larger than the previous item duration the - * receiver may just preload this item shortly after the previous item has started playing - * (there will never be two items being preloaded in parallel). - * Also; if an item is inserted in the queue just after the currentItem and the time to preload is higher than the - * time left on the currentItem; the preload will just happen as soon as possible. - */ - preloadTime?: number; - - /** - * Seconds since beginning of content. If the content is live content; - * and startTime is not specified; the stream will start at the live position. - */ - startTime?: number; - } - - /** - * Media event queue INSERT request data. - */ - class QueueInsertRequestData extends RequestData { - constructor(items: QueueItem[]); - - /** - * ID of the current media Item after the insertion (if not provided; - * the currentItem value will be the same as before the insertion). - */ - currentItemId?: number; - - /** - * Index (relative to the items array; starting with 0) of the new current media Item. - * For inserted items we use the index (similar to startIndex in QUEUE_LOAD) and not - * currentItemId; because the itemId is unknown until the items are inserted. - * If not provided; the currentItem value will be the same as before the insertion - * (unless currentItemId is provided). This param allows to make atomic the common use - * case of insert and play an item. - */ - currentItemIndex?: number; - - /** - * Seconds since the beginning of content to start playback of the current item. - * If provided; this value will take precedence over the startTime value provided - * at the QueueItem level but only the first time the item is played. - * This is to cover the common case where the user jumps to the middle of an - * item so the currentTime does not apply to the item permanently like the - * QueueItem startTime does. It avoids having to reset the startTime dynamically - * (that may not be possible if the phone has gone to sleep). - */ - currentTime?: number; - - /** - * ID of the item that will be located immediately after the inserted list. - * If the ID is not found or it is not provided; the list will be appended at - * the end of the existing list. - */ - insertBefore?: number; - - /** - * List of queue items. The itemId field of the items should be empty. - * It is sorted (first element will be played first). - */ - items: QueueItem[]; - } - - /** - * Represents a data message containing the full list of queue ids. - */ - interface QueueIds { - /** - * List of queue item ids. - */ - itemIds?: number[]; - - /** - * The corresponding request id. - */ - requestId?: number; - - type: MessageType; - } - - /** - * Queue data as part of the LOAD request. - */ - class QueueData { - constructor( - id?: string, - name?: string, - description?: string, - repeatMode?: RepeatMode, - items?: QueueItem[], - startIndex?: number, - startTime?: number - ); - - /** - * Description of the queue. - */ - description?: string; - - /** - * Optional Queue entity id; provide Google Assistant deep link. - */ - entity?: string; - - /** - * Id of the queue. - */ - id?: string; - - /** - * Array of queue items. It is sorted (first element will be played first). - */ - items?: QueueItem[]; - - /** - * Name of the queue. - */ - name?: string; - - /** - * Queue type; e.g. album; playlist; radio station; tv series; etc. - */ - queueType?: QueueType; - - /** - * Continuous playback behavior of the queue. - */ - repeatMode?: RepeatMode; - - /** - * The index of the item in the queue that should be used to start playback first. - */ - startIndex?: number; - - /** - * Seconds (since the beginning of content) to start playback of the first item. - */ - startTime?: number; - } - - /** - * Represents a queue change message; such as insert; remove; and update. - */ - interface QueueChange { - /** - * The actual queue change type. - */ - changeType?: QueueChangeType; - - /** - * The id to insert the list of itemIds before. - */ - insertBefore?: number; - - /** - * List of changed itemIds. - */ - itemIds?: number[]; - - /** - * The corresponding request id. - */ - requestId?: number; - - /** - * The queue change sequence ID. Used to coordinate state sync between various - * senders and the receiver. - */ - sequenceNumber?: number; - - type: MessageType; - } - - /** - * Media event PRELOAD request data. - */ - class PreloadRequestData implements LoadRequestData { - /** - * Array of trackIds that are active. If the array is not provided; - * the default tracks will be active. - */ - activeTrackIds: number[]; - /** - * If the autoplay parameter is specified; the media player will begin playing - * the content when it is loaded. Even if autoplay is not specified;the media player - * implementation may choose to begin playback immediately. - */ - autoplay?: boolean; - /** - * Optional user credentials. - */ - credentials?: string; - /** - * Optional credentials type. The type 'cloud' is a reserved type used by load - * requests that were originated by voice assistant commands. - */ - credentialsType?: string; - /** - * Seconds since beginning of content. If the content is live content; - * and currentTime is not specified; the stream will start at the live position. - */ - currentTime?: number; - /** - * If the autoplay parameter is specified; the media player will begin playing - * the content when it is loaded. Even if autoplay is not specified; the media - * player implementation may choose to begin playback immediately. - */ - media: MediaInformation; - /** - * The media playback rate. - */ - playbackRate?: number; - /** - * Queue data. - */ - queueData: QueueData; - /** - * Application-specific data for this request. - * It enables the sender and receiver to easily extend the media protocol - * without having to use a new namespace with custom messages. - */ - customData?: any; - /** - * Id of the media session that the request applies to. - */ - mediaSessionId?: number; - /** - * Id of the request; used to correlate request/response. - */ - requestId: number; - constructor(itemId: number); - - /** - * The ID of the queue item. - */ - itemId: number; - } - - /** - * Media event PRECACHE request data. (Some fields of the load request; - * like autoplay and queueData; are ignored). - */ - class PrecacheRequestData implements LoadRequestData { - /** - * Array of trackIds that are active. If the array is not provided; - * the default tracks will be active. - */ - activeTrackIds: number[]; - /** - * If the autoplay parameter is specified; the media player will begin playing - * the content when it is loaded. Even if autoplay is not specified;the media player - * implementation may choose to begin playback immediately. - */ - autoplay?: boolean; - /** - * Optional user credentials. - */ - credentials?: string; - /** - * Optional credentials type. The type 'cloud' is a reserved type used by load - * requests that were originated by voice assistant commands. - */ - credentialsType?: string; - /** - * Seconds since beginning of content. If the content is live content; and - * currentTime is not specified; the stream will start at the live position. - */ - currentTime?: number; - /** - * If the autoplay parameter is specified; the media player will begin playing - * the content when it is loaded. Even if autoplay is not specified; - * the media player implementation may choose to begin playback immediately. - */ - media: MediaInformation; - /** - * The media playback rate. - */ - playbackRate?: number; - /** - * Queue data. - */ - queueData: QueueData; - /** - * Application-specific data for this request. - * It enables the sender and receiver to easily extend the media protocol - * without having to use a new namespace with custom messages. - */ - customData?: any; - /** - * Id of the media session that the request applies to. - */ - mediaSessionId?: number; - /** - * Id of the request; used to correlate request/response. - */ - requestId: number; - constructor(data?: string); - - /** - * Application precache data. - */ - precacheData?: string; - } - - /** - * PlayString request data. - */ - class PlayStringRequestData { - constructor(stringId: PlayStringId, opt_arguments?: string[]); - - /** - * An optional array of string values to be filled into the text. - */ - arguments?: string[]; - - /** - * An identifier for the text to be played back. - */ - stringId: PlayStringId; - } - - /** - * A photo media description. - */ - interface PhotoMediaMetadata { - /** - * Name of the photographer. - */ - artist?: string; - - /** - * ISO 8601 date and time the photo was taken; e.g. 2014-02-10T15:47:00Z. - */ - creationDateTime?: string; - - /** - * Photo height; in pixels. - */ - height?: number; - - /** - * Images associated with the content. Examples would include a photo thumbnail. - */ - images: Image[]; - - /** - * Latitude. - */ - latitude?: number; - - /** - * Location where the photo was taken. For example; "Seattle; Washington; USA". - */ - location?: string; - - /** - * Longitude. - */ - longitude?: number; - - /** - * Photo title. - */ - title?: string; - - /** - * Photo width; in pixels. - */ - width?: number; - } - - /** - * A music track media description. - */ - interface MusicTrackMediaMetadata { - /** - * Album artist name. - */ - albumArtist?: string; - - /** - * Album name. - */ - albumName?: string; - - /** - * Track artist name. - */ - artist?: string; - - /** - * @deprecated: use @see{@link artist} instead - */ - artistName: string; - - /** - * Track composer name. - */ - composer?: string; - - /** - * Disc number. A positive integer. - */ - discNumber?: number; - - /** - * Content images. Examples would include cover art or a thumbnail of the - * currently playing media. - */ - images: Image[]; - - /** - * ISO 8601 date when the track was released; e.g. 2014-02-10. - */ - releaseDate?: string; - - /** - * @deprecated: Use @see{@link releaseDate} instead - */ - releaseYear?: string; - - /** - * Track name. - */ - songName?: string; - - /** - * Track title. - */ - title?: string; - - /** - * Track number in album. A positive integer. - */ - trackNumber?: number; - } - - /** - * A movie media description. - */ - interface MovieMediaMetadata { - /** - * Content images. Examples would include cover art or a thumbnail of the - * currently playing media. - */ - images: Image[]; - - /** - * ISO 8601 date when the movie was released; e.g. 2014-02-10. - */ - releaseDate?: string; - - /** - * @deprecated: use @see{@link releaseDate} instead - */ - releaseYear?: number; - - /** - * Movie studio. - */ - studio?: string; - - /** - * Movie subtitle. - */ - subtitle?: string; - - /** - * Movie title. - */ - title?: string; - } - /** - * Represents the status of a media session. - */ - interface MediaStatus { - /** - * List of IDs corresponding to the active tracks. - */ - activeTrackIds: number[]; - - /** - * Status of break; if receiver is playing break. - * This field will be defined only when receiver is playing break. - */ - breakStatus: BreakStatus; - - /** - * ID of this media item (the item that originated the status change). - */ - currentItemId?: number; - - /** - * The current playback position. - */ - currentTime: number; - - /** - * Application-specific media status. - */ - customData?: any; - - /** - * Extended media status information. - */ - extendedStatus: ExtendedMediaStatus; - - /** - * If the state is IDLE; the reason the player went to IDLE state. - */ - idleReason: IdleReason; - - /** - * List of media queue items. - */ - items: QueueItem[]; - - /** - * Seekable range of a live or event stream. It uses relative media time in seconds. - * It will be undefined for VOD streams. - */ - liveSeekableRange: LiveSeekableRange; - - /** - * ID of the media Item currently loading. If there is no item being loaded; - * it will be undefined. - */ - loadingItemId?: number; - - /** - * The media information. - */ - media: MediaInformation; - - /** - * Unique id for the session. - */ - mediaSessionId: number; - - /** - * The playback rate. - */ - playbackRate: number; - - /** - * The playback state. - */ - playerState: PlayerState; - - /** - * ID of the next Item; only available if it has been preloaded. - * Media items can be preloaded and cached temporarily in memory; - * so when they are loaded later on; the process is faster - * (as the media does not have to be fetched from the network). - */ - preloadedItemId?: number; - - /** - * Queue data. - */ - queueData: QueueData; - - /** - * The behavior of the queue when all items have been played. - */ - repeatMode: RepeatMode; - - /** - * The commands supported by this player. - */ - supportedMediaCommands: number; - - type: MessageType; - - /** - * The video information. - */ - videoInfo: VideoInformation; - - /** - * The current stream volume. - */ - volume: Volume; - } - /** - * Common media metadata used as part of MediaInformation - */ - class MediaMetadata { - constructor(type: MetadataType); - - /** - * The type of metadata - */ - metadataType: MetadataType; - } - - /** - * Represents the media information. - */ - interface MediaInformation { - /** - * Partial list of break clips that includes current break clip that receiver - * is playing or ones that receiver will play shortly after; instead of sending - * whole list of clips. This is to avoid overflow of MediaStatus message. - */ - breakClips: BreakClip[]; - - /** - * List of breaks. - */ - breaks: Break[]; - - /** - * Typically the url of the media. - */ - contentId: string; - - /** - * The content MIME type. - */ - contentType: string; - - /** - * Optional media url; to allow using contentId for real id. If contentUrl - * is provided; it will be used as media url; otherwise the contentId will - * be used as the media url. - */ - contentUrl?: string; - - /** - * Application-specific media information. - */ - customData?: any; - - /** - * The media duration. - */ - duration?: number; - - /** - * Optional Media entity; provide Google Assistant deep link. - */ - entity?: string; - - /** - * The format of the HLS media segment. - */ - hlsSegmentFormat: HlsSegmentFormat; - - /** - * The media metadata. - */ - metadata: MediaMetadata; - - /** - * The stream type. - */ - streamType: StreamType; - - /** - * The style of text track. - */ - textTrackStyle: TextTrackStyle; - - /** - * The media tracks. - */ - tracks: Track[]; - } - - /** - * Media event LOAD request data. - */ - interface LoadRequestData extends RequestData { - /** - * Array of trackIds that are active. If the array is not provided; the - * default tracks will be active. - */ - activeTrackIds: number[]; - - /** - * If the autoplay parameter is specified; the media player will begin - * playing the content when it is loaded. Even if autoplay is not - * specified;the media player implementation may choose to begin playback - * immediately. - */ - autoplay?: boolean; - - /** - * Optional user credentials. - */ - credentials?: string; - - /** - * Optional credentials type. The type 'cloud' is a reserved type used by - * load requests that were originated by voice assistant commands. - */ - credentialsType?: string; - - /** - * Seconds since beginning of content. If the content is live content; - * and currentTime is not specified; the stream will start at the live position. - */ - currentTime?: number; - - /** - * If the autoplay parameter is specified; the media player will begin playing - * the content when it is loaded. Even if autoplay is not specified; the media - * player implementation may choose to begin playback immediately. - */ - media: MediaInformation; - - /** - * The media playback rate. - */ - playbackRate?: number; - - /** - * Queue data. - */ - queueData: QueueData; - } - - /** - * LoadByEntity request data. - */ - interface LoadByEntityRequestData { - /** - * Content entity information; typically represented by a stringified JSON object - */ - entity: string; - - /** - * Shuffle the items to play. - */ - shuffle?: boolean; - - /** - * Optional request source. It contain the assistent query that initiate the request. - */ - source?: string; - } - - /** - * Provides live seekable range with start and end time in seconds and two more - * attributes. - */ - class LiveSeekableRange { - constructor( - start?: number, - end?: number, - isMovingWindow?: boolean, - isLiveDone?: boolean - ); - - /** - * A boolean value indicates whether a live stream is ended. If it is done; - * the end of live seekable range should stop updating. - */ - isLiveDone?: boolean; - - /** - * A boolean value indicates whether the live seekable range is a moving window. - * If false; it will be either a expanding range or a fixed range meaning live - * has ended. - */ - isMovingWindow?: boolean; - } - - /** - * Represents a data message containing item information for each requested ids. - */ - interface ItemsInfo { - /** - * List of changed itemIds. - */ - items: QueueItem[]; - - /** - * The corresponding request id. - */ - requestId?: number; - - type: MessageType; - } - - /** - * An image that describes a receiver application or media item. - * This could be an application icon; cover art; or a thumbnail. - */ - class Image { - constructor(url: string); - - /** - * The height of the image. - */ - height?: number; - - /** - * the URL to the image - */ - url: string; - - /** - * The width of the image - */ - width?: number; - } - /** Media event GET_STATUS request data. */ - interface GetStatusRequestData extends RequestData { - /** - * The options of a GET_STATUS request. - */ - options: GetStatusOptions; - } - - /** - * Get items info request data. - */ - class GetItemsInfoRequestData extends RequestData { - constructor(itemIds: number[]); - - /** - * List of item ids to be requested. - */ - itemIds: number[]; - } - /** - * A generic media description. - */ - interface GenericMediaMetadata extends MediaMetadata { - /** - * Content images. Examples would include cover art or a thumbnail of the - * currently playing media. - */ - images: Image[]; - - /** - * ISO 8601 date and/or time when the content was released; e.g. 2014-02-10. - */ - releaseDate?: string; - - /** - * @deprecated - use @see{@link releaseDate} instead - */ - releaseYear?: number; - - /** - * Content subtitle. - */ - subtitle?: string; - - /** - * Content title. - */ - title?: string; - } - - /** - * Focus state change message. - */ - interface FocusStateRequestData { - /** - * The focus state of the app. - */ - state: FocusState; - } - - /** Fetch items request data. */ - class FetchItemsRequestData extends RequestData { - constructor(itemId: number, nextCount: number, prevCount: number); - - /** - * ID of the reference media item for fetching more items. - */ - itemId: number; - - /** - * Number of items after the reference item to be fetched. - */ - nextCount: number; - - /** - * Number of items before the reference item to be fetched. - */ - prevCount: number; - } - - /** - * Extended media status information - */ - class ExtendedMediaStatus { - constructor( - playerState: MediaInformation, - opt_media?: MediaInformation - ); - - media: MediaInformation; - - playerState: ExtendedPlayerState; - } - - /** Event data for @see{@link EventType.ERROR} event. */ - class ErrorEvent extends Event { - constructor(detailedErrorCode?: DetailedErrorCode, error?: any); - - /** - * An error code representing the cause of the error. - */ - detailedErrorCode?: DetailedErrorCode; - - /** - * The error object. - * This could be an Error object (e.g.; if an Error was thrown in an event handler) - * or an object with error information (e.g.; if the receiver received an invalid - * command). - */ - error?: any; - } - - class ErrorData { - constructor(type: ErrorType); - - /** - * Application-specific data for this request. - * It enables the sender and receiver to easily extend the media protocol - * without having to use a new namespace with custom messages. - */ - customData?: any; - - /** - * Id of the request; used to correlate request/response. - */ - requestId?: number; - } - - /** Media event EDIT_TRACKS_INFO request data. */ - interface EditTracksInfoRequestData extends RequestData { - /** - * Array of the Track trackIds that should be active. - * If it is not provided; the active tracks will not change. - * If the array is empty; no track will be active. - */ - activeTrackIds?: number[]; - - /** - * Flag to enable or disable text tracks. - * If false it will disable all text tracks; - * if true it will enable the first text track; or the previous active text tracks. - * This flag is ignored if activeTrackIds or language is provided. - */ - enableTextTracks?: boolean; - - /** - * Indicates that the provided language was not explicit user request; but rather - * inferred from used language in voice query. - * It allows receiver apps to use user saved preference instead of spoken language. - */ - isSuggestedLanguage?: boolean; - - /** - * Language for the tracks that should be active. The language field will take - * precedence over activeTrackIds if both are specified. - */ - language?: string; - - textTrackStyle?: TextTrackStyle; - } - - /** - * Media event EDIT_AUDIO_TRACKS request data. If language is not provided; - * the default audio track for the media will be enabled. - */ - interface EditAudioTracksRequestData extends RequestData { - /** - * Indicates that the provided language was not explicit user request; - * but rather inferred from used language in voice query. - * It allows receiver apps to use user saved preference instead of spoken language. - */ - isSuggestedLanguage?: boolean; - - language?: string; - } - - /** DisplayStatus request data. */ - interface DisplayStatusRequestData { - /** - * Optional request source. It contain the assistent query that initiate the request. - */ - source: string; - } - - /** CustomCommand request data. */ - interface CustomCommandRequestData { - /** - * Custom Data; typically represented by a stringified JSON object. - */ - data: string; - - /** - * Optional request source. It contain the assistent query that initiate the request. - */ - source: string; - } - - class BreakStatus { - constructor(currentBreakTime: number, currentBreakClipTime: number); - - /** - * Id of current break clip. - */ - breakClipId: string; - - /** - * Id of current break. - */ - breakId: string; - - /** - * Time in sec elapsed after current break clip starts. - */ - currentBreakClipTime: number; - - /** - * Time in sec elapsed after current break starts. - */ - currentBreakTime: number; - - /** - * The time in sec when this break clip becomes skippable. - * 5 means that end user can skip this break clip after 5 seconds. - * If this field is not defined; it means that current break clip is not skippable. - */ - whenSkippable: number; - } - - /** - * Represents break clip (e.g. a clip of ad during ad break) - */ - class BreakClip { - constructor(id: string); - - /** - * Url of page that sender will display; when end user clicks link on sender UI; while receiver is playing this clip. - */ - clickThroughUrl?: string; - /** - * Typically the url of the break media (playing on the receiver). - */ - contentId?: string; - /** - * The content MIME type. - */ - contentType?: string; - /** - * Optional break media url; to allow using contentId for real id. - * If contentUrl is provided; it will be used as media url; - * otherwise the contentId will be used as the media url. - */ - contentUrl?: string; - /** - * Application-specific break clip data. - */ - customData?: any; - /** - * Duration of break clip in sec. - */ - duration?: number; - /** - * The format of the HLS media segment. - */ - hlsSegmentFormat?: HlsSegmentFormat; - /** - * Unique id of break clip. - */ - id: string; - /** - * Url of content that sender will display while receiver is playing this clip. - */ - posterUrl?: string; - /** - * Title of break clip. Sender might display this on its screen; if provided. - */ - title?: string; - /** - * VAST ad request configuration. Used if contentId or contentUrl is not provided. - */ - vastAdsRequest?: VastAdsRequest; - /** - * The time in sec when this break clip becomes skippable. - * 5 means that end user can skip this break clip after 5 seconds. - * If this field is not defined; it means that current break clip is not skippable. - */ - whenSkippable?: number; - } - - /** Represents break (e.g. ad break) included in main video. */ - class Break { - constructor(id: string, breakClipIds: string[], position: number); - /** - * List of ids of break clip that this break includes. - */ - breakClipIds: string[]; - /** - * Duration of break in sec. - */ - duration?: number; - /** - * Unique id of break. - */ - id: string; - /** - * If true; indicates this is embedded break in main stream. - */ - - isEmbedded?: boolean; - /** - * Whether break is watched. - * Sender can change color of progress bar marker corresponding to this break once - * this field changes from false to true; - * denoting that the end-user already watched this break. - */ - isWatched: boolean; - - /** - * Where the break is located inside main video. -1 represents the end of main video. - */ - position: number; - } +export as namespace messages +export type UserAction = + | "LIKE" + | "DISLIKE" + | "FOLLOW" + | "UNFOLLOW" + | "FLAG" + | "SKIP_AD"; + +export type UserActionContext = + | "UNKNOWN_CONTEXT" + | "ALBUM" + | "ARTIST" + | "PLAYLIST" + | "EPISODE" + | "SERIES" + | "MOVIE" + | "CHANNEL" + | "TEAM" + | "PLAYER" + | "COACH"; + +export type TextTrackType = + | "SUBTITLES" + | "CAPTIONS" + | "DESCRIPTIONS" + | "CHAPTERS" + | "METADATA"; + +export type TextTrackWindowType = "NONE" | "NORMAL" | "ROUNDED_CORNERS"; + +export type TrackType = "TEXT" | "AUDIO" | "VIDEO"; + +export type TextTrackFontGenericFamily = + | "SANS_SERIF" + | "MONOSPACED_SANS_SERIF" + | "SERIF" + | "MONOSPACED_SERIF" + | "CASUAL" + | "CURSIVE" + | "SMALL_CAPITALS"; + +export type TextTrackFontStyle = "NORMAL" | "BOLD" | "BOLD_ITALIC" | "ITALIC"; + +export type TextTrackEdgeType = + | "NONE" + | "OUTLINE" + | "DROP_SHADOW" + | "RAISED" + | "DEPRESSED"; + +export type Command = + | "PAUSE" + | "SEEK" + | "STREAM_VOLUME" + | "STREAM_MUTE" + | "ALL_BASIC_MEDIA" + | "QUEUE_NEXT" + | "QUEUE_PREV" + | "QUEUE_SHUFFLE" + | "SKIP_AD"; + +export type SeekResumeState = "PLAYBACK_START" | "PLAYBACK_PAUSE"; + +export type StreamingProtocolType = + | "UNKNOWN" + | "MPEG_DASH" + | "HLS" + | "SMOOTH_STREAMING"; + +export type StreamType = "BUFFERED" | "LIVE" | "NONE"; + +export type FocusState = "IN_FOCUS" | "NOT_IN_FOCUS"; + +export type ExtendedPlayerState = "LOADING"; + +export type ErrorType = + | "INVALID_PLAYER_STATE" + | "LOAD_FAILED" + | "LOAD_CANCELLED" + | "INVALID_REQUEST" + | "ERROR"; + +export type ErrorReason = + | "INVALID_COMMAND" + | "INVALID_PARAMS" + | "INVALID_MEDIA_SESSION_ID" + | "SKIP_LIMIT_REACHED" + | "NOT_SUPPORTED" + | "LANGUAGE_NOT_SUPPORTED" + | "END_OF_QUEUE" + | "APP_ERROR" + | "AUTHENTICATION_EXPIRED" + | "PREMIUM_ACCOUNT_REQUIRED" + | "CONCURRENT_STREAM_LIMIT" + | "PARENTAL_CONTROL_RESTRICTED" + | "NOT_AVAILABLE_IN_REGION" + | "CONTENT_ALREADY_PLAYING" + | "INVALID_REQUEST" + | "GENERIC_LOAD_ERROR"; + +export type RepeatMode = + | "REPEAT_OFF" + | "REPEAT_ALL" + | "REPEAT_SINGLE" + | "REPEAT_ALL_AND_SHUFFLE"; + +export type IdleReason = "CANCELLED" | "INTERRUPTED" | "FINISHED" | "ERROR"; + +export type HlsSegmentFormat = "AAC" | "AC3" | "MP3" | "TS" | "TS_AAC"; + +export type HdrType = "SDR" | "HDR" | "DV"; + +export type PlayStringId = + | "FREE_TRIAL_ABOUT_TO_EXPIRE" + | "SUBSCRIPTION_ABOUT_TO_EXPIRE" + | "STREAM_HIJACKED"; + +export type GetStatusOptions = "NO_METADATA" | "NO_QUEUE_ITEMS"; + +export type MessageType = + | "MEDIA_STATUS" + | "CLOUD_STATUS" + | "QUEUE_CHANGE" + | "QUEUE_ITEMS" + | "QUEUE_ITEM_IDS" + | "GET_STATUS" + | "LOAD" + | "PAUSE" + | "STOP" + | "PLAY" + | "SKIP_AD" + | "PLAY_AGAIN" + | "SEEK" + | "SET_PLAYBACK_RATE" + | "SET_VOLUME" + | "EDIT_TRACKS_INFO" + | "EDIT_AUDIO_TRACKS" + | "PRECACHE" + | "PRELOAD" + | "QUEUE_LOAD" + | "QUEUE_INSERT" + | "QUEUE_UPDATE" + | "QUEUE_REMOVE" + | "QUEUE_REORDER" + | "QUEUE_NEXT" + | "QUEUE_PREV" + | "QUEUE_GET_ITEM_RANGE" + | "QUEUE_GET_ITEMS" + | "QUEUE_GET_ITEM_IDS" + | "QUEUE_SHUFFLE" + | "SET_CREDENTIALS" + | "LOAD_BY_ENTITY" + | "USER_ACTION" + | "DISPLAY_STATUS" + | "FOCUS_STATE" + | "CUSTOM_COMMAND"; + +export type PlayerState = "IDLE" | "PLAYING" | "PAUSED" | "BUFFERING"; + +export type QueueChangeType = + | "INSERT" + | "REMOVE" + | "ITEMS_CHANGE" + | "UPDATE" + | "NO_CHANGE"; + +export type QueueType = + | "ALBUM" + | "PLAYLIST" + | "AUDIOBOOK" + | "RADIO_STATION" + | "PODCAST_SERIES" + | "TV_SERIES" + | "VIDEO_PLAYLIST" + | "LIVE_TV" + | "MOVIE"; + +export type MetadataType = + | "GENERIC" + | "MOVIE" + | "TV_SHOW" + | "MUSIC_TRACK" + | "PHOTO"; + +/** + * RefreshCredentials request data. + */ +export interface RefreshCredentialsRequestData { + [key: string]: any; +} + +/** + * Media event SET_VOLUME request data. + */ +export interface VolumeRequestData extends RequestData { + /** + * The media stream volume + */ + volume?: Volume; +} + +/** + * Represents the volume of a media session stream. + */ +export interface Volume { + /** + * Value from 0 to 1 that represents the current stream volume level. + */ + level?: number; + + /** + * Whether the stream is muted. + */ + muted?: boolean; +} + +/** + * Video information such as video resolution and High Dynamic Range (HDR). + */ +export class VideoInformation { + constructor(width: number, height: number, hdrType: HdrType); + + width: number; + + height: number; + + hdrType: HdrType; +} + +/** + * VAST ad request configuration. + */ +export interface VastAdsRequest { + /** + * Specifies a VAST document to be used as the ads response instead of making a + * request via an ad tag url. + * This can be useful for debugging and other situations where a VAST response is + * already available. + */ + adsResponse?: string; + + /** + * URL for VAST file. + */ + adTagUrl?: string; +} + +/** + * UserAction request data. + */ +export interface UserActionRequestData { + /** + * Optional request source. + * It contain the assistent query that initiate the request. + */ + source?: string; + + /** + * User action to be handled by the application. + */ + userAction?: UserAction; + + /** + * Optional context information for the user action. + */ + userActionContext?: UserActionContext; +} + +/** + * A TV episode media description. + */ +export interface TvShowMediaMetadata { + /** + * TV episode number. A positive integer. + */ + episode?: number; + + /** + * @deprecated use episode instead + */ + episodeNumber?: number; + + /** + * @deprecated use episode instead + */ + episodeTitle?: string; + + /** + * Content images. Examples would include cover art or a thumbnail of + * the currently playing media. + */ + images?: Image[]; + + /** + * ISO 8601 date when the episode originally aired; e.g. 2014-02-10. + */ + originalAirdate?: string; + + /** + * @deprecated use originalAirdate instead. + */ + releaseYear?: number; + + /** + * TV episode season. A positive integer. + */ + season?: number; + + /** + * @deprecated use season instead. + */ + seasonNumber?: number; + + /** + * TV series title. + */ + seriesTitle?: string; + + /** + * TV episode title. + */ + title?: string; +} +/** + * Describes track metadata information. + */ +export class Track { + constructor(trackId: number, trackType: TrackType); + + /** + * Custom data set by the receiver application. + */ + customData?: string; + + /** + * Language tag as per RFC 5646 (If subtype is “SUBTITLES” it is mandatory). + */ + language?: string; + + /** + * A descriptive; human readable name for the track. For example "Spanish". + */ + name?: string; + + /** + * For text tracks; the type of text track. + */ + subtype?: string; + + /** + * It can be the url of the track or any other identifier that allows the receiver + * to find the content (when the track is not inband or included in the manifest). + * For example it can be the url of a vtt file. + */ + trackContentId?: string; + + /** + * It represents the MIME type of the track content. For example if the track + * is a vtt file it will be ‘text/vtt’. This field is needed for out of band tracks; + * so it is usually provided if a trackContentId has also been provided. + * It is not mandatory if the receiver has a way to identify the content from + * the trackContentId; but recommended. + * The track content type; if provided; must be consistent with the track type. + */ + trackContentType?: string; + + /** + * Unique identifier of the track within the context of a MediaInformation object. + */ + trackId?: number; + + /** + * The type of track. + */ + type: TrackType; +} +/** + * Describes style information for a text track. + */ +export interface TextTrackStyle { + /** + * The background 32 bit RGBA color. The alpha channel should be used for transparent backgrounds. + */ + backgroundColor?: string; + + /** + * Custom data set by the receiver application. + */ + customData?: any; + + /** + * RGBA color for the edge; this value will be ignored if edgeType is NONE. + */ + edgeColor?: string; + + edgeType?: TextTrackEdgeType; + + /** + * If the font is not available in the receiver the fontGenericFamily will be used. + */ + fontFamily?: string; + + /** + * The text track generic family. + */ + fontGenericFamily?: TextTrackFontGenericFamily; + + /** + * The font scaling factor for the text track (the default is 1). + */ + fontScale?: number; + + /** + * The text track font style. + */ + fontStyle?: TextTrackFontStyle; + + /** + * The foreground 32 bit RGBA color. + */ + foregroundColor?: string; + + /** + * 32 bit RGBA color for the window. This value will be ignored if windowType is NONE. + */ + windowColor?: string; + + /** + * Rounded corner radius absolute value in pixels (px). This value will be ignored + * if windowType is not ROUNDED_CORNERS. + */ + windowRoundedCornerRadius?: number; + + /** + * The window concept is defined in CEA-608 and CEA-708. In WebVTT is called a region. + */ + windowType?: TextTrackWindowType; +} + +/** + * Media event playback rate request data. + */ +export interface SetPlaybackRateRequestData extends RequestData { + /** + * New playback rate (>0). + */ + playbackRate?: number; + + /** + * New playback rate relative to current playback rate. + * New rate will be the result of multiplying the current rate with the value. + * For example a value of 1.1 will increase rate by 10%. + * (Only used if the playbackRate value is not provided). + */ + relativePlaybackRate?: number; +} + +/** + * SetCredentials request data. + */ +export interface SetCredentialsRequestData { + /** + * Credentials to use by receiver. + */ + credentials?: string; + + /** + * If it is a response for refresh credentials; it will indicate the request id + * of the refresh credentials request. + */ + forRequestId?: number; + + /** + * Optional request source. It contain the assistent query that initiate the request. + */ + source?: string; +} + +/** + * Media event SEEK request data. + */ +export interface SeekRequestData extends RequestData { + /** + * Seconds since beginning of content. + */ + currentTime?: number; + + /** + * Seconds relative to the current playback position. If this field is defined; + * the currentTime field will be ignored. + */ + relativeTime?: number; + + /** + * The playback state after a SEEK request. + */ + resumeState?: SeekResumeState; +} + +/** + * Provides seekable range in seconds. + */ +export class SeekableRange { + constructor(start?: number, end?: number); + + /** + * End of the seekable range in seconds. + */ + end?: number; + + /** + * Start of the seekable range in seconds. + */ + start?: number; +} + +/** + * Media event request data. + */ +export class RequestData { + constructor(type: MessageType); + + /** + * Application-specific data for this request. + * It enables the sender and receiver to easily extend the media protocol + * without having to use a new namespace with custom messages. + */ + customData?: any; + + /** + * Id of the media session that the request applies to. + */ + mediaSessionId?: number; + + /** + * Id of the request; used to correlate request/response. + */ + requestId: number; +} + +/** + * Media event UPDATE queue request data. + */ +export interface QueueUpdateRequestData { + /** + * ID of the current media Item after the deletion + * (if not provided; the currentItem value will be the same as before the deletion; + * if it does not exist because it has been deleted; the currentItem will point to + * the next logical item in the list). + */ + currentItemId?: number; + + /** + * Seconds since the beginning of content to start playback of the current item. + * If provided; this value will take precedence over the startTime value provided + * at the QueueItem level but only the first time the item is played. + * This is to cover the common case where the user jumps to the middle of an + * item so the currentTime does not apply to the item permanently like the + * QueueItem startTime does. It avoids having to reset the startTime dynamically + * (that may not be possible if the phone has gone to sleep). + */ + currentTime?: number; + + /** + * List of queue items to be updated. No reordering will happen; the items will + * retain the existing order. + */ + items?: QueueItem[]; + + /** + * Skip/Go back number of items with respect to the position of currentItem + * (it can be negative). If it is out of boundaries; the currentItem will be the + * next logical item in the queue wrapping around the boundaries. + * The new currentItem position will follow the rules of the queue repeat behavior. + */ + jump?: number; + + /** + * Behavior of the queue when all items have been played. + */ + repeatMode?: RepeatMode; + + /** + * Shuffle the queue items when the update is processed. + * After the queue items are shuffled; the item at the currentItem position will + * be loaded. + */ + shuffle?: boolean; +} + +/** + * Media event queue REORDER request data. + */ +export class QueueReorderRequestData extends RequestData { + constructor(itemIds: number[]); + + /** + * ID of the current media Item after the deletion (if not provided; + * the currentItem value will be the same as before the deletion; + * if it does not exist because it has been deleted; + * the currentItem will point to the next logical item in the list). + */ + currentItemId?: number; + + /** + * Seconds since the beginning of content to start playback of the current item. + * If provided; this value will take precedence over the startTime value provided + * at the QueueItem level but only the first time the item is played. + * This is to cover the common case where the user jumps to the middle of an + * item so the currentTime does not apply to the item permanently like + * the QueueItem startTime does. It avoids having to reset the startTime dynamically + * (that may not be possible if the phone has gone to sleep). + */ + currentTime?: number; + + /** + * ID of the item that will be located immediately after the reordered list. + * If the ID is not found or it is not provided; + * the reordered list will be appended at the end of the existing list. + */ + insertBefore?: number; + + /** + * IDs of the items to be reordered; in the new order. + * Items not provided will keep their existing order. + * The provided list will be inserted at the position determined by insertBefore. + * For example: + * If insertBefore is not specified Existing queue: “A”;”D”;”G”;”H”;”B”;”E” itemIds: + * “D”;”H”;”B” New Order: “A”;”G”;”E”;“D”;”H”;”B” + * If insertBefore is “A” Existing queue: “A”;”D”;”G”;”H”;”B” itemIds: + * “D”;”H”;”B” New Order: “D”;”H”;”B”;“A”;”G”;”E” + * If insertBefore is “G” Existing queue: “A”;”D”;”G”;”H”;”B” itemIds: + * “D”;”H”;”B” New Order: “A”;“D”;”H”;”B”;”G”;”E” + */ + itemIds: number[]; +} + +/** + * Media event queue REMOVE request data. + */ +export class QueueRemoveRequestData extends RequestData { + constructor(itemIds: number[]); + + /** + * ID of the current media Item after the deletion + * (if not provided; the currentItem value will be the same as before the deletion; + * if it does not exist because it has been deleted; + * the currentItem will point to the next logical item in the list). + */ + currentItemId?: number; + + /** + * Seconds since the beginning of content to start playback of the current item. + * If provided; this value will take precedence over the startTime value provided + * at the QueueItem level but only the first time the item is played. + * This is to cover the common case where the user jumps to the middle of an + * item so the currentTime does not apply to the item permanently like the + * QueueItem startTime does. It avoids having to reset the startTime dynamically + * (that may not be possible if the phone has gone to sleep). + */ + currentTime?: number; + + /** + * IDs of queue items to be deleted. + */ + itemIds?: number[]; +} +/** + * Media event queue LOAD request data. + */ +export class QueueLoadRequestData extends RequestData { + constructor(items: QueueItem[]); + + /** + * Seconds (since the beginning of content) to start playback of the first item to + * be played. If provided; this value will take precedence over the + * startTime value provided at the QueueItem level but only the first + * time the item is played. This is to cover the common case where the user + * casts the item that was playing locally so the currentTime does not apply + * to the item permanently like the QueueItem startTime does. + * It avoids having to reset the startTime dynamically + * (that may not be possible if the phone has gone to sleep). + */ + currentTime?: number; + + /** + * Behavior of the queue when all items have been played. + */ + items: QueueItem[]; + + /** + * Id of the request; used to correlate request/response. + */ + repeatMode?: RepeatMode; + + /** + * The index of the item in the items array that must be the first currentItem + * (the item that will be played first). Note this is the index of the array + * (starts at 0) and not the itemId (as it is not known until the queue is created). + * If repeatMode is REPEAT_OFF playback will end when the last item in the array is + * played (elements before the startIndex will not be played). + * This may be useful for continuation scenarios where the user was already + * using the sender app and in the middle decides to cast. + * In this way the sender app does not need to map between the local and remote queue + * positions or saves one extra QUEUE_UPDATE request. + */ + startIndex?: number; +} + +/** + * Queue item information. Application developers may need to create a QueueItem to + * insert a queue element using InsertQueueItems. In this case they should not + * provide an itemId (as the actual itemId will be assigned when the item is inserted + * in the queue). This prevents ID collisions with items added from a sender app. + */ +export class QueueItem { + constructor(opt_itemId?: number); + + /** + * Array of Track trackIds that are active. If the array is not provided; + * the default tracks will be active. + */ + activeTrackIds?: number[]; + + /** + * If the autoplay parameter is not specified or is true; the media player + * will begin playing the element in the queue when the item becomes the currentItem. + */ + autoplay?: boolean; + + /** + * The application can define any extra queue item information needed. + */ + customData?: any; + + /** + * Unique identifier of the item in the queue. + * The attribute is optional because for LOAD or INSERT should not be provided + * (as it will be assigned by the receiver when an item is first created/inserted). + */ + itemId?: number; + + /** + * Metadata (including contentId) of the playlist element. + */ + media?: MediaInformation; + + /** + * Playback duration of the item; if it is larger than the actual duration - + * startTime it will be ignored (default behavior). + * It can be negative; in such case the duration will be the actual asset + * duration minus the duration provided. + * It can be used for photo slideshows to control the duration the item should + * be presented or for live events to control the duration that the program + * should be played. It may be useful for autoplay scenarios to avoid displaying all + * the credits after an episode has ended. + */ + playbackDuration?: number; + + /** + * This parameter is a hint for the receiver to preload this media + * item before it is played. It allows for a smooth transition between items + * played from the queue. The time is expressed in seconds; relative to + * the beginning of this item playback (usually the end of the previous item playback). + * Only positive values are valid. For example; if the value is 10 seconds; this item + * will be preloaded 10 seconds before the previous item has finished. + * The receiver will try to honor this value but will not guarantee it; + * for example if the value is larger than the previous item duration the + * receiver may just preload this item shortly after the previous item has started playing + * (there will never be two items being preloaded in parallel). + * Also; if an item is inserted in the queue just after the currentItem and the time to preload is higher than the + * time left on the currentItem; the preload will just happen as soon as possible. + */ + preloadTime?: number; + + /** + * Seconds since beginning of content. If the content is live content; + * and startTime is not specified; the stream will start at the live position. + */ + startTime?: number; +} + +/** + * Media event queue INSERT request data. + */ +export class QueueInsertRequestData extends RequestData { + constructor(items: QueueItem[]); + + /** + * ID of the current media Item after the insertion (if not provided; + * the currentItem value will be the same as before the insertion). + */ + currentItemId?: number; + + /** + * Index (relative to the items array; starting with 0) of the new current media Item. + * For inserted items we use the index (similar to startIndex in QUEUE_LOAD) and not + * currentItemId; because the itemId is unknown until the items are inserted. + * If not provided; the currentItem value will be the same as before the insertion + * (unless currentItemId is provided). This param allows to make atomic the common use + * case of insert and play an item. + */ + currentItemIndex?: number; + + /** + * Seconds since the beginning of content to start playback of the current item. + * If provided; this value will take precedence over the startTime value provided + * at the QueueItem level but only the first time the item is played. + * This is to cover the common case where the user jumps to the middle of an + * item so the currentTime does not apply to the item permanently like the + * QueueItem startTime does. It avoids having to reset the startTime dynamically + * (that may not be possible if the phone has gone to sleep). + */ + currentTime?: number; + + /** + * ID of the item that will be located immediately after the inserted list. + * If the ID is not found or it is not provided; the list will be appended at + * the end of the existing list. + */ + insertBefore?: number; + + /** + * List of queue items. The itemId field of the items should be empty. + * It is sorted (first element will be played first). + */ + items: QueueItem[]; +} + +/** + * Represents a data message containing the full list of queue ids. + */ +export interface QueueIds { + /** + * List of queue item ids. + */ + itemIds?: number[]; + + /** + * The corresponding request id. + */ + requestId?: number; + + type: MessageType; +} + +/** + * Queue data as part of the LOAD request. + */ +export class QueueData { + constructor( + id?: string, + name?: string, + description?: string, + repeatMode?: RepeatMode, + items?: QueueItem[], + startIndex?: number, + startTime?: number + ); + + /** + * Description of the queue. + */ + description?: string; + + /** + * Optional Queue entity id; provide Google Assistant deep link. + */ + entity?: string; + + /** + * Id of the queue. + */ + id?: string; + + /** + * Array of queue items. It is sorted (first element will be played first). + */ + items?: QueueItem[]; + + /** + * Name of the queue. + */ + name?: string; + + /** + * Queue type; e.g. album; playlist; radio station; tv series; etc. + */ + queueType?: QueueType; + + /** + * Continuous playback behavior of the queue. + */ + repeatMode?: RepeatMode; + + /** + * The index of the item in the queue that should be used to start playback first. + */ + startIndex?: number; + + /** + * Seconds (since the beginning of content) to start playback of the first item. + */ + startTime?: number; +} + +/** + * Represents a queue change message; such as insert; remove; and update. + */ +export interface QueueChange { + /** + * The actual queue change type. + */ + changeType?: QueueChangeType; + + /** + * The id to insert the list of itemIds before. + */ + insertBefore?: number; + + /** + * List of changed itemIds. + */ + itemIds?: number[]; + + /** + * The corresponding request id. + */ + requestId?: number; + + /** + * The queue change sequence ID. Used to coordinate state sync between various + * senders and the receiver. + */ + sequenceNumber?: number; + + type: MessageType; +} + +/** + * Media event PRELOAD request data. + */ +export class PreloadRequestData implements LoadRequestData { + /** + * Array of trackIds that are active. If the array is not provided; + * the default tracks will be active. + */ + activeTrackIds: number[]; + /** + * If the autoplay parameter is specified; the media player will begin playing + * the content when it is loaded. Even if autoplay is not specified;the media player + * implementation may choose to begin playback immediately. + */ + autoplay?: boolean; + /** + * Optional user credentials. + */ + credentials?: string; + /** + * Optional credentials type. The type 'cloud' is a reserved type used by load + * requests that were originated by voice assistant commands. + */ + credentialsType?: string; + /** + * Seconds since beginning of content. If the content is live content; + * and currentTime is not specified; the stream will start at the live position. + */ + currentTime?: number; + /** + * If the autoplay parameter is specified; the media player will begin playing + * the content when it is loaded. Even if autoplay is not specified; the media + * player implementation may choose to begin playback immediately. + */ + media: MediaInformation; + /** + * The media playback rate. + */ + playbackRate?: number; + /** + * Queue data. + */ + queueData: QueueData; + /** + * Application-specific data for this request. + * It enables the sender and receiver to easily extend the media protocol + * without having to use a new namespace with custom messages. + */ + customData?: any; + /** + * Id of the media session that the request applies to. + */ + mediaSessionId?: number; + /** + * Id of the request; used to correlate request/response. + */ + requestId: number; + constructor(itemId: number); + + /** + * The ID of the queue item. + */ + itemId: number; +} + +/** + * Media event PRECACHE request data. (Some fields of the load request; + * like autoplay and queueData; are ignored). + */ +export class PrecacheRequestData implements LoadRequestData { + /** + * Array of trackIds that are active. If the array is not provided; + * the default tracks will be active. + */ + activeTrackIds: number[]; + /** + * If the autoplay parameter is specified; the media player will begin playing + * the content when it is loaded. Even if autoplay is not specified;the media player + * implementation may choose to begin playback immediately. + */ + autoplay?: boolean; + /** + * Optional user credentials. + */ + credentials?: string; + /** + * Optional credentials type. The type 'cloud' is a reserved type used by load + * requests that were originated by voice assistant commands. + */ + credentialsType?: string; + /** + * Seconds since beginning of content. If the content is live content; and + * currentTime is not specified; the stream will start at the live position. + */ + currentTime?: number; + /** + * If the autoplay parameter is specified; the media player will begin playing + * the content when it is loaded. Even if autoplay is not specified; + * the media player implementation may choose to begin playback immediately. + */ + media: MediaInformation; + /** + * The media playback rate. + */ + playbackRate?: number; + /** + * Queue data. + */ + queueData: QueueData; + /** + * Application-specific data for this request. + * It enables the sender and receiver to easily extend the media protocol + * without having to use a new namespace with custom messages. + */ + customData?: any; + /** + * Id of the media session that the request applies to. + */ + mediaSessionId?: number; + /** + * Id of the request; used to correlate request/response. + */ + requestId: number; + constructor(data?: string); + + /** + * Application precache data. + */ + precacheData?: string; +} + +/** + * PlayString request data. + */ +export class PlayStringRequestData { + constructor(stringId: PlayStringId, opt_arguments?: string[]); + + /** + * An optional array of string values to be filled into the text. + */ + arguments?: string[]; + + /** + * An identifier for the text to be played back. + */ + stringId: PlayStringId; +} + +/** + * A photo media description. + */ +export interface PhotoMediaMetadata { + /** + * Name of the photographer. + */ + artist?: string; + + /** + * ISO 8601 date and time the photo was taken; e.g. 2014-02-10T15:47:00Z. + */ + creationDateTime?: string; + + /** + * Photo height; in pixels. + */ + height?: number; + + /** + * Images associated with the content. Examples would include a photo thumbnail. + */ + images: Image[]; + + /** + * Latitude. + */ + latitude?: number; + + /** + * Location where the photo was taken. For example; "Seattle; Washington; USA". + */ + location?: string; + + /** + * Longitude. + */ + longitude?: number; + + /** + * Photo title. + */ + title?: string; + + /** + * Photo width; in pixels. + */ + width?: number; +} + +/** + * A music track media description. + */ +export interface MusicTrackMediaMetadata { + /** + * Album artist name. + */ + albumArtist?: string; + + /** + * Album name. + */ + albumName?: string; + + /** + * Track artist name. + */ + artist?: string; + + /** + * @deprecated: use @see{@link artist} instead + */ + artistName: string; + + /** + * Track composer name. + */ + composer?: string; + + /** + * Disc number. A positive integer. + */ + discNumber?: number; + + /** + * Content images. Examples would include cover art or a thumbnail of the + * currently playing media. + */ + images: Image[]; + + /** + * ISO 8601 date when the track was released; e.g. 2014-02-10. + */ + releaseDate?: string; + + /** + * @deprecated: Use @see{@link releaseDate} instead + */ + releaseYear?: string; + + /** + * Track name. + */ + songName?: string; + + /** + * Track title. + */ + title?: string; + + /** + * Track number in album. A positive integer. + */ + trackNumber?: number; +} + +/** + * A movie media description. + */ +export interface MovieMediaMetadata { + /** + * Content images. Examples would include cover art or a thumbnail of the + * currently playing media. + */ + images: Image[]; + + /** + * ISO 8601 date when the movie was released; e.g. 2014-02-10. + */ + releaseDate?: string; + + /** + * @deprecated: use @see{@link releaseDate} instead + */ + releaseYear?: number; + + /** + * Movie studio. + */ + studio?: string; + + /** + * Movie subtitle. + */ + subtitle?: string; + + /** + * Movie title. + */ + title?: string; +} +/** + * Represents the status of a media session. + */ +export interface MediaStatus { + /** + * List of IDs corresponding to the active tracks. + */ + activeTrackIds: number[]; + + /** + * Status of break; if receiver is playing break. + * This field will be defined only when receiver is playing break. + */ + breakStatus: BreakStatus; + + /** + * ID of this media item (the item that originated the status change). + */ + currentItemId?: number; + + /** + * The current playback position. + */ + currentTime: number; + + /** + * Application-specific media status. + */ + customData?: any; + + /** + * Extended media status information. + */ + extendedStatus: ExtendedMediaStatus; + + /** + * If the state is IDLE; the reason the player went to IDLE state. + */ + idleReason: IdleReason; + + /** + * List of media queue items. + */ + items: QueueItem[]; + + /** + * Seekable range of a live or event stream. It uses relative media time in seconds. + * It will be undefined for VOD streams. + */ + liveSeekableRange: LiveSeekableRange; + + /** + * ID of the media Item currently loading. If there is no item being loaded; + * it will be undefined. + */ + loadingItemId?: number; + + /** + * The media information. + */ + media: MediaInformation; + + /** + * Unique id for the session. + */ + mediaSessionId: number; + + /** + * The playback rate. + */ + playbackRate: number; + + /** + * The playback state. + */ + playerState: PlayerState; + + /** + * ID of the next Item; only available if it has been preloaded. + * Media items can be preloaded and cached temporarily in memory; + * so when they are loaded later on; the process is faster + * (as the media does not have to be fetched from the network). + */ + preloadedItemId?: number; + + /** + * Queue data. + */ + queueData: QueueData; + + /** + * The behavior of the queue when all items have been played. + */ + repeatMode: RepeatMode; + + /** + * The commands supported by this player. + */ + supportedMediaCommands: number; + + type: MessageType; + + /** + * The video information. + */ + videoInfo: VideoInformation; + + /** + * The current stream volume. + */ + volume: Volume; +} +/** + * Common media metadata used as part of MediaInformation + */ +export class MediaMetadata { + constructor(type: MetadataType); + + /** + * The type of metadata + */ + metadataType: MetadataType; +} + +/** + * Represents the media information. + */ +export interface MediaInformation { + /** + * Partial list of break clips that includes current break clip that receiver + * is playing or ones that receiver will play shortly after; instead of sending + * whole list of clips. This is to avoid overflow of MediaStatus message. + */ + breakClips: BreakClip[]; + + /** + * List of breaks. + */ + breaks: Break[]; + + /** + * Typically the url of the media. + */ + contentId: string; + + /** + * The content MIME type. + */ + contentType: string; + + /** + * Optional media url; to allow using contentId for real id. If contentUrl + * is provided; it will be used as media url; otherwise the contentId will + * be used as the media url. + */ + contentUrl?: string; + + /** + * Application-specific media information. + */ + customData?: any; + + /** + * The media duration. + */ + duration?: number; + + /** + * Optional Media entity; provide Google Assistant deep link. + */ + entity?: string; + + /** + * The format of the HLS media segment. + */ + hlsSegmentFormat: HlsSegmentFormat; + + /** + * The media metadata. + */ + metadata: MediaMetadata; + + /** + * The stream type. + */ + streamType: StreamType; + + /** + * The style of text track. + */ + textTrackStyle: TextTrackStyle; + + /** + * The media tracks. + */ + tracks: Track[]; +} + +/** + * Media event LOAD request data. + */ +export interface LoadRequestData extends RequestData { + /** + * Array of trackIds that are active. If the array is not provided; the + * default tracks will be active. + */ + activeTrackIds: number[]; + + /** + * If the autoplay parameter is specified; the media player will begin + * playing the content when it is loaded. Even if autoplay is not + * specified;the media player implementation may choose to begin playback + * immediately. + */ + autoplay?: boolean; + + /** + * Optional user credentials. + */ + credentials?: string; + + /** + * Optional credentials type. The type 'cloud' is a reserved type used by + * load requests that were originated by voice assistant commands. + */ + credentialsType?: string; + + /** + * Seconds since beginning of content. If the content is live content; + * and currentTime is not specified; the stream will start at the live position. + */ + currentTime?: number; + + /** + * If the autoplay parameter is specified; the media player will begin playing + * the content when it is loaded. Even if autoplay is not specified; the media + * player implementation may choose to begin playback immediately. + */ + media: MediaInformation; + + /** + * The media playback rate. + */ + playbackRate?: number; + + /** + * Queue data. + */ + queueData: QueueData; +} + +/** + * LoadByEntity request data. + */ +export interface LoadByEntityRequestData { + /** + * Content entity information; typically represented by a stringified JSON object + */ + entity: string; + + /** + * Shuffle the items to play. + */ + shuffle?: boolean; + + /** + * Optional request source. It contain the assistent query that initiate the request. + */ + source?: string; +} + +/** + * Provides live seekable range with start and end time in seconds and two more + * attributes. + */ +export class LiveSeekableRange { + constructor( + start?: number, + end?: number, + isMovingWindow?: boolean, + isLiveDone?: boolean + ); + + /** + * A boolean value indicates whether a live stream is ended. If it is done; + * the end of live seekable range should stop updating. + */ + isLiveDone?: boolean; + + /** + * A boolean value indicates whether the live seekable range is a moving window. + * If false; it will be either a expanding range or a fixed range meaning live + * has ended. + */ + isMovingWindow?: boolean; +} + +/** + * Represents a data message containing item information for each requested ids. + */ +export interface ItemsInfo { + /** + * List of changed itemIds. + */ + items: QueueItem[]; + + /** + * The corresponding request id. + */ + requestId?: number; + + type: MessageType; +} + +/** + * An image that describes a receiver application or media item. + * This could be an application icon; cover art; or a thumbnail. + */ +export class Image { + constructor(url: string); + + /** + * The height of the image. + */ + height?: number; + + /** + * the URL to the image + */ + url: string; + + /** + * The width of the image + */ + width?: number; +} +/** Media event GET_STATUS request data. */ +export interface GetStatusRequestData extends RequestData { + /** + * The options of a GET_STATUS request. + */ + options: GetStatusOptions; +} + +/** + * Get items info request data. + */ +export class GetItemsInfoRequestData extends RequestData { + constructor(itemIds: number[]); + + /** + * List of item ids to be requested. + */ + itemIds: number[]; +} +/** + * A generic media description. + */ +export interface GenericMediaMetadata extends MediaMetadata { + /** + * Content images. Examples would include cover art or a thumbnail of the + * currently playing media. + */ + images: Image[]; + + /** + * ISO 8601 date and/or time when the content was released; e.g. 2014-02-10. + */ + releaseDate?: string; + + /** + * @deprecated - use @see{@link releaseDate} instead + */ + releaseYear?: number; + + /** + * Content subtitle. + */ + subtitle?: string; + + /** + * Content title. + */ + title?: string; +} + +/** + * Focus state change message. + */ +export interface FocusStateRequestData { + /** + * The focus state of the app. + */ + state: FocusState; +} + +/** Fetch items request data. */ +export class FetchItemsRequestData extends RequestData { + constructor(itemId: number, nextCount: number, prevCount: number); + + /** + * ID of the reference media item for fetching more items. + */ + itemId: number; + + /** + * Number of items after the reference item to be fetched. + */ + nextCount: number; + + /** + * Number of items before the reference item to be fetched. + */ + prevCount: number; +} + +/** + * Extended media status information + */ +export class ExtendedMediaStatus { + constructor( + playerState: MediaInformation, + opt_media?: MediaInformation + ); + + media: MediaInformation; + + playerState: ExtendedPlayerState; +} + +/** Event data for @see{@link EventType.ERROR} event. */ +export class ErrorEvent extends Event { + constructor(detailedErrorCode?: DetailedErrorCode, error?: any); + + /** + * An error code representing the cause of the error. + */ + detailedErrorCode?: DetailedErrorCode; + + /** + * The error object. + * This could be an Error object (e.g.; if an Error was thrown in an event handler) + * or an object with error information (e.g.; if the receiver received an invalid + * command). + */ + error?: any; +} + +export class ErrorData { + constructor(type: ErrorType); + + /** + * Application-specific data for this request. + * It enables the sender and receiver to easily extend the media protocol + * without having to use a new namespace with custom messages. + */ + customData?: any; + + /** + * Id of the request; used to correlate request/response. + */ + requestId?: number; +} + +/** Media event EDIT_TRACKS_INFO request data. */ +export interface EditTracksInfoRequestData extends RequestData { + /** + * Array of the Track trackIds that should be active. + * If it is not provided; the active tracks will not change. + * If the array is empty; no track will be active. + */ + activeTrackIds?: number[]; + + /** + * Flag to enable or disable text tracks. + * If false it will disable all text tracks; + * if true it will enable the first text track; or the previous active text tracks. + * This flag is ignored if activeTrackIds or language is provided. + */ + enableTextTracks?: boolean; + + /** + * Indicates that the provided language was not explicit user request; but rather + * inferred from used language in voice query. + * It allows receiver apps to use user saved preference instead of spoken language. + */ + isSuggestedLanguage?: boolean; + + /** + * Language for the tracks that should be active. The language field will take + * precedence over activeTrackIds if both are specified. + */ + language?: string; + + textTrackStyle?: TextTrackStyle; +} + +/** + * Media event EDIT_AUDIO_TRACKS request data. If language is not provided; + * the default audio track for the media will be enabled. + */ +export interface EditAudioTracksRequestData extends RequestData { + /** + * Indicates that the provided language was not explicit user request; + * but rather inferred from used language in voice query. + * It allows receiver apps to use user saved preference instead of spoken language. + */ + isSuggestedLanguage?: boolean; + + language?: string; +} + +/** DisplayStatus request data. */ +export interface DisplayStatusRequestData { + /** + * Optional request source. It contain the assistent query that initiate the request. + */ + source: string; +} + +/** CustomCommand request data. */ +export interface CustomCommandRequestData { + /** + * Custom Data; typically represented by a stringified JSON object. + */ + data: string; + + /** + * Optional request source. It contain the assistent query that initiate the request. + */ + source: string; +} + +export class BreakStatus { + constructor(currentBreakTime: number, currentBreakClipTime: number); + + /** + * Id of current break clip. + */ + breakClipId: string; + + /** + * Id of current break. + */ + breakId: string; + + /** + * Time in sec elapsed after current break clip starts. + */ + currentBreakClipTime: number; + + /** + * Time in sec elapsed after current break starts. + */ + currentBreakTime: number; + + /** + * The time in sec when this break clip becomes skippable. + * 5 means that end user can skip this break clip after 5 seconds. + * If this field is not defined; it means that current break clip is not skippable. + */ + whenSkippable: number; +} + +/** + * Represents break clip (e.g. a clip of ad during ad break) + */ +export class BreakClip { + constructor(id: string); + + /** + * Url of page that sender will display; when end user clicks link on sender UI; while receiver is playing this clip. + */ + clickThroughUrl?: string; + /** + * Typically the url of the break media (playing on the receiver). + */ + contentId?: string; + /** + * The content MIME type. + */ + contentType?: string; + /** + * Optional break media url; to allow using contentId for real id. + * If contentUrl is provided; it will be used as media url; + * otherwise the contentId will be used as the media url. + */ + contentUrl?: string; + /** + * Application-specific break clip data. + */ + customData?: any; + /** + * Duration of break clip in sec. + */ + duration?: number; + /** + * The format of the HLS media segment. + */ + hlsSegmentFormat?: HlsSegmentFormat; + /** + * Unique id of break clip. + */ + id: string; + /** + * Url of content that sender will display while receiver is playing this clip. + */ + posterUrl?: string; + /** + * Title of break clip. Sender might display this on its screen; if provided. + */ + title?: string; + /** + * VAST ad request configuration. Used if contentId or contentUrl is not provided. + */ + vastAdsRequest?: VastAdsRequest; + /** + * The time in sec when this break clip becomes skippable. + * 5 means that end user can skip this break clip after 5 seconds. + * If this field is not defined; it means that current break clip is not skippable. + */ + whenSkippable?: number; +} + +/** Represents break (e.g. ad break) included in main video. */ +export class Break { + constructor(id: string, breakClipIds: string[], position: number); + /** + * List of ids of break clip that this break includes. + */ + breakClipIds: string[]; + /** + * Duration of break in sec. + */ + duration?: number; + /** + * Unique id of break. + */ + id: string; + /** + * If true; indicates this is embedded break in main stream. + */ + + isEmbedded?: boolean; + /** + * Whether break is watched. + * Sender can change color of progress bar marker corresponding to this break once + * this field changes from false to true; + * denoting that the end-user already watched this break. + */ + isWatched: boolean; + + /** + * Where the break is located inside main video. -1 represents the end of main video. + */ + position: number; } diff --git a/types/chromecast-caf-receiver/cast.framework.system.d.ts b/types/chromecast-caf-receiver/cast.framework.system.d.ts index d055e252fb..1aacb05058 100644 --- a/types/chromecast-caf-receiver/cast.framework.system.d.ts +++ b/types/chromecast-caf-receiver/cast.framework.system.d.ts @@ -1,198 +1,196 @@ import { EventType } from "./cast.framework.events"; -export = cast.framework.system; -declare namespace cast.framework.system { - type EventType = - // Fired when the system is ready. - | "READY" - // Fired when the application is terminated - | "SHUTDOWN" - // Fired when a new sender has connected. - | "SENDER_CONNECTED" - // Fired when a sender has disconnected. - | "SENDER_DISCONNECTED" - // Fired when there is a system error. - | "ERROR" - // Fired when the system volume has changed. - | "SYSTEM_VOLUME_CHANGED" - // Fired when the visibility of the application has changed - // (for example after a HDMI Input change or when the TV is turned - // off/on and the cast device is externally powered). - // Note that this API has the same effect as the webkitvisibilitychange event raised - // by your document, we provided it as CastReceiverManager API for convenience and - // to avoid a dependency on a webkit-prefixed event. - | "VISIBILITY_CHANGED" - // Fired when the standby state of the TV has changed. - // This event is related to the visibility chnaged event, as if the TV is in standby - // the visibility will be false, the visibility is more granular - // (as it also detects that the TV has selected a different channel) - // but it is not reliably detected in all TVs, - // standby can be used in those cases as most TVs implement it. - | "STANDBY_CHANGED" - | "MAX_VIDEO_RESOLUTION_CHANGED" - | "FEEDBACK_STARTED"; +export as namespace system +export type EventType = + // Fired when the system is ready. + | "READY" + // Fired when the application is terminated + | "SHUTDOWN" + // Fired when a new sender has connected. + | "SENDER_CONNECTED" + // Fired when a sender has disconnected. + | "SENDER_DISCONNECTED" + // Fired when there is a system error. + | "ERROR" + // Fired when the system volume has changed. + | "SYSTEM_VOLUME_CHANGED" + // Fired when the visibility of the application has changed + // (for example after a HDMI Input change or when the TV is turned + // off/on and the cast device is externally powered). + // Note that this API has the same effect as the webkitvisibilitychange event raised + // by your document, we provided it as CastReceiverManager API for convenience and + // to avoid a dependency on a webkit-prefixed event. + | "VISIBILITY_CHANGED" + // Fired when the standby state of the TV has changed. + // This event is related to the visibility chnaged event, as if the TV is in standby + // the visibility will be false, the visibility is more granular + // (as it also detects that the TV has selected a different channel) + // but it is not reliably detected in all TVs, + // standby can be used in those cases as most TVs implement it. + | "STANDBY_CHANGED" + | "MAX_VIDEO_RESOLUTION_CHANGED" + | "FEEDBACK_STARTED"; - type SystemState = - | "NOT_STARTED" - | "STARTING_IN_BACKGROUND" - | "STARTING" - | "READY" - | "STOPPING_IN_BACKGROUND" - | "STOPPING"; +export type SystemState = + | "NOT_STARTED" + | "STARTING_IN_BACKGROUND" + | "STARTING" + | "READY" + | "STOPPING_IN_BACKGROUND" + | "STOPPING"; - type StandbyState = "STANDBY" | "NOT_STANDBY" | "UNKNOWN"; +export type StandbyState = "STANDBY" | "NOT_STANDBY" | "UNKNOWN"; - type DisconnectReason = "REQUESTED_BY_SENDER" | "ERROR" | "UNKNOWN"; +export type DisconnectReason = "REQUESTED_BY_SENDER" | "ERROR" | "UNKNOWN"; + +/** + * Event dispatched by @see{@link CastReceiverManager} when the visibility of the application changes (HDMI input change; TV is turned off). + */ +export class VisibilityChangedEvent { + constructor(isVisible: boolean); /** - * Event dispatched by @see{@link CastReceiverManager} when the visibility of the application changes (HDMI input change; TV is turned off). + * Whether the Cast device is the active input or not. */ - class VisibilityChangedEvent { - constructor(isVisible: boolean); + isVisible: boolean; +} - /** - * Whether the Cast device is the active input or not. - */ - isVisible: boolean; - } +/** + * Represents the system volume data. + */ +export interface SystemVolumeData { + /** + * The level (from 0.0 to 1.0) of the system volume + */ + level: number; + + /** + * Whether the system volume is muted or not. + */ + muted: boolean; +} +/** + * Event dispatched by @see{CastReceiverManager} when the system volume changes. + */ +export class SystemVolumeChangedEvent extends Event { + constructor(volume: SystemVolumeData); + + /** + * The system volume data + */ + data: SystemVolumeData; +} +/** + * Event dispatched by @see{@link CastReceiverManager} when the TV enters/leaves the standby state. + */ +export class StandbyChangedEvent { + constructor(isStandby: boolean); + + isStandby: boolean; +} +/** + * Whether the TV is in standby or not. + */ +export interface ShutdownEvent extends Event { + [key: string]: any; +} + +/** + * Event dispatched by @see{@link CastReceiverManager} when a sender is disconnected. + */ +export class SenderDisconnectedEvent extends Event { + constructor(senderId: string, userAgent: string); + /** + * The ID of the sender connected. + */ + senderId: string; /** - * Represents the system volume data. + * The user agent of the sender. */ - interface SystemVolumeData { - /** - * The level (from 0.0 to 1.0) of the system volume - */ - level: number; - - /** - * Whether the system volume is muted or not. - */ - muted: boolean; - } + userAgent: string; + /** - * Event dispatched by @see{CastReceiverManager} when the system volume changes. + * The reason the sender was disconnected. */ - class SystemVolumeChangedEvent extends Event { - constructor(volume: SystemVolumeData); - - /** - * The system volume data - */ - data: SystemVolumeData; - } + reason?: DisconnectReason; +} + +/** + * Event dispatched by @see{@link CastReceiverManager} when a sender is connected. + */ +export class SenderConnectedEvent extends Event { + constructor(senderId: string, userAgent: string); /** - * Event dispatched by @see{@link CastReceiverManager} when the TV enters/leaves the standby state. + * The ID of the sender connected. */ - class StandbyChangedEvent { - constructor(isStandby: boolean); + senderId: string; - isStandby: boolean; - } /** - * Whether the TV is in standby or not. + * The user agent of the sender. */ - interface ShutdownEvent extends Event { - [key: string]: any; - } + userAgent: string; +} +/** + * Represents the data of a connected sender device. + */ +export interface Sender { /** - * Event dispatched by @see{@link CastReceiverManager} when a sender is disconnected. + * The sender Id. */ - class SenderDisconnectedEvent extends Event { - constructor(senderId: string, userAgent: string); - /** - * The ID of the sender connected. - */ - senderId: string; - - /** - * The user agent of the sender. - */ - userAgent: string; - - /** - * The reason the sender was disconnected. - */ - reason?: DisconnectReason; - } + id: string; /** - * Event dispatched by @see{@link CastReceiverManager} when a sender is connected. + * Indicate the sender supports large messages (>64KB) */ - class SenderConnectedEvent extends Event { - constructor(senderId: string, userAgent: string); - /** - * The ID of the sender connected. - */ - senderId: string; - - /** - * The user agent of the sender. - */ - userAgent: string; - } + largeMessageSupported?: boolean; /** - * Represents the data of a connected sender device. + * The userAgent of the sender. */ - interface Sender { - /** - * The sender Id. - */ - id: string; - - /** - * Indicate the sender supports large messages (>64KB) - */ - largeMessageSupported?: boolean; - - /** - * The userAgent of the sender. - */ - userAgent?: string; - } + userAgent?: string; +} + +/** + * Event dispatched by CastReceiverManager when the system is ready. + */ +export class ReadyEvent { + constructor(applicationData: ApplicationData); /** - * Event dispatched by CastReceiverManager when the system is ready. + * The application data */ - class ReadyEvent { - constructor(applicationData: ApplicationData); + data: ApplicationData; +} - /** - * The application data - */ - data: ApplicationData; - } +/** + * Event dispatched by @see{@link CastReceiverManager} when the system needs to update the restriction on maximum video resolution. + */ +export class MaxVideoResolutionChangedEvent extends Event { + constructor(height: number); /** - * Event dispatched by @see{@link CastReceiverManager} when the system needs to update the restriction on maximum video resolution. + * Maximum video resolution requested by the system. The value of 0 means there is no restriction. */ - class MaxVideoResolutionChangedEvent extends Event { - constructor(height: number); - - /** - * Maximum video resolution requested by the system. The value of 0 means there is no restriction. - */ - height: number; - } - /** Event dispatched by @see{@link CastReceiverManager} when the systems starts to create feedback report. */ - interface FeedbackStartedEvent extends Event { - [key: string]: any; - } - /** Event dispatched by @see{@link CastReceiverContext} which contains system information. */ - class Event { - constructor(type: EventType, data?: any); - type: EventType; - data?: any; - } - - /** Represents the data of the launched application. */ - interface ApplicationData { - id(): string; - launchingSenderId(): string; - name(): string; - namespaces(): string[]; - sessionId(): number; - } + height: number; +} +/** Event dispatched by @see{@link CastReceiverManager} when the systems starts to create feedback report. */ +export interface FeedbackStartedEvent extends Event { + [key: string]: any; +} +/** Event dispatched by @see{@link CastReceiverContext} which contains system information. */ +export class Event { + constructor(type: EventType, data?: any); + type: EventType; + data?: any; +} + +/** Represents the data of the launched application. */ +export interface ApplicationData { + id(): string; + launchingSenderId(): string; + name(): string; + namespaces(): string[]; + sessionId(): number; } diff --git a/types/chromecast-caf-receiver/cast.framework.ui.d.ts b/types/chromecast-caf-receiver/cast.framework.ui.d.ts index 77d93c8082..cd3fb79e2a 100644 --- a/types/chromecast-caf-receiver/cast.framework.ui.d.ts +++ b/types/chromecast-caf-receiver/cast.framework.ui.d.ts @@ -1,197 +1,193 @@ import { PlayerDataEventType } from "./cast.framework.ui"; import { MediaMetadata } from "./cast.framework.messages"; -import { PlayerDataChangedEventHandler } from "./index"; -export = cast.framework.ui; +export as namespace ui +export type ContentType = "video" | "audio" | "image"; -declare namespace cast.framework.ui { - type ContentType = "video" | "audio" | "image"; +export type State = + | "launching" + | "idle" + | "loading" + | "buffering" + | "paused" + | "playing"; - type State = - | "launching" - | "idle" - | "loading" - | "buffering" - | "paused" - | "playing"; +export type PlayerDataEventType = + | "ANY_CHANGE" + | "STATE_CHANGED" + | "IS_SEEKING_CHANGED" + | "DURATION_CHANGED" + | "CURRENT_TIME_CHANGED" + | "METADATA_CHANGED" + | "TITLE_CHANGED" + | "SUBTITLE_CHANGED" + | "THUMBNAIL_URL_CHANGED" + | "NEXT_TITLE_CHANGED" + | "NEXT_SUBTITLE_CHANGED" + | "NEXT_THUMBNAIL_URL_CHANGED" + | "PRELOADING_NEXT_CHANGED" + | "CONTENT_TYPE_CHANGED" + | "IS_LIVE_CHANGED" + | "BREAK_PERCENTAGE_POSITIONS_CHANGED" + | "IS_PLAYING_BREAK_CHANGED" + | "IS_BREAK_SKIPPABLE_CHANGED" + | "WHEN_SKIPPABLE_CHANGED" + | "NUMBER_BREAK_CLIPS_CHANGED" + | "CURRENT_BREAK_CLIP_NUMBER_CHANGED" + | "DISPLAY_STATUS_CHANGED"; - type PlayerDataEventType = - | "ANY_CHANGE" - | "STATE_CHANGED" - | "IS_SEEKING_CHANGED" - | "DURATION_CHANGED" - | "CURRENT_TIME_CHANGED" - | "METADATA_CHANGED" - | "TITLE_CHANGED" - | "SUBTITLE_CHANGED" - | "THUMBNAIL_URL_CHANGED" - | "NEXT_TITLE_CHANGED" - | "NEXT_SUBTITLE_CHANGED" - | "NEXT_THUMBNAIL_URL_CHANGED" - | "PRELOADING_NEXT_CHANGED" - | "CONTENT_TYPE_CHANGED" - | "IS_LIVE_CHANGED" - | "BREAK_PERCENTAGE_POSITIONS_CHANGED" - | "IS_PLAYING_BREAK_CHANGED" - | "IS_BREAK_SKIPPABLE_CHANGED" - | "WHEN_SKIPPABLE_CHANGED" - | "NUMBER_BREAK_CLIPS_CHANGED" - | "CURRENT_BREAK_CLIP_NUMBER_CHANGED" - | "DISPLAY_STATUS_CHANGED"; +/** + * Player data changed event. Provides the changed field (type); and new value. + */ +export class PlayerDataChangedEvent { + constructor(type: PlayerDataEventType, field: string, value: any); /** - * Player data changed event. Provides the changed field (type); and new value. + * The field name that was changed. */ - class PlayerDataChangedEvent { - constructor(type: PlayerDataEventType, field: string, value: any); + field: string; - /** - * The field name that was changed. - */ - field: string; + type: PlayerDataEventType; - type: PlayerDataEventType; - - /** - * The new field value. - */ - value: any; - } /** - * Player data binder. Bind a player data object to the player state. - * The player data will be updated to reflect correctly the current player state without firing any change event. + * The new field value. */ - class PlayerDataBinder { - constructor(playerData: PlayerData); - - /** - * Add listener to player data changes. - */ - addEventListener: ( - type: PlayerDataEventType, - listener: PlayerDataChangedEventHandler - ) => void; - - /** - * Remove listener to player data changes. - */ - removeEventListener: ( - type: PlayerDataEventType, - listener: PlayerDataChangedEventHandler - ) => void; - } - /** - * Player data. Provide the player media and break state. - */ - interface PlayerData { - /** - * Array of breaks positions in percentage. - */ - breakPercentagePositions: number[]; - - /** - * Content Type. - */ - contentType: ContentType; - - /** - * The number of the current playing break clip in the break. - */ - currentBreakClipNumber: number; - - /** - * Media current position in seconds; or break current position if playing break. - */ - currentTime: number; - - /** - * Whether the player metadata (ie: title; currentTime) should be displayed. - * This will be true if at least one field in the metadata should be displayed. - * In some cases; displayStatus will be true; but parts of the metadata should be hidden - * (ie: the media title while media is seeking). - * In these cases; additional css can be applied to hide those elements. - * For cases where the media is audio-only; this will almost always be true. - * In cases where the media is video; this will be true when: - * (1) the video is loading; buffering; or seeking - * (2) a play request was made in the last five seconds while media is already playing; - * (3) there is a request made to show the status in the last five seconds; or - * (4) the media was paused in the last five seconds. - */ - displayStatus: boolean; - - /** - * Media duration in seconds; Or break duration if playing break. - */ - duration: number; - - /** - * Indicate break clip can be skipped. - */ - isBreakSkippable: boolean; - - /** - * Indicate if the content is a live stream. - */ - isLive: boolean; - - /** - * Indicate that the receiver is playing a break. - */ - isPlayingBreak: boolean; - - /** - * Indicate the player is seeking (can be either during playing or pausing). - */ - isSeeking: boolean; - - /** - * Media metadata. - */ - metadata: MediaMetadata; - - /** - * Next Item subtitle. - */ - nextSubtitle: string; - - /** - * Next Item thumbnail url. - */ - nextThumbnailUrl: string; - - /** - * Next Item title. - */ - nextTitle: string; - - /** - * Number of break clips in current break. - */ - numberBreakClips: number; - - /** - * Flag to show/hide next item metadata. - */ - preloadingNext: boolean; - - /** - * Current player state. - */ - state: State; - - /** - * Content thumbnail url. - */ - thumbnailUrl: string; - - /** - * Content title. - */ - title: string; - - /** - * Provide the time a break is skipable - relative to current playback time. Undefined if not skippable. - */ - whenSkippable?: number; - } + value: any; +} +/** + * Player data binder. Bind a player data object to the player state. + * The player data will be updated to reflect correctly the current player state without firing any change event. + */ +export class PlayerDataBinder { + constructor(playerData: PlayerData); + + /** + * Add listener to player data changes. + */ + addEventListener: ( + type: PlayerDataEventType, + listener: PlayerDataChangedEventHandler + ) => void; + + /** + * Remove listener to player data changes. + */ + removeEventListener: ( + type: PlayerDataEventType, + listener: PlayerDataChangedEventHandler + ) => void; +} +/** + * Player data. Provide the player media and break state. + */ +export interface PlayerData { + /** + * Array of breaks positions in percentage. + */ + breakPercentagePositions: number[]; + + /** + * Content Type. + */ + contentType: ContentType; + + /** + * The number of the current playing break clip in the break. + */ + currentBreakClipNumber: number; + + /** + * Media current position in seconds; or break current position if playing break. + */ + currentTime: number; + + /** + * Whether the player metadata (ie: title; currentTime) should be displayed. + * This will be true if at least one field in the metadata should be displayed. + * In some cases; displayStatus will be true; but parts of the metadata should be hidden + * (ie: the media title while media is seeking). + * In these cases; additional css can be applied to hide those elements. + * For cases where the media is audio-only; this will almost always be true. + * In cases where the media is video; this will be true when: + * (1) the video is loading; buffering; or seeking + * (2) a play request was made in the last five seconds while media is already playing; + * (3) there is a request made to show the status in the last five seconds; or + * (4) the media was paused in the last five seconds. + */ + displayStatus: boolean; + + /** + * Media duration in seconds; Or break duration if playing break. + */ + duration: number; + + /** + * Indicate break clip can be skipped. + */ + isBreakSkippable: boolean; + + /** + * Indicate if the content is a live stream. + */ + isLive: boolean; + + /** + * Indicate that the receiver is playing a break. + */ + isPlayingBreak: boolean; + + /** + * Indicate the player is seeking (can be either during playing or pausing). + */ + isSeeking: boolean; + + /** + * Media metadata. + */ + metadata: MediaMetadata; + + /** + * Next Item subtitle. + */ + nextSubtitle: string; + + /** + * Next Item thumbnail url. + */ + nextThumbnailUrl: string; + + /** + * Next Item title. + */ + nextTitle: string; + + /** + * Number of break clips in current break. + */ + numberBreakClips: number; + + /** + * Flag to show/hide next item metadata. + */ + preloadingNext: boolean; + + /** + * Current player state. + */ + state: State; + + /** + * Content thumbnail url. + */ + thumbnailUrl: string; + + /** + * Content title. + */ + title: string; + + /** + * Provide the time a break is skipable - relative to current playback time. Undefined if not skippable. + */ + whenSkippable?: number; } diff --git a/types/chromecast-caf-receiver/chromecast-caf-receiver-tests.ts b/types/chromecast-caf-receiver/chromecast-caf-receiver-tests.ts index 08ce57cf86..0df790c5f7 100644 --- a/types/chromecast-caf-receiver/chromecast-caf-receiver-tests.ts +++ b/types/chromecast-caf-receiver/chromecast-caf-receiver-tests.ts @@ -1,64 +1,60 @@ -import { - PlayerData, - PlayerDataBinder -} from "chromecast-caf-receiver/cast.framework.ui"; -import { - ReadyEvent, - ApplicationData -} from "chromecast-caf-receiver/cast.framework.system"; -import { - RequestEvent, - Event, - BreaksEvent -} from "chromecast-caf-receiver/cast.framework.events"; -import { - QueueBase, - TextTracksManager, - QueueManager, - PlayerManager -} from "chromecast-caf-receiver/cast.framework"; -import { - BreakSeekData, - BreakClipLoadInterceptorContext, - BreakManager -} from "chromecast-caf-receiver/cast.framework.breaks"; -import { - Break, - BreakClip, - LoadRequestData, - Track, - MediaMetadata -} from "chromecast-caf-receiver/cast.framework.messages"; +import { MediaMetadata } from "chromecast-caf-receiver/cast.framework.messages"; -const breaksEvent = new BreaksEvent('BREAK_STARTED'); -breaksEvent.breakId = 'some-break-id'; -breaksEvent.breakClipId = 'some-break-clip-id'; +// The following test showcases how you can import individual types directly from the namespace: -const track = new Track(1, "TEXT"); -const breakClip = new BreakClip("id"); -const adBreak = new Break("id", ["id"], 1); -const rEvent = new RequestEvent("BITRATE_CHANGED", { requestId: 2 }); -const pManager = new PlayerManager(); -pManager.addEventListener("STALLED", () => { }); -const ttManager = new TextTracksManager(); -const qManager = new QueueManager(); -const qBase = new QueueBase(); +const mediaMetadata = new MediaMetadata("GENERIC"); +mediaMetadata.metadataType = "TV_SHOW"; + +// The following tests showcase how you can globally access 'cast' types using +// the nested namespace style. This is the preferred method as it +// conforms exactly to the CAF documentation. + +// tslint:disable-next-line +const breaksEvent = new cast.framework.events.BreaksEvent("BREAK_STARTED"); +breaksEvent.breakId = "some-break-id"; +breaksEvent.breakClipId = "some-break-clip-id"; + +// tslint:disable-next-line +const track = new cast.framework.messages.Track(1, "TEXT"); +// tslint:disable-next-line +const breakClip = new cast.framework.messages.BreakClip("id"); +// tslint:disable-next-line +const adBreak = new cast.framework.messages.Break("id", ["id"], 1); +// tslint:disable-next-line +const rEvent = new cast.framework.events.RequestEvent("BITRATE_CHANGED", { + requestId: 2 +}); +// tslint:disable-next-line +const pManager = new cast.framework.PlayerManager(); +pManager.addEventListener("STALLED", () => {}); +// tslint:disable-next-line +const ttManager = new cast.framework.TextTracksManager(); +// tslint:disable-next-line +const qManager = new cast.framework.QueueManager(); +// tslint:disable-next-line +const qBase = new cast.framework.QueueBase(); const items = qBase.fetchItems(1, 3, 4); -const breakSeekData = new BreakSeekData(0, 100, []); -const breakClipLoadContext = new BreakClipLoadInterceptorContext(adBreak); -const breakManager: BreakManager = { +// tslint:disable-next-line +const breakSeekData = new cast.framework.breaks.BreakSeekData(0, 100, []); +// tslint:disable-next-line +const breakClipLoadContext = new cast.framework.breaks.BreakClipLoadInterceptorContext( + adBreak +); +// tslint:disable-next-line +const breakManager: cast.framework.breaks.BreakManager = { getBreakById: () => adBreak, getBreakClipById: () => breakClip, getBreakClips: () => [breakClip], getBreaks: () => [adBreak], getPlayWatchedBreak: () => true, - setBreakClipLoadInterceptor: () => { }, - setBreakSeekInterceptor: () => { }, - setPlayWatchedBreak: () => { }, - setVastTrackingInterceptor: () => { } + setBreakClipLoadInterceptor: () => {}, + setBreakSeekInterceptor: () => {}, + setPlayWatchedBreak: () => {}, + setVastTrackingInterceptor: () => {} }; -const lrd: LoadRequestData = { +// tslint:disable-next-line +const lrd: cast.framework.messages.LoadRequestData = { requestId: 1, activeTrackIds: [1, 2], media: { @@ -75,7 +71,8 @@ const lrd: LoadRequestData = { queueData: {} }; -const appData: ApplicationData = { +// tslint:disable-next-line +const appData: cast.framework.system.ApplicationData = { id: () => "id", launchingSenderId: () => "launch-id", name: () => "name", @@ -83,9 +80,11 @@ const appData: ApplicationData = { sessionId: () => 1 }; -const readyEvent = new ReadyEvent(appData); +// tslint:disable-next-line +const readyEvent = new cast.framework.system.ReadyEvent(appData); const data = readyEvent.data; -const pData: PlayerData = { +// tslint:disable-next-line +const pData: cast.framework.ui.PlayerData = { breakPercentagePositions: [1], contentType: "video", currentBreakClipNumber: 2, @@ -96,7 +95,8 @@ const pData: PlayerData = { isLive: true, isPlayingBreak: false, isSeeking: true, - metadata: new MediaMetadata("GENERIC"), + // tslint:disable-next-line + metadata: new cast.framework.messages.MediaMetadata("GENERIC"), nextSubtitle: "sub", nextThumbnailUrl: "url", nextTitle: "title", @@ -107,5 +107,6 @@ const pData: PlayerData = { title: "title", whenSkippable: 321 }; -const binder = new PlayerDataBinder(pData); -binder.addEventListener("ANY_CHANGE", e => { }); +// tslint:disable-next-line +const binder = new cast.framework.ui.PlayerDataBinder(pData); +binder.addEventListener("ANY_CHANGE", e => {}); diff --git a/types/chromecast-caf-receiver/index.d.ts b/types/chromecast-caf-receiver/index.d.ts index 73a13f53ca..444dba0af4 100644 --- a/types/chromecast-caf-receiver/index.d.ts +++ b/types/chromecast-caf-receiver/index.d.ts @@ -11,14 +11,18 @@ /// /// +import * as framework from "./cast.framework"; import { PlayerDataChangedEvent } from './cast.framework.ui'; -import { NetworkRequestInfo } from './cast.framework'; import { Event } from './cast.framework.events'; export as namespace cast; -export type EventHandler = (event: Event) => void; -export type PlayerDataChangedEventHandler = ( - event: PlayerDataChangedEvent -) => void; -export type RequestHandler = (request: NetworkRequestInfo) => void; -export type BinaryHandler = (data: Uint8Array) => Uint8Array; +export { framework }; + +declare global { + type EventHandler = (event: Event) => void; + type PlayerDataChangedEventHandler = ( + event: PlayerDataChangedEvent + ) => void; + type RequestHandler = (request: framework.NetworkRequestInfo) => void; + type BinaryHandler = (data: Uint8Array) => Uint8Array; +} diff --git a/types/ckeditor/ckeditor-tests.ts b/types/ckeditor/ckeditor-tests.ts index 6a0b50a4d8..7e224ab683 100644 --- a/types/ckeditor/ckeditor-tests.ts +++ b/types/ckeditor/ckeditor-tests.ts @@ -369,6 +369,7 @@ function test_dom_walker() { node = walker.lastForward(); node = walker.next(); node = walker.previous(); + isSomething = walker.guard(node, true); walker.reset(); isSomething = CKEDITOR.dom.walker.blockBoundary({ div: 1 })(node); @@ -485,7 +486,7 @@ function test_dialog() { { id: 'tab-basic', label: 'Basic Settings', - elements: [] + elements: [] as any [] }, { id: 'tab-adv', diff --git a/types/ckeditor/index.d.ts b/types/ckeditor/index.d.ts index 69c23d6a99..2889b30574 100644 --- a/types/ckeditor/index.d.ts +++ b/types/ckeditor/index.d.ts @@ -498,7 +498,7 @@ declare namespace CKEDITOR { class walker { evaluator: (node: node) => boolean; - guard: (node: node) => boolean; + guard: (node: node, movingOut?: boolean) => boolean; static validEmptyBlockContainers: { [key: string]: any }; diff --git a/types/ckeditor__ckeditor5-core/ckeditor__ckeditor5-core-tests.ts b/types/ckeditor__ckeditor5-core/ckeditor__ckeditor5-core-tests.ts new file mode 100644 index 0000000000..68a20aff51 --- /dev/null +++ b/types/ckeditor__ckeditor5-core/ckeditor__ckeditor5-core-tests.ts @@ -0,0 +1,328 @@ +import * as utils from "ckeditor__ckeditor5-utils"; +import * as core from "ckeditor__ckeditor5-core"; +import * as engine from "ckeditor__ckeditor5-engine"; + +declare let bool: boolean; +declare let command: core.Command; +declare let commandCollection: core.CommandCollection; +declare let commands: core.Command[]; +declare let componentFactory: core.ComponentFactory; +declare let config: utils.Config; +declare let conversion: engine.conversion.Conversion; +declare let dataController: engine.controller.DataController; +declare let editingController: engine.controller.EditingController; +declare let editingKeystrokeHandler: core.EditingKeystrokeHandler; +declare let editor: core.editor.Editor; +declare let focusTracker: utils.FocusTracker; +declare let htmlElement: HTMLElement; +declare let keystrokes: core.EditingKeystrokeHandler; +declare let locale: utils.Locale; +declare let model: engine.model.Model; +declare let num: number; +declare let pendingActions: core.PendingActions; +declare let plugin: core.Plugin; +declare let pluginCollection: core.PluginCollection; +declare let pluginCollectionStr: core.PluginCollection>; +declare let pluginStr: core.Plugin; +declare let myPlugin: MyPlugin; +declare let myPluginMaybe: MyPlugin | undefined; +declare let myPlugins: MyPlugin[]; +declare let str: string; +declare let strOrUndef: string | undefined; +declare let strs: string[]; +declare let ui: core.editor.EditorUI; +declare let undef: undefined; +declare let view: core.EditorUIView; + +class MyPlugin extends core.Plugin { + constructor(editor: core.editor.Editor) { + super(editor); + } + + static get pluginName() { + return "A"; + } + + myMethod() { + return "this is MyPlugin method"; + } +} + +class SomeCommand extends core.Command { + execute() {} +} + +// core/editor/utils/dataapimixin ============================================= + +class DataApiEditor extends core.editor.Editor implements core.editor.utils.DataApi { + // mixin by DataApiMixin + getData: () => string; + setData: (data: string) => void; +} +utils.mix(DataApiEditor, core.editor.utils.DataApiMixin); +const dataApiEditor = new DataApiEditor(); + +dataApiEditor.setData("foo"); +str = dataApiEditor.getData(); + +// core/editor/utils/elementapimixin ========================================== + +class ElementApiEditor extends core.editor.Editor implements core.editor.utils.ElementApi { + // mixin by ElementApiMixin + readonly sourceElement: HTMLElement; + updateSourceElement: () => void; +} +utils.mix(ElementApiEditor, core.editor.utils.ElementApiMixin); +const elementApiEditor = new ElementApiEditor(); + +htmlElement = elementApiEditor.sourceElement; +elementApiEditor.updateSourceElement(); + +// core/editor/utils/attachtoform ============================================= + +// $ExpectError +core.editor.utils.attachToForm(editor); +core.editor.utils.attachToForm(elementApiEditor); + +// core/editor/editor ========================================================= + +commandCollection = editor.commands; +config = editor.config; +editingController = editor.editing; +conversion = editor.conversion; +dataController = editor.data; +editor.isReadOnly = bool; +editingKeystrokeHandler = editor.keystrokes; +locale = editor.locale; +model = editor.model; +pluginCollection = editor.plugins; + +if (editor.state === "initializing") { + console.log("new Editor()"); +} else if (editor.state === "ready") { + console.log("Editor.create()"); +} else if (editor.state === "destroyed") { + console.log("editor.destroy"); +} else { + const n: never = editor.state; +} + +editor.state = "ready"; + +core.editor.Editor.builtinPlugins = [plugin, pluginStr, plugin]; +const plugins: Array> = core.editor.Editor.builtinPlugins; + +core.editor.Editor.defaultConfig = { + foo: { + a: 1, + b: 2 + } +}; + +editor = new core.editor.Editor(); +editor = new core.editor.Editor({language: "pl"}); + +editor.destroy(); +editor.destroy().then(() => { + console.log(`${editor.state} == destroyed`); +}); + +editor.execute("someCommand"); +editor.execute("someCommand2", "arg1", 2); + +editor.initPlugins(); +editor.initPlugins().then(() => { + console.log(`init ${Array.from(editor.plugins).length} plugins`); +}); + +locale.t = editor.t; +str = editor.t("Label"); +str = editor.t('Created file "%0" in %1ms.', ["fileName", "100"]); + +// core/editor/editorui ======================================================= + +componentFactory = ui.componentFactory; +editor = ui.editor; +focusTracker = ui.focusTracker; +view = ui.view; + +ui = new core.editor.EditorUI(editor, view); +ui.destroy(); +ui.update(); + +// core/editor/editorwithui =================================================== + +declare let ewui: core.editor.EditorWithUI; +htmlElement = ewui.element!; +ui = ewui.ui; + +// core/command =============================================================== + +editor = command.editor; + +bool = command.isEnabled; + +undef = command.value; +strOrUndef = new core.Command(editor).value; + +command = new core.Command(editor); + +command.destroy(); + +command.execute(); + +command.refresh(); + +// core/commandcollection ===================================================== + +commandCollection = new core.CommandCollection(); + +const collectionsPairs = Array.from(commandCollection); +const collectionsPair = collectionsPairs[0]; +str = collectionsPair[0]; +command = collectionsPair[1]; + +commandCollection.add("foo", new SomeCommand(editor)); + +command = commandCollection.commands().next().value; +commands = Array.from(commandCollection.commands()); + +commandCollection.destroy(); + +commandCollection.execute("foo"); +commandCollection.execute("bar", 1, "param"); + +command = commandCollection.get("foo"); + +str = commandCollection.names().next().value; +strs = Array.from(commandCollection.names()); + +// core/editingkeystrokehandler =============================================== + +keystrokes = new core.EditingKeystrokeHandler(editor); + +editor = keystrokes.editor; + +keystrokes.press({keyCode: 123}); + +keystrokes.set("Ctrl+A", "foo"); +keystrokes.set(["shift", "33"], "foo"); +keystrokes.set(["ctrl", "A"], "foo", {priority: 10}); +keystrokes.set(["ctrl", "A"], "foo", {priority: "high"}); +keystrokes.set(["ctrl", "A"], () => console.log("key")); +keystrokes.set(["ctrl", "A"], (keyEvtData, cancel) => { + console.log(keyEvtData.keyCode); + cancel(); +}); + +// core/pendingactions ======================================================== + +pendingActions = new core.PendingActions(editor); + +str = core.PendingActions.pluginName; + +const firstAction = pendingActions.first; + +bool = pendingActions.hasAny; + +strs = Array.from(pendingActions, action => action.message); + +const action1 = pendingActions.add("Action 1"); + +pendingActions.remove(action1); + +firstAction!.fire("I'm an Observable with a message"); +str = firstAction!.message; +str = action1.message; + +// core/plugin ================================================================ + +class MyPluginMini extends core.Plugin { + constructor(editor: core.editor.Editor) { + super(editor); + } +} + +class MyPluginAll extends core.Plugin { + constructor(editor: core.editor.Editor) { + super(editor); + } + + static get pluginName() { + return "All"; + } + + static get requires() { + return [MyPlugin, MyPluginMini]; + } + + afterInit() {return Math.random() ? null : Promise.resolve("resolved"); } + destroy() {return Math.random() ? null : Promise.resolve("destroy"); } + init() {return Math.random() ? null : Promise.resolve("init"); } +} + +plugin = new MyPlugin(editor); +plugin = new MyPluginMini(editor); +pluginStr = new MyPluginAll(editor); + +const Plugin: MyPlugin = new MyPlugin(editor); +const pluginMini: MyPluginMini = new MyPluginMini(editor); +const pluginAll: MyPluginAll = new MyPluginAll(editor); + +editor = myPlugin.editor; + +str = MyPluginAll.pluginName; +strOrUndef = MyPluginMini.pluginName; // Todo: should be undefined. + +plugin = new MyPluginAll.requires[0](editor); + +const fs: Function[] = MyPluginAll.requires; +const fsOrUndef = MyPluginMini.requires; // Todo: should be undefined. + +// $ExpectError +pluginMini.afterInit(); +pluginAll.afterInit(); + +// $ExpectError +pluginMini.destroy(); +pluginAll.destroy(); + +// $ExpectError +pluginMini.init(); +pluginAll.init(); + +// core/plugincollection ====================================================== + +pluginCollectionStr = new core.PluginCollection(editor, [MyPluginAll]); +// $ExpectError +pluginCollectionStr = new core.PluginCollection(editor, [MyPlugin]); + +const aColl = new core.PluginCollection(editor, [MyPluginAll, MyPluginMini]); + +const myColl = new core.PluginCollection(editor, [MyPlugin]); + +const myCollArray = Array.from(myColl); +myPlugins = myCollArray.map(entry => entry[1]); +myPlugin = new (myCollArray[0][0])(editor); + +myColl.destroy() + .then(destroyedPlugins => { + num = destroyedPlugins.length; + const plugin = destroyedPlugins[0]; + editor = plugin.editor; + plugin.init!(); + plugin.destroy(); + str = plugin.myMethod(); + }); + +myPluginMaybe = myColl.get("A"); +myPluginMaybe = myColl.get(MyPlugin); + +myColl.load([MyPlugin, "A"]) + .then((loadedPlugins) => { + const plugin = loadedPlugins[0]; + editor = plugin.editor; + str = plugin.myMethod(); + }); + +myColl.load([MyPlugin, "A"], [MyPlugin, "A"]); diff --git a/types/ckeditor__ckeditor5-core/index.d.ts b/types/ckeditor__ckeditor5-core/index.d.ts new file mode 100644 index 0000000000..63ae237739 --- /dev/null +++ b/types/ckeditor__ckeditor5-core/index.d.ts @@ -0,0 +1,269 @@ +// Type definitions for @ckeditor/ckeditor5-core 11.0 +// Project: https://github.com/ckeditor/ckeditor5-core +// Definitions by: denisname +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import * as engine from "ckeditor__ckeditor5-engine"; +import * as ckutils from "ckeditor__ckeditor5-utils"; + +// TODO: depends on other libraries +export interface AlignmentConfig {} +export interface AutosaveConfig {} +export interface CKFinderAdapterConfig {} +export interface CloudServicesConfig {} +export interface FontFamilyConfig {} +export interface FontSizeConfig {} +export interface HeadingConfig {} +export interface HighlightConfig {} +export interface ImageConfig {} +export interface MediaEmbedConfig {} +export interface TypingConfig {} +export interface ComponentFactory {} // CKEditor 5 UI +export interface EditorUIView {} // CKEditor 5 UI + +export namespace editor { + namespace utils { + // core/editor/utils/attachtoform + + function attachToForm(editor: Editor & ElementApi): void; + + // core/editor/utils/dataapimixin + + const DataApiMixin: DataApi; + + interface DataApi { + getData(): string; + setData(data: string): void; + } + + // core/editor/utils/elementapimixin + + const ElementApiMixin: ElementApi; + + interface ElementApi { + readonly sourceElement: HTMLElement; + updateSourceElement(): void; + } + } + + // core/editor/editor + + class Editor implements ckutils.Emitter, ckutils.Observable { + readonly commands: CommandCollection; + readonly config: ckutils.Config; + readonly conversion: engine.conversion.Conversion; + readonly data: engine.controller.DataController; + readonly editing: engine.controller.EditingController; + isReadOnly: boolean; + readonly keystrokes: EditingKeystrokeHandler; + readonly locale: ckutils.Locale; + readonly model: engine.model.Model; + readonly plugins: PluginCollection>; + state: "initializing" | "ready" | "destroyed"; + + static builtinPlugins: Array>; + static defaultConfig: object; + + constructor(config?: object); + destroy(): Promise; + execute(commandName: string, ...commandParams: any[]): void; + initPlugins(): Promise; + t(str: string, values?: string[]): string; + + static create(config: object): Promise; + + // Emitter + delegate(...events: string[]): ckutils.EmitterMixinDelegateChain; + fire(eventOrInfo: string | ckutils.EventInfo, ...args: any[]): any; + listenTo(emitter: ckutils.Emitter, event: string, callback: Function, options?: {priority?: ckutils.PriorityString | number }): void; + off(event: string, callback?: Function): void; + on(event: string, callback: Function, options?: {priority: ckutils.PriorityString | number}): void; + once(event: string, callback: Function, options?: {priority: ckutils.PriorityString | number}): void; + stopDelegating(event?: string, emitter?: ckutils.Emitter): void; + stopListening(emitter?: ckutils.Emitter, event?: string, callback?: Function): void; + + // Observable + bind(...bindProperties: string[]): ckutils.BindChain; + decorate(methodName: string): void; + set(name: object): void; + set(name: string, value: any): void; + unbind(...unbindProperties: string[]): void; + } + + // core/editor/editorconfig + + interface EditorConfig { + alignment: AlignmentConfig; + autosave: AutosaveConfig; + balloonToolbar: string[]; + blockToolbar: string[]; + ckfinder: CKFinderAdapterConfig; + cloudServices: CloudServicesConfig; + fontFamily: FontFamilyConfig; + fontSize: FontSizeConfig; + heading: HeadingConfig; + highlight: HighlightConfig; + image: ImageConfig; + language: string; + mediaEmbed: MediaEmbedConfig; + plugins: Array; + removePlugins: string[]; + toolbar: string[] | {items: string[]; viewportTopOffset: number; }; + typing: TypingConfig; + } + + // core/editor/editorui + + class EditorUI implements ckutils.Emitter { + readonly componentFactory: ComponentFactory; + readonly editor: Editor; + readonly focusTracker: ckutils.FocusTracker; + readonly view: EditorUIView; + + constructor(editor: Editor, view: EditorUIView); + destroy(): void; + update(): void; + + // Emitter + delegate(...events: string[]): ckutils.EmitterMixinDelegateChain; + fire(eventOrInfo: string | ckutils.EventInfo, ...args: any[]): any; + listenTo(emitter: ckutils.Emitter, event: string, callback: Function, options?: {priority?: ckutils.PriorityString | number }): void; + off(event: string, callback?: Function): void; + on(event: string, callback: Function, options?: {priority: ckutils.PriorityString | number}): void; + once(event: string, callback: Function, options?: {priority: ckutils.PriorityString | number}): void; + stopDelegating(event?: string, emitter?: ckutils.Emitter): void; + stopListening(emitter?: ckutils.Emitter, event?: string, callback?: Function): void; + } + + // core/editor/editorwithui + + interface EditorWithUI { + readonly element: HTMLElement | null; + readonly ui: EditorUI; + } +} + +// core/command + +export class Command implements ckutils.Emitter, ckutils.Observable { + readonly editor: editor.Editor; + readonly isEnabled: boolean; + readonly value: T | undefined; + + constructor(editor: editor.Editor); + destroy(): void; + execute(): void; + refresh(): void; + + // Emitter + delegate(...events: string[]): ckutils.EmitterMixinDelegateChain; + fire(eventOrInfo: string | ckutils.EventInfo, ...args: any[]): any; + listenTo(emitter: ckutils.Emitter, event: string, callback: Function, options?: {priority?: ckutils.PriorityString | number }): void; + off(event: string, callback?: Function): void; + on(event: string, callback: Function, options?: {priority: ckutils.PriorityString | number}): void; + once(event: string, callback: Function, options?: {priority: ckutils.PriorityString | number}): void; + stopDelegating(event?: string, emitter?: ckutils.Emitter): void; + stopListening(emitter?: ckutils.Emitter, event?: string, callback?: Function): void; + + // Observable + bind(...bindProperties: string[]): ckutils.BindChain; + decorate(methodName: string): void; + set(name: object): void; + set(name: string, value: any): void; + unbind(...unbindProperties: string[]): void; +} + +// core/commandcollection + +export class CommandCollection { + constructor(); + [Symbol.iterator](): Iterator<[string, Command]>; + add(commandName: string, command: Command): void; + commands(): IterableIterator; + destroy(): void; + execute(commandName: string, ...commandParams: any[]): void; + get(commandName: string): Command; + names(): IterableIterator; +} + +// core/editingkeystrokehandler + +export class EditingKeystrokeHandler extends ckutils.KeystrokeHandler { + readonly editor: editor.Editor; + + constructor(editor: editor.Editor); + set( + keystroke: string | Array, + callback: string | ((keyEvtData: engine.view.observer.KeyEventData, cancel: () => void) => void), + options?: {priority: ckutils.PriorityString | number} + ): void; +} + +// core/pendingactions + +export class PendingActions extends Plugin { + static readonly pluginName: "PendingActions"; + + first: null | ckutils.Observable & {message: string}; + readonly hasAny: boolean; + + [Symbol.iterator](): Iterator; + add(message: string): ckutils.Observable & {message: string}; + remove(action: ckutils.Observable & {message: string}): void; +} + +// core/plugin + +export abstract class Plugin implements ckutils.Emitter, ckutils.Observable { + readonly editor: editor.Editor; + + static readonly pluginName?: string; + static readonly requires?: Array Plugin>; + + constructor(editor: editor.Editor); + afterInit?(): null | Promise; + destroy?(): null | Promise; + init?(): null | Promise; + + // Emitter + delegate(...events: string[]): ckutils.EmitterMixinDelegateChain; + fire(eventOrInfo: string | ckutils.EventInfo, ...args: any[]): any; + listenTo(emitter: ckutils.Emitter, event: string, callback: Function, options?: {priority?: ckutils.PriorityString | number }): void; + off(event: string, callback?: Function): void; + on(event: string, callback: Function, options?: {priority: ckutils.PriorityString | number}): void; + once(event: string, callback: Function, options?: {priority: ckutils.PriorityString | number}): void; + stopDelegating(event?: string, emitter?: ckutils.Emitter): void; + stopListening(emitter?: ckutils.Emitter, event?: string, callback?: Function): void; + + // Observable + bind(...bindProperties: string[]): ckutils.BindChain; + decorate(methodName: string): void; + set(name: object): void; + set(name: string, value: any): void; + unbind(...unbindProperties: string[]): void; +} + +// PluginInterface, see Plugin + +// core/plugincollection + +export class PluginCollection

> { + constructor( + editor: editor.Editor, + availablePlugins?: Array P> + ); + + [Symbol.iterator](): Iterator<[new(editor: editor.Editor) => P, P]>; + + destroy(): Promise}>>; + + get( + key: string | (new(editor: editor.Editor) => P) + ): P | undefined; + + load( + plugins: Array P)>, + removePlugins?: Array P)> + ): Promise; +} diff --git a/types/ckeditor__ckeditor5-core/tsconfig.json b/types/ckeditor__ckeditor5-core/tsconfig.json new file mode 100644 index 0000000000..5f53bb9035 --- /dev/null +++ b/types/ckeditor__ckeditor5-core/tsconfig.json @@ -0,0 +1,26 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "lib": [ + "es6", + "dom", + "es2015.promise" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "ckeditor__ckeditor5-core-tests.ts" + ] +} diff --git a/types/ckeditor__ckeditor5-core/tslint.json b/types/ckeditor__ckeditor5-core/tslint.json new file mode 100644 index 0000000000..b4dd998211 --- /dev/null +++ b/types/ckeditor__ckeditor5-core/tslint.json @@ -0,0 +1,22 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "ban-types": { + "options": [ + ["Object", "Avoid using the `Object` type. Did you mean `object`?"], + ["Boolean", "Avoid using the `Boolean` type. Did you mean `boolean`?"], + ["Number", "Avoid using the `Number` type. Did you mean `number`?"], + ["String", "Avoid using the `String` type. Did you mean `string`?"], + ["Symbol", "Avoid using the `Symbol` type. Did you mean `symbol`?"] + ] + }, + "no-empty-interface": false, + "prefer-switch": false, + "quotemark": [ + true, + "double", + "avoid-escape", + "avoid-template" + ] + } +} diff --git a/types/ckeditor__ckeditor5-engine/ckeditor__ckeditor5-engine-tests.ts b/types/ckeditor__ckeditor5-engine/ckeditor__ckeditor5-engine-tests.ts new file mode 100644 index 0000000000..676f30ac3b --- /dev/null +++ b/types/ckeditor__ckeditor5-engine/ckeditor__ckeditor5-engine-tests.ts @@ -0,0 +1,81 @@ +import * as engine from "ckeditor__ckeditor5-engine"; + +declare let pattern: engine.view.MatcherPattern; + +pattern = {name: /^p/}; + +pattern = { + attributes: { + title: "foobar", + foo: /^\w+/, + bar: true, + } +}; + +pattern = { + classes: "foobar" +}; + +pattern = { + classes: /foo.../ +}; + +pattern = { + classes: ["baz", "bar", /foo.../] +}; + +pattern = { + styles: { + position: "absolute", + color: /^\w*blue$/ + } +}; + +pattern = { + name: "span", + styles: { + "font-weight": "bold" + }, + classes: "highlighted" +}; + +pattern = (element: engine.view.Element) => { + if (element.name === "div" && element.childCount > 0) { + return {name: true}; + } + + return null; +}; + +pattern = (element: engine.view.Element) => { + if (element.name === "p") { + const fontSize = element.getStyle("font-size")!; + const size = fontSize.match(/(\d+)/px); + + if (size && Number(size[1]) > 26) { + return {name: true, attribute: ["font-size"]}; + } + } + + return null; +}; + +declare let viewDefinition: engine.view.ElementDefinition; + +viewDefinition = "p"; + +viewDefinition = { + name: "h1", + classes: ["foo", "bar"], +}; + +viewDefinition = { + name: "span", + styles: { + "font-size": "12px", + "font-weight": "bold", + }, + attributes: { + "data-id": "123", + } +}; diff --git a/types/ckeditor__ckeditor5-engine/index.d.ts b/types/ckeditor__ckeditor5-engine/index.d.ts new file mode 100644 index 0000000000..280b6ea213 --- /dev/null +++ b/types/ckeditor__ckeditor5-engine/index.d.ts @@ -0,0 +1,1368 @@ +// Type definitions for @ckeditor/ckeditor5-engine 11.0 +// Project: https://github.com/ckeditor/ckeditor5-engine +// Definitions by: denisname +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import * as ckutils from "ckeditor__ckeditor5-utils"; + +export namespace controller { + // engine/controller/datacontroller + + class DataController implements ckutils.Emitter, ckutils.Observable { + readonly downcastDispatcher: conversion.DowncastDispatcher; + readonly mapper: conversion.Mapper; + readonly model: model.Model; + readonly processor: dataprocessor.DataProcessor; + readonly upcastDispatcher: conversion.UpcastDispatcher; + + constructor(model: model.Model, dataProcessor?: dataprocessor.DataProcessor); + destroy(): void; + get(rootName?: string): string; + init(data: string, rootName?: string): Promise; + parse(data: string, context?: model.SchemaContextDefinition): model.DocumentFragment; + stringify(modelElementOrFragment: Element | model.DocumentFragment): string; + toModel(viewElementOrFragment: Element | model.DocumentFragment, context?: model.SchemaContextDefinition): model.DocumentFragment; + toView(modelElementOrFragment: Element | model.DocumentFragment): model.DocumentFragment; + + // Emitter + delegate(...events: string[]): ckutils.EmitterMixinDelegateChain; + fire(eventOrInfo: string | ckutils.EventInfo, ...args: any[]): any; + listenTo(emitter: ckutils.Emitter, event: string, callback: Function, options?: {priority?: ckutils.PriorityString | number }): void; + off(event: string, callback?: Function): void; + on(event: string, callback: Function, options?: {priority: ckutils.PriorityString | number}): void; + once(event: string, callback: Function, options?: {priority: ckutils.PriorityString | number}): void; + stopDelegating(event?: string, emitter?: ckutils.Emitter): void; + stopListening(emitter?: ckutils.Emitter, event?: string, callback?: Function): void; + + // Observable + bind(...bindProperties: string[]): ckutils.BindChain; + decorate(methodName: string): void; + set(name: object): void; + set(name: string, value: any): void; + unbind(...unbindProperties: string[]): void; + } + + // engine/controller/editingcontroller + + class EditingController implements ckutils.Emitter, ckutils.Observable { + readonly downcastDispatcher: conversion.DowncastDispatcher; + readonly mapper: conversion.Mapper; + readonly model: model.Model; + readonly view: view.View; + + constructor(model: model.Model); + destroy(): void; + + // Emitter + delegate(...events: string[]): ckutils.EmitterMixinDelegateChain; + fire(eventOrInfo: string | ckutils.EventInfo, ...args: any[]): any; + listenTo(emitter: ckutils.Emitter, event: string, callback: Function, options?: {priority?: ckutils.PriorityString | number }): void; + off(event: string, callback?: Function): void; + on(event: string, callback: Function, options?: {priority: ckutils.PriorityString | number}): void; + once(event: string, callback: Function, options?: {priority: ckutils.PriorityString | number}): void; + stopDelegating(event?: string, emitter?: ckutils.Emitter): void; + stopListening(emitter?: ckutils.Emitter, event?: string, callback?: Function): void; + + // Observable + bind(...bindProperties: string[]): ckutils.BindChain; + decorate(methodName: string): void; + set(name: object): void; + set(name: string, value: any): void; + unbind(...unbindProperties: string[]): void; + } +} + +export namespace conversion { + // engine/conversion/conversion + + class Conversion { + constructor(); + attributeToAttribute(definition?: {model: string | Object, view?: string | Object, upcastAlso?: view.MatcherPattern | view.MatcherPattern[]}): void; + attributeToElement(definition: ConverterDefinition): void; + elementToElement(definition: ConverterDefinition): void; + for(groupName: string): {add: () => void}; + register(groupName: string, dispatchers: Array): void; + } + + interface ConverterDefinition { + converterPriority: ckutils.PriorityString; + model: any; + upcastAlso: view.MatcherPattern | view.MatcherPattern[]; + view: view.ElementDefinition | Object; + } + + // engine/conversion/downcast-converters + + interface HighlightDescriptor { + attributes: Object; + classes: string | string[]; + id: string; + priority: number; + } + + // engine/conversion/downcast-selection-converters + + function clearAttributes(): Function; + + function convertCollapsedSelection(): Function; + + function convertRangeSelection(): Function; + + // engine/conversion/downcastdispatcher + + class DowncastDispatcher { + // TODO + } + + // engine/conversion/mapper + + class Mapper { + constructor(); + bindElementToMarker(element: view.Element, name: string): void; + bindElements(modelElement: model.Element, viewElement: view.Element): void; + clearBindings(): void; + getModelLength(viewNode: view.Element): number; + markerNameToElements(name: string): Set | null; + registerViewToModelLength(viewElementName: string, lengthCallback: Function): void; + toModelElement(viewElement: view.Element): model.Element | undefined; + toModelPosition(viewPosition: view.Position): model.Position; + toModelRange(viewRange: view.Range): model.Range; + toViewElement(modelElement: model.Element): view.Element | undefined; + toViewPosition(modelPosition: model.Position, options?: {isPhantom: boolean}): view.Position; + toViewRange(modelRange: model.Range): view.Range; + unbindElementsFromMarkerName(name: string): void; + unbindModelElement(modelElement: model.Element): void; + unbindViewElement(viewElement: view.Element): void; + } + + // engine/conversion/modelconsumable + + class ModelConsumable { + constructor(); + add(item: model.Item | model.Selection | model.Range, type: string): void; + consume(item: model.Item | model.Selection | model.Range, type: string): boolean; + revert(item: model.Item | model.Selection | model.Range, type: string): null | boolean; + test(item: model.Item | model.Selection | model.Range, type: string): null | boolean; + } + + // engine/conversion/upcast-converters + + function convertText(): Function; + + function convertToModelFragment(): Function; + + function upcastAttributeToAttribute( + config: {view: string | {key: string, name: string, value: string | RegExp | Function}, + model: string | {key: string, value: string | Function}, + converterPriority?: ckutils.PriorityString} + ): Function; + + function upcastElementToAttribute( + config: {view: view.MatcherPattern, model: string | {key: string, value: string | Function}, converterPriority?: ckutils.PriorityString} + ): Function; + + function upcastElementToElement( + config: {view: view.MatcherPattern, model: string | Element | Function, converterPriority?: ckutils.PriorityString} + ): Function; + + function upcastElementToMarker( + config: {view: view.MatcherPattern, model: string | Function, converterPriority?: ckutils.PriorityString} + ): Function; + + // engine/conversion/upcast-selection-converters + + function convertSelectionChange(model: model.Model, mapper: Mapper): Function; + + // engine/conversion/upcastdispatcher + + class UpcastDispatcher { + // TODO + } + + interface ViewConversionApi { + // TODO + } + + // engine/conversion/viewconsumable + + class ViewConsumable { + // TODO + } +} + +export namespace dataprocessor { + // engine/dataprocessor/basichtmlwriter + + class BasicHtmlWriter implements HtmlWriter { + getHtml(fragment: model.DocumentFragment): string; + } + + // engine/dataprocessor/dataprocessor + + interface DataProcessor { + // TODO + } + + // engine/dataprocessor/htmldataprocessor + + class HtmlDataProcessor implements DataProcessor { + // TODO + } + + // engine/dataprocessor/htmlwriter + + interface HtmlWriter { + getHtml(fragment: model.DocumentFragment): string; + } + + // engine/dataprocessor/xmldataprocessor + + class XmlDataProcessor implements DataProcessor { + // TODO + } +} + +export namespace devUtils { + // engine/dev-utils/enableenginedebug + + class DebugPlugin {} + + function disableEngineDebug(): void; + + function enableEngineDebug(_logger: {log: (...arg: any[]) => string, error: (...arg: any[]) => string}): DebugPlugin; + + // engine/dev-utils/model + + namespace devmodel { + function getData( + model: model.Model, + options?: { + withoutSelection?: boolean, + rootName?: string, + convertMarkers?: boolean + } + ): string; + + function parse( + data: string, + schema: model.Schema, + batch: model.Batch, + options?: { + selectionAttributes?: Object[], + lastRangeBackward?: boolean, + context?: model.SchemaContextDefinition + } + ): model.Element | model.Text | model.DocumentFragment | Object; + + function setData(model: string, data: Object, options: {rootName?: string, selectionAttributes?: Object[], lastRangeBackward?: boolean, batchType?: string}): void; + + function stringify( + node: model.RootElement | model.Element | model.Text | model.DocumentFragment, + selectionOrPositionOrRange: model.Selection | model.Position | model.Range, // TODO optional + markers: Iterable | null + ): string; + } + + // engine/dev-utils/operationreplayer + + class OperationReplayer { + // TODO + } + + // engine/dev-utils/view + + function getData( + view: view.View, + options?: { + withoutSelection?: boolean, + rootName?: boolean, + showType?: boolean, + showPriority?: boolean, + showAttributeElementId?: boolean, + renderUIElements?: boolean, + } + ): string; + + function parse( + data: string, + options: { + order?: number[], + lastRangeBackward?: boolean, + rootElement?: view.Element | view.DocumentFragment, + sameSelectionCharacters?: boolean + } + ): view.Text | view.Element | view.DocumentFragment | Object; + + function setData( + view: view.View, + data: string, + options: {rootName?: string} + ): void; + + function stringify( + node: view.Text | view.Element | view.DocumentFragment, + selectionOrPositionOrRange?: view.DocumentSelection | view.Position | view.Range, + options?: { + showType?: boolean, + showPriority?: boolean, + showAttributeElementId?: boolean, + ignoreRoot?: boolean, + sameSelectionCharacters?: boolean, + renderUIElements?: boolean, + } + ): string; +} + +export namespace model { + namespace operation { + // engine/model/operation/attributeoperation + + class AttributeOperation { + // TODO + } + + // engine/model/operation/detachoperation + + class DetachOperation { + // TODO + } + + // engine/model/operation/insertoperation + + class InsertOperation { + // TODO + } + + // engine/model/operation/markeroperation + + class MarkerOperation { + // TODO + } + + // engine/model/operation/mergeoperation + + class MergeOperation { + // TODO + } + + // engine/model/operation/moveoperation + + class MoveOperation { + // TODO + } + + // engine/model/operation/nooperation + + class NoOperation { + // TODO + } + + // engine/model/operation/operation + + class Operation { + // TODO + } + + // engine/model/operation/operationfactory + + class OperationFactory { + // TODO + } + + // engine/model/operation/renameoperation + + class RenameOperation { + // TODO + } + + // engine/model/operation/rootattributeoperation + + class RootAttributeOperation { + // TODO + } + + // engine/model/operation/splitoperation + + class SplitOperation { + // TODO + } + + // engine/model/operation/transform + + class TransformationContext { + // TODO + } + + function transform(a: Operation, b: Operation, context: TransformationContext): Operation[]; + + function transformSets(operationsA: Operation[], operationsB: Operation[], options: {document: Document | null, useRelations: boolean, padWithNoOps: boolean}): object; + } + + namespace utils { + function deleteContent( + model: Model, + selection: Selection | DocumentSelection, + batch: Batch, + options?: {leaveUnmerged: boolean, doNotResetEntireContent: boolean} + ): void; + + function getSelectedContent( + model: Model, + selection: Selection | DocumentSelection + ): DocumentFragment; + + function insertContent( + model: Model, + content: DocumentFragment | Item, + selectable?: Selection | DocumentSelection | Position | Element | Iterable | Range | null + ): void; + + function modifySelection( + model: Model, + selection: Selection | DocumentSelection, + options?: {direction?: "forward" | "backward", unit?: "character" | "codePoint" | "word"} + ): void; + + function injectSelectionPostFixer( + model: Model + ): void; + } + + // engine/model/batch + + class Batch { + // TODO + } + + // engine/model/differ + + class Differ { + // TODO + } + + // engine/model/document + + class Document { + // TODO + } + + // engine/model/documentfragment + + class DocumentFragment { + readonly childCount: number; + readonly isEmpty: boolean; + readonly markers: Map; + readonly maxOffset: number; + readonly parent: null; + readonly root: DocumentFragment; + + protected constructor(children?: Node | Iterable); + [Symbol.iterator](): Iterator; + getChild(index: number): Node | null; + getChildIndex(node: Node): number | null; + getChildStartOffset(node: Node): number | null; + getChildren(): Iterable; + getNodeByPath(relativePath: number[]): Node | DocumentFragment; + getPath(): number[]; /*TS3.0: []*/ + is(type: string): boolean; + offsetToIndex(offset: number): number; + toJSON(): Object; + protected _appendChild(items: Item | Iterable): void; + protected _insertChild(index: number, items: Item | Iterable): void; + protected _removeChildren(index: number, howMany?: number): Node[]; + + static fromJSON(json: object): DocumentFragment; + } + + // engine/model/documentselection + + class DocumentSelection { + // TODO + } + + // engine/model/element + + class Element extends Node { + readonly childCount: number; + readonly isEmpty: boolean; + readonly maxOffset: number; + readonly name: string; + + protected constructor( + name: string, + attrs?: Map | ReadonlyArray<[string, any]>, + children?: Node | Iterable + ); + getChild(index: number): Node; + getChildIndex(node: Node): number; + getChildStartOffset(node: Node): number; + getChildren(): Iterable; + getNodeByPath(relativePath: number[]): Node; + is(type: string, name?: string): boolean; + offsetToIndex(offset: number): number; + toJSON(): object; + protected _appendChild(nodes: Item | Iterable): void; + protected _clone(deep?: boolean): Element; + protected _insertChild(index: number, items: Item | Iterable): void; + protected _removeChildren(index: number, howMany?: number): Node[]; + + static fromJSON(json: object): Element; + } + + // engine/model/history + + class History { + // TODO + } + + // engine/model/item + + type Item = Node | TextProxy; + + // engine/model/liveposition + + class LivePosition { + // TODO + } + + // engine/model/liverange + + class LiveRange { + // TODO + } + + // engine/model/markercollection + + class Marker { + // TODO + } + + class MarkerCollection { + // TODO + } + + // engine/model/model + + class Model implements ckutils.Emitter, ckutils.Observable { + readonly document: Document; + readonly markers: MarkerCollection; + readonly schema: Schema; + + applyOperation(operation: operation.Operation): void; + change(callback: Function): any; + deleteContent(selection: Selection | DocumentSelection, batch: Batch, options: {leaveUnmerged?: boolean, doNotResetEntireContent?: boolean}): void; + destroy(): void; + enqueueChange(batchOrType: Batch | "transparent" | "default", callback: Function): void; + getSelectedContent(selection: Selection | DocumentSelection): DocumentFragment; + hasContent(rangeOrElement: Range | Element): boolean; + insertContent(content: DocumentFragment | Item, selectable?: Selection | DocumentSelection | Position | Element | Iterable | Range | null): void; + modifySelection(selection: Selection | DocumentSelection, options?: {direction?: "forward" | "backward", unit?: "character" | "codePoint" | "word"}): void; + + // Emitter + delegate(...events: string[]): ckutils.EmitterMixinDelegateChain; + fire(eventOrInfo: string | ckutils.EventInfo, ...args: any[]): any; + listenTo(emitter: ckutils.Emitter, event: string, callback: Function, options?: {priority?: ckutils.PriorityString | number }): void; + off(event: string, callback?: Function): void; + on(event: string, callback: Function, options?: {priority: ckutils.PriorityString | number}): void; + once(event: string, callback: Function, options?: {priority: ckutils.PriorityString | number}): void; + stopDelegating(event?: string, emitter?: ckutils.Emitter): void; + stopListening(emitter?: ckutils.Emitter, event?: string, callback?: Function): void; + + // Observable + bind(...bindProperties: string[]): ckutils.BindChain; + decorate(methodName: string): void; + set(name: object): void; + set(name: string, value: any): void; + unbind(...unbindProperties: string[]): void; + } + + // engine/model/node + + class Node { + readonly document: Document | null; + readonly endOffset: number | null; + readonly index: number | null; + readonly nextSibling: Node | null; + readonly offsetSize: number; + readonly parent: Element | DocumentFragment | null; + readonly previousSibling: Node | null; + readonly root: Node | DocumentFragment; + readonly startOffset: number | null; + + constructor(attrs?: Map | ReadonlyArray<[string, any]>); + getAncestors(options: {includeSelf: boolean, parentFirst: boolean}): Node[]; + getAttribute(key: string): any /*| undefined*/; + getAttributeKeys(): Iterable; + getAttributes(): Iterable; + getCommonAncestor(node: Node, options?: {includeSelf: boolean}): Element | DocumentFragment | null; + getPath(): number[]; + hasAttribute(key: string): boolean; + + is(type: "element"): this is Element; + is(type: "rootElement"): this is RootElement; + is(type: "text"): this is Text; + is(type: "textProxy"): this is TextProxy; + is(type: "documentFragment"): this is DocumentFragment; + is(type: string, name: string): boolean; + + isAfter(node: Node): boolean; + isBefore(node: Node): boolean; + toJSON(): object; + } + + type NodeSet = Node | TextProxy | string | NodeList | DocumentFragment | Iterable; + + // engine/model/nodelist + + class NodeList implements Iterable { + readonly length: number; + readonly maxOffset: number; + + [Symbol.iterator](): Iterator; + getNode(index: number): Node | null; + getNodeIndex(node: Node): number | null; + getNodeStartOffset(node: Node): number | null; + indexToOffset(index: number): number; + offsetToIndex(offset: number): number; + toJSON(): Node[]; + } + + // engine/model/position + + class Position { + readonly index: number; + readonly isAtEnd: boolean; + readonly isAtStart: boolean; + readonly nodeAfter: Node | null; + readonly nodeBefore: Node; + offset: number; + readonly parent: Element; + readonly path: number[]; + readonly root: Element | DocumentFragment; + stickiness: PositionStickiness; + readonly textNode: Text | null; + + constructor(root: Element | DocumentFragment, path: number[], stickiness?: PositionStickiness); + compareWith(otherPosition: Position): PositionRelation; + getAncestors(): Item[]; + getCommonAncestor(position: Position): Element | DocumentFragment | null; + getCommonPath(position: Position): number[]; + getLastMatchingPosition(skip: (t: TreeWalkerValue) => boolean, options: object): Position; + getParentPath(): number[]; + getShiftedBy(shift: number): Position; + getTransformedByOperation(operation: operation.Operation): Position; + hasSameParentAs(position: Position): boolean; + isAfter(otherPosition: Position): boolean; + isBefore(otherPosition: Position): boolean; + isEqual(otherPosition: Position): boolean; + isTouching(otherPosition: Position): boolean; + toJSON(): object; + + static createAfter(item: Item): Position; + static createAt(itemOrPosition: Item | Position, offset?: number | "end" | "before" | "after"): void; + static createBefore(item: Item): Position; + static createFromParentAndOffset(parent: Element | DocumentFragment, offset: number): Position; + static createFromPosition(position: Position): Position; + static fromJSON(json: object, doc: Document): Position; + } + + type PositionRelation = "before" | "after" | "same"; + + type PositionStickiness = "toNone" | "toNext" | "toPrevious"; + + // engine/model/range + + class Range implements Iterable { + readonly end: Position; + isCollapsed: boolean; + isFlat: boolean; + root: Element | DocumentFragment; + readonly start: Position; + + constructor(start: Position, end?: Position); + [Symbol.iterator](): Iterator; + containsItem(item: Item): void; + containsPosition(position: Position): boolean; + containsRange(otherRange: Range, loose?: boolean): boolean; + getCommonAncestor(): Element | DocumentFragment | null; + getDifference(otherRange: Range): Range[]; + getIntersection(otherRange: Range): Range | null; + getMinimalFlatRanges(): Range[]; + getPositions(options: object): Iterable; + getTransformedByOperation(operation: operation.Operation): Range[]; + getTransformedByOperations(operations: Iterable): Range[]; + getWalker(options: { + startPosition: Position, + singleCharacters: boolean, + shallow: boolean, + ignoreElementEnd: boolean, + }): void; + isEqual(otherRange: Range): boolean; + isIntersecting(otherRange: Range): boolean; + toJSON(): object; + } + + function getItems(options: object): Iterable; + + // engine/model/rootelement + + class RootElement extends Element { + readonly document: Document | null; + readonly rootName: string; + + constructor(doc: Document, name: string, rootName: string); + // TODO: toJSON(): string; + } + + // engine/model/schema + + class Schema { + // TODO + } + + class SchemaContext { + // TODO + } + + interface SchemaCompiledItemDefinition { + name: string; + allowIn: string | string[]; + allowAttributes: string | string[]; + isBlock: boolean; + isLimit: boolean; + isObject: boolean; + } + + type SchemaContextDefinition = Node | Position | SchemaContext | string | Array; + + interface SchemaContextItem { + name: string; + getAttributeKeys: Iterable; + getAttribute: (key: string) => string; + } + + interface SchemaItemDefinition { + allowIn: string | string[]; + allowAttributes: string | string[]; + allowContentOf: string | string[]; + allowWhere: string | string[]; + allowAttributesOf: string | string[]; + inheritTypesFrom: string | string[]; + inheritAllFrom: string | string[]; + isBlock: boolean; + isLimit: boolean; + isObject: boolean; + } + + // engine/model/selection + + class Selection implements ckutils.Emitter { + // TODO + + // Emitter + delegate(...events: string[]): ckutils.EmitterMixinDelegateChain; + fire(eventOrInfo: string | ckutils.EventInfo, ...args: any[]): any; + listenTo(emitter: ckutils.Emitter, event: string, callback: Function, options?: {priority?: ckutils.PriorityString | number }): void; + off(event: string, callback?: Function): void; + on(event: string, callback: Function, options?: {priority: ckutils.PriorityString | number}): void; + once(event: string, callback: Function, options?: {priority: ckutils.PriorityString | number}): void; + stopDelegating(event?: string, emitter?: ckutils.Emitter): void; + stopListening(emitter?: ckutils.Emitter, event?: string, callback?: Function): void; + } + + // engine/model/text + + class Text extends Node { + readonly data: string; + protected _data: string; + + protected constructor(data: string, attrs?: Map | ReadonlyArray<[string, any]>); + toJSON(): object; + protected _clone(): Text; + + static fromJSON(json: object): Text; + } + + // engine/model/textproxy + + class TextProxy { + readonly data: string; + readonly document: Document | null; + readonly endOffset: number; + readonly isPartial: boolean; + readonly offsetInText: number; + readonly offsetSize: number; + readonly parent: Element | DocumentFragment | null; + readonly root: Node | DocumentFragment; + readonly startOffset: number; + readonly textNode: Text; + + protected constructor(textNode: Text, offsetInText: number, length: number); + getAncestors(options: {includeSelf?: boolean, parentFirst?: boolean}): Array; + getAttribute(key: string): any; + getAttributeKeys(): Iterable; + getAttributes(): Iterable; + getPath(): number[]; + hasAttribute(key: string): boolean; + is(type: "textProxy"): this is TextProxy; + is(type: string): boolean; + } + + // engine/model/treewalker + + class TreeWalker implements Iterable { + readonly boundaries: Range; + readonly direction: "backward" | "forward"; + readonly ignoreElementEnd: boolean; + readonly position: Position; + readonly shallow: boolean; + readonly singleCharacters: boolean; + + constructor(options?: { + direction?: "forward" | "backward", + boundaries?: Range, + startPosition: Position, + singleCharacters?: boolean, + shallow?: boolean, + ignoreElementEnd?: boolean + }); + [Symbol.iterator](): Iterator; + next(): TreeWalkerValue; + skip(skip: (t: TreeWalkerValue) => boolean): void; + } + + interface TreeWalkerValue { + item: Item; + length: number; + nextPosition: Position; + previousPosition: Position; + type: TreeWalkerValueType; + } + + type TreeWalkerValueType = "elementStart" | "elementEnd" | "character" | "text"; + + // engine/model/writer + + class Writer { + // TODO + } +} + +export namespace utils { + // engine/utils/bindtwostepcarettoattribute + + function bindTwoStepCaretToAttribute(view: view.View, model: model.Model, emitter: ckutils.Emitter, attribute: string): void; +} + +export namespace view { + namespace observer { + // engine/view/observer/clickobserver + + class ClickObserver extends DomEventObserver { + // TODO + } + + // engine/view/observer/compositionobserver + + class CompositionObserver extends DomEventObserver { + // TODO + } + + // engine/view/observer/domeventdata + + class DomEventData { + // TODO + } + + // engine/view/observer/domeventobserver + + class DomEventObserver extends Observer { + readonly domEventType: string | string[]; + useCapture: boolean; + + fire(eventType: string, domEvent: Event, additionalData?: Object): void; + onDomEvent(): void; + } + + // engine/view/observer/fakeselectionobserver + + class FakeSelectionObserver extends Observer { + constructor(view: View); + destroy(): void; + observe(): void; + } + + // engine/view/observer/focusobserver + + class FocusObserver extends DomEventObserver { + // TODO + } + + // engine/view/observer/keyobserver + + class KeyEventData extends DomEventData implements ckutils.KeystrokeInfo { + // KeystrokeInfo + altKey?: boolean; + ctrlKey?: boolean; + keyCode: number; + keystroke: number; + shiftKey?: boolean; + } + + class KeyObserver extends DomEventObserver { + // TODO + } + + // engine/view/observer/mouseobserver + + class MouseObserver extends DomEventObserver { + // TODO + } + + // engine/view/observer/mutationobserver + + class MutationObserver extends Observer { + domConverter: DomConverter; + renderer: Renderer; + } + + interface MutatedChildren { + newChildren: Node[]; + node: Element; + oldChildren: Node[]; + type: string; + } + + interface MutatedText { + newText: string; + node: Text; + oldText: string; + type: string; + } + + // engine/view/observer/observer + + class Observer { + readonly document: Document; + readonly isEnabled: boolean; + readonly view: View; + + constructor(view: View); + destroy(): void; + disable(): void; + enable(): void; + observe(domElement: HTMLElement, name: string): void; + } + + // engine/view/observer/selectionobserver + + class SelectionObserver extends Observer { + readonly domConverter: DomConverter; + readonly mutationObserver: MutationObserver; + readonly selection: DocumentSelection; + } + } + + // engine/view/attributeelement + + class AttributeElement extends Element { + readonly id: string | number; + readonly priority: number; + protected _clonesGroup: Set | null; + protected _id: string | number; + protected _priority: number; + + static DEFAULT_PRIORITY: number; + + protected constructor( + name: string, + attrs?: object | Iterable<[string, string]> | Map, + children?: Node | Iterable + ); + getElementsWithSameId(): Set; + getFillerOffset(): number | null; + isSimilar(otherElement: Element): boolean; + protected _clone(deep: boolean): AttributeElement; + } + + // engine/view/containerelement + + class ContainerElement extends Element { + protected constructor( + name: string, + attrs?: object | Iterable<[string, string]> | Map, + children?: Node | Iterable + ); + getFillerOffset(): number | null; + } + + // engine/view/document + + class Document implements ckutils.Emitter, ckutils.Observable { + readonly isComposing: boolean; + readonly isFocused: boolean; + isReadOnly: boolean; + readonly roots: ckutils.Collection; + readonly selection: DocumentSelection; + + constructor(); + getRoot(name?: string): RootEditableElement | null; + registerPostFixer(postFixer: (downcastWriter: DowncastWriter) => boolean): void; + protected _callPostFixers(writer: DowncastWriter): void; + + // Emitter + delegate(...events: string[]): ckutils.EmitterMixinDelegateChain; + fire(eventOrInfo: string | ckutils.EventInfo, ...args: any[]): any; + listenTo(emitter: ckutils.Emitter, event: string, callback: Function, options?: {priority?: ckutils.PriorityString | number }): void; + off(event: string, callback?: Function): void; + on(event: string, callback: Function, options?: {priority: ckutils.PriorityString | number}): void; + once(event: string, callback: Function, options?: {priority: ckutils.PriorityString | number}): void; + stopDelegating(event?: string, emitter?: ckutils.Emitter): void; + stopListening(emitter?: ckutils.Emitter, event?: string, callback?: Function): void; + + // Observable + bind(...bindProperties: string[]): ckutils.BindChain; + decorate(methodName: string): void; + set(name: object): void; + set(name: string, value: any): void; + unbind(...unbindProperties: string[]): void; + } + + type ChangeType = "children" | "attributes" | "text"; + + // engine/view/documentfragment + + class DocumentFragment { + readonly childCount: number; + readonly isEmpty: boolean; + readonly parent: null; + readonly root: DocumentFragment; + protected _children: Element[]; + + protected constructor(children?: Node | Iterable); + [Symbol.iterator](): Iterator; + _appendChild(items: Item | Iterable): number; + _insertChild(index: number, items: Item | Iterable): number; + _removeChildren(index: number, howMany?: number): Node[]; + getChild(index: number): Node; + getChildIndex(node: Node): number; + getChildren(): Iterable; + is(type: string): boolean; + } + + // engine/view/documentselection + + class DocumentSelection { + // TODO + } + + // engine/view/domconverter + + class DomConverter { + // TODO + } + + // engine/view/downcastwriter + + class DowncastWriter { + // TODO + } + + // engine/view/editableelement + + class EditableElement extends ContainerElement { + // TODO + } + + // engine/view/element + + class Element extends Node { + readonly childCount: number; + readonly isEmpty: boolean; + readonly name: string; + protected _attrs: Map; + protected _children: Node[]; + protected _classes: Set; + protected _customProperties: Map; + protected _styles: Map; + + protected constructor( + name: string, + attrs?: object | Iterable<[string, string]> | Map, + children?: Node | Iterable + ); + _removeChildren(index: number, howMany?: number): Node[]; + _removeClass(className: string[] | string): void; + findAncestor(patterns: Object | string | RegExp | Function): Element | null; + getAttribute(key: string): string | undefined; + getAttributeKeys(): Iterable; + getAttributes(): Iterable; + getChild(index: number): Node; + getChildIndex(node: Node): number; + getChildren(): Iterable; + getClassNames(): Iterable; + getCustomProperties(): Iterable; + getCustomProperty(key: string | symbol): any; + getFillerOffset(): void; + getIdentity(): string; + getStyle(property: string): string | undefined; + getStyleNames(): Iterable; + hasAttribute(key: string): boolean; + hasClass(className: string): void; + hasStyle(property: string): void; + is(type: string, name?: string): boolean; + isSimilar(otherElement: Element): boolean; + protected _addClass(className: string[] | string): void; + protected _appendChild(items: Item | Iterable): number; + protected _clone(deep?: boolean): Element; + protected _insertChild(index: number, items: Item | Iterable): number; + protected _removeAttribute(key: string): boolean; + protected _removeCustomProperty(key: string | symbol): boolean; + protected _removeStyle(property: string[] | string): void; + protected _setAttribute(key: string, value: string): void; + protected _setCustomProperty(key: string | symbol, value: any): void; + protected _setStyle(property: string | {[key: string]: string}, value?: string): void; + } + + // engine/view/elementdefinition + + type ElementDefinition = string | { + attributes?: {[key: string]: string}; + classes?: string | string[]; + name: string; + priority?: number; + styles?: {[key: string]: string}; + }; + + // engine/view/emptyelement + + class EmptyElement extends Element { + protected constructor( + name: string, + attrs?: object | Iterable<[string, string]> | Map, + children?: Node | Iterable + ); + getFillerOffset(): null; + } + + // engine/view/filler + + const INLINE_FILLER_LENGTH: number; + + const INLINE_FILLER: string; + + function BR_FILLER(): void; + + function NBSP_FILLER(): void; + + function getDataWithoutFiller(domText: Text): string; + + function injectQuirksHandling(view: View): void; + + function isBlockFiller(domNode: /*TODO globals.*/Node, blockFiller: Function): boolean; + + function isInlineFiller(domText: /*TODO globals.*/Text): boolean; + + function startsWithFiller(domNode: /*TODO globals.*/Text): boolean; + + // engine/view/item + + type Item = Node | TextProxy; + + // engine/view/matcher + + class Matcher { + // TODO + } + + type MatcherPattern = + ((element: Element) => null | {name: boolean; attribute?: string[]; }) | + string | + RegExp | + { + attributes?: {[key: string]: string | RegExp | boolean}; + classes?: string | RegExp | Array; + name?: string | RegExp; + styles?: {[key: string]: string | RegExp}; + }; + + // engine/view/node + + class Node { + readonly document: Document | null; + readonly index: number | null; + readonly nextSibling: Node | null; + readonly parent: Element | DocumentFragment | null; + readonly previousSibling: Node | null; + readonly root: Node | DocumentFragment; + + constructor(); + _fireChange(type: ChangeType, node: Node): void; + getAncestors(options: {includeSelf: boolean, parentFirst?: boolean}): Array; + getCommonAncestor(node: Node, options: {includeSelf?: boolean}): Element | DocumentFragment | null; + getPath(): number[]; + + is(type: "element"): this is Element; + is(type: "containerElement"): this is ContainerElement; + is(type: "attributeElement"): this is AttributeElement; + is(type: "emptyElement"): this is EmptyElement; + is(type: "uiElement"): this is UIElement; + is(type: "documentFragment"): this is DocumentFragment; + is(type: "text"): this is Text; + is(type: "textProxy"): this is TextProxy; + is(type: string, name: string): boolean; + + isAfter(node: Node): boolean; + isBefore(node: Node): boolean; + isSimilar(otherElement: Node): boolean; + toJSON(): object; + protected _clone(): Node; + protected _remove(): void; + } + + // engine/view/placeholder + + function attachPlaceholder(view: View, element: Element, placeholderText: string, checkFunction?: Function): void; + + function detachPlaceholder(view: View, element: Element): void; + + // engine/view/position + + class Position { + // TODO + } + + type PositionRelation = "before" | "after" | "same" | "different"; + + // engine/view/range + + class Range { + // TODO + } + + // engine/view/renderer + + class Renderer { + // TODO + } + + // engine/view/rooteditableelement + + class RootEditableElement extends EditableElement { + // TODO + } + + // engine/view/selection + + class Selection { + // TODO + } + + // engine/view/text + + class Text extends Node { + readonly data: string; + protected _data: string; + protected _textData: string; + + protected constructor(data: string); + isSimilar(otherNode: Text): boolean; + protected _clone(): Text; + } + + // engine/view/textproxy + + class TextProxy { + readonly data: string; + readonly document: Document | null; + readonly isPartial: boolean; + readonly offsetInText: number; + readonly offsetSize: number; + readonly parent: Element | DocumentFragment | null; + readonly root: Node | DocumentFragment; + readonly textNode: Text; + + protected constructor(textNode: Text, offsetInText: number, length: number); + getAncestors(options: {includeSelf?: boolean, parentFirst?: boolean}): Array; + is(type: "textProxy"): this is TextProxy; + is(type: string): boolean; + } + + // engine/view/treewalker + + class TreeWalker { + readonly boundaries: Range; + readonly direction: TreeWalkerDirection; + readonly ignoreElementEnd: boolean; + readonly position: Position; + readonly shallow: boolean; + readonly singleCharacters: boolean; + + constructor(options: { + boundaries?: Range, + startPosition?: Position, + direction?: TreeWalkerDirection, + singleCharacters?: boolean, + shallow?: boolean, + ignoreElementEnd?: boolean; + }); + [Symbol.iterator](): Iterator; + next(): TreeWalkerValue; + skip(skip: (treeWalkerValue: TreeWalkerValue) => boolean): void; + } + + type TreeWalkerDirection = "forward" | "backward"; + + interface TreeWalkerValue { + item: Item; + length: number; + nextPosition: Position; + previousPosition: Position; + type: TreeWalkerValueType; + } + + type TreeWalkerValueType = "elementStart" | "elementEnd" | "text"; + + // engine/view/uielement + + class UIElement extends Element { + protected constructor( + name: string, + attrs?: object | Iterable<[string, string]> | Map, + children?: Node | Iterable + ); + getFillerOffset(): null; + render(domDocument: /*TODO: globals.*/Document): HTMLElement; + toDomElement(domDocument: /*TODO: globals.*/Document): HTMLElement; + } + + // engine/view/upcastwriter + + class UpcastWriter { + // TODO + } + + // engine/view/view + + class View implements ckutils.Emitter, ckutils.Observable { + // TODO + + // Emitter + delegate(...events: string[]): ckutils.EmitterMixinDelegateChain; + fire(eventOrInfo: string | ckutils.EventInfo, ...args: any[]): any; + listenTo(emitter: ckutils.Emitter, event: string, callback: Function, options?: {priority?: ckutils.PriorityString | number }): void; + off(event: string, callback?: Function): void; + on(event: string, callback: Function, options?: {priority: ckutils.PriorityString | number}): void; + once(event: string, callback: Function, options?: {priority: ckutils.PriorityString | number}): void; + stopDelegating(event?: string, emitter?: ckutils.Emitter): void; + stopListening(emitter?: ckutils.Emitter, event?: string, callback?: Function): void; + + // Observable + bind(...bindProperties: string[]): ckutils.BindChain; + decorate(methodName: string): void; + set(name: object): void; + set(name: string, value: any): void; + unbind(...unbindProperties: string[]): void; + } +} diff --git a/types/ckeditor__ckeditor5-engine/tsconfig.json b/types/ckeditor__ckeditor5-engine/tsconfig.json new file mode 100644 index 0000000000..36da122d77 --- /dev/null +++ b/types/ckeditor__ckeditor5-engine/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "ckeditor__ckeditor5-engine-tests.ts" + ] +} diff --git a/types/ckeditor__ckeditor5-engine/tslint.json b/types/ckeditor__ckeditor5-engine/tslint.json new file mode 100644 index 0000000000..6a214f0cfd --- /dev/null +++ b/types/ckeditor__ckeditor5-engine/tslint.json @@ -0,0 +1,20 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "ban-types": { + "options": [ + ["Boolean", "Avoid using the `Boolean` type. Did you mean `boolean`?"], + ["Number", "Avoid using the `Number` type. Did you mean `number`?"], + ["String", "Avoid using the `String` type. Did you mean `string`?"], + ["Symbol", "Avoid using the `Symbol` type. Did you mean `symbol`?"] + ] + }, + "no-empty-interface": false, + "quotemark": [ + true, + "double", + "avoid-escape", + "avoid-template" + ] + } +} diff --git a/types/ckeditor__ckeditor5-utils/ckeditor__ckeditor5-utils-tests.ts b/types/ckeditor__ckeditor5-utils/ckeditor__ckeditor5-utils-tests.ts index 82c272a6ec..19f21f667a 100644 --- a/types/ckeditor__ckeditor5-utils/ckeditor__ckeditor5-utils-tests.ts +++ b/types/ckeditor__ckeditor5-utils/ckeditor__ckeditor5-utils-tests.ts @@ -489,24 +489,30 @@ utils.mapsEqual(map, map); // utils/mix ================================================================== -class Editor { - b: () => number; -} - interface SomeMixin { a: () => string; } +class Editor implements SomeMixin { + a: () => string; + b() { return 3; } +} + const SomeMixin = { - a() { - return "a"; - } + a() { return "a"; } +}; + +const SomeMixinNum = { + a() { return 3; } }; utils.mix(Editor, SomeMixin); -const mixEditor = new Editor() as Editor & SomeMixin; -mixEditor.a(); -mixEditor.b(); +// $ExpectError +utils.mix(Editor, SomeMixinNum); + +const editor = new Editor(); +str = editor.a(); +num = editor.b(); // utils/nth ================================================================== diff --git a/types/ckeditor__ckeditor5-utils/index.d.ts b/types/ckeditor__ckeditor5-utils/index.d.ts index 8d9d50e889..50571483f8 100644 --- a/types/ckeditor__ckeditor5-utils/index.d.ts +++ b/types/ckeditor__ckeditor5-utils/index.d.ts @@ -367,7 +367,11 @@ export class KeystrokeHandler { destroy(): void; listenTo(emitter: Emitter): void; press(keyEvtData: KeystrokeInfo): boolean; - set(keystroke: string | Array, callback: Function, options?: {priority?: PriorityString | number}): void; + set( + keystroke: string | Array, + callback: (keyEvtData: KeystrokeInfo, cancel: () => void) => void, + options?: {priority?: PriorityString | number} + ): void; } // utils/locale @@ -392,7 +396,7 @@ export function mapsEqual(mapsA: Map, mapsB: Map): boolean; // utils/mix -export function mix(baseClass: {new(): any}, ...mixins: any[]): void; +export function mix(baseClass: {new(...p: any[]): T}, ...mixins: Array>): void; // utils/nth diff --git a/types/cli-box/cli-box-tests.ts b/types/cli-box/cli-box-tests.ts new file mode 100644 index 0000000000..a26b436e21 --- /dev/null +++ b/types/cli-box/cli-box-tests.ts @@ -0,0 +1,47 @@ +import Box = require('cli-box'); + +// Create a simple box +const b1: Box = Box("20x10"); +// console.log(b1.toString()); + +// Set custom marks +const b2: Box = new Box({ + w: 10 + , h: 10 + , stringify: false + , marks: { + nw: "╔" + , n: "══" + , ne: "╗" + , e: "║" + , se: "╝" + , s: "══" + , sw: "╚" + , w: "║" + , b: "░░" + } +}); +// console.log(b2.stringify()); + +// Box with text and use the stringify +const b3: Box = Box("20x10", "I will be \u001b[31mdis\u001b[0mplayed inside! \n A\u001b[34mnd I'm in a\u001b[0m new line!"); +// console.log(b3); + +// Box with aligned text to top-right +const b4: Box = Box("30x20", { + text: "Box content" + , stretch: true + , autoEOL: true + , vAlign: "top" + , hAlign: "right" +}); +// console.log(b4); + +// Full screen box +const b5: Box = Box({fullscreen: true, marks: {}}, "Hello World!"); +// console.log(b5.toString()); + +const b5s: string = Box({stringify: true, fullscreen: true, marks: {}}, "Hello World!"); +const b5ns: Box = Box({stringify: false, fullscreen: true, marks: {}}, "Hello World!"); + +const defaults = Box.defaults; diff --git a/types/cli-box/index.d.ts b/types/cli-box/index.d.ts new file mode 100644 index 0000000000..c2466853a6 --- /dev/null +++ b/types/cli-box/index.d.ts @@ -0,0 +1,70 @@ +// Type definitions for cli-box 6.0 +// Project: https://github.com/IonicaBizau/node-cli-box +// Definitions by: Kent Wong +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +/*~ Note that ES6 modules cannot directly export callable functions. + *~ This file should be imported using the CommonJS-style: + *~ import x = require('someLibrary'); + *~ + *~ Refer to the documentation to understand common + *~ workarounds for this limitation of ES6 modules. + */ + +/*~ This declaration specifies that the function + *~ is the exported object from the file + */ +export = Box; + +type MarksKeys = 'nw' | 'n' | 'ne' | 'e' | 'se' | 's' | 'sw' | 'w' | 'b'; +type Marks = Record; + +interface Options { + w?: number; + width?: number; + h?: number; + height?: number; + fullscreen?: boolean; + stringify?: boolean; + marks?: Partial; +} + +interface Text { + text?: string; + stretch?: boolean; + autoEOL?: boolean; + hAlign?: 'left' | 'middle' | 'right'; + vAlign?: 'top' | 'center' | 'bottom'; +} + +interface Box { + stringify(): string; + settings: { + width: number; + height: number; + marks: Marks; + lines: Array<{ + text: string; + offset: { + y: number; + } + }> + }; + options: { + width: number; + height: number; + marks: Marks; + fullscreen: boolean; + stringify: boolean; + }; +} + +interface BoxConstructor { + new(options: Options | string, text?: Text | string): Box; + (options: (Exclude & { stringify: true }), text?: Text | string): string; + (options: Options | string, text?: Text | string): Box; + defaults: { marks: Marks }; +} + +declare const Box: BoxConstructor; diff --git a/types/cli-box/tsconfig.json b/types/cli-box/tsconfig.json new file mode 100644 index 0000000000..d9a3d38876 --- /dev/null +++ b/types/cli-box/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictFunctionTypes": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "cli-box-tests.ts" + ] +} diff --git a/types/cli-box/tslint.json b/types/cli-box/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/cli-box/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/command-exists/command-exists-tests.ts b/types/command-exists/command-exists-tests.ts new file mode 100644 index 0000000000..60efc1e0e5 --- /dev/null +++ b/types/command-exists/command-exists-tests.ts @@ -0,0 +1,14 @@ +import commandExists = require('command-exists'); + +commandExists('ls', (err, commandExists) => { + // $ExpectType boolean + commandExists; +}); + +commandExists('ls').then(command => { + // $ExpectType string + command; +}); + +// $ExpectType boolean +commandExists.sync('ls'); diff --git a/types/command-exists/index.d.ts b/types/command-exists/index.d.ts new file mode 100644 index 0000000000..634d2a035e --- /dev/null +++ b/types/command-exists/index.d.ts @@ -0,0 +1,16 @@ +// Type definitions for command-exists 1.2 +// Project: https://github.com/mathisonian/command-exists +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = commandExists; + +declare function commandExists(commandName: string): Promise; +declare function commandExists( + commandName: string, + cb: (error: null, exists: boolean) => void +): void; + +declare namespace commandExists { + function sync(commandName: string): boolean; +} diff --git a/types/command-exists/tsconfig.json b/types/command-exists/tsconfig.json new file mode 100644 index 0000000000..9782cd2715 --- /dev/null +++ b/types/command-exists/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "command-exists-tests.ts" + ] +} diff --git a/types/command-exists/tslint.json b/types/command-exists/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/command-exists/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/common-tags/common-tags-tests.ts b/types/common-tags/common-tags-tests.ts index e504624943..37a1fba789 100644 --- a/types/common-tags/common-tags-tests.ts +++ b/types/common-tags/common-tags-tests.ts @@ -1,167 +1,242 @@ -import * as commonTags from 'common-tags'; +import { + html, + safeHtml, + oneLine, + oneLineTrim, + stripIndent, + stripIndents, + inlineLists, + oneLineInlineLists, + commaLists, + commaListsOr, + commaListsAnd, + oneLineCommaLists, + oneLineCommaListsOr, + oneLineCommaListsAnd, + id, + TemplateTag, + trimResultTransformer, + stripIndentTransformer, + replaceResultTransformer, + replaceSubstitutionTransformer, + inlineArrayTransformer, + splitStringTransformer, + createTag, + TemplateTransformer, + replaceStringTransformer, +} from 'common-tags'; -/* Test Built-in Tags */ - -commonTags.commaLists ` - I like ${['apples', 'bananas', 'watermelons']} - They're good! +const userMessages = ['hi', 'what are you up to?', '']; +html` +

+
    + ${userMessages.map(message => safeHtml`
  • ${message}
  • `)} +
+
`; -commonTags.commaListsAnd` - I like ${['apples', 'bananas', 'watermelons']} - They're good! -`; - -commonTags.commaListsOr` - I like ${['apples', 'bananas', 'watermelons']} - They're good! -`; - -let fruits = ['apple', 'orange', 'watermelon']; - -commonTags.html` -
-
    - ${fruits.map(fruit => `
  • ${fruit}
  • `)} - ${'
  • kiwi
  • \n
  • guava
  • '} -
-
-`; - -commonTags.codeBlock` -
-
    - ${fruits.map(fruit => `
  • ${fruit}
  • `)} - ${'
  • kiwi
  • \n
  • guava
  • '} -
-
-`; - -commonTags.source` -
-
    - ${fruits.map(fruit => `
  • ${fruit}
  • `)} - ${'
  • kiwi
  • \n
  • guava
  • '} -
-
-`; - -let userMessages = ['hi', 'what are you up to?', ''] -commonTags.html` -
-
    - ${userMessages.map(message => commonTags.safeHtml`
  • ${message}
  • `)} -
-
-` - -commonTags.oneLine` +oneLine` foo bar baz `; -commonTags.oneLineTrim` +oneLineTrim` https://news.com/article ?utm_source=designernews.co `; -commonTags.oneLineCommaLists` - I like ${['apples', 'bananas', 'watermelons']} - They're good! -`; - -commonTags.oneLineCommaListsOr` - I like ${['apples', 'bananas', 'watermelons']} - They're good! -`; - -commonTags.oneLineCommaListsAnd` - I like ${['apples', 'bananas', 'watermelons']} - They're good! -`; - -commonTags.inlineLists` - I like ${['apples', 'bananas', 'watermelons']} - They're good! -`; - -commonTags.oneLineInlineLists` - I like ${['apples', 'bananas', 'watermelons']} - They're good! -`; - -let verb = 'notice'; - -commonTags.stripIndent` +const verb = 'notice'; +stripIndent` This is a multi-line string. You'll ${verb} that it is indented. We don't want to output this indentation. But we do want to keep this line indented. `; -commonTags.stripIndents` +stripIndents` This is a multi-line string. You'll ${verb} that it is indented. We don't want to output this indentation. We don't want to keep this line indented either. `; -/* Test Tag Constructor */ +inlineLists` + I like ${['apples', 'bananas', 'watermelons']} + They're good! +`; -new commonTags.TemplateTag(); +oneLineInlineLists` + I like ${['apples', 'bananas', 'watermelons']} + They're good! +`; -const substitutionReplacer = (oldValue : string, newValue : string) => ({ - onSubstitution(substitution : string, resultSoFar : string) { +commaLists` + I like ${['apples', 'bananas', 'watermelons']} + They're good! +`; + +commaListsOr` + I like ${['apples', 'bananas', 'watermelons']} + They're good! +`; + +commaListsAnd` + I like ${['apples', 'bananas', 'watermelons']} + They're good! +`; + +oneLineCommaLists` + I like ${['apples', 'bananas', 'watermelons']} + They're good! +`; + +oneLineCommaListsOr` + I like ${['apples', 'bananas', 'watermelons']} + They're good! +`; + +oneLineCommaListsAnd` + I like ${['apples', 'bananas', 'watermelons']} + They're good! +`; + +id`hello ${'world'}`; + +oneLine(String.raw)` + foo + bar\nbaz +`; + +stripIndent(' foo\n bar'); + +const doNothing = createTag(); +doNothing`foo bar`; + +const substitutionReplacer = (oldValue: string, newValue: string): TemplateTransformer => ({ + onSubstitution(substitution, resultSoFar) { if (substitution === oldValue) { return newValue; } return substitution; - } + }, }); -new commonTags.TemplateTag(substitutionReplacer('fizz', 'buzz')); +const replaceFizzWithBuzz = createTag(substitutionReplacer('fizz', 'buzz')); +replaceFizzWithBuzz`foo bar ${'fizz'}`; -new commonTags.TemplateTag( - substitutionReplacer('fizz', 'buzz'), - substitutionReplacer('foo', 'bar') +createTag(); +createTag(substitutionReplacer('fizz', 'buzz')); +createTag(substitutionReplacer('fizz', 'buzz'), substitutionReplacer('foo', 'bar')); +createTag([substitutionReplacer('fizz', 'buzz'), substitutionReplacer('foo', 'bar')]); +new TemplateTag(); +new TemplateTag(substitutionReplacer('fizz', 'buzz')); +new TemplateTag(substitutionReplacer('fizz', 'buzz'), substitutionReplacer('foo', 'bar')); +new TemplateTag([substitutionReplacer('fizz', 'buzz'), substitutionReplacer('foo', 'bar')]); + +const tt: TemplateTransformer<{ foo: string }> = { + getInitialContext() { + return { foo: 'bar' }; + }, + onString(str, context) { + // $ExpectType string + str; + // $ExpectType { foo: string; } + context; + return ''; + }, + onSubstitution(substitution, resultSoFar, context) { + // $ExpectType string + substitution; + // $ExpectType string + resultSoFar; + // $ExpectType { foo: string; } + context; + return ''; + }, + onEndResult(endResult, context) { + // $ExpectType string + endResult; + // $ExpectType { foo: string; } + context; + return ''; + }, +}; + +createTag({}); +createTag(tt); +createTag({ + onString: str => `${str}!`, +}); +createTag({ + onSubstitution: substitution => `${substitution}!`, +}); +createTag({ + onEndResult: endResult => `${endResult}!`, +}); +new TemplateTag({}); +new TemplateTag(tt); +new TemplateTag({ + onString: str => `${str}!`, +}); +new TemplateTag({ + onSubstitution: substitution => `${substitution}!`, +}); +new TemplateTag({ + onEndResult: endResult => `${endResult}!`, +}); + +createTag(trimResultTransformer()); +createTag(trimResultTransformer('')); +createTag(trimResultTransformer('start')); +createTag(trimResultTransformer('end')); +createTag(trimResultTransformer('left')); +createTag(trimResultTransformer('right')); + +createTag(stripIndentTransformer()); +createTag(stripIndentTransformer('initial')); +createTag(stripIndentTransformer('all')); + +createTag(replaceResultTransformer('foo', 'bar')); +createTag(replaceResultTransformer(/baz/g, 'bar')); +createTag( + replaceResultTransformer(/baz/g, (substring, ...matches) => { + // $ExpectType string + substring; + // $ExpectType any[] + matches; + return ''; + }) ); -new commonTags.TemplateTag([ - substitutionReplacer('fizz', 'buzz'), - substitutionReplacer('foo', 'bar') -]); +createTag(replaceSubstitutionTransformer('foo', 'bar')); +createTag(replaceSubstitutionTransformer(/baz/g, 'bar')); +createTag( + replaceSubstitutionTransformer(/baz/g, (substring, ...matches) => { + // $ExpectType string + substring; + // $ExpectType any[] + matches; + return ''; + }) +); -new commonTags.TemplateTag({}); +createTag(replaceStringTransformer('foo', 'bar')); +createTag(replaceStringTransformer(/baz/g, 'bar')); +createTag( + replaceStringTransformer(/baz/g, (substring, ...matches) => { + // $ExpectType string + substring; + // $ExpectType any[] + matches; + return ''; + }) +); -new commonTags.TemplateTag({ - onEndResult: endResult => `${endResult}!` -}); +createTag(inlineArrayTransformer()); +createTag(inlineArrayTransformer({})); +createTag(inlineArrayTransformer({ separator: 'foo' })); +createTag(inlineArrayTransformer({ conjunction: 'bar' })); +createTag(inlineArrayTransformer({ serial: true })); -new commonTags.TemplateTag({ - onSubstitution: substitution => `${substitution}!`, - onEndResult: endResult => `${endResult}!` -}); - -/* Tests Built-in Transformers */ - -new commonTags.TemplateTag(commonTags.trimResultTransformer()); -new commonTags.TemplateTag(commonTags.trimResultTransformer('left')); -new commonTags.TemplateTag(commonTags.trimResultTransformer('right')); - -new commonTags.TemplateTag(commonTags.stripIndentTransformer()); -new commonTags.TemplateTag(commonTags.stripIndentTransformer('initial')); -new commonTags.TemplateTag(commonTags.stripIndentTransformer('all')); - -new commonTags.TemplateTag(commonTags.replaceResultTransformer('foo', 'bar')); -new commonTags.TemplateTag(commonTags.replaceSubstitutionTransformer(/baz/g, 'bar')); - -new commonTags.TemplateTag(commonTags.replaceSubstitutionTransformer('foo', 'bar')); -new commonTags.TemplateTag(commonTags.replaceSubstitutionTransformer(/baz/g, 'bar')); - -new commonTags.TemplateTag(commonTags.inlineArrayTransformer()); -new commonTags.TemplateTag(commonTags.inlineArrayTransformer({})); -new commonTags.TemplateTag(commonTags.inlineArrayTransformer({separator: 'foo'})); -new commonTags.TemplateTag(commonTags.inlineArrayTransformer({conjunction: 'bar'})); - -new commonTags.TemplateTag(commonTags.splitStringTransformer('foo')); +createTag(splitStringTransformer('foo')); diff --git a/types/common-tags/index.d.ts b/types/common-tags/index.d.ts index 65f0b61673..3a12c91109 100644 --- a/types/common-tags/index.d.ts +++ b/types/common-tags/index.d.ts @@ -1,67 +1,220 @@ -// Type definitions for common-tags v1.4.0 +// Type definitions for common-tags 1.8 // Project: https://github.com/declandewet/common-tags // Definitions by: Viktor Zozuliak // Paul Wang +// BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 -declare module 'common-tags' { - type TemplateTag = (literals: TemplateStringsArray, ...placeholders: any[]) => string; +export as namespace commonTags; - type TemplateTransformer = { - onSubstitution?: (substitution: string, resultSoFar: string) => string; - onEndResult?: (endResult : string) => string; - } +export type JSTag = (literals: TemplateStringsArray, ...placeholders: any[]) => string; - /* Built-in Tags */ - export var commaLists: TemplateTag; - - export var commaListsAnd: TemplateTag; - - export var commaListsOr: TemplateTag; - - export var html: TemplateTag; - - export var codeBlock: TemplateTag; - - export var source: TemplateTag; - - export var safeHtml: TemplateTag; - - export var oneLine: TemplateTag; - - export var oneLineTrim: TemplateTag; - - export var oneLineCommaLists: TemplateTag; - - export var oneLineCommaListsOr: TemplateTag; - - export var oneLineCommaListsAnd: TemplateTag; - - export var inlineLists: TemplateTag; - - export var oneLineInlineLists: TemplateTag; - - export var stripIndent: TemplateTag; - - export var stripIndents: TemplateTag; - - /* New Tag Constructor */ - export var TemplateTag: { - new(): TemplateTag; - new(...transformers: TemplateTransformer[]): TemplateTag; - new(transformers: TemplateTransformer[]): TemplateTag; - }; - - /* Built-in Transformers */ - export var trimResultTransformer: (side?: 'left'|'right') => TemplateTransformer; - - export var stripIndentTransformer: (type?: 'initial'|'all') => TemplateTransformer; - - export var replaceResultTransformer: (replaceWhat: string|RegExp, replaceWith: string) => TemplateTransformer; - - export var replaceSubstitutionTransformer: (replaceWhat: string|RegExp, replaceWith: string) => TemplateTransformer; - - export var inlineArrayTransformer: (opts?: {separator?: string, conjunction?: string}) => TemplateTransformer; - - export var splitStringTransformer: (splitBy: string) => TemplateTransformer; +export interface TemplateTag { + (str: string): string; + (tag: JSTag): TemplateTag; + (literals: TemplateStringsArray, ...placeholders: any[]): string; } + +/** + * You'll often find that you might want to include an array in a template. + * Typically, doing something like `${array.join(', ')}` would work - but what if you're printing a list of items + * in an HTML template and want to maintain the indentation? You'd have to count the spaces manually and include + * them in the `.join()` call - which is a bit ugly for my taste. + * This tag properly indents arrays, as well as newline characters in string substitutions, + * by converting them to an array split by newline and re-using the same array inclusion logic. + */ +export const html: TemplateTag; + +/** + * alias for `html` + */ +export const codeBlock: TemplateTag; + +/** + * alias for `html` + */ +export const source: TemplateTag; + +/** + * A tag very similar to `html` but it does safe HTML escaping for strings coming from substitutions. + * When combined with regular `html` tag, you can do basic HTML templating that is safe from + * XSS (Cross-Site Scripting) attacks. + */ +export const safeHtml: TemplateTag; + +/** + * Allows you to keep your single-line strings under 80 characters without resorting to crazy string concatenation. + */ +export const oneLine: TemplateTag; + +/** + * Allows you to keep your single-line strings under 80 characters while trimming the new lines. + */ +export const oneLineTrim: TemplateTag; + +/** + * If you want to strip the initial indentation from the beginning of each line in a multiline string. + * Important note: this tag will not indent multiline strings coming from the substitutions. + * If you want that behavior, use the `html` tag (aliases: `source`, `codeBlock`). + */ +export const stripIndent: TemplateTag; + +/** + * If you want to strip *all* of the indentation from the beginning of each line in a multiline string. + */ +export const stripIndents: TemplateTag; + +/** + * Allows you to inline an array substitution as a list. + */ +export const inlineLists: TemplateTag; + +/** + * Allows you to inline an array substitution as a list, rendered out on a single line. + */ +export const oneLineInlineLists: TemplateTag; + +/** + * Allows you to inline an array substitution as a comma-separated list. + */ +export const commaLists: TemplateTag; + +/** + * Allows you to inline an array substitution as a comma-separated list, the last of which is preceded by the word "or". + */ +export const commaListsOr: TemplateTag; + +/** + * Allows you to inline an array substitution as a comma-separated list, the last of which is preceded by the word "and". + */ +export const commaListsAnd: TemplateTag; + +/** + * Allows you to inline an array substitution as a comma-separated list, and is rendered out on to a single line. + */ +export const oneLineCommaLists: TemplateTag; + +/** + * Allows you to inline an array substitution as a comma-separated list, the last of which is preceded by the word "or", and is rendered out on to a single line. + */ +export const oneLineCommaListsOr: TemplateTag; + +/** + * Allows you to inline an array substitution as a comma-separated list, the last of which is preceded by the word "and", and is rendered out on to a single line. + */ +export const oneLineCommaListsAnd: TemplateTag; + +/** + * A no-op tag that might come in useful in some scenarios, e.g. mocking. + */ +export const id: TemplateTag; + +export interface TemplateTransformer { + /** + * Called before everything else. + * The result of this hook will be passed to other hooks as `context`. + * If omitted, `context` will be an empty object. + */ + getInitialContext?: () => TCtx; + /** + * Called when the tag encounters a string. + * (a string is whatever's not inside "${}" in your template literal) + * `str` is the value of the current string + */ + onString?: (str: string, context: TCtx) => string; + /** + * Called when the tag encounters a substitution. + * (a substitution is whatever's inside "${}" in your template literal) + * `substitution` is the value of the current substitution + * `resultSoFar` is the end result up to the point of this substitution + */ + onSubstitution?: (substitution: string, resultSoFar: string, context: TCtx) => string; + /** + * Called when all substitutions have been parsed + * `endResult` is the final value. + */ + onEndResult?: (endResult: string, context: TCtx) => string; +} + +export type PluginFunction = (oldValue: string, newValue: string) => TemplateTransformer; + +/** + * New Tag factory + */ +export function createTag(transformers?: Array>): TemplateTag; +export function createTag(...transformers: Array>): TemplateTag; +export function createTag(...pluginFunctions: PluginFunction[]): TemplateTag; + +export const TemplateTag: { + /** + * New Tag Constructor + * @deprecated + */ + new (transformers?: Array>): TemplateTag; + new (...transformers: Array>): TemplateTag; + new (...pluginFunctions: PluginFunction[]): TemplateTag; +}; + +/** + * TemplateTag transformer that trims whitespace on the end result of a tagged template + * @param [side=''] The side of the string to trim. Can be 'start' or 'end' (alternatively 'left' or 'right') + * @return a TemplateTag transformer + */ +export function trimResultTransformer( + side?: 'start' | 'end' | 'left' | 'right' | '' +): TemplateTransformer; + +/** + * strips indentation from a template literal + * @param [type='initial'] whether to remove all indentation or just leading indentation. can be 'all' or 'initial' + * @return a TemplateTag transformer + */ +export function stripIndentTransformer(type?: 'initial' | 'all'): TemplateTransformer; + +/** + * Replaces a value or pattern in the end result with a new value. + * @param replaceWhat the value or pattern that should be replaced + * @param replaceWith the replacement value + * @return a TemplateTag transformer + */ +export function replaceResultTransformer( + replaceWhat: string | RegExp, + replaceWith: string | ((substring: string, ...args: any[]) => string) +): TemplateTransformer; + +/** + * Replaces the result of all substitutions (results of calling ${ ... }) with a new value. + * Same as for `replaceResultTransformer`, replaceWhat can be a string or regular expression and replaceWith is the new value. + */ +export function replaceSubstitutionTransformer( + replaceWhat: string | RegExp, + replaceWith: string | ((substring: string, ...args: any[]) => string) +): TemplateTransformer; + +/** + * Replaces the result of all strings (what's not in ${ ... }) with a new value. + * Same as for `replaceResultTransformer`, replaceWhat can be a string or regular expression and replaceWith is the new value. + */ +export function replaceStringTransformer( + replaceWhat: string | RegExp, + replaceWith: string | ((substring: string, ...args: any[]) => string) +): TemplateTransformer; + +/** + * Converts an array substitution to a string containing a list + * @param [opts.separator=''] what to separate each item with (always followed by a space) + * @param [opts.conjunction=''] replace the last separator with this value + * @param [opts.serial=false] should the separator be included before the conjunction? As in the case of serial/oxford commas + * @return a TemplateTag transformer + */ +export function inlineArrayTransformer(opts?: { + separator?: string; + conjunction?: string; + serial?: boolean; +}): TemplateTransformer; + +/** + * Splits a string substitution into an array by the provided splitBy substring, only if the string contains the splitBy substring. + */ +export function splitStringTransformer(splitBy: string): TemplateTransformer; diff --git a/types/common-tags/tslint.json b/types/common-tags/tslint.json index a41bf5d19a..f93cf8562a 100644 --- a/types/common-tags/tslint.json +++ b/types/common-tags/tslint.json @@ -1,79 +1,3 @@ { - "extends": "dtslint/dt.json", - "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false - } + "extends": "dtslint/dt.json" } diff --git a/types/compression-webpack-plugin/compression-webpack-plugin-tests.ts b/types/compression-webpack-plugin/compression-webpack-plugin-tests.ts index 423ca4cea7..a679b7f599 100644 --- a/types/compression-webpack-plugin/compression-webpack-plugin-tests.ts +++ b/types/compression-webpack-plugin/compression-webpack-plugin-tests.ts @@ -1,15 +1,76 @@ import { Configuration } from 'webpack'; import CompressionPlugin = require('compression-webpack-plugin'); -const c: Configuration = { +new CompressionPlugin(); + +new CompressionPlugin({ + include: ["a"] as ReadonlyArray, + exclude: [/a/g] as ReadonlyArray, + test: "a", +}); + +const config: Configuration = { plugins: [ new CompressionPlugin({ - asset: "[path].gz[query]", algorithm: "gzip", cache: true, + filename: "[path].gz[query]", + minRatio: 0.8, test: /\.js$|\.html$/, threshold: 10240, - minRatio: 0.8 + deleteOriginalAssets: true + }) + ] +}; + +const configDefaultAlgo = new CompressionPlugin({ + compressionOptions: { level: 7 } +}); + +// $ExpectError +new CompressionPlugin({ asset: "[path].gz[query]" }); + +const zlib: Configuration = { + plugins: [ + new CompressionPlugin({ + algorithm: "deflate", + compressionOptions: { + flush: 5, + windowBits: 20, + level: 7 + } + }) + ] +}; + +const badZlib: Configuration = { + plugins: [ + // $ExpectError + new CompressionPlugin({ + algorithm: "deflate", + compressionOptions: 5 + }) + ] +}; + +function customAlgorithm(input: string, options: number, callback: (err: Error, result: Buffer) => void) { +} + +const custom: Configuration = { + plugins: [ + new CompressionPlugin({ + algorithm: customAlgorithm, + compressionOptions: 5 + }) + ] +}; + +const badCustom: Configuration = { + plugins: [ + // $ExpectError + new CompressionPlugin({ + algorithm: customAlgorithm, + compressionOptions: { flush: 5 } }) ] }; diff --git a/types/compression-webpack-plugin/index.d.ts b/types/compression-webpack-plugin/index.d.ts index a7b38383ef..5d72f1fca8 100644 --- a/types/compression-webpack-plugin/index.d.ts +++ b/types/compression-webpack-plugin/index.d.ts @@ -1,42 +1,47 @@ -// Type definitions for compression-webpack-plugin 0.4 +// Type definitions for compression-webpack-plugin 2.0 // Project: https://github.com/webpack-contrib/compression-webpack-plugin // Definitions by: Anton Kandybo +// Rhys van der Waerden // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.4 import { Plugin } from 'webpack'; +import { ZlibOptions as ZlibCompressionOptions } from 'zlib'; export = CompressionPlugin; -declare class CompressionPlugin extends Plugin { - constructor(options?: CompressionPlugin.Options); +declare class CompressionPlugin extends Plugin { + constructor(options?: CompressionPlugin.Options); } declare namespace CompressionPlugin { - interface Options { - asset?: string; - algorithm?: string; + type AlgorithmCallback = (error: Error | null, result: Buffer) => void; + type Algorithm = (source: string, options: O, callback: AlgorithmCallback) => void; + + // NOTE: These are the async compression algorithms on the zlib object. + type ZlibAlgorithm = 'deflate' | 'deflateRaw' | 'gzip'; + type Pattern = string | RegExp | ReadonlyArray | ReadonlyArray; + + interface BaseOptions { cache?: boolean | string; - test?: RegExp | RegExp[]; - regExp?: RegExp | RegExp[]; - threshold?: number; + deleteOriginalAssets?: boolean; + exclude?: Pattern; + filename?: string; + include?: Pattern; minRatio?: number; - - // zopfli options - verbose?: boolean; - verbose_more?: boolean; - numiterations?: number; - blocksplitting?: boolean; - blocksplittinglast?: boolean; - blocksplittingmax?: number; - - // zlib options - level?: number; - flush?: number; - chunkSize?: number; - windowBits?: number; - memLevel?: number; - strategy?: number; - dictionary?: any; + test?: Pattern; + threshold?: number; } + + interface ZlibOptions extends BaseOptions { + algorithm?: ZlibAlgorithm; + compressionOptions?: ZlibCompressionOptions; + } + + interface CustomOptions extends BaseOptions { + algorithm: Algorithm; + compressionOptions?: O; + } + + type Options = ZlibOptions | CustomOptions; } diff --git a/types/conf/conf-tests.ts b/types/conf/conf-tests.ts index 1da0e4de2d..ce67cd4799 100644 --- a/types/conf/conf-tests.ts +++ b/types/conf/conf-tests.ts @@ -4,18 +4,24 @@ const conf = new Conf(); new Conf({ defaults: { foo: 'bar', - unicorn: 'rainbow' + unicorn: 'rainbow', }, - configName: '', - projectName: 'foo', - cwd: '' }); +new Conf({ configName: '' }); +new Conf({ projectName: 'foo' }); +new Conf({ cwd: '' }); +new Conf({ encryptionKey: '' }); +new Conf({ encryptionKey: new Buffer('') }); +new Conf({ encryptionKey: new Uint8Array([1]) }); +new Conf({ encryptionKey: new DataView(new ArrayBuffer(2)) }); +new Conf({ fileExtension: '.foo' }); + // $ExpectError new Conf({ defaults: { foo: 'bar', - unicorn: ['rainbow'] - } + unicorn: ['rainbow'], + }, }); conf.set('foo', 'bar'); conf.set('hello', 1); @@ -28,10 +34,17 @@ conf.get('foo', null); // $ExpectError conf.delete('foo'); conf.has('foo'); // $ExpectType boolean conf.clear(); +conf.onDidChange('foo', (oldVal, newVal) => { + // $ExpectType string | number | boolean | undefined + oldVal; + // $ExpectType string | number | boolean | undefined + newVal; +}); +conf.size; // $ExpectType number conf.store = { foo: 'bar', - unicorn: 'rainbow' + unicorn: 'rainbow', }; conf.path; // $ExpectType string diff --git a/types/conf/index.d.ts b/types/conf/index.d.ts index e58dc3ede7..57d7285a3e 100644 --- a/types/conf/index.d.ts +++ b/types/conf/index.d.ts @@ -1,31 +1,37 @@ -// Type definitions for conf 1.4 +// Type definitions for conf 2.1 // Project: https://github.com/sindresorhus/conf // Definitions by: Sam Verschueren // BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -interface Options { - defaults?: {[key: string]: T}; - configName?: string; - projectName?: string; - cwd?: string; -} +/// declare class Conf implements Iterable<[string, T]> { - store: {[key: string]: T}; + store: { [key: string]: T }; readonly path: string; - readonly size: number; + readonly size: number; - constructor(options?: Options); - get(key: string, defaultValue?: T): T; - set(key: string, val: T): void; - set(object: {[key: string]: T}): void; - has(key: string): boolean; - delete(key: string): void; - clear(): void; - onDidChange(key: string, callback: (oldVal: any, newVal: any) => void): void; - [Symbol.iterator](): Iterator<[string, T]>; + constructor(options?: Conf.Options); + get(key: string, defaultValue?: T): T; + set(key: string, val: T): void; + set(object: { [key: string]: T }): void; + has(key: string): boolean; + delete(key: string): void; + clear(): void; + onDidChange(key: string, callback: (oldVal: T | undefined, newVal: T | undefined) => void): void; + [Symbol.iterator](): Iterator<[string, T]>; +} + +declare namespace Conf { + interface Options { + defaults?: { [key: string]: T }; + configName?: string; + projectName?: string; + cwd?: string; + encryptionKey?: string | Buffer | NodeJS.TypedArray | DataView; + fileExtension?: string; + } } export = Conf; diff --git a/types/conf/tsconfig.json b/types/conf/tsconfig.json index 84d6bf7657..479fa6b41f 100644 --- a/types/conf/tsconfig.json +++ b/types/conf/tsconfig.json @@ -21,4 +21,4 @@ "index.d.ts", "conf-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/conf/v1/conf-tests.ts b/types/conf/v1/conf-tests.ts new file mode 100644 index 0000000000..4ee492da8d --- /dev/null +++ b/types/conf/v1/conf-tests.ts @@ -0,0 +1,41 @@ +import Conf = require('conf'); + +const conf = new Conf(); +new Conf({ + defaults: { + foo: 'bar', + unicorn: 'rainbow', + }, + configName: '', + projectName: 'foo', + cwd: '', +}); +// $ExpectError +new Conf({ + defaults: { + foo: 'bar', + unicorn: ['rainbow'], + }, +}); +conf.set('foo', 'bar'); +conf.set('hello', 1); +conf.set('unicorn', false); +conf.set('null', null); // $ExpectError + +conf.get('foo'); // $ExpectType string | number | boolean +conf.get('foo', 'bar'); // $ExpectType string | number | boolean +conf.get('foo', null); // $ExpectError +conf.delete('foo'); +conf.has('foo'); // $ExpectType boolean +conf.clear(); + +conf.store = { + foo: 'bar', + unicorn: 'rainbow', +}; +conf.path; // $ExpectType string + +for (const [key, value] of conf) { + key; // $ExpectType string + value; // $ExpectType string | number | boolean +} diff --git a/types/conf/v1/index.d.ts b/types/conf/v1/index.d.ts new file mode 100644 index 0000000000..f08cff1584 --- /dev/null +++ b/types/conf/v1/index.d.ts @@ -0,0 +1,31 @@ +// Type definitions for conf 1.4 +// Project: https://github.com/sindresorhus/conf +// Definitions by: Sam Verschueren +// BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +interface Options { + defaults?: { [key: string]: T }; + configName?: string; + projectName?: string; + cwd?: string; +} + +declare class Conf implements Iterable<[string, T]> { + store: { [key: string]: T }; + readonly path: string; + readonly size: number; + + constructor(options?: Options); + get(key: string, defaultValue?: T): T; + set(key: string, val: T): void; + set(object: { [key: string]: T }): void; + has(key: string): boolean; + delete(key: string): void; + clear(): void; + onDidChange(key: string, callback: (oldVal: any, newVal: any) => void): void; + [Symbol.iterator](): Iterator<[string, T]>; +} + +export = Conf; diff --git a/types/conf/v1/tsconfig.json b/types/conf/v1/tsconfig.json new file mode 100644 index 0000000000..86b3a62f41 --- /dev/null +++ b/types/conf/v1/tsconfig.json @@ -0,0 +1,29 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "target": "es6", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "paths": { + "conf": [ + "conf/v1" + ] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "conf-tests.ts" + ] +} diff --git a/types/conf/v1/tslint.json b/types/conf/v1/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/conf/v1/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/configstore/configstore-tests.ts b/types/configstore/configstore-tests.ts index ffd04e31a7..9365afdbda 100644 --- a/types/configstore/configstore-tests.ts +++ b/types/configstore/configstore-tests.ts @@ -5,6 +5,7 @@ let value: any; let key: string; let num: number; let object: any; +let path: string; cs.set(key, value); value = cs.get(key); @@ -13,4 +14,12 @@ cs.delete(key); object = cs.all; cs.all = object; num = cs.size; -key = cs.path; +path = cs.path; + +const csWithPathOption = new Configstore('foo', null, { configPath: path }); + +csWithPathOption.set(key, value); +value = csWithPathOption.get(key); +csWithPathOption.delete(key); + +key = csWithPathOption.path; diff --git a/types/configstore/index.d.ts b/types/configstore/index.d.ts index 2617f2bce0..bbc0740c23 100644 --- a/types/configstore/index.d.ts +++ b/types/configstore/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for configstore 2.1 +// Type definitions for configstore 4.0 // Project: https://github.com/yeoman/configstore // Definitions by: ArcticLight // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -67,5 +67,6 @@ declare class Configstore { declare namespace Configstore { interface ConfigstoreOptions { globalConfigPath?: boolean; + configPath?: string; } } diff --git a/types/connect-mongo/index.d.ts b/types/connect-mongo/index.d.ts index ea39a13f42..7173cb50dc 100644 --- a/types/connect-mongo/index.d.ts +++ b/types/connect-mongo/index.d.ts @@ -110,6 +110,7 @@ declare namespace connectMongo { length: (callback: (err: any, length: number) => void) => void; clear: (callback?: (err?: any) => void) => void; touch: (sid: string, session: Express.SessionData, callback?: (err: any) => void) => void; + close: () => void; } } diff --git a/types/convict/index.d.ts b/types/convict/index.d.ts index 2c3dbf0547..fd605f5077 100644 --- a/types/convict/index.d.ts +++ b/types/convict/index.d.ts @@ -37,6 +37,24 @@ declare namespace convict { parse: (content: string) => any; } + type PredefinedFormat = + | '*' + | 'int' + | 'port' + | 'windows_named_pipe' + | 'port_or_windows_named_pipe' + | 'url' + | 'email' + | 'ipaddress' + | 'duration' + | 'timestamp' + | 'nat' + | String + | Object + | Number + | RegExp + | Boolean; + interface SchemaObj { default: T; doc?: string; @@ -52,7 +70,7 @@ declare namespace convict { * If omitted, format will be set to the value of Object.prototype.toString.call * for the default value */ - format?: string | any[] | ((val: any) => void); + format?: PredefinedFormat | any[] | ((val: any) => void); env?: string; arg?: string; sensitive?: boolean; diff --git a/types/create-hash/create-hash-tests.ts b/types/create-hash/create-hash-tests.ts new file mode 100644 index 0000000000..d039a5a704 --- /dev/null +++ b/types/create-hash/create-hash-tests.ts @@ -0,0 +1,9 @@ +import createHash = require('create-hash'); + +const hash = createHash('sha224'); + +hash.update('synchronous write'); +hash.digest(); +hash.write('write to it as a stream'); +hash.end(); +hash.read(); diff --git a/types/create-hash/index.d.ts b/types/create-hash/index.d.ts new file mode 100644 index 0000000000..712be2520f --- /dev/null +++ b/types/create-hash/index.d.ts @@ -0,0 +1,26 @@ +// Type definitions for create-hash 1.2 +// Project: https://github.com/crypto-browserify/createHash +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +/// + +import { Hash } from 'crypto'; + +export = createHash; + +declare function createHash(algo: createHash.Algorithm): Hash; + +declare namespace createHash { + type Algorithm = + | 'md5' + | 'rmd160' + | 'ripemd160' + | 'sha' + | 'sha1' + | 'sha224' + | 'sha256' + | 'sha384' + | 'sha512'; +} diff --git a/types/create-hash/tsconfig.json b/types/create-hash/tsconfig.json new file mode 100644 index 0000000000..83e50b425c --- /dev/null +++ b/types/create-hash/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "create-hash-tests.ts" + ] +} diff --git a/types/create-hash/tslint.json b/types/create-hash/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/create-hash/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/create-hmac/create-hmac-tests.ts b/types/create-hmac/create-hmac-tests.ts new file mode 100644 index 0000000000..f233a0390a --- /dev/null +++ b/types/create-hmac/create-hmac-tests.ts @@ -0,0 +1,9 @@ +import createHmac = require('create-hmac'); + +const hmac = createHmac('sha224', Buffer.from('secret key')); + +hmac.update('synchronous write'); +hmac.digest(); +hmac.write('write to it as a stream'); +hmac.end(); +hmac.read(); diff --git a/types/create-hmac/index.d.ts b/types/create-hmac/index.d.ts new file mode 100644 index 0000000000..3d6bcfeafa --- /dev/null +++ b/types/create-hmac/index.d.ts @@ -0,0 +1,26 @@ +// Type definitions for create-hmac 1.1 +// Project: https://github.com/crypto-browserify/createHmac +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +/// + +import { Hmac } from 'crypto'; + +export = createHmac; + +declare function createHmac(algo: createHmac.Algorithm, key: string | Buffer): Hmac; + +declare namespace createHmac { + type Algorithm = + | 'rmd160' + | 'ripemd160' + | 'md5' + | 'sha' + | 'sha1' + | 'sha224' + | 'sha256' + | 'sha384' + | 'sha512'; +} diff --git a/types/create-hmac/tsconfig.json b/types/create-hmac/tsconfig.json new file mode 100644 index 0000000000..badd99da29 --- /dev/null +++ b/types/create-hmac/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "create-hmac-tests.ts" + ] +} diff --git a/types/create-hmac/tslint.json b/types/create-hmac/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/create-hmac/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/cropperjs/index.d.ts b/types/cropperjs/index.d.ts index 30556e11fc..d444c20705 100644 --- a/types/cropperjs/index.d.ts +++ b/types/cropperjs/index.d.ts @@ -426,8 +426,9 @@ declare class cropperjs { /** * Replace the image's src and rebuild the cropper. * @param url A new image url + * @param hasSameSize If the new image has the same size with the old one, then it will not rebuilt the cropper and only update the urls of all related images. (Default: false) */ - replace(url: string): void; + replace(url: string, hasSameSize?: boolean): void; /** * Enable (unfreeze) the cropper. diff --git a/types/crumb/crumb-tests.ts b/types/crumb/crumb-tests.ts new file mode 100644 index 0000000000..90612a3e4a --- /dev/null +++ b/types/crumb/crumb-tests.ts @@ -0,0 +1,47 @@ +import * as hapi from 'hapi'; +import * as crumb from 'crumb'; + +const server = new hapi.Server({ port: 8000 }); + +server.register({ + plugin: crumb, + options: { + key: 'csrf-token', + size: 50, + autoGenerate: true, + addToViewContext: true, + cookieOptions: { + path: '/', + }, + headerName: 'X-CSRF-Token', + restful: true, + skip: () => false, + enforce: true, + logUnauthorized: false, + } +}); + +server.route({ + method: 'get', + path: '/', + handler: async (_, h) => { + return h.continue; + }, +}); + +server.route({ + method: 'get', + path: '/custom', + options: { + plugins: { + crumb: { + key: 'x-csrf-token', + source: 'query', + restful: true, + }, + }, + }, + handler: async (_, h) => { + return h.continue; + }, +}); diff --git a/types/crumb/index.d.ts b/types/crumb/index.d.ts new file mode 100644 index 0000000000..16311c99bf --- /dev/null +++ b/types/crumb/index.d.ts @@ -0,0 +1,114 @@ +// Type definitions for crumb 7.2 +// Project: https://github.com/hapijs/crumb +// Definitions by: Silas Rech +// Simon Schick +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import { Request, Plugin, ResponseToolkit, ServerStateCookieOptions } from 'hapi'; + +declare module 'hapi' { + interface PluginSpecificConfiguration { + crumb?: boolean | { + /** + * The name of the cookie to store the CSRF crumb into. + */ + key?: string; + + /** + * Specifies how the crumb will be sent in requests. + * + * @default 'payload' + */ + source?: 'payload' | 'query'; + + /** + * Override for the server's 'restful' setting + */ + restful?: boolean; + }; + } +} + +declare namespace crumb { + type SkipFunction = (request?: Request, h?: ResponseToolkit) => boolean; + + interface RegisterOptions { + /** + * The name of the cookie to store the CSRF crumb into. + * + * @default 'crumb' + */ + key?: string; + + /** + * The length of the crumb to generate. + * See {@link https://github.com/hapijs/cryptiles cryptiles} for more information. + * + * @default 43 + */ + size?: number; + + /** + * Whether to automatically generate a new crumb for requests. + * + * @default true + */ + autoGenerate?: boolean; + + /** + * Whether to automatically add the crumb to view contexts as the given key. + * + * @default true + */ + addToViewContext?: boolean; + + /** + * Storage options for the cookie containing the crumb + * + * @default { path: '/' } + */ + cookieOptions?: ServerStateCookieOptions; + + /** + * Specify the name of the custom CSRF header. + * + * @default 'X-CSRF-Token' + */ + headerName?: string; + + /** + * RESTful mode that validates crumb tokens from 'X-CSRF-Token' request header for POST, PUT, PATCH and DELETE server routes. + * Disables payload/query crumb validation. + * + * @default false + */ + restful?: boolean; + + /** + * A function which when provided, is called for every request. + * If the provided function returns true, validation and generation of crumb is skipped. + * + * @default false + */ + skip?: boolean | SkipFunction; + + /** + * Using enforce with false will set the CSRF header cookie but won't execute the validation. + * + * @default true + */ + enforce?: boolean; + + /** + * Whether to add to the request log with tag 'crumb' and data 'validation failed'. + * + * @default false + */ + logUnauthorized?: boolean; + } +} + +declare const crumb: Plugin; + +export = crumb; diff --git a/types/crumb/tsconfig.json b/types/crumb/tsconfig.json new file mode 100644 index 0000000000..5beceb6a88 --- /dev/null +++ b/types/crumb/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "crumb-tests.ts" + ] +} diff --git a/types/crumb/tslint.json b/types/crumb/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/crumb/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/crypto-hash/crypto-hash-tests.ts b/types/crypto-hash/crypto-hash-tests.ts new file mode 100644 index 0000000000..73e62ad1c6 --- /dev/null +++ b/types/crypto-hash/crypto-hash-tests.ts @@ -0,0 +1,29 @@ +import { sha1, sha256, sha384, sha512 } from 'crypto-hash'; + +// $ExpectType Promise +sha1('🦄'); +// $ExpectType Promise +sha1('🦄', { outputFormat: 'buffer' }); +// $ExpectType Promise +sha1('🦄', { outputFormat: 'hex' }); + +// $ExpectType Promise +sha256('🦄'); +// $ExpectType Promise +sha256('🦄', { outputFormat: 'buffer' }); +// $ExpectType Promise +sha256('🦄', { outputFormat: 'hex' }); + +// $ExpectType Promise +sha384('🦄'); +// $ExpectType Promise +sha384('🦄', { outputFormat: 'buffer' }); +// $ExpectType Promise +sha384('🦄', { outputFormat: 'hex' }); + +// $ExpectType Promise +sha512('🦄'); +// $ExpectType Promise +sha512('🦄', { outputFormat: 'buffer' }); +// $ExpectType Promise +sha512('🦄', { outputFormat: 'hex' }); diff --git a/types/crypto-hash/index.d.ts b/types/crypto-hash/index.d.ts new file mode 100644 index 0000000000..c22864b2ae --- /dev/null +++ b/types/crypto-hash/index.d.ts @@ -0,0 +1,48 @@ +// Type definitions for crypto-hash 1.0 +// Project: https://github.com/sindresorhus/crypto-hash#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export function sha1( + buffer: string | ArrayBuffer | ArrayBufferView, + options?: OptionsHexOutput +): Promise; +export function sha1( + buffer: string | ArrayBuffer | ArrayBufferView, + options: OptionBufferOutput +): Promise; + +export function sha256( + buffer: string | ArrayBuffer | ArrayBufferView, + options?: OptionsHexOutput +): Promise; +export function sha256( + buffer: string | ArrayBuffer | ArrayBufferView, + options: OptionBufferOutput +): Promise; + +export function sha384( + buffer: string | ArrayBuffer | ArrayBufferView, + options?: OptionsHexOutput +): Promise; +export function sha384( + buffer: string | ArrayBuffer | ArrayBufferView, + options: OptionBufferOutput +): Promise; + +export function sha512( + buffer: string | ArrayBuffer | ArrayBufferView, + options?: OptionsHexOutput +): Promise; +export function sha512( + buffer: string | ArrayBuffer | ArrayBufferView, + options: OptionBufferOutput +): Promise; + +export interface OptionsHexOutput { + outputFormat?: 'hex'; +} + +export interface OptionBufferOutput { + outputFormat: 'buffer'; +} diff --git a/types/crypto-hash/tsconfig.json b/types/crypto-hash/tsconfig.json new file mode 100644 index 0000000000..410ee34985 --- /dev/null +++ b/types/crypto-hash/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "crypto-hash-tests.ts" + ] +} diff --git a/types/crypto-hash/tslint.json b/types/crypto-hash/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/crypto-hash/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/cryptr/cryptr-tests.ts b/types/cryptr/cryptr-tests.ts new file mode 100644 index 0000000000..3c655d7288 --- /dev/null +++ b/types/cryptr/cryptr-tests.ts @@ -0,0 +1,10 @@ +import Cryptr = require('cryptr'); + +// $ExpectType Cryptr +const cryptr = new Cryptr('myTotallySecretKey'); + +// $ExpectType string +const encrypted_string = cryptr.encrypt('bacon'); + +// $ExpectType string +cryptr.decrypt(encrypted_string); diff --git a/types/cryptr/index.d.ts b/types/cryptr/index.d.ts new file mode 100644 index 0000000000..4aec15c419 --- /dev/null +++ b/types/cryptr/index.d.ts @@ -0,0 +1,20 @@ +// Type definitions for cryptr 4.0 +// Project: https://github.com/MauriceButler/cryptr +// Definitions by: Roman Rogowski +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare class Cryptr { + /** + * Cryptr provides a mechanism for aes-256-ctr encryption/decryption. + * @param secret key used for encryption/decryption + */ + constructor(secret: string); + + /** Encrypt a string. */ + encrypt(value: string): string; + + /** Decrypt a string. */ + decrypt(value: string): string; +} + +export = Cryptr; diff --git a/types/cryptr/tsconfig.json b/types/cryptr/tsconfig.json new file mode 100644 index 0000000000..2727c48e08 --- /dev/null +++ b/types/cryptr/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "strictFunctionTypes": true + }, + "files": [ + "index.d.ts", + "cryptr-tests.ts" + ] +} diff --git a/types/cryptr/tslint.json b/types/cryptr/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/cryptr/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/d3-brush/d3-brush-tests.ts b/types/d3-brush/d3-brush-tests.ts index dc2c9a0dc8..c5a287b562 100644 --- a/types/d3-brush/d3-brush-tests.ts +++ b/types/d3-brush/d3-brush-tests.ts @@ -48,7 +48,7 @@ brush = brush.extent(function(d, i, group) { // chainable brush = brush.filter(function(d, i, group) { // Cast d3 event to D3ZoomEvent to be used in filter logic - const e = > event; + const e = event as d3Brush.D3BrushEvent; console.log('Owner SVG Element of svg group: ', this.ownerSVGElement); // this is of type SVGGElement return e.sourceEvent.type !== 'zoom' || !d.filterZoomEvent; // datum type is BrushDatum (as propagated to SVGGElement with brush event attached) diff --git a/types/d3-drag/d3-drag-tests.ts b/types/d3-drag/d3-drag-tests.ts index cf5428e7e2..5e376c003b 100644 --- a/types/d3-drag/d3-drag-tests.ts +++ b/types/d3-drag/d3-drag-tests.ts @@ -134,7 +134,7 @@ touchableFn = circleDrag.touchable(); circleCustomDrag.subject(function(d, i, g) { // Cast event type for completeness, otherwise event is of type any. - const e = > event; + const e = event as d3Drag.D3DragEvent; const that: SVGCircleElement = this; const datum: CircleDatum = d; const index: number = i; @@ -163,14 +163,14 @@ subjectAccessor = circleCustomDrag.subject(); function dragstarted(this: SVGCircleElement, d: CircleDatum) { // cast d3 event to drag event. Otherwise, d3 event is currently defined as type 'any' - const e = > event; + const e = event as d3Drag.D3DragEvent; e.sourceEvent.stopPropagation(); select(this).classed('dragging', true); } function dragged(this: SVGCircleElement, d: CircleDatum) { // cast d3 event to drag event. Otherwise, d3 event is currently defined as type 'any' - const e = > event; + const e = event as d3Drag.D3DragEvent; select(this).attr('cx', d.x = e.x).attr('cy', d.y = e.y); } diff --git a/types/d3-hierarchy/d3-hierarchy-tests.ts b/types/d3-hierarchy/d3-hierarchy-tests.ts index 16b372993d..b5982a4d5f 100644 --- a/types/d3-hierarchy/d3-hierarchy-tests.ts +++ b/types/d3-hierarchy/d3-hierarchy-tests.ts @@ -12,6 +12,7 @@ import * as d3Hierarchy from 'd3-hierarchy'; // Preparatory Steps // ----------------------------------------------------------------------- +let str: string; let num: number; let numOrUndefined: number | undefined; let size: [number, number]; @@ -825,22 +826,34 @@ copiedPackNode = packRootNode.copy(); // Pack Siblings and Enclosure // ----------------------------------------------------------------------- -interface CircleData extends d3Hierarchy.PackCircle { - v: string; -} - -let circles: CircleData[] = [ +const radius = [ { r: 10, v: 'a' }, - { r: 1, v: 'b' }, + { r: 30, v: 'b' }, { r: 20, v: 'c' } ]; // packSiblings -circles = d3Hierarchy.packSiblings(circles); +const circles = d3Hierarchy.packSiblings(radius); +str = circles[0].v; +num = circles[0].r; +num = circles[0].x; +num = circles[0].y; // packEnclose -let enclosure: { r: number, x: number, y: number }; +const moreCircles = [ + { r: 10, v: 'a', x: 0, y: 10 }, + { r: 30, v: 'b', x: 5, y: 15 }, + { r: 20, v: 'c', x: 7, y: 30 } +]; -enclosure = d3Hierarchy.packEnclose(circles); +const circle = d3Hierarchy.packEnclose(moreCircles); +num = circle.r; +num = circle.x; +num = circle.y; +// $ExpectError +str = circle.v; // fails, property 'v' does not exist + +// $ExpectError +d3Hierarchy.packEnclose(radius); diff --git a/types/d3-hierarchy/index.d.ts b/types/d3-hierarchy/index.d.ts index 0ec823cc78..fb5ebd5656 100644 --- a/types/d3-hierarchy/index.d.ts +++ b/types/d3-hierarchy/index.d.ts @@ -802,7 +802,7 @@ export function pack(): PackLayout; // Pack Siblings and Enclosure // ----------------------------------------------------------------------- -export interface PackCircle { +export interface PackRadius { /** * The radius of the circle. */ @@ -819,10 +819,25 @@ export interface PackCircle { y?: number; } +export interface PackCircle { + /** + * The radius of the circle. + */ + r: number; + + /** + * The x-coordinate of the circle’s center. + */ + x: number; + + /** + * The y-coordinate of the circle’s center. + */ + y: number; +} + // TODO: Since packSiblings manipulates the circles array in place, technically the x and y properties // are optional on invocation, but will be created after execution for each entry. -// For invocation of packEnclose the x and y coordinates are mandatory. It seems easier to just comment -// on the mandatory nature, then to create separate interfaces and having to deal with recasting. /** * Packs the specified array of circles, each of which must have a `circle.r` property specifying the circle’s radius. @@ -830,7 +845,7 @@ export interface PackCircle { * * @param circles The specified array of circles to pack. */ -export function packSiblings(circles: Datum[]): Datum[]; +export function packSiblings(circles: Datum[]): Array; /** * Computes the smallest circle that encloses the specified array of circles, each of which must have @@ -839,4 +854,4 @@ export function packSiblings(circles: Datum[]): Datum[ * * @param circles The specified array of circles to pack. */ -export function packEnclose(circles: Datum[]): { r: number, x: number, y: number }; +export function packEnclose(circles: Datum[]): PackCircle; diff --git a/types/d3-selection/d3-selection-tests.ts b/types/d3-selection/d3-selection-tests.ts index bafc1aeb11..092e8bfa5a 100644 --- a/types/d3-selection/d3-selection-tests.ts +++ b/types/d3-selection/d3-selection-tests.ts @@ -1060,7 +1060,7 @@ interface SuccessEvent { const successEvent = { type: 'wonEuro2016', team: 'Island' }; function customListener(this: HTMLBodyElement | null, finalOpponent: string): string { - const e = d3Selection.event; + const e = d3Selection.event as SuccessEvent; return `${e.team} defeated ${finalOpponent} in the EURO 2016 Cup. Who would have thought!!!`; } diff --git a/types/d3-selection/tslint.json b/types/d3-selection/tslint.json index c89636b4b7..26ee29cf50 100644 --- a/types/d3-selection/tslint.json +++ b/types/d3-selection/tslint.json @@ -2,7 +2,6 @@ "extends": "dtslint/dt.json", "rules": { // TODO - "no-angle-bracket-type-assertion": false, "no-this-assignment": false, "unified-signatures": false, "no-unnecessary-generics": false diff --git a/types/d3-shape/index.d.ts b/types/d3-shape/index.d.ts index eccf7f1b80..0c0e27cbd7 100644 --- a/types/d3-shape/index.d.ts +++ b/types/d3-shape/index.d.ts @@ -38,7 +38,7 @@ export interface CanvasPath_D3Shape { // ----------------------------------------------------------------------------------- /** - * Interface corresponding to the minimum data type assumed by the accessor functions of the Arc generator + * Interface corresponding to the minimum data type assumed by the accessor functions of the Arc generator */ export interface DefaultArcObject { /** @@ -994,14 +994,17 @@ export function lineRadial(): LineRadial<[number, number]>; */ export function lineRadial(): LineRadial; +/** + * @deprecated Use LineRadial + */ export type RadialLine = LineRadial; /** - * DEPRECATED: Use lineRadial() + * @deprecated Use lineRadial() */ export function radialLine(): RadialLine<[number, number]>; /** - * DEPRECATED: Use lineRadial() + * @deprecated Use lineRadial() */ export function radialLine(): RadialLine; @@ -1620,16 +1623,16 @@ export function areaRadial(): AreaRadial<[number, number]>; export function areaRadial(): AreaRadial; /** - * DEPRECATED: Use AreaRadial interface + * @deprecated Use AreaRadial interface */ export type RadialArea = AreaRadial; /** - * DEPRECATED: Use areaRadial() + * @deprecated Use areaRadial() */ export function radialArea(): RadialArea<[number, number]>; /** - * DEPRECATED: Use areaRadial() + * @deprecated Use areaRadial() */ export function radialArea(): RadialArea; @@ -2239,7 +2242,7 @@ export interface LinkRadial { } /** - * DEPRECATED: Use LinkRadial interface + * @deprecated Use LinkRadial interface */ export type RadialLink = LinkRadial; diff --git a/types/d3-zoom/d3-zoom-tests.ts b/types/d3-zoom/d3-zoom-tests.ts index 19a16930d6..42393b9e82 100644 --- a/types/d3-zoom/d3-zoom-tests.ts +++ b/types/d3-zoom/d3-zoom-tests.ts @@ -9,7 +9,7 @@ import * as d3Zoom from 'd3-zoom'; import { ArrayLike, select, Selection, event } from 'd3-selection'; import { Transition } from 'd3-transition'; -import { scaleLinear, ScaleLinear } from 'd3-scale'; +import { scaleLinear, ScaleLinear, ScaleTime, scaleTime } from 'd3-scale'; import { interpolateZoom, interpolate, interpolateArray, ZoomInterpolator, ZoomView } from 'd3-interpolate'; // -------------------------------------------------------------------------- @@ -91,7 +91,7 @@ interface GroupDatum { function zoomedCanvas(this: HTMLCanvasElement, d: CanvasDatum) { // Cast d3 event to D3ZoomEvent to be used in zoom event handler - const e = > event; + const e = event as d3Zoom.D3ZoomEvent; if (context) { context.save(); context.clearRect(0, 0, this.width, this.height); // this element @@ -112,7 +112,7 @@ canvasZoom = d3Zoom.zoom() function zoomedSVGOverlay(this: SVGRectElement) { // Cast d3 event to D3ZoomEvent to be used in zoom event handler - const e = > event; + const e = event as d3Zoom.D3ZoomEvent; g.attr('transform', e.transform.toString()); } @@ -146,7 +146,7 @@ constraintFn = svgZoom.constrain(); // chainable svgZoom = svgZoom.filter(function(d, i, group) { // Cast d3 event to D3ZoomEvent to be used in filter logic - const e = > event; + const e = event as d3Zoom.D3ZoomEvent; console.log('Overlay Rectangle width: ', this.width.baseVal.value); // this typing is SVGRectElement return e.sourceEvent.type !== 'brush' || !d.filterBrushEvent; // datum type is SVGDatum (as propagated to SVGRectElement with zoom event attached) @@ -178,7 +178,7 @@ touchableFn = svgZoom.touchable(); // chainable svgZoom = svgZoom.wheelDelta(function(d, i, group) { // Cast d3 event to D3ZoomEvent to be used in filter logic - const e = event; + const e = event as WheelEvent; const that: SVGRectElement = this; const datum: SVGDatum = d; const index: number = i; @@ -248,15 +248,15 @@ let zoomInterpolatorFactory: (a: ZoomView, b: ZoomView) => ZoomInterpolator; // Basic case without casting basicInterpolatorFactory = svgZoom.interpolate(); -// Assuming it is know that a specialized interpolation factory was used. E.g. ZoomInterpolator also has a duration -// argument +// Assuming it is know that a specialized interpolation factory was used. E.g. ZoomInterpolator also has a duration argument zoomInterpolatorFactory = svgZoom.interpolate<(a: ZoomView, b: ZoomView) => ZoomInterpolator>(); // on() -------------------------------------------------------------------- // chainable svgZoom = svgZoom.on('zoom', zoomedSVGOverlay); -// svgZoom = svgZoom.on('zoom', zoomedCanvas); // fails, zoom event handler has wrong this and datum type +// $ExpectError +svgZoom = svgZoom.on('zoom', zoomedCanvas); // fails, zoom event handler has wrong this and datum type let zoomHandler: ((this: SVGRectElement, datum: SVGDatum, index: number, group: SVGRectElement[] | ArrayLike) => void) | undefined; zoomHandler = svgZoom.on('zoom'); @@ -297,7 +297,8 @@ const svgOverlayTransition = svgOverlay.transition(); // use on selection svgZoom.transform(svgOverlay, d3Zoom.zoomIdentity); -// svgZoom.transform(groupsSelection, d3Zoom.zoomIdentity); // fails, as groupSelection mismatches DOM Element type and datum type +// $ExpectError +svgZoom.transform(groupsSelection, d3Zoom.zoomIdentity); // fails, as groupSelection mismatches DOM Element type and datum type svgZoom.transform(svgOverlay, function(datum, index, groups) { const that: SVGRectElement = this; @@ -308,9 +309,11 @@ svgZoom.transform(svgOverlay, function(datum, index, groups) { console.log('Filter Brush Event status as per datum: ', d.filterBrushEvent); // datum type is SVGDatum return d3Zoom.zoomIdentity; }); + // use on transition svgOverlayTransition.call(svgZoom.transform, d3Zoom.zoomIdentity); -// svgZoom.transform(groupsTransition, d3Zoom.zoomIdentity); // fails, as groupTransition mismatches DOM Element type and datum type +// $ExpectError +svgZoom.transform(groupsTransition, d3Zoom.zoomIdentity); // fails, as groupTransition mismatches DOM Element type and datum type svgZoom.transform(svgOverlayTransition, d3Zoom.zoomIdentity); svgZoom.transform(svgOverlayTransition, function(datum, index, groups) { @@ -327,7 +330,8 @@ svgZoom.transform(svgOverlayTransition, function(datum, index, groups) { // use on selection svgZoom.translateBy(svgOverlay, 20, 50); -// svgZoom.translateBy(groupsSelection, 20, 50); // fails, as groupSelection mismatches DOM Element type and datum type +// $ExpectError +svgZoom.translateBy(groupsSelection, 20, 50); // fails, as groupSelection mismatches DOM Element type and datum type svgZoom.translateBy( svgOverlay, @@ -376,7 +380,8 @@ svgZoom.translateBy( // use on transition svgZoom.translateBy(svgOverlayTransition, 20, 50); -// svgZoom.translateBy(groupsTransition, 20, 50); // fails, as groupTransition mismatches DOM Element type and datum type +// $ExpectError +svgZoom.translateBy(groupsTransition, 20, 50); // fails, as groupTransition mismatches DOM Element type and datum type svgZoom.translateBy( svgOverlayTransition, @@ -427,7 +432,8 @@ svgZoom.translateBy( // use on selection svgZoom.translateTo(svgOverlay, 20, 50); -// svgZoom.translateTo(groupsSelection, 20, 50); // fails, as groupSelection mismatches DOM Element type and datum type +// $ExpectError +svgZoom.translateTo(groupsSelection, 20, 50); // fails, as groupSelection mismatches DOM Element type and datum type svgZoom.translateTo( svgOverlay, @@ -476,7 +482,8 @@ svgZoom.translateTo( // use on transition svgZoom.translateTo(svgOverlayTransition, 20, 50); -// svgZoom.translateTo(groupsTransition, 20, 50); // fails, as groupTransition mismatches DOM Element type and datum type +// $ExpectError +svgZoom.translateTo(groupsTransition, 20, 50); // fails, as groupTransition mismatches DOM Element type and datum type svgZoom.translateTo( svgOverlayTransition, @@ -527,7 +534,8 @@ svgZoom.translateTo( // use on selection svgZoom.scaleBy(svgOverlay, 3); -// svgZoom.scaleBy(groupsSelection, 3); // fails, as groupSelection mismatches DOM Element type and datum type +// $ExpectError +svgZoom.scaleBy(groupsSelection, 3); // fails, as groupSelection mismatches DOM Element type and datum type svgZoom.scaleBy(svgOverlay, function(datum, index, groups) { const that: SVGRectElement = this; @@ -540,7 +548,8 @@ svgZoom.scaleBy(svgOverlay, function(datum, index, groups) { }); // use on transition svgZoom.scaleBy(svgOverlayTransition, 3); -// svgZoom.scaleBy(groupsTransition, 3); // fails, as groupTransition mismatches DOM Element type and datum type +// $ExpectError +svgZoom.scaleBy(groupsTransition, 3); // fails, as groupTransition mismatches DOM Element type and datum type svgZoom.scaleBy(svgOverlayTransition, function(datum, index, groups) { const that: SVGRectElement = this; @@ -556,7 +565,8 @@ svgZoom.scaleBy(svgOverlayTransition, function(datum, index, groups) { // use on selection svgZoom.scaleTo(svgOverlay, 3); -// svgZoom.scaleBy(groupsSelection, 3); // fails, as groupSelection mismatches DOM Element type and datum type +// $ExpectError +svgZoom.scaleBy(groupsSelection, 3); // fails, as groupSelection mismatches DOM Element type and datum type svgZoom.scaleTo(svgOverlay, function(datum, index, groups) { const that: SVGRectElement = this; @@ -569,7 +579,8 @@ svgZoom.scaleTo(svgOverlay, function(datum, index, groups) { }); // use on transition svgZoom.scaleTo(svgOverlayTransition, 3); -// svgZoom.scaleBy(groupsTransition, 3); // fails, as groupTransition mismatches DOM Element type and datum type +// $ExpectError +svgZoom.scaleBy(groupsTransition, 3); // fails, as groupTransition mismatches DOM Element type and datum type svgZoom.scaleTo(svgOverlayTransition, function(datum, index, groups) { const that: SVGRectElement = this; @@ -616,15 +627,18 @@ const invertedPoint: [number, number] = zTransform.invert([150, 240]); const invertedX: number = zTransform.invertX(150); const invertedY: number = zTransform.invertY(240); -// TODO: reScaleX, reScaleY - let linearScale: ScaleLinear = scaleLinear(); +let timeScale: ScaleTime = scaleTime(); linearScale = zTransform.rescaleX(linearScale); linearScale = zTransform.rescaleY(linearScale); +timeScale = zTransform.rescaleX(timeScale); +timeScale = zTransform.rescaleY(timeScale); + const transformation: string = zTransform.toString(); +zTransform = zTransform.scale(2); zTransform = zTransform.translate(50, 40); // zoomIdentity ------------------------------------------------------------- diff --git a/types/d3-zoom/index.d.ts b/types/d3-zoom/index.d.ts index 827390b871..3f6100d4b8 100644 --- a/types/d3-zoom/index.d.ts +++ b/types/d3-zoom/index.d.ts @@ -1,6 +1,9 @@ // Type definitions for d3JS d3-zoom module 1.7 // Project: https://github.com/d3/d3-zoom/ -// Definitions by: Tom Wanzek , Alex Ford , Boris Yankov +// Definitions by: Tom Wanzek +// Alex Ford +// Boris Yankov +// denisname // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -26,12 +29,12 @@ export type ZoomedElementBaseType = Element; * that can be passed into zoomTransform methods rescaleX and rescaleY */ export interface ZoomScale { - domain(): number[]; - domain(domain: number[]): this; + domain(): number[] | Date[]; + domain(domain: Array): this; range(): number[]; range(range: number[]): this; copy(): ZoomScale; - invert(value: number): number; + invert(value: number): number | Date; } // -------------------------------------------------------------------------- diff --git a/types/d3-zoom/tslint.json b/types/d3-zoom/tslint.json index c89636b4b7..26ee29cf50 100644 --- a/types/d3-zoom/tslint.json +++ b/types/d3-zoom/tslint.json @@ -2,7 +2,6 @@ "extends": "dtslint/dt.json", "rules": { // TODO - "no-angle-bracket-type-assertion": false, "no-this-assignment": false, "unified-signatures": false, "no-unnecessary-generics": false diff --git a/types/datatables.net/tslint.json b/types/datatables.net/tslint.json index 3db14f85ea..2b6ccb9109 100644 --- a/types/datatables.net/tslint.json +++ b/types/datatables.net/tslint.json @@ -1 +1,6 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + "no-angle-bracket-type-assertion": false + } +} \ No newline at end of file diff --git a/types/db-migrate-base/db-migrate-base-tests.ts b/types/db-migrate-base/db-migrate-base-tests.ts index e9c46f4873..b094be1280 100644 --- a/types/db-migrate-base/db-migrate-base-tests.ts +++ b/types/db-migrate-base/db-migrate-base-tests.ts @@ -318,4 +318,4 @@ db.runSqlAsync('DROP TABLE `pets`').then(onResolve); /// allAsync(sql, [params]) db.allAsync('SELECT * FROM `module_user` WHERE `?` = \'?\'', ['first_name', 'Test']).then(onResolve); -db.allAsync('SELECT * FROM `module_user`').then(onResolve); \ No newline at end of file +db.allAsync('SELECT * FROM `module_user`').then(onResolve); diff --git a/types/dd-trace/dd-trace-tests.ts b/types/dd-trace/dd-trace-tests.ts index 9d6936875a..cee1b6e3ee 100644 --- a/types/dd-trace/dd-trace-tests.ts +++ b/types/dd-trace/dd-trace-tests.ts @@ -2,14 +2,15 @@ import * as tracer from "dd-trace"; import SpanContext = require("dd-trace/src/opentracing/span_context"); tracer.init({ + enabled: true, service: "MyLovelyService", hostname: "localhost", port: 8126, + env: "dev", logger: { debug: msg => {}, error: err => {}, - }, - tags: { tracerEnv: 'dev'} + } }); function useWebFrameworkPlugin(plugin: "express" | "hapi" | "koa" | "restify") { diff --git a/types/dd-trace/index.d.ts b/types/dd-trace/index.d.ts index 311fa7675e..a55b7f8de7 100644 --- a/types/dd-trace/index.d.ts +++ b/types/dd-trace/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for dd-trace-js 0.6 +// Type definitions for dd-trace-js 0.7 // Project: https://github.com/DataDog/dd-trace-js // Definitions by: Colin Bradley // Eloy Durán @@ -54,6 +54,12 @@ declare class TraceProxy extends Tracer { } interface TracerOptions { + /** + * Whether to enable the tracer. + * @default true + */ + enabled?: boolean; + /** * Enable debug logging in the tracer. * @default false @@ -77,6 +83,11 @@ interface TracerOptions { */ port?: number | string; + /** + * Set an application’s environment e.g. prod, pre-prod, stage. + */ + env?: string; + /** * Percentage of spans to sample as a float between 0 and 1. * @default 1 @@ -185,6 +196,7 @@ declare class Scope { type Plugin = | "amqp10" | "amqplib" + | "bluebird" | "elasticsearch" | "express" | "graphql" @@ -197,8 +209,10 @@ type Plugin = | "mysql" | "mysql2" | "pg" + | "q" | "redis" - | "restify"; + | "restify" + | "when"; interface BasePluginOptions { /** diff --git a/types/debounce-promise/debounce-promise-tests.ts b/types/debounce-promise/debounce-promise-tests.ts new file mode 100644 index 0000000000..75b53dc764 --- /dev/null +++ b/types/debounce-promise/debounce-promise-tests.ts @@ -0,0 +1,25 @@ +import debounce = require("debounce-promise"); +import { DebounceOptions } from "debounce-promise"; + +const options: DebounceOptions = {}; +const optionsA: DebounceOptions = { leading: true }; +const f = async () => 2; +const f2 = (a: string) => 2; +debounce(f, 100); +debounce(f, 0, options); +debounce(f, 100, optionsA); +debounce(f, 10, { accumulate: true }); +const foo = debounce(async () => f2, 10, { + leading: true, + accumulate: true +}); +foo().then(f => f("2")); +const bar = debounce(async () => [1, 2, 3], 100); +bar().then(ar => ar.concat()); + +// Converts the return value from the producer function to a promise +const two = debounce((a: string, b: number, c: { d: boolean }) => [4], 10, { + leading: true, + accumulate: true +}); +two("1", 2, { d: false }).then(ar => ar.pop(), () => 2); diff --git a/types/debounce-promise/index.d.ts b/types/debounce-promise/index.d.ts new file mode 100644 index 0000000000..905ca7fc50 --- /dev/null +++ b/types/debounce-promise/index.d.ts @@ -0,0 +1,24 @@ +// Type definitions for debounce-promise 3.1 +// Project: https://github.com/bjoerge/debounce-promise +// Definitions by: Wu Haotian +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 3.0 + +declare namespace debounce { + interface DebounceOptions { + leading?: boolean; + accumulate?: boolean; + } +} + +declare function debounce any>( + func: T, + wait?: number, + options?: debounce.DebounceOptions +): ( + ...args: Parameters +) => ReturnType extends Promise + ? ReturnType + : Promise>; + +export = debounce; diff --git a/types/debounce-promise/tsconfig.json b/types/debounce-promise/tsconfig.json new file mode 100644 index 0000000000..7e41251117 --- /dev/null +++ b/types/debounce-promise/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "debounce-promise-tests.ts"] +} diff --git a/types/debounce-promise/tslint.json b/types/debounce-promise/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/debounce-promise/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/debounce/debounce-tests.ts b/types/debounce/debounce-tests.ts index 4acff7c446..5f0463a4c1 100644 --- a/types/debounce/debounce-tests.ts +++ b/types/debounce/debounce-tests.ts @@ -14,6 +14,9 @@ const imm1: number = (debounce((x: number) => x * 2, 100, true))(2); const clearable = debounce(doThings); clearable.clear(); +const flushable = debounce(doThings); +flushable.flush(); + // Intentionally asserts that the member variable has all the same benefits as the direct export. // Eventually, if debounce stop supporting the CommonJS-only module calling (`require("debounce")(...)`), // we can remove this and change the top import&require to `import { debounce } from "debounce";`. diff --git a/types/debounce/index.d.ts b/types/debounce/index.d.ts index fa244351d6..e561cb51fe 100644 --- a/types/debounce/index.d.ts +++ b/types/debounce/index.d.ts @@ -1,13 +1,15 @@ -// Type definitions for debounce 3.0 +// Type definitions for debounce 1.2 // Project: https://github.com/component/debounce // Definitions by: Denis Sokolov // Josh Goldberg +// Wayne Carson // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace _debounce { const debounce: typeof _debounce; } -declare function _debounce(f: A, interval?: number, immediate?: boolean): A & { clear(): void; }; +declare function _debounce(f: A, interval?: number, immediate?: boolean): A & { clear(): void; } + & { flush(): void }; export = _debounce; diff --git a/types/deprecate/deprecate-tests.ts b/types/deprecate/deprecate-tests.ts new file mode 100644 index 0000000000..3df2257c40 --- /dev/null +++ b/types/deprecate/deprecate-tests.ts @@ -0,0 +1,9 @@ +import deprecate = require('deprecate'); + +deprecate('someMethod'); +deprecate('someMethod', 'This is deprecated'); +deprecate('someMethod', 'This is deprecated', 'foo', 'bar'); + +deprecate.color = '\x1b[31;1m'; +deprecate.silence = true; +deprecate.stream = process.stderr; diff --git a/types/deprecate/index.d.ts b/types/deprecate/index.d.ts new file mode 100644 index 0000000000..a053721ff5 --- /dev/null +++ b/types/deprecate/index.d.ts @@ -0,0 +1,33 @@ +// Type definitions for deprecate 1.1 +// Project: https://github.com/brianc/node-deprecate +// Definitions by: Toilal +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +/// + +declare namespace deprecate { + /** + * Set to false to not output a color. Defaults to '\x1b[31;1m' which is red. + */ + let color: string; + + /** + * Set to false to do nothing at all when the deprecate method is called. Useful in tests of the library you're deprecating things within. + */ + let silence: boolean; + + /** + * The stream to which output is written. Defaults to process.stderr + */ + let stream: NodeJS.WriteStream; +} + +/** + * Call deprecate within a function you are deprecating. + * + * It will spit out all the messages to the console the first time and only the first time the method is called. + */ +declare function deprecate(methodName: string, ...message: string[]): void; + +export = deprecate; diff --git a/types/deprecate/tsconfig.json b/types/deprecate/tsconfig.json new file mode 100644 index 0000000000..75acd6cda6 --- /dev/null +++ b/types/deprecate/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "deprecate-tests.ts" + ] +} diff --git a/types/deprecate/tslint.json b/types/deprecate/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/deprecate/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/detox/detox-tests.ts b/types/detox/detox-tests.ts deleted file mode 100644 index 58fe5c1912..0000000000 --- a/types/detox/detox-tests.ts +++ /dev/null @@ -1,31 +0,0 @@ -declare var describe: (test: string, callback: () => void) => void; -declare var beforeAll: (callback: () => void) => void; -declare var afterAll: (callback: () => void) => void; -declare var test: (test: string, callback: () => void) => void; - -describe('Test', () => { - beforeAll(async () => { - await device.reloadReactNative(); - }); - - afterAll(async () => { - await element(by.id('element')).clearText(); - }); - - test('Test', async () => { - await element(by.id('element')).replaceText('text'); - await element(by.id('element')).tap(); - await element(by.id('element')).scroll(50, 'down'); - await element(by.id('scrollView')).scrollTo('bottom'); - await expect(element(by.id('element')).atIndex(0)).toNotExist(); - await element(by.id('scrollView')).swipe('down', 'fast'); - await element(by.type('UIPickerView')).setColumnToValue(1, "6"); - - await expect(element(by.id('element').withAncestor(by.id('parent_element')))).toNotExist(); - await expect(element(by.id('element').withDescendant(by.id('child_element')))).toNotExist(); - - await waitFor(element(by.id('element'))).toBeVisible().withTimeout(2000); - await device.pressBack(); - await waitFor(element(by.text('Text5'))).toBeVisible().whileElement(by.id('ScrollView630')).scroll(50, 'down'); - }); -}); diff --git a/types/detox/index.d.ts b/types/detox/index.d.ts index a7bfa12bca..de74163bf1 100644 --- a/types/detox/index.d.ts +++ b/types/detox/index.d.ts @@ -3,428 +3,435 @@ // Definitions by: Tareq El-Masri , Steve Chun // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare const detox: Detox.Detox; -declare const device: Detox.Device; -declare const element: Detox.Element; -declare const waitFor: Detox.WaitFor; -declare const expect: Detox.Expect>; -declare const by: Detox.Matchers; +declare global { + const detox: Detox.Detox; + const device: Detox.Device; + const element: Detox.Element; + const waitFor: Detox.WaitFor; + const expect: Detox.Expect>; + const by: Detox.Matchers; -declare namespace Detox { - interface Detox { - /** - * The setup phase happens inside detox.init(). This is the phase where detox reads its configuration, starts a server, loads its expection library and starts a simulator - * @param config - * @param options - * @example const config = require('../package.json').detox; - * - * before(async () => { - * await detox.init(config); - * }); - */ - init(config: any, options?: DetoxInitOptions): Promise; - /** - * Artifacts currently include only logs from the app process before each task - * @param args - */ - beforeEach(...args: any[]): Promise; - /** - * Artifacts currently include only logs from the app process after each task - * @param args - */ - afterEach(...args: any[]): Promise; - /** - * The cleanup phase should happen after all the tests have finished. This is the phase where detox-server shuts down. - * @example after(async () => { - * await detox.cleanup(); - * }); - */ - cleanup(): Promise; - } - interface Device { - /** - * Launch the app - * @param config - * @example // Terminate the app and launch it again. If set to false, the simulator will try to bring app from background, - * // if the app isn't running, it will launch a new instance. default is false - * await device.launchApp({newInstance: true}); - * // Grant or deny runtime permissions for your application. - * await device.launchApp({permissions: {calendar: 'YES'}}); - * // Mock opening the app from URL to test your app's deep link handling mechanism. - * await device.launchApp({url: url}); - */ - launchApp(config: DeviceLanchAppConfig): Promise; - /** - * By default, terminateApp() with no params will terminate the app - * To terminate another app, specify its bundle id - * @param bundle - * @example await device.terminateApp('other.bundle.id'); - */ - terminateApp(bundle?: string): Promise; - /** - * Send application to background by bringing com.apple.springboard to the foreground. - * Combining sendToHome() with launchApp({newInstance: false}) will simulate app coming back from background. - * @example await device.sendToHome(); - * await device.launchApp({newInstance: false}); - */ - sendToHome(): Promise; - /** - * If this is a React Native app, reload the React Native JS bundle. This action is much faster than device.launchApp(), and can be used if you just need to reset your React Native logic. - * @example await device.reloadReactNative() - */ - reloadReactNative(): Promise; - /** - * By default, installApp() with no params will install the app file defined in the current configuration. - * To install another app, specify its path - * @param path - * @example await device.installApp('path/to/other/app'); - */ - installApp(path?: any): Promise; - /** - * By default, uninstallApp() with no params will uninstall the app defined in the current configuration. - * To uninstall another app, specify its bundle id - * @param bundle - * @example await device.installApp('other.bundle.id'); - */ - uninstallApp(bundle?: string): Promise; - /** - * Mock opening the app from URL. sourceApp is an optional parameter to specify source application bundle id. - * @param url - */ - openURL(url: {url: string, sourceApp?: string}): Promise; - /** - * Mock handling of received user notification when app is in foreground. - * @param params - */ - sendUserNotification(...params: any[]): Promise; - /** - * Mock handling of received user activity when app is in foreground. - * @param params - */ - sendUserActivity(...params: any[]): Promise; - /** - * Takes "portrait" or "landscape" and rotates the device to the given orientation. Currently only available in the iOS Simulator. - * @param orientation - */ - setOrientation(orientation: Orientation): Promise; - /** - * Note: setLocation is dependent on fbsimctl. if fbsimctl is not installed, the command will fail, it must be installed. Sets the simulator location to the given latitude and longitude. - * @param lat - * @param lon - * @example await device.setLocation(32.0853, 34.7818); - */ - setLocation(lat: number, lon: number): Promise; - /** - * Disable EarlGrey's network synchronization mechanism on preffered endpoints. Usful if you want to on skip over synchronizing on certain URLs. - * @param urls - * @example await device.setURLBlacklist(['.*127.0.0.1.*']); - */ - setURLBlacklist(urls: string[]): Promise; - /** - * Enable EarlGrey's synchronization mechanism (enabled by default). This is being reset on every new instance of the app. - * @example await device.enableSynchronization(); - */ - enableSynchronization(): Promise; - /** - * Disable EarlGrey's synchronization mechanism (enabled by default) This is being reset on every new instance of the app. - * @example await device.disableSynchronization(); - */ - disableSynchronization(): Promise; - /** - * Resets the Simulator to clean state (like the Simulator > Reset Content and Settings... menu item), especially removing previously set permissions. - * @example await device.resetContentAndSettings(); - */ - resetContentAndSettings(): Promise; - /** - * Returns the current device, ios or android. - * @example if (device.getPlatform() === 'ios') { - * await expect(loopSwitch).toHaveValue('1'); - * } - */ - getPlatform(): "ios" | "android"; - /** - * Simulate press back button (Android Only) - */ - pressBack(): Promise; - /** - * Simulate shake (iOS Only) - */ - shake(): Promise; - } + namespace Detox { + interface Detox { + /** + * The setup phase happens inside detox.init(). This is the phase where detox reads its configuration, starts a server, loads its expection library and starts a simulator + * @param config + * @param options + * @example const config = require('../package.json').detox; + * + * before(async () => { + * await detox.init(config); + * }); + */ + init(config: any, options?: DetoxInitOptions): Promise; + /** + * Artifacts currently include only logs from the app process before each task + * @param args + */ + beforeEach(...args: any[]): Promise; + /** + * Artifacts currently include only logs from the app process after each task + * @param args + */ + afterEach(...args: any[]): Promise; + /** + * The cleanup phase should happen after all the tests have finished. This is the phase where detox-server shuts down. + * @example after(async () => { + * await detox.cleanup(); + * }); + */ + cleanup(): Promise; + } + interface Device { + /** + * Launch the app + * @param config + * @example // Terminate the app and launch it again. If set to false, the simulator will try to bring app from background, + * // if the app isn't running, it will launch a new instance. default is false + * await device.launchApp({newInstance: true}); + * // Grant or deny runtime permissions for your application. + * await device.launchApp({permissions: {calendar: 'YES'}}); + * // Mock opening the app from URL to test your app's deep link handling mechanism. + * await device.launchApp({url: url}); + */ + launchApp(config: DeviceLanchAppConfig): Promise; + /** + * By default, terminateApp() with no params will terminate the app + * To terminate another app, specify its bundle id + * @param bundle + * @example await device.terminateApp('other.bundle.id'); + */ + terminateApp(bundle?: string): Promise; + /** + * Send application to background by bringing com.apple.springboard to the foreground. + * Combining sendToHome() with launchApp({newInstance: false}) will simulate app coming back from background. + * @example await device.sendToHome(); + * await device.launchApp({newInstance: false}); + */ + sendToHome(): Promise; + /** + * If this is a React Native app, reload the React Native JS bundle. This action is much faster than device.launchApp(), and can be used if you just need to reset your React Native logic. + * @example await device.reloadReactNative() + */ + reloadReactNative(): Promise; + /** + * By default, installApp() with no params will install the app file defined in the current configuration. + * To install another app, specify its path + * @param path + * @example await device.installApp('path/to/other/app'); + */ + installApp(path?: any): Promise; + /** + * By default, uninstallApp() with no params will uninstall the app defined in the current configuration. + * To uninstall another app, specify its bundle id + * @param bundle + * @example await device.installApp('other.bundle.id'); + */ + uninstallApp(bundle?: string): Promise; + /** + * Mock opening the app from URL. sourceApp is an optional parameter to specify source application bundle id. + * @param url + */ + openURL(url: { url: string; sourceApp?: string }): Promise; + /** + * Mock handling of received user notification when app is in foreground. + * @param params + */ + sendUserNotification(...params: any[]): Promise; + /** + * Mock handling of received user activity when app is in foreground. + * @param params + */ + sendUserActivity(...params: any[]): Promise; + /** + * Takes "portrait" or "landscape" and rotates the device to the given orientation. Currently only available in the iOS Simulator. + * @param orientation + */ + setOrientation(orientation: Orientation): Promise; + /** + * Note: setLocation is dependent on fbsimctl. if fbsimctl is not installed, the command will fail, it must be installed. Sets the simulator location to the given latitude and longitude. + * @param lat + * @param lon + * @example await device.setLocation(32.0853, 34.7818); + */ + setLocation(lat: number, lon: number): Promise; + /** + * Disable EarlGrey's network synchronization mechanism on preffered endpoints. Usful if you want to on skip over synchronizing on certain URLs. + * @param urls + * @example await device.setURLBlacklist(['.*127.0.0.1.*']); + */ + setURLBlacklist(urls: string[]): Promise; + /** + * Enable EarlGrey's synchronization mechanism (enabled by default). This is being reset on every new instance of the app. + * @example await device.enableSynchronization(); + */ + enableSynchronization(): Promise; + /** + * Disable EarlGrey's synchronization mechanism (enabled by default) This is being reset on every new instance of the app. + * @example await device.disableSynchronization(); + */ + disableSynchronization(): Promise; + /** + * Resets the Simulator to clean state (like the Simulator > Reset Content and Settings... menu item), especially removing previously set permissions. + * @example await device.resetContentAndSettings(); + */ + resetContentAndSettings(): Promise; + /** + * Returns the current device, ios or android. + * @example if (device.getPlatform() === 'ios') { + * await expect(loopSwitch).toHaveValue('1'); + * } + */ + getPlatform(): "ios" | "android"; + /** + * Simulate press back button (Android Only) + */ + pressBack(): Promise; + /** + * Simulate shake (iOS Only) + */ + shake(): Promise; + } - type DetoxAny = Element & Actions & WaitFor; + type DetoxAny = Element & Actions & WaitFor; - interface Element { - (by: Matchers): DetoxAny; + interface Element { + (by: Matchers): DetoxAny; - /** - * Choose from multiple elements matching the same matcher using index - * @param index - * @example await element(by.text('Product')).atIndex(2); - */ - atIndex(index: number): DetoxAny; - } - interface Matchers { - (by: Matchers): Matchers; + /** + * Choose from multiple elements matching the same matcher using index + * @param index + * @example await element(by.text('Product')).atIndex(2); + */ + atIndex(index: number): DetoxAny; + } + interface Matchers { + (by: Matchers): Matchers; - /** - * by.id will match an id that is given to the view via testID prop. - * @param id - * @example // In a React Native component add testID like so: - * - * // Then match with by.id: - * await element(by.id('tap_me')); - */ - id(id: string): Matchers; - /** - * Find an element by text, useful for text fields, buttons. - * @param text - * @example await element(by.text('Tap Me')); - */ - text(text: string): Matchers; - /** - * Find an element by accessibilityLabel on iOS, or by contentDescription on Android. - * @param label - * @example await element(by.label('Welcome')); - */ - label(label: string): Matchers; - /** - * Find an element by native view type. - * @param nativeViewType - * @example await element(by.type('RCTImageView')); - */ - type(nativeViewType: string): Matchers; - /** - * Find an element with an accessibility trait. (iOS only) - * @example await element(by.traits(['button'])); - */ - traits(traits: string[]): Matchers; - /** - * Find an element by a matcher with a parent matcher - * @param parentBy - * @example await element(by.id('Grandson883').withAncestor(by.id('Son883'))); - */ - withAncestor(parentBy: Matchers): Matchers; - /** - * Find an element by a matcher with a child matcher - * @param childBy - * @example await element(by.id('Son883').withDescendant(by.id('Grandson883'))); - */ - withDescendant(childBy: Matchers): Matchers; - /** - * Find an element by multiple matchers - * @param by - * @example await element(by.text('Product').and(by.id('product_name')); - */ - and(by: Matchers): Matchers; - } - interface Expect { - (element: Element): Expect; - /** - * Expect the view to be at least 75% visible. - * @example await expect(element(by.id('UniqueId204'))).toBeVisible(); - */ - toBeVisible(): R; - /** - * Expect the view to not be visible. - * @example await expect(element(by.id('UniqueId205'))).toBeNotVisible(); - */ - toBeNotVisible(): R; - /** - * Expect the view to exist in the UI hierarchy. - * @example await expect(element(by.id('UniqueId205'))).toExist(); - */ - toExist(): R; - /** - * Expect the view to not exist in the UI hierarchy. - * @example await expect(element(by.id('RandomJunk959'))).toNotExist(); - */ - toNotExist(): R; - /** - * In React Native apps, expect UI component of type to have text. - * In native iOS apps, expect UI elements of type UIButton, UILabel, UITextField or UITextViewIn to have inputText with text. - * @param text - * @example await expect(element(by.id('UniqueId204'))).toHaveText('I contain some text'); - */ - toHaveText(text: string): R; - /** - * It searches by accessibilityLabel on iOS, or by contentDescription on Android. - * In React Native it can be set for both platforms by defining an accessibilityLabel on the view. - * @param label - * @example await expect(element(by.id('UniqueId204'))).toHaveLabel('Done'); - */ - toHaveLabel(label: string): R; - /** - * In React Native apps, expect UI component to have testID with that id. - * In native iOS apps, expect UI element to have accesibilityIdentifier with that id. - * @param id - * @example await expect(element(by.text('I contain some text'))).toHaveId('UniqueId204'); - */ - toHaveId(id: string): R; - /** - * Expect components like a Switch to have a value ('0' for off, '1' for on). - * @param value - * @example await expect(element(by.id('UniqueId533'))).toHaveValue('0'); - */ - toHaveValue(value: any): R; - } - interface WaitFor { - /** - * This API polls using the given expectation continuously until the expectation is met. Use manual synchronization with waitFor only as a last resort. - * NOTE: Every waitFor call must set a timeout using withTimeout(). Calling waitFor without setting a timeout will do nothing. - * @example await waitFor(element(by.id('UniqueId336'))).toExist().withTimeout(2000); - */ - (element: Element): Expect; - /** - * Waits for the condition to be met until the specified time (millis) have elapsed. - * @param millis number - * @example await waitFor(element(by.id('UniqueId336'))).toExist().withTimeout(2000); - */ - withTimeout(millis: number): Promise; - /** - * Performs the action repeatedly on the element until an expectation is met - * @param by - * @example await waitFor(element(by.text('Text5'))).toBeVisible().whileElement(by.id('ScrollView630')).scroll(50, 'down'); - */ - whileElement(by: Matchers): DetoxAny; - } - interface Actions { - /** - * Simulate tap on an element - * @example await element(by.id('tappable')).tap(); - */ - tap(): Promise>; - /** - * Simulate long press on an element - * @example await element(by.id('tappable')).longPress(); - */ - longPress(): Promise>; - /** - * Simulate multiple taps on an element. - * @param times number - * @example await element(by.id('tappable')).multiTap(3); - */ - multiTap(times: number): Promise>; - /** - * Simulate tap at a specific point on an element. - * Note: The point coordinates are relative to the matched element and the element size could changes on different devices or even when changing the device font size. - * @param point - * @example await element(by.id('tappable')).tapAtPoint({ x:5, y:10 }); - */ - tapAtPoint(point: { x: number, y: number }): Promise>; - /** - * Use the builtin keyboard to type text into a text field. - * @param text - * @example await element(by.id('textField')).typeText('passcode'); - */ - typeText(text: string): Promise>; - /** - * Paste text into a text field. - * @param text - * @example await element(by.id('textField')).replaceText('passcode again'); - */ - replaceText(text: string): Promise>; - /** - * Clear text from a text field. - * @example await element(by.id('textField')).clearText(); - */ - clearText(): Promise>; - /** - * - * @param pixels - * @param direction - * @example - * await element(by.id('scrollView')).scroll(100, 'down'); - * await element(by.id('scrollView')).scroll(100, 'up'); - */ - scroll(pixels: number, direction: Direction): Promise>; - /** - * Scroll to edge. - * @param edge - * @example await element(by.id('scrollView')).scrollTo('bottom'); - * await element(by.id('scrollView')).scrollTo('top'); - */ - scrollTo(edge: Direction): Promise>; - /** - * - * @param direction - * @param speed - * @param percentage - * @example await element(by.id('scrollView')).swipe('down'); - * await element(by.id('scrollView')).swipe('down', 'fast'); - * await element(by.id('scrollView')).swipe('down', 'fast', 0.5); - */ - swipe(direction: Direction, speed?: Speed, percentage?: number): Promise>; - /** - * (iOS Only) column - number of datepicker column (starts from 0) value - string value in setted column (must be correct) - * @param column - * @param value - * @example await expect(element(by.type('UIPickerView'))).toBeVisible(); - * await element(by.type('UIPickerView')).setColumnToValue(1,"6"); - * await element(by.type('UIPickerView')).setColumnToValue(2,"34"); - */ - setColumnToValue(column: number, value: string): Promise>; - } + /** + * by.id will match an id that is given to the view via testID prop. + * @param id + * @example // In a React Native component add testID like so: + * + * // Then match with by.id: + * await element(by.id('tap_me')); + */ + id(id: string): Matchers; + /** + * Find an element by text, useful for text fields, buttons. + * @param text + * @example await element(by.text('Tap Me')); + */ + text(text: string): Matchers; + /** + * Find an element by accessibilityLabel on iOS, or by contentDescription on Android. + * @param label + * @example await element(by.label('Welcome')); + */ + label(label: string): Matchers; + /** + * Find an element by native view type. + * @param nativeViewType + * @example await element(by.type('RCTImageView')); + */ + type(nativeViewType: string): Matchers; + /** + * Find an element with an accessibility trait. (iOS only) + * @example await element(by.traits(['button'])); + */ + traits(traits: string[]): Matchers; + /** + * Find an element by a matcher with a parent matcher + * @param parentBy + * @example await element(by.id('Grandson883').withAncestor(by.id('Son883'))); + */ + withAncestor(parentBy: Matchers): Matchers; + /** + * Find an element by a matcher with a child matcher + * @param childBy + * @example await element(by.id('Son883').withDescendant(by.id('Grandson883'))); + */ + withDescendant(childBy: Matchers): Matchers; + /** + * Find an element by multiple matchers + * @param by + * @example await element(by.text('Product').and(by.id('product_name')); + */ + and(by: Matchers): Matchers; + } + interface Expect { + (element: Element): Expect; + /** + * Expect the view to be at least 75% visible. + * @example await expect(element(by.id('UniqueId204'))).toBeVisible(); + */ + toBeVisible(): R; + /** + * Expect the view to not be visible. + * @example await expect(element(by.id('UniqueId205'))).toBeNotVisible(); + */ + toBeNotVisible(): R; + /** + * Expect the view to exist in the UI hierarchy. + * @example await expect(element(by.id('UniqueId205'))).toExist(); + */ + toExist(): R; + /** + * Expect the view to not exist in the UI hierarchy. + * @example await expect(element(by.id('RandomJunk959'))).toNotExist(); + */ + toNotExist(): R; + /** + * In React Native apps, expect UI component of type to have text. + * In native iOS apps, expect UI elements of type UIButton, UILabel, UITextField or UITextViewIn to have inputText with text. + * @param text + * @example await expect(element(by.id('UniqueId204'))).toHaveText('I contain some text'); + */ + toHaveText(text: string): R; + /** + * It searches by accessibilityLabel on iOS, or by contentDescription on Android. + * In React Native it can be set for both platforms by defining an accessibilityLabel on the view. + * @param label + * @example await expect(element(by.id('UniqueId204'))).toHaveLabel('Done'); + */ + toHaveLabel(label: string): R; + /** + * In React Native apps, expect UI component to have testID with that id. + * In native iOS apps, expect UI element to have accesibilityIdentifier with that id. + * @param id + * @example await expect(element(by.text('I contain some text'))).toHaveId('UniqueId204'); + */ + toHaveId(id: string): R; + /** + * Expect components like a Switch to have a value ('0' for off, '1' for on). + * @param value + * @example await expect(element(by.id('UniqueId533'))).toHaveValue('0'); + */ + toHaveValue(value: any): R; + } + interface WaitFor { + /** + * This API polls using the given expectation continuously until the expectation is met. Use manual synchronization with waitFor only as a last resort. + * NOTE: Every waitFor call must set a timeout using withTimeout(). Calling waitFor without setting a timeout will do nothing. + * @example await waitFor(element(by.id('UniqueId336'))).toExist().withTimeout(2000); + */ + (element: Element): Expect; + /** + * Waits for the condition to be met until the specified time (millis) have elapsed. + * @param millis number + * @example await waitFor(element(by.id('UniqueId336'))).toExist().withTimeout(2000); + */ + withTimeout(millis: number): Promise; + /** + * Performs the action repeatedly on the element until an expectation is met + * @param by + * @example await waitFor(element(by.text('Text5'))).toBeVisible().whileElement(by.id('ScrollView630')).scroll(50, 'down'); + */ + whileElement(by: Matchers): DetoxAny; + } + interface Actions { + /** + * Simulate tap on an element + * @example await element(by.id('tappable')).tap(); + */ + tap(): Promise>; + /** + * Simulate long press on an element + * @example await element(by.id('tappable')).longPress(); + */ + longPress(): Promise>; + /** + * Simulate multiple taps on an element. + * @param times number + * @example await element(by.id('tappable')).multiTap(3); + */ + multiTap(times: number): Promise>; + /** + * Simulate tap at a specific point on an element. + * Note: The point coordinates are relative to the matched element and the element size could changes on different devices or even when changing the device font size. + * @param point + * @example await element(by.id('tappable')).tapAtPoint({ x:5, y:10 }); + */ + tapAtPoint(point: { x: number; y: number }): Promise>; + /** + * Use the builtin keyboard to type text into a text field. + * @param text + * @example await element(by.id('textField')).typeText('passcode'); + */ + typeText(text: string): Promise>; + /** + * Paste text into a text field. + * @param text + * @example await element(by.id('textField')).replaceText('passcode again'); + */ + replaceText(text: string): Promise>; + /** + * Clear text from a text field. + * @example await element(by.id('textField')).clearText(); + */ + clearText(): Promise>; + /** + * + * @param pixels + * @param direction + * @example + * await element(by.id('scrollView')).scroll(100, 'down'); + * await element(by.id('scrollView')).scroll(100, 'up'); + */ + scroll(pixels: number, direction: Direction): Promise>; + /** + * Scroll to edge. + * @param edge + * @example await element(by.id('scrollView')).scrollTo('bottom'); + * await element(by.id('scrollView')).scrollTo('top'); + */ + scrollTo(edge: Direction): Promise>; + /** + * + * @param direction + * @param speed + * @param percentage + * @example await element(by.id('scrollView')).swipe('down'); + * await element(by.id('scrollView')).swipe('down', 'fast'); + * await element(by.id('scrollView')).swipe('down', 'fast', 0.5); + */ + swipe( + direction: Direction, + speed?: Speed, + percentage?: number + ): Promise>; + /** + * (iOS Only) column - number of datepicker column (starts from 0) value - string value in setted column (must be correct) + * @param column + * @param value + * @example await expect(element(by.type('UIPickerView'))).toBeVisible(); + * await element(by.type('UIPickerView')).setColumnToValue(1,"6"); + * await element(by.type('UIPickerView')).setColumnToValue(2,"34"); + */ + setColumnToValue( + column: number, + value: string + ): Promise>; + } - type Direction = "left" | "right" | "top" | "bottom" | "up" | "down"; - type Orientation = "portrait" | "landscape"; - type Speed = "fast" | "slow"; - - interface LanguageAndLocale { - language?: string; - locale?: string; - } - - interface DetoxInitOptions { - /** - * Detox exports device, expect, element, by and waitFor as globals by default, if you want to control their initialization manually, set init detox with initGlobals set to false. - * This is useful when during E2E tests you also need to run regular expectations in node. jest Expect for instance, will not be overriden by Detox when this option is used. - */ - initGlobals?: boolean; - /** - * By default await detox.init(config); will launch the installed app. If you wish to control when your app is launched, add {launchApp: false} param to your init. - */ - launchApp?: boolean; - } - - interface DeviceLanchAppConfig { - /** - * Restart the app - * Terminate the app and launch it again. If set to false, the simulator will try to bring app from background, if the app isn't running, it will launch a new instance. default is false - */ - newInstance?: boolean; - /** - * Set runtime permissions - * Grant or deny runtime permissions for your application. - */ - permissions?: any; - /** - * Launch from URL - * Mock opening the app from URL to test your app's deep link handling mechanism. - */ - url?: any; - /** - * Launch with user notifications - */ - userNotification?: any; - /** - * Launch with user activity - */ - userActivity?: any; - /** - * Launch into a fresh installation - * A flag that enables relaunching into a fresh installation of the app (it will uninstall and install the binary again), default is false. - */ - delete?: boolean; - /** - * Detox can start the app with additional launch arguments - * The added launchArgs will be passed through the launch command to the device and be accessible via [[NSProcessInfo processInfo] arguments] - */ - launchArgs?: any; - - /** - * Launch config for specifying the native language and locale - */ - languageAndLocale?: LanguageAndLocale; + type Direction = "left" | "right" | "top" | "bottom" | "up" | "down"; + type Orientation = "portrait" | "landscape"; + type Speed = "fast" | "slow"; + interface LanguageAndLocale { + language?: string; + locale?: string; + } + interface DetoxInitOptions { + /** + * Detox exports device, expect, element, by and waitFor as globals by default, if you want to control their initialization manually, set init detox with initGlobals set to false. + * This is useful when during E2E tests you also need to run regular expectations in node. jest Expect for instance, will not be overriden by Detox when this option is used. + */ + initGlobals?: boolean; + /** + * By default await detox.init(config); will launch the installed app. If you wish to control when your app is launched, add {launchApp: false} param to your init. + */ + launchApp?: boolean; + } + interface DeviceLanchAppConfig { + /** + * Restart the app + * Terminate the app and launch it again. If set to false, the simulator will try to bring app from background, if the app isn't running, it will launch a new instance. default is false + */ + newInstance?: boolean; + /** + * Set runtime permissions + * Grant or deny runtime permissions for your application. + */ + permissions?: any; + /** + * Launch from URL + * Mock opening the app from URL to test your app's deep link handling mechanism. + */ + url?: any; + /** + * Launch with user notifications + */ + userNotification?: any; + /** + * Launch with user activity + */ + userActivity?: any; + /** + * Launch into a fresh installation + * A flag that enables relaunching into a fresh installation of the app (it will uninstall and install the binary again), default is false. + */ + delete?: boolean; + /** + * Detox can start the app with additional launch arguments + * The added launchArgs will be passed through the launch command to the device and be accessible via [[NSProcessInfo processInfo] arguments] + */ + launchArgs?: any; + /** + * Launch config for specifying the native language and locale + */ + languageAndLocale?: LanguageAndLocale; + } } } + +export { by, detox, device, element, expect, waitFor }; diff --git a/types/detox/runners/jest/adapters/index.d.ts b/types/detox/runners/jest/adapters/index.d.ts new file mode 100644 index 0000000000..ca195ae744 --- /dev/null +++ b/types/detox/runners/jest/adapters/index.d.ts @@ -0,0 +1,9 @@ +interface DetoxJestAdapter { + detox: Detox.Detox; + beforeEach: () => Promise; + afterAll: () => Promise; +} + +declare const adapter: DetoxJestAdapter; + +export default adapter; diff --git a/types/detox/runners/mocha/adapters/index.d.ts b/types/detox/runners/mocha/adapters/index.d.ts new file mode 100644 index 0000000000..8e13b3bc01 --- /dev/null +++ b/types/detox/runners/mocha/adapters/index.d.ts @@ -0,0 +1,9 @@ +interface DetoxMochaAdapter { + detox: Detox.Detox; + beforeEach: (context: any) => Promise; + afterEach: (context: any) => Promise; +} + +declare const adapter: DetoxMochaAdapter; + +export default adapter; diff --git a/types/detox/test/detox-global-tests.ts b/types/detox/test/detox-global-tests.ts new file mode 100644 index 0000000000..42415c548d --- /dev/null +++ b/types/detox/test/detox-global-tests.ts @@ -0,0 +1,40 @@ +declare var describe: (test: string, callback: () => void) => void; +declare var beforeAll: (callback: () => void) => void; +declare var afterAll: (callback: () => void) => void; +declare var test: (test: string, callback: () => void) => void; + +describe("Test", () => { + beforeAll(async () => { + await device.reloadReactNative(); + }); + + afterAll(async () => { + await element(by.id("element")).clearText(); + }); + + test("Test", async () => { + await element(by.id("element")).replaceText("text"); + await element(by.id("element")).tap(); + await element(by.id("element")).scroll(50, "down"); + await element(by.id("scrollView")).scrollTo("bottom"); + await expect(element(by.id("element")).atIndex(0)).toNotExist(); + await element(by.id("scrollView")).swipe("down", "fast"); + await element(by.type("UIPickerView")).setColumnToValue(1, "6"); + + await expect( + element(by.id("element").withAncestor(by.id("parent_element"))) + ).toNotExist(); + await expect( + element(by.id("element").withDescendant(by.id("child_element"))) + ).toNotExist(); + + await waitFor(element(by.id("element"))) + .toBeVisible() + .withTimeout(2000); + await device.pressBack(); + await waitFor(element(by.text("Text5"))) + .toBeVisible() + .whileElement(by.id("ScrollView630")) + .scroll(50, "down"); + }); +}); diff --git a/types/detox/test/detox-jest-setup-tests.ts b/types/detox/test/detox-jest-setup-tests.ts new file mode 100644 index 0000000000..002b5605bb --- /dev/null +++ b/types/detox/test/detox-jest-setup-tests.ts @@ -0,0 +1,28 @@ +declare var beforeAll: (callback: () => void) => void; +declare var beforeEach: (callback: () => void) => void; +declare var afterAll: (callback: () => void) => void; + +import adapter from "detox/runners/jest/adapters"; + +// Normally the Detox configuration from the project's package.json like so: +// const config = require("./package.json").detox; +declare const config: any; + +beforeAll(async () => { + await detox.init(config); + + const initOptions: Detox.DetoxInitOptions = { + initGlobals: false, + launchApp: false, + }; + await detox.init(config, initOptions); +}); + +beforeEach(async () => { + await adapter.beforeEach(); +}); + +afterAll(async () => { + await adapter.afterAll(); + await detox.cleanup(); +}); diff --git a/types/detox/test/detox-mocha-setup-tests.ts b/types/detox/test/detox-mocha-setup-tests.ts new file mode 100644 index 0000000000..3f502d1391 --- /dev/null +++ b/types/detox/test/detox-mocha-setup-tests.ts @@ -0,0 +1,32 @@ +// tslint:disable:only-arrow-functions + +declare var before: (callback: () => void) => void; +declare var beforeEach: (callback: () => void) => void; +declare var after: (callback: () => void) => void; +declare var afterEach: (callback: () => void) => void; + +import adapter from "detox/runners/mocha/adapters"; + +// Normally the Detox configuration from the project's package.json like so: +// const config = require("./package.json").detox; +declare const config: any; + +// Normally, the beforeEach and afterEach function should take `this` as its argument, +// but `this` cannot be used since it doesn't have a type signature (and therefore always implicltly any) +declare const context: any; + +before(async function() { + await detox.init(config); +}); + +beforeEach(async function() { + await adapter.beforeEach(context); +}); + +afterEach(async function() { + await adapter.afterEach(context); +}); + +after(async function() { + await detox.cleanup(); +}); diff --git a/types/detox/test/detox-module-tests.ts b/types/detox/test/detox-module-tests.ts new file mode 100644 index 0000000000..318569c03d --- /dev/null +++ b/types/detox/test/detox-module-tests.ts @@ -0,0 +1,42 @@ +declare var describe: (test: string, callback: () => void) => void; +declare var beforeAll: (callback: () => void) => void; +declare var afterAll: (callback: () => void) => void; +declare var test: (test: string, callback: () => void) => void; + +import { by, device, element, expect, waitFor } from "detox"; + +describe("Test", () => { + beforeAll(async () => { + await device.reloadReactNative(); + }); + + afterAll(async () => { + await element(by.id("element")).clearText(); + }); + + test("Test", async () => { + await element(by.id("element")).replaceText("text"); + await element(by.id("element")).tap(); + await element(by.id("element")).scroll(50, "down"); + await element(by.id("scrollView")).scrollTo("bottom"); + await expect(element(by.id("element")).atIndex(0)).toNotExist(); + await element(by.id("scrollView")).swipe("down", "fast"); + await element(by.type("UIPickerView")).setColumnToValue(1, "6"); + + await expect( + element(by.id("element").withAncestor(by.id("parent_element"))) + ).toNotExist(); + await expect( + element(by.id("element").withDescendant(by.id("child_element"))) + ).toNotExist(); + + await waitFor(element(by.id("element"))) + .toBeVisible() + .withTimeout(2000); + await device.pressBack(); + await waitFor(element(by.text("Text5"))) + .toBeVisible() + .whileElement(by.id("ScrollView630")) + .scroll(50, "down"); + }); +}); diff --git a/types/detox/tsconfig.json b/types/detox/tsconfig.json index 2d1a22fb79..7be4d3bb9e 100644 --- a/types/detox/tsconfig.json +++ b/types/detox/tsconfig.json @@ -1,24 +1,25 @@ { "compilerOptions": { "module": "commonjs", - "lib": [ - "es6" - ], + "lib": ["es6"], "target": "ES2015", "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", - "typeRoots": [ - "../" - ], + "typeRoots": ["../"], "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true }, "files": [ "index.d.ts", - "detox-tests.ts" + "runners/jest/adapters/index.d.ts", + "runners/mocha/adapters/index.d.ts", + "test/detox-global-tests.ts", + "test/detox-module-tests.ts", + "test/detox-jest-setup-tests.ts", + "test/detox-mocha-setup-tests.ts" ] } diff --git a/types/devexpress-web/v172/tslint.json b/types/devexpress-web/v172/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/devexpress-web/v172/tslint.json +++ b/types/devexpress-web/v172/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/devexpress-web/v181/tslint.json b/types/devexpress-web/v181/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/devexpress-web/v181/tslint.json +++ b/types/devexpress-web/v181/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/dhtmlxgantt/dhtmlxgantt-tests.ts b/types/dhtmlxgantt/dhtmlxgantt-tests.ts index 6ea32b509d..e31665d486 100644 --- a/types/dhtmlxgantt/dhtmlxgantt-tests.ts +++ b/types/dhtmlxgantt/dhtmlxgantt-tests.ts @@ -28,10 +28,12 @@ gantt.locale.labels.new_task = "New task"; gantt.init("scheduler_here", start); gantt.load("/data/events"); +const wbs: string = gantt.getWBSCode(gantt.getTask(1)); + //events gantt.attachEvent("onBeforeLightbox", function (id?: string) { gantt.showTask(id); }); //gantt enterprise var gantt2 = Gantt.getGanttInstance(); -gantt2.config.api_date = "format"; +gantt2.config.xml_date = "format"; diff --git a/types/dhtmlxgantt/index.d.ts b/types/dhtmlxgantt/index.d.ts index 79d02cc181..f2e322b0e3 100644 --- a/types/dhtmlxgantt/index.d.ts +++ b/types/dhtmlxgantt/index.d.ts @@ -1,18 +1,12 @@ -// Type definitions for dhtmlxGantt 4.0.0 -// Project: http://dhtmlx.com/docs/products/dhtmlxGantt +// Type definitions for dhtmlxGantt 6.0.0 +// Project: https://dhtmlx.com/docs/products/dhtmlxGantt // Definitions by: Maksim Kozhukh , Christophe Camicas // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - type GanttCallback = (...args: any[]) => any; -type GanttEventName = 'onAfterAutoSchedule'|'onAfterBatchUpdate'|'onAfterLightbox'|'onAfterLinkAdd'|'onAfterLinkDelete'|'onAfterLinkUpdate'|'onAfterRedo'|'onAfterTaskAdd'|'onAfterTaskAutoSchedule'|'onAfterTaskDelete'|'onAfterTaskDrag'|'onAfterTaskMove'|'onAfterTaskUpdate'|'onAfterUndo'|'onAjaxError'|'onBeforeAutoSchedule'|'onBeforeBatchUpdate'|'onBeforeCollapse'|'onBeforeDataRender'|'onBeforeExpand'|'onBeforeGanttReady'|'onBeforeGanttRender'|'onBeforeLightbox'|'onBeforeLinkAdd'|'onBeforeLinkDelete'|'onBeforeLinkDisplay'|'onBeforeLinkUpdate'|'onBeforeParse'|'onBeforeRedo'|'onBeforeRowDragEnd'|'onBeforeTaskAdd'|'onBeforeTaskAutoSchedule'|'onBeforeTaskChanged'|'onBeforeTaskDelete'|'onBeforeTaskDisplay'|'onBeforeTaskDrag'|'onBeforeTaskMove'|'onBeforeTaskSelected'|'onBeforeTaskUpdate'|'onBeforeUndo'|'onCircularLinkError'|'onClear'|'onCollapse'|'onColumnResize'|'onColumnResizeEnd'|'onColumnResizeStart'|'onContextMenu'|'onDataRender'|'onEmptyClick'|'onError'|'onExpand'|'onGanttReady'|'onGanttRender'|'onGanttScroll'|'onGridHeaderClick'|'onGridResize'|'onGridResizeEnd'|'onGridResizeStart'|'onLightbox'|'onLightboxButton'|'onLightboxCancel'|'onLightboxChange'|'onLightboxDelete'|'onLightboxSave'|'onLinkClick'|'onLinkDblClick'|'onLinkIdChange'|'onLinkValidation'|'onLoadEnd'|'onLoadStart'|'onMouseMove'|'onOptionsLoad'|'onParse'|'onRowDragEnd'|'onRowDragStart'|'onScaleAdjusted'|'onScaleClick'|'onTaskClick'|'onTaskClosed'|'onTaskCreated'|'onTaskDblClick'|'onTaskDrag'|'onTaskIdChange'|'onTaskLoading'|'onTaskOpened'|'onTaskRowClick'|'onTaskSelected'|'onTaskUnselected'|'onTemplatesReady'; +type GanttEventName = "onAfterAutoSchedule"|"onAfterBatchUpdate"|"onAfterLightbox"|"onAfterLinkAdd"|"onAfterLinkDelete"|"onAfterLinkUpdate"|"onAfterQuickInfo"|"onAfterRedo"|"onAfterSort"|"onAfterTaskAdd"|"onAfterTaskAutoSchedule"|"onAfterTaskDelete"|"onAfterTaskDrag"|"onAfterTaskMove"|"onAfterTaskUpdate"|"onAfterUndo"|"onAjaxError"|"onAutoScheduleCircularLink"|"onBeforeAutoSchedule"|"onBeforeBatchUpdate"|"onBeforeCollapse"|"onBeforeDataRender"|"onBeforeExpand"|"onBeforeGanttReady"|"onBeforeGanttRender"|"onBeforeLightbox"|"onBeforeLinkAdd"|"onBeforeLinkDelete"|"onBeforeLinkDisplay"|"onBeforeLinkUpdate"|"onBeforeMultiSelect"|"onBeforeParse"|"onBeforeRedo"|"onBeforeRedoStack"|"onBeforeRowDragEnd"|"onBeforeRowDragMove"|"onBeforeTaskAdd"|"onBeforeTaskAutoSchedule"|"onBeforeTaskChanged"|"onBeforeTaskDelete"|"onBeforeTaskDisplay"|"onBeforeTaskDrag"|"onBeforeTaskMove"|"onBeforeTaskMultiSelect"|"onBeforeTaskSelected"|"onBeforeTaskUpdate"|"onBeforeUndo"|"onBeforeUndoStack"|"onCircularLinkError"|"onClear"|"onCollapse"|"onColumnResize"|"onColumnResizeEnd"|"onColumnResizeStart"|"onContextMenu"|"onDataProcessorReady"|"onDataRender"|"onDestroy"|"onEmptyClick"|"onError"|"onExpand"|"onGanttLayoutReady"|"onGanttReady"|"onGanttRender"|"onGanttScroll"|"onGridHeaderClick"|"onGridResize"|"onGridResizeEnd"|"onGridResizeStart"|"onLightbox"|"onLightboxButton"|"onLightboxCancel"|"onLightboxChange"|"onLightboxDelete"|"onLightboxSave"|"onLinkClick"|"onLinkDblClick"|"onLinkIdChange"|"onLinkValidation"|"onLoadEnd"|"onLoadStart"|"onMouseMove"|"onMultiSelect"|"onOptionsLoad"|"onParse"|"onQuickInfo"|"onRowDragEnd"|"onRowDragStart"|"onScaleAdjusted"|"onScaleClick"|"onTaskClick"|"onTaskClosed"|"onTaskCreated"|"onTaskDblClick"|"onTaskDrag"|"onTaskIdChange"|"onTaskLoading"|"onTaskMultiSelect"|"onTaskOpened"|"onTaskRowClick"|"onTaskSelected"|"onTaskUnselected"|"onTemplatesReady"; interface GanttTemplates { - /** - * specifies the format of dates that are set by means of API methods. Used to parse incoming dates - * @param date the date which needs formatting - */ - api_date(date: Date): string; /** * specifies the content of start date or end date columns in grid @@ -37,7 +31,7 @@ interface GanttTemplates { drag_link(from: string|number, from_start: boolean, to: string|number, to_start: boolean): string; /** - * specifies the CSS class that will be applied to the link receiver (pop-up circle near the task bar) + * specifies the CSS class that will be applied to the pop-up that appears when a user drags a link * @param from the id of the source task * @param from_start true, if the link is being dragged from the start of the source task, false - if
from the end of the task * @param to the id of the target task( 'null' or 'undefined', if the target task isn't specified yet) @@ -96,6 +90,42 @@ interface GanttTemplates { */ grid_row_class(start: Date, end: Date, task: any): string; + /** + * defines the height of the filled area in the resourceHistogram + * @param start_date start date of the scale cell + * @param end_date end date of the scale cell + * @param resource the resource object + * @param tasks tasks that are assigned to the specified resource and overlap start/end dates of the cell + */ + histogram_cell_allocated(start_date: Date, end_date: Date, resource: any, tasks: any[]): void; + + /** + * specifies the height of the line that defines the available capacity of the resource + * @param start_date start date of the scale cell + * @param end_date end date of the scale cell + * @param resource the resource object + * @param tasks tasks that are assigned to the specified resource and overlap start/end dates of the cell + */ + histogram_cell_capacity(start_date: Date, end_date: Date, resource: any, tasks: any[]): void; + + /** + * defines the CSS class which is applied to a cell of the resource panel + * @param start_date start date of the scale cell + * @param end_date end date of the scale cell + * @param resource the resource object + * @param tasks tasks that are assigned to the specified resource and overlap start/end dates of the cell + */ + histogram_cell_class(start_date: Date, end_date: Date, resource: any, tasks: any[]): void; + + /** + * defines the label inside a cell + * @param start_date start date of the scale cell + * @param end_date end date of the scale cell + * @param resource the resource object + * @param tasks tasks that are assigned to the specified resource and overlap start/end dates of the cell + */ + histogram_cell_label(start_date: Date, end_date: Date, resource: any, tasks: any[]): void; + /** * specifies the CSS class that will be applied to a link * @param link the link object @@ -148,6 +178,24 @@ interface GanttTemplates { */ quick_info_title(start: Date, end: Date, task: any): string; + /** + * defines the CSS class names of cells in the resource timeline cells + * @param start_date start date of the scale cell + * @param end_date end date of the scale cell + * @param resource the resource object + * @param tasks tasks that are assigned to specified resource and overlap start/end dates of the cell + */ + resource_cell_class(start_date: Date, end_date: Date, resource: any, tasks: any[]): string; + + /** + * defines the HTML content of resource timeline cells + * @param start_date start date of the scale cell + * @param end_date end date of the scale cell + * @param resource the resource object + * @param tasks tasks that are assigned to specified resource and overlap start/end dates of the cell + */ + resource_cell_value(start_date: Date, end_date: Date, resource: any, tasks: any[]): string; + /** * specifies the CSS class that will be applied to cells of the time scale of the timeline area * @param date the date of a cell @@ -165,7 +213,7 @@ interface GanttTemplates { * @param item the task object assigned to the row * @param date the date of a cell */ - task_cell_class(item: Date, date: Date): string; + task_cell_class(item: any, date: Date): string; /** * specifies the CSS class that will be applied to task bars @@ -266,14 +314,9 @@ interface GanttTemplates { * @param task the task's object */ lightbox_header(start_date: Date, end_date: Date, task: any): string; - } interface GanttConfigOptions { - /** - * sets the date format for addTask() method to - */ - api_date: string; /** * enables auto scheduling @@ -281,7 +324,7 @@ interface GanttConfigOptions { auto_scheduling: boolean; /** - * allows or forbids creation of links from parent tasks (projects) to their children + * allows or forbids creating links from parent tasks (projects) to their children */ auto_scheduling_descendant_links: boolean; @@ -290,16 +333,36 @@ interface GanttConfigOptions { */ auto_scheduling_initial: boolean; + /** + * defines whether the whole project will be moved (see the details below) + */ + auto_scheduling_move_projects: boolean; + /** * enables the auto scheduling mode, in which tasks will always be rescheduled to the earliest possible date */ auto_scheduling_strict: boolean; + /** + * automatically converts tasks with subtasks to projects and projects without subtasks back to tasks + */ + auto_types: boolean; + /** * enables automatic adjusting of the grid's columns to the grid's width */ autofit: boolean; + /** + * enables autoscrolling while dragging a task or link out of the current browser screen + */ + autoscroll: boolean; + + /** + * defines the speed of autoscrolling (in ms) while dragging a task or link out of the current browser screen + */ + autoscroll_speed: number; + /** * forces the Gantt chart to automatically change its size to show all tasks without scrolling */ @@ -311,10 +374,15 @@ interface GanttConfigOptions { autosize_min_width: number; /** - * enables the dynamic loading in the Gantt chart + * enables dynamic loading in the Gantt chart */ branch_loading: boolean; + /** + * specifies that the task has children that are not yet loaded from the backend + */ + branch_loading_property: string; + /** * stores a collection of buttons resided in the left bottom corner of the lightbox */ @@ -325,6 +393,16 @@ interface GanttConfigOptions { */ buttons_right: any[]; + /** + * changes the name of the property that affects binding of a calendar to a task/group of tasks + */ + calendar_property: string; + + /** + * enables cascade deleting of nested tasks and links + */ + cascade_delete: boolean; + /** * configures the columns of the table */ @@ -380,6 +458,11 @@ interface GanttConfigOptions { */ drag_progress: boolean; + /** + * enables drag and drop of items of the project type + */ + drag_project: boolean; + /** * enables the possibility to resize tasks by drag-and-drop */ @@ -400,6 +483,11 @@ interface GanttConfigOptions { */ editable_property: string; + /** + * an object that contains definitions of inline editors + */ + editor_types: any; + /** * sets the end value of the time scale */ @@ -426,7 +514,7 @@ interface GanttConfigOptions { grid_resizer_column_attribute: string; /** - * sets the maximum width of the grid + * sets the width of the grid */ grid_width: number; @@ -446,15 +534,30 @@ interface GanttConfigOptions { initial_scroll: boolean; /** - * 'says' to preserve the initial grid's width during resizing the columns within + * 'says' to preserve the initial grid's width while resizing columns within */ keep_grid_width: boolean; + /** + * enables keyboard navigation in gantt + */ + keyboard_navigation: boolean; + + /** + * enables keyboard navigation by cells + */ + keyboard_navigation_cells: boolean; + /** * sets the name of the attribute of the task layer's DOM element */ layer_attribute: string; + /** + * specifies the layout object + */ + layout: any; + /** * specifies the lightbox object */ @@ -496,7 +599,7 @@ interface GanttConfigOptions { min_column_width: number; /** - * sets the minimum step (in milliseconds) for task's time values + * Sets the minimum duration (in milliseconds) that can be set for a task during resizing. */ min_duration: number; @@ -521,15 +624,20 @@ interface GanttConfigOptions { open_tree_initially: boolean; /** - * activates the 'branch' mode that allows dragging tasks only within the parent branch + * activates the 'branch' mode that allows reordering tasks within the same nesting level */ - order_branch: boolean; + order_branch: string|boolean; /** - * activates the 'branch' mode that allows dragging tasks within the whole gantt + * activates the 'branch' mode that allows reordering tasks within the whole gantt */ order_branch_free: boolean; + /** + * adds an empty row into the end of the list of tasks to simplify tasks editing via keyboard + */ + placeholder_task: boolean; + /** * preserves the current position of the vertical and horizontal scrolls while re-drawing the gantt chart */ @@ -565,6 +673,26 @@ interface GanttConfigOptions { */ redo: boolean; + /** + * defines a set of working calendars that can be assigned to a specific resource, e.g. a user + */ + resource_calendars: any; + + /** + * defines the property of a task object that stores a resource id associated with resourceGrid/Timeline/Histogram + */ + resource_property: string; + + /** + * tells the resource timeline to render elements and call templates for non-allocated cells + */ + resource_render_empty_cells: boolean; + + /** + * specifies the name of the dataStore connected to the resourceGrid/resourceTimeline/resourceHistogram views + */ + resource_store: string; + /** * sets the id of the virtual root element */ @@ -580,6 +708,11 @@ interface GanttConfigOptions { */ row_height: number; + /** + * switches gantt to the right-to-left mode + */ + rtl: boolean; + /** * sets the height of the time scale and the header of the grid */ @@ -600,6 +733,11 @@ interface GanttConfigOptions { */ scroll_on_click: boolean; + /** + * set the sizes of the vertical (width) and horizontal (height) scrolls + */ + scroll_size: number; + /** * enables selection of tasks in the Gantt chart */ @@ -665,6 +803,11 @@ interface GanttConfigOptions { */ smart_rendering: boolean; + /** + * specifies that only visible part of the time scale is rendered on the screen + */ + smart_scales: boolean; + /** * enables sorting in the table */ @@ -676,7 +819,7 @@ interface GanttConfigOptions { start_date: Date; /** - * sets the start day of weeks + * sets the starting day of the week */ start_on_monday: boolean; @@ -731,12 +874,12 @@ interface GanttConfigOptions { tooltip_hide_timeout: number; /** - * sets the the right (if positive) offset of the tooltip's position + * sets the right (if positive) offset of the tooltip's position */ tooltip_offset_x: number; /** - * sets the the top (if positive) offset of the tooltip's position + * sets the top (if positive) offset of the tooltip's position */ tooltip_offset_y: number; @@ -756,10 +899,15 @@ interface GanttConfigOptions { touch_drag: number|boolean; /** - * enables/disables vibration while moving tasks on touch devices + * returns vibration feedback before/after drag and drop on touch devices */ touch_feedback: boolean; + /** + * defines the duration of vibration feedback before/after drag and drop on touch devices (in milliseconds) + */ + touch_feedback_duration: number; + /** * redefines functions responsible for displaying different types of tasks */ @@ -790,33 +938,33 @@ interface GanttConfigOptions { */ undo_types: any; + /** + * enables WAI-ARIA support to make the component recognizable for screen readers + */ + wai_aria_attributes: boolean; + /** * enables calculating the duration of tasks in working time instead of calendar time */ work_time: boolean; /** - * sets the date format that is used to parse data from the data set + * defines date formats that are used to parse data from a data set and to send data to a server */ xml_date: string; - } interface GanttDateHelpers { add(origin: Date, count: number, unit: string): Date; copy(origin: Date): Date; - date_part(origin: Date): Date; time_part(origin: Date): Date; - day_start(origin: Date): Date; month_start(origin: Date): Date; week_start(origin: Date): Date; year_start(origin: Date): Date; - getISOWeek(origin: Date): number; getUTCISOWeek(origin: Date): number; - date_to_str(format: string): any; str_to_date(format: string): any; convert_to_utc(origin: Date): Date; @@ -828,8 +976,6 @@ interface GanttHotkeys { edit_cancel: number; } -//Gantt.locale - interface GanttLocaleDate { month_full: string[]; month_short: string[]; @@ -867,22 +1013,102 @@ interface GanttLocale { } interface GanttEnterprise { - /** - * Creates a new instance of Gantt - */ getGanttInstance(): GanttStatic; } interface GanttStatic { - templates: GanttTemplates; - config: GanttConfigOptions; - date: GanttDateHelpers; - keys: GanttHotkeys; - skin: string; - version: string; - locale: GanttLocale; + + /** + * redefines the default click behavior for buttons of the Gantt chart + */ $click: any; + /** + * dhtmlx ajax module + */ + ajax: any; + + /** + * the interface of the working calendar object + */ + calendar: any; + + /** + * defines configuration options for dates, scale, controls + */ + config: GanttConfigOptions; + + /** + * stores various constants to reduce the use of magic numbers in the code + */ + constants: any; + + /** + * a set of date formatting methods + */ + date: GanttDateHelpers; + + /** + * a set of flags which describe current environment + */ + env: any; + + /** + * an object that stores various extensions + */ + ext: any; + + /** + * specifies JSON serialization and parsing + */ + json: any; + + /** + * defines the hot keys for the Gantt chart + */ + keys: GanttHotkeys; + + /** + * a locale object (region-specific labels) of the Gantt chart + */ + locale: GanttLocale; + + /** + * specifies serialization and parsing in the XML format of dhtmlxGantt 1.0 + */ + oldxml: any; + + /** + * returns the current skin of the Gantt chart + */ + skin: string; + + /** + * returns objects of the available skins + */ + skins: any; + + /** + * defines formatting templates for dates, titles, tooltips in the Gantt chart + */ + templates: GanttTemplates; + + /** + * returns the version of dhtmlxGantt + */ + version: string; + + /** + * specifies XML serialization and parsing + */ + xml: any; + + /** + * adds a calendar into Gantt + * @param calendar an object with configuration of the calendar + */ + addCalendar(calendar: any): number; + /** * adds a new dependency link * @param link the link object @@ -890,10 +1116,10 @@ interface GanttStatic { addLink(link: any): string|number; /** - * displayes an additional layer with custom elements for a link in the timeline area - * @param func a render function or a config object + * displays an additional layer with custom elements for a link in the timeline area + * @param func a render function or a config object */ - addLinkLayer(func: GanttCallback|any): string; + addLinkLayer(func: any): string; /** * adds a marker to the timeline area @@ -901,25 +1127,33 @@ interface GanttStatic { */ addMarker(marker: any): string; + /** + * adds a new keyboard shortcut + * @param shortcut the key name or the name of keys combination for a shortcut (
shortcut syntax) + * @param handler the handler of the shortcut call + * @param scope the name of the context element to attach the handler function to (list of scopes) + */ + addShortcut(shortcut: string, handler: GanttCallback, scope: string): void; + /** * adds a new task * @param task the task object * @param parent the parent's id - * @param index optional, the position the task will be added into (0 or greater) + * @param index optional, optional, the position the task will be added into (0 or greater) */ addTask(task: any, parent: string, index?: number): string|number; /** - * displayes an additional layer with custom elements for a task in the timeline area - * @param func a render function or a config object + * displays an additional layer with custom elements for a task in the timeline area + * @param func a render function or a config object */ - addTaskLayer(func: GanttCallback|any): string; + addTaskLayer(func: any): string; /** * calls an alert message box * @param config the alert box's configuration */ - alert(config: any): void; + alert(config: any): HTMLElement; /** * if the specified expression is false, an errorMessage is shown in the red popup at the top right corner of the screen @@ -937,8 +1171,9 @@ interface GanttStatic { /** * recalculates the schedule of the project + * @param taskId optional, optional, the task id */ - autoSchedule(): void; + autoSchedule(taskId?: string|number): void; /** * updates multiple tasks/links at once @@ -960,6 +1195,12 @@ interface GanttStatic { */ calculateDuration(start: Date, end: Date): number; + /** + * calculates the duration of a task + * @param config the configuration object of a time span + */ + calculateDuration(config: any): number; + /** * calculates the end date of a task * @param start the date when a task is scheduled to begin @@ -968,6 +1209,12 @@ interface GanttStatic { */ calculateEndDate(start: Date, duration: number, unit: string): Date; + /** + * calculates the end date of a task + * @param config the configuration object of a time span + */ + calculateEndDate(config: any): Date; + /** * calculates the level of a task * @param task the task's object @@ -982,10 +1229,10 @@ interface GanttStatic { callEvent(name: string, params: any[]): boolean; /** - * changes the name of the lighbox's structure defined for of the task - * @param id the task id + * repaints the lighbox for the task according to its type + * @param type the task type */ - changeLightboxType(id: string|number): void; + changeLightboxType(type: string): void; /** * changes the link's id @@ -1008,10 +1255,20 @@ interface GanttStatic { checkEvent(name: GanttEventName): boolean; /** - * removes all tasks from the Gantt chart + * removes all tasks and additional elements (including markers) from the Gantt chart */ clearAll(): void; + /** + * clears the stack of stored redo commands + */ + clearRedoStack(): void; + + /** + * clears the stack of stored undo commands + */ + clearUndoStack(): void; + /** * closes the branch with the specified id * @param id the branch id @@ -1023,11 +1280,17 @@ interface GanttStatic { */ collapse(): void; + /** + * returns the index of the column by the date + * @param date a date object + */ + columnIndexByDate(date: Date): void; + /** * calls a confirm message box * @param config the confirm box's configuration */ - confirm(config: any): void; + confirm(config: any): HTMLElement; /** * creates a deep copy of provided object @@ -1041,11 +1304,23 @@ interface GanttStatic { */ correctTaskWorkTime(task: any): void; + /** + * creates a working calendar + * @param parentCalendar optional, (optional) an existing calendar that is used for creating a new one on the base of it + */ + createCalendar(parentCalendar?: any): void; + + /** + * creates a datastore according to the provided configuration + * @param config a configuration object of a datastore + */ + createDatastore(config: any): void; + /** * adds a new task and opens the lightbox to confirm * @param task the task object * @param parent the parent's id - * @param index optional, the position the task will be added into (0 or greater) + * @param index optional, optional, the position the task will be added into (0 or greater) */ createTask(task: any, parent: string, index?: number): string|number; @@ -1056,7 +1331,7 @@ interface GanttStatic { dataProcessor(url: string): void; /** - * returns the date of the specified horizontal position in the chart area + * gets the date of the specified horizontal position in the chart area * @param pos the relative horizontal position you want to know the date of */ dateFromPos(pos: number): Date; @@ -1067,6 +1342,12 @@ interface GanttStatic { */ defined(task: any): boolean; + /** + * deletes a task calendar by its id + * @param id the id of the calendar + */ + deleteCalendar(id: string|number): void; + /** * deletes the specified dependency link * @param id the dependency link's id @@ -1083,7 +1364,12 @@ interface GanttStatic { * deletes the specified task * @param id the task's id */ - deleteTask(id: string): void; + deleteTask(id: string|number): void; + + /** + * destroys the gantt instance + */ + destructor(): void; /** * detaches all events from dhtmlxGantt (both custom and inner) @@ -1096,6 +1382,14 @@ interface GanttStatic { */ detachEvent(id: string): void; + /** + * iterates over all parent tasks of the specified task in the Gantt chart + * @param code a function that will iterate over tasks. Takes a task object as a parameter + * @param startTask the id of the item the parent tasks of which should be iterated over + * @param master optional, the object, that 'this' will refer to + */ + eachParent(code: GanttCallback, startTask: string|number, master?: any): void; + /** * iterates over all selected tasks in the Gantt chart * @param code a function that will iterate over tasks. Takes a task id as a parameter @@ -1103,10 +1397,10 @@ interface GanttStatic { eachSelectedTask(code: GanttCallback): void; /** - * iterates over specified tasks in the Gantt chart + * iterates over all child tasks in the Gantt chart * @param code a function that will iterate over tasks. Takes a task object as a parameter - * @param parent the parent id. If specified, the function will iterate over childs of the
specified parent - * @param master the object, that 'this' will refer to + * @param parent optional, the parent id. If specified, the function will iterate over childs of the
specified parent + * @param master optional, the object, that 'this' will refer to */ eachTask(code: GanttCallback, parent?: string|number, master?: any): void; @@ -1115,21 +1409,81 @@ interface GanttStatic { * @param node the HTML node or its id * @param event the name of an HTML event (without the 'on' prefix) * @param handler the event handler - * @param master an object that the this keyword refers to + * @param options optional, optional, the value of either the useCapture or options parameter. Read details */ - event(node: HTMLElement|string, event: string, handler: GanttCallback, master?: any): string; + event(node: HTMLElement|string, event: string, handler: GanttCallback, options?: any): void; /** * removes an event handler from an HTML element - * @param id the id of an event handler + * @param node the HTML node or its id + * @param event the name of an HTML event (without the 'on' prefix) + * @param handler the event handler + * @param options optional, optional, the value of either the useCapture or options parameter. Read details */ - eventRemove(id: string): void; + eventRemove(node: HTMLElement|string, event: string, handler: GanttCallback, options?: any): void; /** * expands gantt to the full screen mode */ expand(): void; + /** + * exports data from the Gantt chart to an Excel document + * @param _export_ an object with export settings (see the details) + */ + exportToExcel(_export_: any): void; + + /** + * exports data from the Gantt chart to an iCal string + * @param _export_ an object with export settings (see the details) + */ + exportToICal(_export_: any): void; + + /** + * exports the structure and data of a Gantt chart into a JSON object + * @param config an object with Gantt configuration + */ + exportToJSON(config: any): void; + + /** + * exports data from the Gantt chart to MS Project + * @param _export_ an object with export settings (see the details) + */ + exportToMSProject(_export_: any): void; + + /** + * exports a Gantt chart into the PDF format + * @param _export_ an object with export settings (see the details) + */ + exportToPDF(_export_: any): void; + + /** + * exports a Gantt chart into the PNG format + * @param _export_ an object with export settings (see the details) + */ + exportToPNG(_export_: any): void; + + /** + * returns all dependency loops in the chart + */ + findCycles(): any[]; + + /** + * sets focus on the gantt + */ + focus(): void; + + /** + * gets worktime calendar by id + * @param calendarId the id of the global calendar or "global" + */ + getCalendar(calendarId: string|number): any; + + /** + * gets all the calendars added into Gantt + */ + getCalendars(): any[]; + /** * returns the 1st-level child tasks of the specified parent branch * @param id the parent branch's id @@ -1143,10 +1497,34 @@ interface GanttStatic { getClosestWorkTime(config: any): Date; /** - * get the index of a task in the tree + * returns the index of the column by its name + * @param name the name of the column + */ + getColumnIndex(name: string): number; + + /** + * returns all tasks and links that a task is connected with + * @param id optional, optional, the id of a task + */ + getConnectedGroup(id?: string|number): any; + + /** + * returns the configuration object of a datastore + * @param name the name of the datastore + */ + getDatastore(name: string): any; + + /** + * returns the free slack of a task + * @param task the object of a task + */ + getFreeSlack(task: any): number; + + /** + * gets the index of a task in the tree * @param id the task id */ - getGlobalTaskIndex(id: string|number): void; + getGlobalTaskIndex(id: string|number): number; /** * gets the configuration object of a column @@ -1251,10 +1629,21 @@ interface GanttStatic { getPrevSibling(id: string|number): string|number; /** - * returns the stack of stored redo commands + * returns the stack of stored redo user actions */ getRedoStack(): any[]; + /** + * returns all tasks assigned to the resource + * @param resourceId the id of the resource + */ + getResourceAssignments(resourceId: string|number): any[]; + + /** + * returns the configuration of the time scale + */ + getScale(): any; + /** * returns the scroll position */ @@ -1263,13 +1652,20 @@ interface GanttStatic { /** * returns the id of the selected task */ - getSelectedId(): string|number; + getSelectedId(): string; /** * returns an array of the currently selected tasks */ getSelectedTasks(): any[]; + /** + * gets a key navigation shortcut handler + * @param shortcut the key name or the name of keys combination for a shortcut (shortcut syntax) + * @param scope the name of the context element to attach the handler function to (list of scopes) + */ + getShortcutHandler(shortcut: string, scope: string): GanttCallback; + /** * returns siblings of the specified task (including itself) * @param id the task id @@ -1290,30 +1686,66 @@ interface GanttStatic { /** * calculates the combined start/end dates of tasks nested in a project or another task - * @param task_id the task's id, api/gantt_root_id_config.md will be used if not specified + * @param task_id optional, the task's id, api/gantt_root_id_config.md will be used if not specified */ getSubtaskDates(task_id?: string|number): any; + /** + * calculates the combined duration of tasks nested in a project or another task. + * @param task_id optional, the task's id, api/gantt_root_id_config.md will be used if not specified + */ + getSubtaskDuration(task_id?: string|number): number; + /** * returns the task object * @param id the task id */ getTask(id: string|number): any; + /** + * finds a task by the specified criteria + * @param propertyName the name of the property to match, or a filter function + * @param propertyValue the property value + */ + getTaskBy(propertyName: string|GanttCallback, propertyValue: any): any[]; + + /** + * returns a task by its index + * @param index the task index in the tree (zero-based numbering) + */ + getTaskByIndex(index: number): any; + /** * returns a collection of tasks which occur during the specified period - * @param from the start date of the period - * @param to the end date of the period + * @param from optional, the start date of the period + * @param to optional, the end date of the period */ getTaskByTime(from?: Date, to?: Date): any[]; + /** + * returns a task by its WBS code + * @param code the WBS code of the task + */ + getTaskByWBSCode(code: string): any; + + /** + * gets a calendar assigned to the specified task (a task level calendar) + * @param task the object of a task + */ + getTaskCalendar(task: any): any; + /** * gets the number of tasks that are currently loaded in the gantt */ getTaskCount(): number; /** - * get the index of a task in the branch + * returns the visible height of a task + */ + getTaskHeight(): number; + + /** + * gets the index of a task in the branch * @param id the task id */ getTaskIndex(id: string|number): number; @@ -1345,7 +1777,19 @@ interface GanttStatic { getTaskTop(id: number|string): number; /** - * returns the stack of stored undo commands + * returns the type of a task + * @param task the task object + */ + getTaskType(task: any): string; + + /** + * returns the total slack of a task + * @param task the object of a task + */ + getTotalSlack(task: any): number; + + /** + * returns the stack of stored undo user actions */ getUndoStack(): any[]; @@ -1354,6 +1798,12 @@ interface GanttStatic { */ getVisibleTaskCount(): number; + /** + * returns the WBS code (the outline number) of a task + * @param task the object of a task + */ + getWBSCode(task: any): string; + /** * returns the working hours of the specified date * @param date a date to check @@ -1374,7 +1824,7 @@ interface GanttStatic { /** * hides the lightbox modal overlay that blocks interactions with the remaining screen - * @param box an element to hide + * @param box optional, an element to hide */ hideCover(box?: HTMLElement): void; @@ -1388,11 +1838,23 @@ interface GanttStatic { */ hideQuickInfo(): void; + /** + * converts an Excel file to JSON + * @param config an object with configuration properties of an imported file + */ + importFromExcel(config: any): void; + + /** + * converts an XML or MPP MS Project file to JSON + * @param config an object with configuration properties of an imported file + */ + importFromMSProject(config: any): void; + /** * constructor. Initializes a dhtmlxGantt object * @param container an HTML container ( or its id) where a dhtmlxGantt object will be initialized - * @param from the start value of the time scale (X–Axis) - * @param to the end value of the time scale (X–Axis) + * @param from optional, the start value of the time scale (X–Axis) + * @param to optional, the end value of the time scale (X–Axis) */ init(container: string|HTMLElement, from?: Date, to?: Date): void; @@ -1403,6 +1865,12 @@ interface GanttStatic { */ isChildOf(childId: string|number, parentId: string|number): boolean; + /** + * checks whether the link is circular + * @param link the link object + */ + isCircularLink(link: any): boolean; + /** * checks whether the specified link is critical * @param link the link's object @@ -1427,12 +1895,30 @@ interface GanttStatic { */ isLinkExists(id: string|number): boolean; + /** + * checks whether the specified task or link is read-only + * @param id the task/link id + */ + isReadonly(id: string|number): boolean; + /** * checks whether the specified task is currently selected * @param task the task's id */ isSelectedTask(task: string|number): boolean; + /** + * checks whether the specified task is split + * @param task the object of a task + */ + isSplitTask(task: any): boolean; + + /** + * checks whether the specified task is summary + * @param task the object of a task + */ + isSummaryTask(task: any): boolean; + /** * checks whether the specified task exists * @param id the task id @@ -1458,11 +1944,17 @@ interface GanttStatic { */ isWorkTime(date: Date, timeunit: string): boolean; + /** + * checks whether the specified date is working or not + * @param config the configuration object of a time span + */ + isWorkTime(config: any): boolean; + /** * loads data to the gantt from an external data source * @param url the server-side url (may be a static file or a server side script that outputs data) - * @param type ('json', 'xml', 'oldxml') the data type. The default value - 'json' - * @param callback the callback function + * @param type optional, ('json', 'xml', 'oldxml') the data type. The default value - 'json' + * @param callback optional, the callback function */ load(url: string, type?: string, callback?: GanttCallback): void; @@ -1476,7 +1968,7 @@ interface GanttStatic { * calls a message box of the specified type * @param config the message box's configuration */ - message(config: any): void; + message(config: any): HTMLElement; /** * adds properties of the 'source' object into the 'target' object @@ -1488,15 +1980,15 @@ interface GanttStatic { /** * calls a modalbox - * @param config the modal box' configuration + * @param config the modal box's configuration */ - modalbox(config: any): void; + modalbox(config: any): HTMLElement; /** * moves a task to a new position * @param sid the id of the task to move * @param tindex the index of the position that the task will be moved to
(the index within a branch) - * @param parent the parent id. If specified, the tindex will refer to the index in the
'parent' branch + * @param parent optional, the parent id. If specified, the tindex will refer to the index in the
'parent' branch */ moveTask(sid: string|number, tindex: number, parent?: string|number): void; @@ -1509,9 +2001,9 @@ interface GanttStatic { /** * loads data from a client-side resource * @param url a string or object which represents data - * @param type ( 'json', 'xml' ) the data type. The default value - 'json' + * @param type optional, optional, ('json', 'xml') the data type. The default value - 'json' */ - parse(url: string|any, type?: string): void; + parse(url: any, type?: string): void; /** * gets the relative horizontal position of the specified date in the chart area @@ -1538,8 +2030,9 @@ interface GanttStatic { /** * refreshes the task and its related links * @param id the task id + * @param refresh_links optional, optional, defines whether links related to the task should be refreshed, true by default */ - refreshTask(id: string|number): void; + refreshTask(id: string|number, refresh_links?: boolean): void; /** * removes the specified layer related to a link @@ -1547,6 +2040,13 @@ interface GanttStatic { */ removeLinkLayer(layerId: string): void; + /** + * removes a keyboard shortcut + * @param shortcut the key name or the name of keys combination for a shortcut (shortcut syntax) + * @param scope the element to which the shortcut is attached (list of scopes) + */ + removeShortcut(shortcut: string, scope: any): void; + /** * removes the specified layer related to a task * @param layerId a DOM element that will be displayed in the layer @@ -1569,7 +2069,7 @@ interface GanttStatic { resetLightbox(): void; /** - * re-calculates the duration of a project task depending on dates its childs + * re-calculates the duration of a project task depending on the dates of its children * @param task the task's object */ resetProjectDates(task: any): void; @@ -1598,8 +2098,8 @@ interface GanttStatic { /** * scrolls the Gantt container to the specified position - * @param x the value of the horizontal scroll or 'null' (to not display the horizontal scroll) - * @param y the value of the vertical scroll or 'null' (to not display the vertical scroll) + * @param x value of horizontal scroll or 'null' (if the scroll position shouldn't be changed) + * @param y value of vertical scroll or 'null' (if the scroll position shouldn't be changed) */ scrollTo(x: number, y: number): void; @@ -1611,16 +2111,16 @@ interface GanttStatic { /** * serializes the data into JSON or XML format - * @param type the format that the data will be serialized into.
Possible values: 'json' (default ), 'xml'. + * @param type optional, the format that the data will be serialized into.
Possible values: 'json' (default ), 'xml'. */ serialize(type?: string): void; /** * returns a list of options * @param list_name the name of a list - * @param options an array of options + * @param options optional, an array of options */ - serverList(list_name: string, options?: any[]): void; + serverList(list_name: string, options?: any[]): any[]; /** * set the parent for a task @@ -1642,7 +2142,7 @@ interface GanttStatic { /** * shows the lightbox modal overlay that blocks interactions with the remaining screen - * @param box an element to hide + * @param box optional, an element to hide */ showCover(box?: HTMLElement): void; @@ -1671,11 +2171,11 @@ interface GanttStatic { showTask(id: string|number): void; /** - * sorts the tasks in the grid - * @param field the name of the column that the grid will be sorted by or a custom
sorting function - * @param desc specifies the sorting direction: true - descending sort and false - ascending
sort. By default, false - * @param parent the id of the parent task. Specify the parameter if you want to sort tasks only in
the branch of the specified parent. - * @param silent specifies whether rendering shall be invoked after reordering items + * sorts tasks in the grid + * @param field the name of the column that the grid will be sorted by or a custom sorting function + * @param desc optional, specifies the sorting direction: true - descending sort and false - ascending
sort. By default, false + * @param parent optional, the id of the parent task. Specify the parameter if you want to sort tasks only in the branch of the specified parent. + * @param silent optional, specifies whether rendering should be invoked after reordering items */ sort(field: string|GanttCallback, desc?: boolean, parent?: string|number, silent?: boolean): void; @@ -1697,8 +2197,15 @@ interface GanttStatic { /** * removes selection from the selected task + * @param id optional, optional, the id of the task to remove selection from, see details */ - unselectTask(): void; + unselectTask(id?: string|number): void; + + /** + * unsets a working time in the Gantt Chart + * @param config the configuration object of a time span + */ + unsetWorkTime(config: any): void; /** * updates the specified collection with new options @@ -1724,11 +2231,8 @@ interface GanttStatic { * @param id the task id */ updateTask(id: string): void; - } - - declare var gantt: GanttStatic; declare var Gantt: GanttEnterprise; @@ -1737,5 +2241,5 @@ declare module "gantt" { } declare module "Gantt" { - export = GanttEnterprise; -} + export = Gantt; +} \ No newline at end of file diff --git a/types/dialogflow/index.d.ts b/types/dialogflow/index.d.ts index c421c47f68..8329021bb8 100644 --- a/types/dialogflow/index.d.ts +++ b/types/dialogflow/index.d.ts @@ -23,12 +23,7 @@ export namespace v2 { searchAgents( request: SearchAgentRequest, options?: gax.CallOptions, - cb?: ( - err: Error, - agents: Agent[], - arg3: any, - response: any - ) => void + cb?: (err: Error, agents: Agent[], arg3: any, response: any) => void ): Promise; searchAgentsStream( request: SearchAgentRequest, @@ -213,7 +208,28 @@ export namespace v2 { getProjectId(): Promise; getProjectId(callback?: (error: Error, id: string) => string): void; - // TODO: add Session Entity Types service methods + // TODO: add streaming calls + + listSessionEntityTypes( + request: ListSessionEntityTypesRequest, + options?: gax.CallOptions + ): Promise<[SessionEntityType[]]>; + getSessionEntityType( + request: GetSessionEntityTypeRequest, + options?: gax.CallOptions + ): Promise<[SessionEntityType]>; + createSessionEntityType( + request: CreateSessionEntityTypeRequest, + options?: gax.CallOptions + ): Promise<[SessionEntityType]>; + updateSessionEntityType( + request: UpdateSessionEntityTypeRequest, + options?: gax.CallOptions + ): Promise<[SessionEntityType]>; + deleteSessionEntityType( + request: DeleteSessionEntityTypeRequest, + options?: gax.CallOptions + ): Promise; } class SessionsClient { @@ -504,6 +520,30 @@ export interface DeleteEntityTypeRequest { name: string; } +export interface ListSessionEntityTypesRequest { + parent: string; + pageSize?: number; +} + +export interface GetSessionEntityTypeRequest { + name: string; +} + +export interface CreateSessionEntityTypeRequest { + parent: string; + sessionEntityType: SessionEntityType; +} + +export interface UpdateSessionEntityTypeRequest { + sessionEntityType: SessionEntityType; + /** @link https://github.com/google/protobuf/blob/master/src/google/protobuf/field_mask.proto */ + updateMask: any; +} + +export interface DeleteSessionEntityTypeRequest { + name: string; +} + export interface ListIntentsRequest { parent: string; languageCode?: string; diff --git a/types/dockerode/index.d.ts b/types/dockerode/index.d.ts index bab3ee6f2b..cd06bc7ebb 100644 --- a/types/dockerode/index.d.ts +++ b/types/dockerode/index.d.ts @@ -7,6 +7,7 @@ // Marius Meisenzahl // Rob Moran // Cameron Diver +// Pascal Sthamer // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -15,8 +16,16 @@ import * as stream from 'stream'; import * as events from 'events'; +// The modem parameter is an instance of docker-modem, which is missing type declarations. +// https://github.com/apocas/docker-modem + declare namespace Dockerode { - interface Container { + class Container { + constructor(modem: any, id: string); + + modem: any; + id: string; + inspect(options: {}, callback: Callback): void; inspect(callback: Callback): void; inspect(options?: {}): Promise; @@ -100,18 +109,20 @@ declare namespace Dockerode { logs(callback: Callback): void; logs(options?: ContainerLogsOptions): Promise; - stats(options: {}, callback: Callback): void; - stats(callback: Callback): void; - stats(options?: {}): Promise; + stats(options: {}, callback: Callback): void; + stats(callback: Callback): void; + stats(options?: {}): Promise; - attach(options: {}, callback: Callback): void; - attach(options: {}): Promise; - - modem: any; - id?: string; + attach(options: {}, callback: Callback): void; + attach(options: {}): Promise; } - interface Image { + class Image { + constructor(modem: any, name: string); + + modem: any; + id: string; + inspect(callback: Callback): void; inspect(): Promise; @@ -132,24 +143,28 @@ declare namespace Dockerode { remove(options: {}, callback: Callback): void; remove(callback: Callback): void; remove(options?: {}): Promise; - - modem: any; - id?: string; } - interface Volume { + class Volume { + constructor(modem: any, name: string); + + modem: any; + name: string; + inspect(callback: Callback): void; inspect(): Promise; remove(options: {}, callback: Callback): void; remove(callback: Callback): void; remove(options?: {}): Promise; - - modem: any; - name?: string; } - interface Service { + class Service { + constructor(modem: any, id: string); + + modem: any; + id: string; + inspect(callback: Callback): void; inspect(): Promise; @@ -159,20 +174,24 @@ declare namespace Dockerode { update(options: {}, callback: Callback): void; update(options: {}): Promise; - - modem: any; - id?: string; } - interface Task { + class Task { + constructor(modem: any, id: string); + + modem: any; + id: string; + inspect(callback: Callback): void; inspect(): Promise; - - modem: any; - id?: string; } - interface Node { + class Node { + constructor(modem: any, id: string); + + modem: any; + id: string; + inspect(callback: Callback): void; inspect(): Promise; @@ -183,12 +202,11 @@ declare namespace Dockerode { remove(options: {}, callback: Callback): void; remove(callback: Callback): void; remove(options?: {}): Promise; - - modem: any; - id?: string; } - interface Plugin { + class Plugin { + constructor(modem: any, name: string, remote?: any); + modem: any; name: string; remote: any; @@ -227,7 +245,12 @@ declare namespace Dockerode { upgrade(auth: any, options?: {}): Promise; } - interface Secret { + class Secret { + constructor(modem: any, id: string); + + modem: any; + id: string; + inspect(callback: Callback): void; inspect(): Promise; @@ -238,12 +261,14 @@ declare namespace Dockerode { remove(options: {}, callback: Callback): void; remove(callback: Callback): void; remove(options?: {}): Promise; - - modem: any; - id?: string; } - interface Network { + class Network { + constructor(modem: any, id: string); + + modem: any; + id: string; + inspect(callback: Callback): void; inspect(): Promise; @@ -258,12 +283,14 @@ declare namespace Dockerode { disconnect(options: {}, callback: Callback): void; disconnect(callback: Callback): void; disconnect(options?: {}): Promise; - - modem: any; - id?: string; } - interface Exec { + class Exec { + constructor(modem: any, id: string); + + modem: any; + id: string; + inspect(callback: Callback): void; inspect(): Promise; @@ -272,9 +299,6 @@ declare namespace Dockerode { resize(options: {}, callback: Callback): void; resize(options: {}): Promise; - - modem: any; - id?: string; } interface ImageInfo { @@ -446,20 +470,99 @@ declare namespace Dockerode { GlobalIPv6Address: string; GlobalIPv6PrefixLen: number; MacAddress: string; - } + }; }; Node?: { - ID: string; - IP: string; - Addr: string; - Name: string; - Cpus: number; - Memory: number; - Labels: any; - } + ID: string; + IP: string; + Addr: string; + Name: string; + Cpus: number; + Memory: number; + Labels: any; + }; }; } + interface NetworkStats { + [name: string]: { + rx_bytes: number; + rx_dropped: number; + rx_errors: number; + rx_packets: number; + tx_bytes: number; + tx_dropped: number; + tx_errors: number; + tx_packets: number; + }; + } + + interface CPUStats { + cpu_usage: { + percpu_usage: number[]; + usage_in_usermode: number; + total_usage: number; + usage_in_kernelmode: number; + }; + system_cpu_usage: number; + online_cpus: number; + throttling_data: { + periods: number; + throttled_periods: number; + throttled_time: number; + }; + } + + interface MemoryStats { + stats: { + total_pgmajfault: number; + cache: number; + mapped_file: number; + total_inactive_file: number; + pgpgout: number; + rss: number; + total_mapped_file: number; + writeback: number; + unevictable: number; + pgpgin: number; + total_unevictable: number; + pgmajfault: number; + total_rss: number; + total_rss_huge: number; + total_writeback: number; + total_inactive_anon: number; + rss_huge: number; + hierarchical_memory_limit: number; + total_pgfault: number; + total_active_file: number; + active_anon: number; + total_active_anon: number; + total_pgpgout: number; + total_cache: number; + inactive_anon: number; + active_file: number; + pgfault: number; + inactive_file: number; + total_pgpgin: number; + }; + max_usage: number; + usage: number; + failcnt: number; + limit: number; + } + + interface ContainerStats { + read: string; + pid_stats: { + current: number; + }; + networks: NetworkStats; + memory_stats: MemoryStats; + blkio_stats: {}; + cpu_stats: CPUStats; + precpu_stats: CPUStats; + } + interface HostConfig { AutoRemove: boolean; Binds: string[]; @@ -652,13 +755,45 @@ declare namespace Dockerode { GlobalIPv6Address?: string; GlobalIPV6PrefixLen?: number; MacAddress?: string; - DriverOpts?: {[key: string]: string}; + DriverOpts?: { [key: string]: string }; } interface EndpointsConfig { [key: string]: EndpointSettings; } + type MountType = + | "bind" + | "volume" + | "tmpfs"; + + type MountConsistency = + | "default" + | "consistent" + | "cached" + | "delegated"; + + type MountPropagation = + | "private" + | "rprivate" + | "shared" + | "rshared" + | "slave" + | "rslave"; + + interface MountSettings { + Target: string; + Source: string; + Type: MountType; + ReadOnly ?: boolean; + Consistency ?: MountConsistency; + BindOptions ?: { + Propagation: MountPropagation; + }; + } + + type MountConfig = MountSettings[]; + interface ContainerCreateOptions { name?: string; Hostname?: string; @@ -715,6 +850,7 @@ declare namespace Dockerode { DnsSearch?: string[]; ExtraHosts?: any; VolumesFrom?: string[]; + Mounts?: MountConfig; CapAdd?: string[]; CapDrop?: string[]; GroupAdd?: string[]; @@ -894,8 +1030,8 @@ declare namespace Dockerode { } interface ImageBuildContext { - context: string; - src: string[]; + context: string; + src: string[]; } interface DockerVersion { @@ -906,7 +1042,7 @@ declare namespace Dockerode { Details: { ApiVersion: string; Arch: string; - BuilTime: Date; + BuildTime: Date; Experimental: string; GitCommit: string; GoVersion: string; diff --git a/types/dynatrace/dynatrace-tests.ts b/types/dynatrace/dynatrace-tests.ts new file mode 100644 index 0000000000..027b924cf9 --- /dev/null +++ b/types/dynatrace/dynatrace-tests.ts @@ -0,0 +1,88 @@ +function customActions() { + const actionId = dynaTrace.enterAction("my custom action", "click"); + dynaTrace.leaveAction(actionId); +} + +function customVisit() { + dynaTrace.tagVisit("My Custom Visit"); + /** after some code execution we can end the visit early */ + dynaTrace.endVisit(); +} + +function signal() { + dynaTrace.signalLoadStart(); + dynaTrace.signalLoadEnd(); + dynaTrace.signalOnLoadStart(); + dynaTrace.signalOnLoadEnd(); + + dynaTrace.sendSignal(false, false, true); +} + +function load() { + dynaTrace.setLoadEndManually(); + dynaTrace.incrementOnLoadEndMarkers(); +} + +function automaticDetection() { + dynaTrace.setAutomaticActionDetection(false); +} + +function reporting() { + dynaTrace.reportError(" Custom error"); + const actionId = dynaTrace.enterAction("second action", "keypress"); + dynaTrace.reportError("Second custom error", actionId); + + dynaTrace.reportEvent("My Event"); + dynaTrace.reportString("My Key", "Custom value"); + dynaTrace.reportValue("Value Key", 2); + dynaTrace.reportWarning("Warning"); +} + +function thirdParty() { + const url = "http://somescript.com"; + dynaTrace.startThirdParty("s", url); + dynaTrace.stopThirdParty(url, true, Date.now() - 1000, Date.now()); +} + +function listener() { + const clickListener = (key: string) => ({}); + dynaTrace.addPageLeavingListener(clickListener); +} + +function streaming() { + dynaTrace.addStreamingNode( + "http://youtube.com", + 120, + true, + false, + 120, + 30, + 10, + 5, + "_info_" + ); +} + +function userInput() { + const userInput = dynaTrace.beginUserInput("", "click", "RETURN", 23); + dynaTrace.endUserInput(userInput); +} + +function Xhr() { + const enterActionId = dynaTrace.enterXhrAction( + "Angular Http request", + 0, + false + ); + dynaTrace.enterXhrCallback(enterActionId); + dynaTrace.leaveXhrCallback(enterActionId); + dynaTrace.leaveXhrAction(enterActionId); +} + +function appVersion() { + dynaTrace.setAppVersion("1.1.1"); +} + +function metadata() { + dynaTrace.setMetaData("some metadata", "value"); +} diff --git a/types/dynatrace/index.d.ts b/types/dynatrace/index.d.ts new file mode 100644 index 0000000000..5627e6b1db --- /dev/null +++ b/types/dynatrace/index.d.ts @@ -0,0 +1,234 @@ +// Type definitions for dynatrace 1.0 +// Project: https://www.dynatrace.com/ +// Definitions by: Alvaro Cruz +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +interface dynaTrace { + /** + * @description disable automatic detection + * Use in conjuction with enterAction + * @example + * dynaTrace.setAutomaticActionDetection(false); + * dynaTrace.enterAction('action message', 'select', null, null); + */ + setAutomaticActionDetection(on: boolean): void; + /** + * @description capture load event manually. + * followed by a signalLoadEnd to complete the capture. + */ + setLoadEndManually(): void; + /** + * @description Signal load start. If load start can be determined more accurately + * than the automatic detection, this function can be used. + */ + signalLoadStart(): void; + /** + * @description Signals that the page has finished loading + */ + signalLoadEnd(): void; + /** + * @description Force signal sending to make certain that actions aren't lost. + * @param forceSync - Force synchronous sending of signal (if false, it'll be sent asynchronously) + * @param sendPreview - Force sending of preview signals which haven't been closed yet. + * @param killUnfinished - Kills unfinished actions and sends them immediately. Handle with care, actions might be inaccurate. + */ + sendSignal( + forceSync: boolean, + sendPreview: boolean, + killUnfinished: boolean + ): void; + /** + * @description parentAction: optional id of parent action. + * - if parameter is not passed => appended to currently running action + * - if a number is passed => action is added as subaction to action with given id + * - if false => new root action is started. + * The function returns an internal tracking object that represents the action that was started. + * This tracking object must be passed to dynaTrace.leaveAction(). + * @param name - name of the action + * @param type + * @param startTime - time in milliseconds. if null, current time is used. + * @param parentAction optional id of parent action. if parameter is not passed=> appended to + * currently running action, if false => root action, if a number is passed, action is added + * as subaction to action with given id. + * @returns id of created action + */ + enterAction( + name: string, + type: string, + time?: number, + parentAction?: number | boolean + ): number; + /** + * @description stops the action that is represented by the given tracking object. + * @param actionId - id of action to leave. must be the value returned by enterAction + * @param time - end time in milliseconds + * @param startTime - optional start time in milliseconds (necessary if start time should be modified) + */ + leaveAction(actionId: number, time?: number, startTime?: number): void; + /** + * @description Reports an error message + * @param parentAction - parent action id. if not passed or null, error is added to current action + */ + reportError(error: string | Error, parentAction?: number): void; + /** + * @description Reports a warning message + * @param parentAction - parent action id. if not passed or null, error is added to current action + */ + reportWarning(warning: string, parentAction?: number): void; + /** + * @description Reports an event + * @param parentAction - parent action id. if not passed or null, error is added to current action + */ + reportEvent(msg: string, parentAction?: number): void; + /** + * @description Reports a key value pair to the server. The data can e.g. be used to create charts. + */ + reportValue(key: string, value: number): void; + /** + * @description Reports a key value pair to the server. The data can e.g. be used to create charts. + * The difference to the reportValue function is that here the value is a string. + */ + reportString(key: string, value: string): void; + /** + * @description The JavaScript ADK enables you to tag your visits with any value you want. + * Use tagVisit(visitName) to tag the current visit with the specified value + */ + tagVisit(visitName: string): void; + /** + * @description Indicates start of a third party resource + * @param type - i = image, s = script, c = custom + */ + startThirdParty(type: "i" | "s" | "c", url: string): void; + /** + * @description Indicates stop of a third party resource + * @param url - Complete URL of resource (must match URL provided in startThirdParty). + * @param success - True if the resource was loaded successfully, false if not. + * @param start - Absolute start time in milliseconds. When parameter is not passed or <= 0, + * time of startThirdParty call is used. + * @param stop - Absolute stop time in milliseconds. When parameter is not passed or <= 0, + * time of stopThirdParty call is used. + */ + stopThirdParty( + url: string, + success: boolean, + start?: number, + stop?: number + ): void; + /** + * @description Adds a listener that is called when the user is leaving the page, + * but before the monitor signal is sent + * @param listener A function that will be called in case the user leaves the page. + */ + addPageLeavingListener(listener: (key: string) => {}): void; + /** + * @description Sends a Streaming Node to the Server + * @param source - URL of the streaming resource + * @param duration - duration of the streaming resource in seconds + * @param userTriggered - did the user trigger the playback or did it start automatically? + * @param watchedCompletely - did the streaming resource play to the end? + * @param maxPlayTime - maximum progress this streaming resource had in seconds + * @param playTime - the time this streaming resource was playing in seconds + * @param bufferingCount - amount of bufferings that occured during the playback + * @param bufferingTime - total time spent with buffering in seconds + * @param type - action type of the streaming node. Is used for classifying events + * on the serverside, e.g. _info_, _warn_, _error_ + */ + addStreamingNode( + source: string, + duration: number, + userTriggered: boolean, + watchedCompletely: boolean, + maxPlayTime: number, + playTime: number, + bufferingCount: number, + bufferingTime: number, + type: "_info_" | "_warn_" | "_error_" + ): void; + /** + * @description Indicates the start of a user input. User inputs must always + * be stopped by calling endUserInput. If an xhr call or a page load happens + * it is checked if a user input is active. If yes, the user input is set to + * have triggered the page action. + * @param domNode - Which triggered the action (button, etc) is used for determining its caption + * @param type - Type of the user input: 'click', 'keypress', 'scroll',... + * @param addInfo - Additional info for user input such as key, mouse button, etc ('F5', 'RETURN',...) + * @param validTime - How long should the user input be able to open actions? default is 30ms + */ + beginUserInput( + domNode: any, + type: string, + addInfo: string, + validTime: number + ): any; + /** + * @description the user input object returned by beginUserInput + */ + endUserInput(userInputObject: any): void; + /** + * @description Initiate ajax action. Must be closed by leaveXhrAction afterwards. + * @param type Additional info about type of xhr (eg. framework name,etc) + * @param mode - The action mode: 0 .. just extend running ajax actions 1 .. extend any running action 2 .. + * extend any running action - visible subaction 3 .. start action if user input is present + * @param webSocket - Indicates if this action is a webSocket action or not + * @returns id of action + */ + enterXhrAction(type: string, mode: number, webSocket: boolean): number; + /** + * @description Indicates the end of an xhr action. Must be started by leaveXhrAction beforehand. + * @param id - id of action (must be the value returned by enterXhrAction) + */ + leaveXhrAction(id: number): void; + /** + * @description Indicates that an xhr callback is active (eg. XMLHttpRequest onreadystatechange). + * This is necessary to automatically add actions started during a callback as subactions. + * Xhr callback must be stopped by leaveXhrCallback. + * @param actionId - id of action where callback belongs to + */ + enterXhrCallback(actionId: number): void; + /** + * @description Indicates the end of an xhr callback. Must be called after enterXhrCallback. + * @param actionId - id of action where callback belongs to + */ + leaveXhrCallback(actionId: number): void; + /** + * @description Indicates the start of a load action. Frameworks often have their own load callback functions. + * This can be used when framework starts load before "DOMContentLoaded". + */ + signalOnLoadStart(): void; + /** + * @description Tells the JavaScript agent to wait for an additional call of signalOnLoadEnd. + * When the last call of signalOnLoadEnd is performed the "onload" action is closed. + * Note: if this function is called, signalOnLoadEnd MUST be called afterwards to indicated the end of one load. + * Otherwise there will be unexpected action behaviour. + */ + incrementOnLoadEndMarkers(): void; + /** + * @description Indicates the end of a load action. needs incrementOnLoadEndMarkers to be called before. + * As soon as the last signalOnLoadEnd is called, the "onload" action is closed. + */ + signalOnLoadEnd(): void; + /** + * @description By default a visit ends after a configurable inactivity time (default is 30 min.). + * Using the ADK, a visit can be ended forcibly, for example when a user logs out from an application. + * Simply call dynaTrace.endVisit() and the visit ends without waiting for the inactivity time. + * For correlation purposes the visit shows as active in the client for about three minutes, + * but actions sent after dynaTrace.endVisit() are added to a new visit. + * End the current UEM visit. This is useful for "logout" buttons, so that, + * when the user logs out, the user's visit can also be closed by calling this method. + */ + endVisit(): void; + /** + * @description Set the application version for this visit. + * This will be read on the server side and included as part of each visit for easy splitting. + * @param appVersion - The version string to be set. + */ + setAppVersion(appVersion: string): void; + /** + * @description Set meta-data for the page via a key/value pair. + * @param key - The readable key for the value + * @param value - The value to associate with the identifier + */ + setMetaData(key: string, value: string): void; +} + +declare let dynaTrace: dynaTrace; diff --git a/types/dynatrace/tsconfig.json b/types/dynatrace/tsconfig.json new file mode 100644 index 0000000000..6c137be982 --- /dev/null +++ b/types/dynatrace/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "dynatrace-tests.ts" + ] +} diff --git a/types/dynatrace/tslint.json b/types/dynatrace/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/dynatrace/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/ej.web.all/index.d.ts b/types/ej.web.all/index.d.ts index 32b9d1a18b..77db23312f 100644 --- a/types/ej.web.all/index.d.ts +++ b/types/ej.web.all/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for ej.web.all 16.3 +// Type definitions for ej.web.all 16.4 // Project: http://help.syncfusion.com/js/typescript // Definitions by: Syncfusion // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -8,7 +8,7 @@ /*! * filename: ej.web.all.d.ts -* version : 16.3.0.21 +* version : 16.4.0.40-beta * Copyright Syncfusion Inc. 2001 - 2018. All rights reserved. * Use of this code is subject to the terms of our license. * A copy of the current license can be obtained at any time by e-mailing @@ -590,6 +590,21 @@ declare namespace ej { */ scope?: string; + /** Used to enable auto scroll while drag and drop the element. + * @Default {'false'} + */ + autoScroll?: boolean; + + /** Represents when to start the scrolling inside the scroll container on dragging + * @Default {'20'} + */ + scrollSensitivity?: number; + + /** Specifies how much distance of scroll should move on dragging once reached scroll sensitivity area. + * @Default {'20'} + */ + scrollSpeed?: number; + /** This event is triggered when dragging element is destroyed. */ destroy?(e: DestroyEventArgs): void; @@ -6293,6 +6308,11 @@ declare namespace ej { */ getValue(): string; + /** sets the date value for the DatePicker. + * @returns {string} + */ + setValue(): string; + /** Close the DatePicker popup, if it is in opened state. * @returns {void} */ @@ -10920,7 +10940,7 @@ declare namespace ej { show(): void; /** To show item in the given index. - * @param {number} Specifies the index value to show the hided item. + * @param {number} Specifies the index value to show the hidden item. * @returns {void} */ showItem(index: number): void; @@ -11069,7 +11089,7 @@ declare namespace ej { itemRequestCount?: number; /** Specifies the maximum number of items to be fetched. Note: This will work only with Virtual scrolling - * @Default {null} + * @Default {5} */ totalItemsCount?: number; @@ -29321,6 +29341,11 @@ declare namespace ej { */ memberEditorPageSize?: number; + /** Enables/Disables sorting option in member editor dialog for the members of the respective field. + * @Default {false} + */ + enableMemberEditorSorting?: boolean; + /** Enables/disables the display of grand total for rows and columns. * @Default {true} */ @@ -31523,6 +31548,11 @@ declare namespace ej { */ memberEditorPageSize?: number; + /** Enables/Disables sorting option in member editor dialog for the members of the respective field. + * @Default {false} + */ + enableMemberEditorSorting?: boolean; + /** Sets the summary layout for the pivot grid. Following are the ways in which the summary can be positioned: normal summary (bottom), top summary, no summary, and Microsoft Excel * summary. * @Default {ej.PivotGrid.Layout.Normal} @@ -37776,6 +37806,11 @@ declare namespace ej { */ reportLoaded?(e: ReportLoadedEventArgs): void; + /** Fires when user clicks on a failed report item in the rendered report, before displaying error details dialog. If you want to show custom error detail or perform any action before + * viewing error detail, you can make use of the showError event. + */ + showError?(e: ShowErrorEventArgs): void; + /** Fires when click the View Report Button. */ viewReportClick?(e: ViewReportClickEventArgs): void; @@ -37914,6 +37949,25 @@ declare namespace ej { type?: string; } + export interface ShowErrorEventArgs { + + /** true if the event should be canceled; otherwise, false. + */ + cancel?: boolean; + + /** returns the error code. + */ + errorCode?: string; + + /** returns the error message. + */ + message?: string; + + /** returns the detailed error information. + */ + detail?: string; + } + export interface ViewReportClickEventArgs { /** true if the event should be canceled; otherwise, false. @@ -42902,17 +42956,22 @@ declare namespace ej { */ redo(): void; - /** This method is used to refresh the content in Spreadsheet. + /** This method is used to refresh the Spreadsheet based on the sheet model values. * @param {number} Pass the index of the sheet. * @returns {void} */ refreshContent(sheetIdx: number): void; - /** This method is used to refresh the Spreadsheet. + /** This method is used to refresh the Spreadsheet element based on the page layout. * @returns {void} */ refreshSpreadsheet(): void; + /** This method destroys and re-creates the entire Spreadsheet control. + * @returns {void} + */ + refresh(): void; + /** This method is used to remove custom formulae in Spreadsheet. * @param {string} Pass the name of the formula. * @param {string} Pass the name of the function. @@ -44335,6 +44394,11 @@ declare namespace ej { */ importSettings?: ImportSettings; + /** Gets a value that indicates whether importing or not while loading the sheets in Spreadsheet. + * @Default {false} + */ + isImport?: boolean; + /** Gets or sets a value that indicates whether to enable or disable readonly support in the Spreadsheet. * @Default {false} */ @@ -46435,6 +46499,11 @@ declare namespace ej { */ abortPrint(): void; + /** Aborts the download operation. + * @returns {void} + */ + abortDownload(): void; + /** Shows/hides the print icon in the toolbar. * @param {boolean} shows/hides print button in the toolbar * @returns {void} @@ -46508,6 +46577,12 @@ declare namespace ej { */ showMagnificationTools(show: boolean): void; + /** Shows/hides the search tool in the toolbar. + * @param {boolean} shows/hides search tool in the toolbar + * @returns {void} + */ + showTextSearchTool(show: boolean): void; + /** Scales the page to fit the page in the container in the control. * @returns {void} */ @@ -46528,6 +46603,11 @@ declare namespace ej { */ zoomOut(): void; + /** Resize the viewer based on the parent element height. + * @returns {void} + */ + updateViewerSize(): void; + /** Scales the page to the specified percentage ranging from 50 to 400. If the given zoomValue is less than 50 or greater than 400; the PDF viewer scales the page to 50 and 400 * respectively. * @param {number} zoom value for scaling the pages in the PDF Viewer @@ -46551,6 +46631,12 @@ declare namespace ej { */ searchPrevious(): void; + /** Set the JSON data that are formed for rendering the document content in PDF viewer. + * @param {any} Set the JSON data that are formed for rendering the document content. + * @returns {void} + */ + setJSONData(jsonData: any): void; + /** Searches the target text with its casing. * @param {boolean} Specifies whether the text search must be performed with match case or not. * @returns {void} @@ -46643,6 +46729,14 @@ declare namespace ej { */ signatureSettings?: SignatureSettings; + /** Enables/ disables the text selection context menu. + */ + textSelectionContextMenu?: TextSelectionContextMenu; + + /** Enables/disables the annotation context menu. + */ + annotationContextMenu?: AnnotationContextMenu; + /** Specifies the type of the annotations. */ annotationType?: ej.PdfViewer.AnnotationType|string; @@ -46667,6 +46761,10 @@ declare namespace ej { */ interactionMode?: ej.PdfViewer.InteractionMode|string; + /** Gets or sets the buffering mode of the PDF viewer control when allowClientBuffering is set to true. + */ + bufferingMode?: ej.PdfViewer.BufferingMode|string; + /** Specifies the open state of the hyperlink in the PDF document. */ hyperlinkOpenState?: ej.PdfViewer.LinkTarget|string; @@ -46711,6 +46809,10 @@ declare namespace ej { */ ajaxRequestFailure?(e: AjaxRequestFailureEventArgs): void; + /** Triggers when the ajax request is Success. + */ + ajaxRequestSuccess?(e: AjaxRequestSuccessEventArgs): void; + /** Triggers when there is change in the magnification value. */ zoomChange?(e: ZoomChangeEventArgs): void; @@ -46767,6 +46869,14 @@ declare namespace ej { */ bufferEnd?(e: BufferEndEventArgs): void; + /** Triggers when the download is started. + */ + downloadStart?(e: DownloadStartEventArgs): void; + + /** Triggers when the download is completed or aborted. + */ + downloadEnd?(e: DownloadEndEventArgs): void; + /** Triggers when PDF viewer control is destroyed successfully. */ destroy?(e: DestroyEventArgs): void; @@ -46844,6 +46954,25 @@ declare namespace ej { message?: string; } + export interface AjaxRequestSuccessEventArgs { + + /** true, if the event should be canceled; otherwise, false. + */ + cancel?: boolean; + + /** Returns the PDF viewer model + */ + model?: any; + + /** Returns the name of the event + */ + type?: string; + + /** Returns the response data on ajax success. + */ + responseData?: string; + } + export interface ZoomChangeEventArgs { /** Returns the cancel option value. @@ -47194,6 +47323,52 @@ declare namespace ej { isBuffering?: boolean; } + export interface DownloadStartEventArgs { + + /** true, if the event should be canceled; otherwise, false + */ + cancel?: boolean; + + /** Returns the PDF viewer model + */ + model?: any; + + /** Returns the name of the event + */ + type?: string; + + /** Returns the name of the file being displayed in the PDF viewer. + */ + fileName?: string; + + /** Returns the status about the download is started. + */ + status?: string; + } + + export interface DownloadEndEventArgs { + + /** true, if the event should be canceled; otherwise, false + */ + cancel?: boolean; + + /** Returns the PDF viewer model + */ + model?: any; + + /** Returns the name of the event + */ + type?: string; + + /** Returns the name of the file being displayed in the PDF viewer. + */ + fileName?: string; + + /** Returns the status about the download is completed or aborted. + */ + status?: string; + } + export interface DestroyEventArgs { /** Returns the cancel option value. @@ -47331,6 +47506,48 @@ declare namespace ej { opacity?: number; } + export interface TextSelectionContextMenu { + + /** Enables/ disables the text selection context menu. + */ + isEnable?: boolean; + + /** Enables/disables the copy menu in the text selection context menu. + */ + isCopyEnable?: boolean; + + /** Enables/disables the search menu in the text selection context menu. + */ + isSearchEnable?: boolean; + + /** Enables/disables the highlight annotation menu in the text selection context menu. + */ + isHighlightEnable?: boolean; + + /** Enables/disables the strikeout annotation menu in the text selection context menu. + */ + isStrikeoutEnable?: boolean; + } + + export interface AnnotationContextMenu { + + /** Enables/disables the annotation context menu. + */ + isEnable?: boolean; + + /** Enables/disables the popup menu in the annotation context menu. + */ + isPopupEnable?: boolean; + + /** Enables/disables the delete menu in the annotation context menu. + */ + isDeleteEnable?: boolean; + + /** Enables/disables the properties menu in the annotation context menu. + */ + isPropertiesEnable?: boolean; + } + enum ToolbarItems { ///Shows only magnification tools in the toolbar. @@ -47395,6 +47612,16 @@ declare namespace ej { } + enum BufferingMode { + + ///Retrieves details to render first two pages in a request and rest of the pages in other request. + Default, + + ///Retrieves complete details to render all the pages in a single request. + Complete + } + + enum LinkTarget { ///Opens the hyperlink in the same tab of the browser. @@ -47533,6 +47760,11 @@ declare namespace ej { */ enableAsync?: boolean; + /** To set either ‘Post’ or ‘Get’ for ajax request type which invokes when validate, get suggestion and dictionary action.Possible values are ‘POST’ or ‘GET’ + * @Default {GET} + */ + ajaxRequestType?: string; + /** Sets the data type for the ajax call used within the SpellCheck control, denoting the type of data that are expected to be retrieved from the server. The applicable values are * json and jsonp. * @Default {jsonp} @@ -50374,11 +50606,11 @@ declare namespace ej.datavisualization { /** returns the pointer element. */ - markerpointerelement?: any; + markerPointerElement?: any; /** returns the value of the pointer. */ - markerpointervalue?: number; + markerPointerValue?: number; /** returns the pointer style */ diff --git a/types/ej.web.all/tslint.json b/types/ej.web.all/tslint.json index 35e3f27cc8..0615bdcb0e 100644 --- a/types/ej.web.all/tslint.json +++ b/types/ej.web.all/tslint.json @@ -37,6 +37,7 @@ "radix": false, "prefer-for-of": false, "one-line": false, - "no-unnecessary-type-assertion": false + "no-unnecessary-type-assertion": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/electron-packager/electron-packager-tests.ts b/types/electron-packager/electron-packager-tests.ts index 06cadf97f0..6b10ea4bf3 100644 --- a/types/electron-packager/electron-packager-tests.ts +++ b/types/electron-packager/electron-packager-tests.ts @@ -13,25 +13,6 @@ function ignoreFunction(path: string) { return true; } -// this is the obsolete API and will be removed in a future version - -packager({ - dir: ".", - name: "myapplication", - platform: "win32", - arch: "all", - electronVersion: "0.34.0", - win32metadata: { - CompanyName: "Acme CO", - FileDescription: "My application", - OriginalFilename: "myapp.exe", - ProductName: "Application", - InternalName: "roadrunner", - "requested-execution-level": "highestAvailable", - "application-manifest": "manifest.xml" - } -}, callback); - function onCompleted(appPaths: string | string[]) { } @@ -102,7 +83,7 @@ packager({ afterExtract: [ completeFunction ], - afterPrune: [ + afterPrune: [ completeFunction ], appCopyright: "Copyright", @@ -122,7 +103,6 @@ packager({ ignore: /ab+c/, out: "out", overwrite: true, - packageManager: false, prune: true, quiet: true, tmpdir: "/tmp", @@ -157,7 +137,6 @@ packager({ new RegExp('abc') ], overwrite: false, - packageManager: "npm", platform: "darwin", prune: false, quiet: false, @@ -184,7 +163,14 @@ packager({ strictSSL: false }, ignore: ignoreFunction, - packageManager: "cnpm", + platform: "linux" +}).then(onCompleted).catch(onError); + +packager({ + dir: ".", + arch: "mips64el", + electronVersion: "1.8.8", + prebuiltAsar: "prebuilt.asar", platform: "linux" }).then(onCompleted).catch(onError); @@ -200,11 +186,14 @@ packager({ quiet: true, strictSSL: false }, - packageManager: "yarn", platform: "mas", extendInfo: { foo: "bar" }, + osxNotarize: { + appleId: "My ID", + appleIdPassword: "Bad Password" + }, osxSign: { identity: "myidentity", entitlements: "path/to/my.entitlements", diff --git a/types/electron-packager/index.d.ts b/types/electron-packager/index.d.ts index 0e438ebc6e..04e62a28b5 100644 --- a/types/electron-packager/index.d.ts +++ b/types/electron-packager/index.d.ts @@ -1,9 +1,10 @@ -// Type definitions for electron-packager 12.0 +// Type definitions for electron-packager 13.0 // Project: https://github.com/electron-userland/electron-packager // Definitions by: Maxime LUCE // Juan Jimenez-Anca // John Kleinschmidt // Brendan Forster +// Mark Lee // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -23,20 +24,6 @@ export = electronPackager; */ declare function electronPackager(opts: electronPackager.Options): Promise; -/** - * This will: - * - Find or download the correct release of Electron - * - Use that version of electron to create a app in /-- - * - * You should be able to launch the app on the platform you built for. If not, check your settings and try again. - * - * @param opts - Options to configure packaging. - * @param callback - Callback which is called when packaging is done or an error occured. - * - * @deprecated since version 12.0 - */ -declare function electronPackager(opts: electronPackager.Options, callback: electronPackager.finalCallback): void; - declare namespace electronPackager { /** * Callback which is called when electron-packager is done. @@ -48,8 +35,7 @@ declare namespace electronPackager { type ignoreFunction = (path: string) => boolean; type onCompleteFn = (buildPath: string, electronVersion: string, platform: string, arch: string, callbackFn: () => void) => void; - type arch = "ia32" | "x64" | "armv7l" | "arm64" |"all"; - type packageManager = "npm" | "cnpm" | "yarn" | false; + type arch = "ia32" | "x64" | "armv7l" | "arm64" | "mips64el" | "all"; type platform = "linux" | "win32" | "darwin" | "mas" | "all"; interface AsarOptions { @@ -65,6 +51,11 @@ declare namespace electronPackager { strictSSL?: boolean; } + interface ElectronNotarizeOptions { + appleId: string; + appleIdPassword: string; + } + interface ElectronOsXSignOptions { identity?: string; entitlements?: string; @@ -116,6 +107,10 @@ declare namespace electronPackager { * Whether to package the application's source code into an archive, using Electron's archive format */ asar?: boolean | AsarOptions; + /** + * The path to a prebuilt ASAR file. + */ + prebuiltAsar?: string; /** * The build version of the application. Defaults to the value of appVersion. * Maps to the FileVersion metadata property on Windows, and CFBundleVersion on OS X. @@ -160,10 +155,6 @@ declare namespace electronPackager { * Whether to replace an already existing output directory for a given platform (true) or skip recreating it (false). */ overwrite?: boolean; - /** - * The package manager used to prune devDependencies modules from the outputted Electron app - */ - packageManager?: packageManager; /** * The target platform(s) to build for. Not required if the all option is set. */ @@ -202,6 +193,14 @@ declare namespace electronPackager { * The bundle identifier to use in the application helper's plist. */ helperBundleId?: string; + /** + * Forces support for Mojave (macOS 10.14) dark mode in the packaged app. + */ + darwinDarkModeSupport?: boolean; + /** + * If present, notarizes OS X target apps when the host platform is OS X and XCode is installed. + */ + osxNotarize?: ElectronNotarizeOptions; /** * If present, signs OS X target apps when the host platform is OS X and XCode is installed. */ diff --git a/types/ember/index.d.ts b/types/ember/index.d.ts index fdb89d3823..4e2b45cd55 100755 --- a/types/ember/index.d.ts +++ b/types/ember/index.d.ts @@ -478,6 +478,7 @@ export namespace Ember { const addObserver: typeof EmberObjectObserversNs.addObserver; const removeObserver: typeof EmberObjectObserversNs.removeObserver; const get: typeof EmberObjectNs.get; + const notifyPropertyChange: typeof EmberObjectNs.notifyPropertyChange; const getWithDefault: typeof EmberObjectNs.getWithDefault; const getProperties: typeof EmberObjectNs.getProperties; const setProperties: typeof EmberObjectNs.setProperties; diff --git a/types/ember/test/object.ts b/types/ember/test/object.ts index 060bf8ca81..853ed46d46 100755 --- a/types/ember/test/object.ts +++ b/types/ember/test/object.ts @@ -65,4 +65,11 @@ export class Foo2 extends Ember.Object { name }); } + + bar() { + Ember.notifyPropertyChange(this, 'name'); + Ember.notifyPropertyChange(this); // $ExpectError + Ember.notifyPropertyChange('name'); // $ExpectError + Ember.notifyPropertyChange(this, 'name', 'bar'); // $ExpectError + } } diff --git a/types/ember__object/index.d.ts b/types/ember__object/index.d.ts index f915bdc82a..06e417999d 100644 --- a/types/ember__object/index.d.ts +++ b/types/ember__object/index.d.ts @@ -385,6 +385,8 @@ export function defineProperty( meta?: any ): void; +export function notifyPropertyChange(obj: object, keyName: string): void; + declare module '@ember/utils/-private/types' { interface TypeLookup { class: typeof EmberObject; diff --git a/types/ember__object/test/object.ts b/types/ember__object/test/object.ts index b47aa22ffb..391ac183a9 100644 --- a/types/ember__object/test/object.ts +++ b/types/ember__object/test/object.ts @@ -1,4 +1,4 @@ -import EmberObject, { computed } from "@ember/object"; +import EmberObject, { computed, notifyPropertyChange } from "@ember/object"; const LifetimeHooks = EmberObject.extend({ resource: null as {} | null, @@ -47,6 +47,12 @@ class Foo extends EmberObject { b: 11 }); } + bar() { + notifyPropertyChange(this, 'name'); + notifyPropertyChange(this); // $ExpectError + notifyPropertyChange('name'); // $ExpectError + notifyPropertyChange(this, 'name', 'bar'); // $ExpectError + } } // TODO: enable after TS 3.0 https://github.com/typed-ember/ember-cli-typescript/issues/291 diff --git a/types/empty-dir/empty-dir-tests.ts b/types/empty-dir/empty-dir-tests.ts new file mode 100644 index 0000000000..63700ae87b --- /dev/null +++ b/types/empty-dir/empty-dir-tests.ts @@ -0,0 +1,25 @@ +import emptyDir = require('empty-dir'); + +emptyDir('./', (err, isEmpty) => { + // $ExpectType ErrnoException + err; + // $ExpectType boolean + isEmpty; +}); + +// $ExpectType boolean +emptyDir.sync('./test/empty'); + +function filter(filepath: string) { + return !/(Thumbs\.db|\.DS_Store)$/i.test(filepath); +} + +emptyDir('./', filter, (err, isEmpty) => { + // $ExpectType ErrnoException + err; + // $ExpectType boolean + isEmpty; +}); + +// $ExpectType boolean +emptyDir.sync('./test/empty', filter); diff --git a/types/empty-dir/index.d.ts b/types/empty-dir/index.d.ts new file mode 100644 index 0000000000..0f623a991d --- /dev/null +++ b/types/empty-dir/index.d.ts @@ -0,0 +1,22 @@ +// Type definitions for empty-dir 1.0 +// Project: https://github.com/js-cli/js-empty-dir +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +export = emptyDir; + +declare function emptyDir( + dir: string, + cb: (err: NodeJS.ErrnoException, isEmpty: boolean) => void +): void; +declare function emptyDir( + dir: string, + filter: (path: string) => boolean, + cb: (err: NodeJS.ErrnoException, isEmpty: boolean) => void +): void; + +declare namespace emptyDir { + function sync(dir: string, filter?: (path: string) => boolean): boolean; +} diff --git a/types/empty-dir/tsconfig.json b/types/empty-dir/tsconfig.json new file mode 100644 index 0000000000..cb73470ad8 --- /dev/null +++ b/types/empty-dir/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "empty-dir-tests.ts" + ] +} diff --git a/types/empty-dir/tslint.json b/types/empty-dir/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/empty-dir/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/escape-goat/escape-goat-tests.ts b/types/escape-goat/escape-goat-tests.ts new file mode 100644 index 0000000000..cfc1808495 --- /dev/null +++ b/types/escape-goat/escape-goat-tests.ts @@ -0,0 +1,14 @@ +import * as escapeGoat from 'escape-goat'; + +// $ExpectType string +escapeGoat.escape('🦄 & 🐐'); + +// $ExpectType string +escapeGoat.unescape('🦄 & 🐐'); + +// $ExpectType string +escapeGoat.escape('Hello World'); + +const url = 'https://sindresorhus.com?x="🦄"'; +// $ExpectType string +escapeGoat.escapeTag`Unicorn`; diff --git a/types/escape-goat/index.d.ts b/types/escape-goat/index.d.ts new file mode 100644 index 0000000000..f76f384fb0 --- /dev/null +++ b/types/escape-goat/index.d.ts @@ -0,0 +1,9 @@ +// Type definitions for escape-goat 1.3 +// Project: https://github.com/sindresorhus/escape-goat#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export function escape(input: string): string; +export function unescape(input: string): string; +export function escapeTag(template: TemplateStringsArray, ...substitutions: any[]): string; +export function unescapeTag(template: TemplateStringsArray, ...substitutions: any[]): string; diff --git a/types/escape-goat/tsconfig.json b/types/escape-goat/tsconfig.json new file mode 100644 index 0000000000..9715cb59e1 --- /dev/null +++ b/types/escape-goat/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "escape-goat-tests.ts" + ] +} diff --git a/types/escape-goat/tslint.json b/types/escape-goat/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/escape-goat/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/eslint/eslint-tests.ts b/types/eslint/eslint-tests.ts index c6b8b786fa..ed211d220e 100644 --- a/types/eslint/eslint-tests.ts +++ b/types/eslint/eslint-tests.ts @@ -480,7 +480,10 @@ cli.addPlugin('my-fancy-plugin', {}); cli.isPathIgnored('./dist/index.js'); -const formatter = cli.getFormatter('codeframe'); +let formatter: CLIEngine.Formatter; + +formatter = cli.getFormatter('codeframe'); +formatter = cli.getFormatter(); formatter(cliReport.results); diff --git a/types/eslint/index.d.ts b/types/eslint/index.d.ts index 451477af40..01f39ee83e 100644 --- a/types/eslint/index.d.ts +++ b/types/eslint/index.d.ts @@ -471,7 +471,7 @@ export class CLIEngine { isPathIgnored(filePath: string): boolean; - getFormatter(format: string): CLIEngine.Formatter; + getFormatter(format?: string): CLIEngine.Formatter; getRules(): Map; diff --git a/types/eureka-js-client/eureka-js-client-tests.ts b/types/eureka-js-client/eureka-js-client-tests.ts index 109dab0278..b4b5c5f54e 100644 --- a/types/eureka-js-client/eureka-js-client-tests.ts +++ b/types/eureka-js-client/eureka-js-client-tests.ts @@ -19,3 +19,27 @@ const client = new Eureka({ port: 32768, } }); + +// example configuration against newer Eureka (https://www.npmjs.com/package/eureka-js-client#400-bad-request-errors-from-eureka-server) +const newerClient = new Eureka({ + // application instance information + instance: { + app: 'jqservice', + hostName: 'localhost', + ipAddr: '127.0.0.1', + port: { + $: 443, + '@enabled': true + }, + vipAddress: 'jq.test.something.com', + dataCenterInfo: { + '@class': 'com.netflix.appinfo.InstanceInfo$DefaultDataCenterInfo', + name: 'MyOwn', + }, + }, + eureka: { + // eureka server host / port + host: '192.168.99.100', + port: 32768, + } +}); diff --git a/types/eureka-js-client/index.d.ts b/types/eureka-js-client/index.d.ts index bfd9f10666..693e1b8ec8 100644 --- a/types/eureka-js-client/index.d.ts +++ b/types/eureka-js-client/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for eureka-js-client 4.3 +// Type definitions for eureka-js-client 4.4 // Project: https://github.com/jquatier/eureka-js-client -// Definitions by: Ilko Hoffmann +// Definitions by: Ilko Hoffmann , Karl O. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export class Eureka { @@ -26,7 +26,7 @@ export namespace EurekaClient { ipAddr: string; vipAddress: string; dataCenterInfo: DataCenterInfo; - port?: number; + port?: number | LegacyPortWrapper; instanceId?: string; appGroupName?: string; sid?: string; @@ -61,6 +61,10 @@ export namespace EurekaClient { useLocalMetadata?: boolean; preferIpAddress?: boolean; } + interface LegacyPortWrapper { + '$': number; + '@enabled': boolean; + } interface PortWrapper { enabled: boolean; port: number; @@ -71,5 +75,6 @@ export namespace EurekaClient { } interface DataCenterInfo { name: DataCenterName; + '@class'?: string; } } diff --git a/types/expirymanager/expirymanager-tests.ts b/types/expirymanager/expirymanager-tests.ts new file mode 100644 index 0000000000..2206b2673e --- /dev/null +++ b/types/expirymanager/expirymanager-tests.ts @@ -0,0 +1,19 @@ +import { ExpiryManager } from "expirymanager"; + +const expiryManager = new ExpiryManager(); + +const keys = ['1', '2']; + +expiryManager.expire(keys, 1); + +expiryManager.unexpire(keys); + +const expiry: number = expiryManager.getExpiry(keys[0]); + +let expiredKeys = expiryManager.getExpiredKeys(); +expiredKeys = expiryManager.getExpiredKeys(expiryManager.now()); + +expiredKeys = expiryManager.extractExpiredKeys(); +expiredKeys = expiryManager.extractExpiredKeys(expiryManager.now()); + +expiryManager.clear(); diff --git a/types/expirymanager/index.d.ts b/types/expirymanager/index.d.ts new file mode 100644 index 0000000000..c192da7af7 --- /dev/null +++ b/types/expirymanager/index.d.ts @@ -0,0 +1,25 @@ +// Type definitions for expirymanager 0.9 +// Project: https://github.com/SocketCluster/expirymanager +// Definitions by: Daniel Rose +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export type Key = any; +export type Keys = Key[]; + +export class ExpiryManager { + constructor(); + + now(): number; + + expire(keys: Keys, seconds: number): void; + unexpire(keys: Keys): void; + + getExpiry(key: Key): number; + + getKeysByExpiry(expiry: number): Keys; + + getExpiredKeys(time?: number): Keys; + extractExpiredKeys(time?: number): Keys; + + clear(): void; +} diff --git a/types/expirymanager/tsconfig.json b/types/expirymanager/tsconfig.json new file mode 100644 index 0000000000..094c4e8c8d --- /dev/null +++ b/types/expirymanager/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "expirymanager-tests.ts" + ] +} diff --git a/types/expirymanager/tslint.json b/types/expirymanager/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/expirymanager/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/expo/expo-tests.tsx b/types/expo/expo-tests.tsx index 75dee784de..aa69df28ad 100644 --- a/types/expo/expo-tests.tsx +++ b/types/expo/expo-tests.tsx @@ -1,5 +1,5 @@ import * as React from 'react'; -import { Text } from 'react-native'; +import { Text, AccessibilityInfo } from 'react-native'; import { Accelerometer, @@ -8,40 +8,46 @@ import { AdMobInterstitial, AdMobRewarded, Amplitude, - Asset, - AuthSession, - Audio, AppLoading, + Asset, + Audio, + AuthSession, BarCodeScanner, - BlurViewProps, BlurView, Brightness, + Calendar, Camera, CameraObject, + Constants, DocumentPicker, + EdgeInsets, + EdgePadding, + EventUserLocation, Facebook, FacebookAds, - FileSystem, - ImagePicker, - ImageManipulator, FaceDetector, - Linking, - Svg, + FileSystem, + Haptic, + ImageManipulator, + ImagePicker, IntentLauncherAndroid, KeepAwake, + KmlMapEvent, LinearGradient, + Linking, + Location, + MailComposer, + MapEvent, + MapStyleElement, + MapView, + MediaLibrary, Permissions, PublisherBanner, + Region, registerRootComponent, ScreenOrientation, - SQLite, - Calendar, - MailComposer, - Location, - Updates, - MediaLibrary, - Haptic, - Constants + Svg, + Updates } from 'expo'; const reverseGeocode: Promise = Location.reverseGeocodeAsync({ @@ -837,6 +843,100 @@ async () => { result.status === 'saved'; }; +// #region MapView +const initialRegion: Region = { + latitude: 0, + longitude: 0, + latitudeDelta: 0, + longitudeDelta: 0, +}; + +const edgePadding: EdgePadding = { + top: 0, + right: 0, + bottom: 0, + left: 0, +}; + +const edgeInsets: EdgeInsets = { + top: 0, + right: 0, + bottom: 0, + left: 0, +}; + +const mapStyleElements: MapStyleElement[] = [{ + featureType: 'featureType', + elementType: 'elementType', + stylers: [{}, {}], +}]; + +const mapEventCallback = (event: MapEvent) => console.log(event); +const regionCallback = (region: Region) => console.log(region); +const kmlCallback = (kml: KmlMapEvent) => console.log(kml); +const userLocationCallback = (event: EventUserLocation) => console.log(event); + +() => ( + ({})} + onKmlReady={kmlCallback} + onRegionChange={regionCallback} + onRegionChangeComplete={regionCallback} + onPress={mapEventCallback} + onLongPress={mapEventCallback} + onUserLocationChange={userLocationCallback} + onPanDrag={mapEventCallback} + onPoiClick={(event: MapEvent<{ placeId: string, name: string }>) => console.log(event)} + onMarkerPress={(event: MapEvent<{ action: 'marker-press', id: string }>) => console.log(event)} + onMarkerSelect={(event: MapEvent<{ action: 'marker-select', id: string }>) => console.log(event)} + onMarkerDeselect={(event: MapEvent<{ action: 'marker-deselect', id: string }>) => console.log(event)} + onCalloutPress={(event: MapEvent<{ action: 'callout-press' }>) => console.log(event)} + onMarkerDragStart={mapEventCallback} + onMarkerDrag={mapEventCallback} + onMarkerDragEnd={mapEventCallback} + + minZoomLevel={0} + maxZoomLevel={0} + kmlSrc="src" + style={{ flex: 1 }} + /> +); +// #endegion + async () => { const updateEventListener: Updates.UpdateEventListener = ({ type, manifest, message }) => { switch (type) { @@ -916,6 +1016,7 @@ async () => { return true; } }; + // #region MediaLibrary async () => { const mlAsset: MediaLibrary.Asset = await MediaLibrary.createAssetAsync('localUri'); diff --git a/types/expo/index.d.ts b/types/expo/index.d.ts index 9e48e391d8..55dc4ffd06 100644 --- a/types/expo/index.d.ts +++ b/types/expo/index.d.ts @@ -16,6 +16,9 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 +export * from 'react-native-maps'; +export { default as MapView } from 'react-native-maps'; + import { EventSubscription } from 'fbemitter'; import { Component, ComponentClass, Ref, ComponentType } from 'react'; import { diff --git a/types/expo/package.json b/types/expo/package.json new file mode 100644 index 0000000000..4abdc24638 --- /dev/null +++ b/types/expo/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "react-native-maps": "*" + } +} diff --git a/types/fabric/fabric-impl.d.ts b/types/fabric/fabric-impl.d.ts index 39b3e45757..60ec11648f 100644 --- a/types/fabric/fabric-impl.d.ts +++ b/types/fabric/fabric-impl.d.ts @@ -4529,7 +4529,7 @@ interface IUtilMisc { * @param [context] Context to invoke callback in * @param [crossOrigin] crossOrigin value to set image element to */ - loadImage(url: string, callback: (image: HTMLImageElement) => void, context?: any, crossOrigin?: boolean): void; + loadImage(url: string, callback: (image: HTMLImageElement) => void, context?: any, crossOrigin?: string): void; /** * Creates corresponding fabric instances from their object representations diff --git a/types/fastify-jwt/fastify-jwt-tests.ts b/types/fastify-jwt/fastify-jwt-tests.ts index 6b92026b04..fc68ac8bcc 100644 --- a/types/fastify-jwt/fastify-jwt-tests.ts +++ b/types/fastify-jwt/fastify-jwt-tests.ts @@ -1,17 +1,16 @@ -import { IncomingMessage, Server, ServerResponse } from "http"; -import fastifyJwt = require("fastify-jwt"); import fastify = require("fastify"); +import fastifyJwt = require("fastify-jwt"); const app = fastify(); app.register(fastifyJwt, { - secret: "super-secret" + secret: "super-secret", }); app.register(fastifyJwt, { secret: (request, reply, callback) => { return ""; - } + }, }); app.get("/path", (request, reply) => { diff --git a/types/fastify-jwt/package.json b/types/fastify-jwt/package.json index e8c68ab969..5eb77c39fa 100644 --- a/types/fastify-jwt/package.json +++ b/types/fastify-jwt/package.json @@ -1,6 +1,6 @@ { "private": true, "dependencies": { - "fastify": "^1.11.2" + "fastify": ">=1.13.1 || 2.0.0-rc.1" } } diff --git a/types/favicons/favicons-tests.ts b/types/favicons/favicons-tests.ts index 485ea1d505..ce64c84e67 100644 --- a/types/favicons/favicons-tests.ts +++ b/types/favicons/favicons-tests.ts @@ -1,6 +1,6 @@ -import favicons, { Configuration } from "favicons"; +import * as favicons from "favicons"; -let config: Partial = { +let config: Partial = { path: "/foo/bar" }; @@ -19,7 +19,15 @@ favicons("path/to/file.png", config, (err, res) => { } }); -favicons("file.png", (err, res) => { +favicons("file.png", (err: any, res: any) => { + html = res.html.join(""); + + for (const { name, contents } of [...res.files, ...res.images]) { + html = name + contents.toString(); + } +}); + +favicons("file.png").then((res) => { html = res.html.join(""); for (const { name, contents } of [...res.files, ...res.images]) { diff --git a/types/favicons/index.d.ts b/types/favicons/index.d.ts index 47a9a9d24a..6bd3a4892e 100644 --- a/types/favicons/index.d.ts +++ b/types/favicons/index.d.ts @@ -1,79 +1,84 @@ -// Type definitions for favicons 5.1 +// Type definitions for favicons 5.3 // Project: https://github.com/evilebottnawi/favicons/blob/master/package.json -// Definitions by: Mohsen Azimi +// Definitions by: Mohsen Azimi , Nikk Radetskiy // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 /// -export interface Configuration { - /** Path for overriding default icons path @default "/" */ - path: string; - /** Your application's name @default null */ - appName: string | null; - /** Your application's description @default null */ - appDescription: string | null; - /** Your (or your developer's) name @default null */ - developerName: string | null; - /** Your (or your developer's) URL @default null */ - developerURL: string | null; - /** Primary text direction for name, short_name, and description @default "auto" */ - dir: string; - /** Primary language for name and short_name @default "en-US */ - lang: string; - /** Background colour for flattened icons @default "#fff" */ - background: string; - /** Theme color user for example in Android's task switcher @default "#fff" */ - theme_color: string; - /** Preferred display mode: "fullscreen", "standalone", "minimal-ui" or "browser" @default "standalone" */ - display: "fullscreen" | "standalone" | "minimal-ui" | "browser"; - /** Default orientation: "any", "natural", "portrait" or "landscape" @default "any" */ - orientation: "any" | "natural" | "portrait" | "landscape"; - /** Start URL when launching the application from a device @default "/?homescreen=1" */ - start_url: string; - /** Your application's version string @default "1.0" */ - version: string; - /** Print logs to console? @default false */ - logging: boolean; - /** - * Platform Options: - * - offset - offset in percentage - * - background: - * * false - use default - * * true - force use default, e.g. set background for Android icons - * * color - set background for the specified icons - */ - icons: Partial<{ - /* Create Android homescreen icon. */ - android: boolean | { offset: string; background: string }; - /* Create Apple touch icons. */ - appleIcon: boolean | { offset: string; background: string }; - /* Create Apple startup images. */ - appleStartup: boolean | { offset: string; background: string }; - /* Create Opera Coast icon. */ - coast: boolean | { offset: string; background: string }; - /* Create regular favicons. */ - favicons: boolean; - /* Create Firefox OS icons. */ - firefox: boolean | { offset: string; background: string }; - /* Create Windows 8 tile icons. */ - windows: boolean | { background: string }; - /* Create Yandex browser icon. */ - yandex: boolean | { background: string }; - }>; +import { Duplex } from "stream"; + +declare namespace favicons { + interface Configuration { + /** Path for overriding default icons path @default "/" */ + path: string; + /** Your application's name @default null */ + appName: string | null; + /** Your application's description @default null */ + appDescription: string | null; + /** Your (or your developer's) name @default null */ + developerName: string | null; + /** Your (or your developer's) URL @default null */ + developerURL: string | null; + /** Primary text direction for name, short_name, and description @default "auto" */ + dir: string; + /** Primary language for name and short_name @default "en-US */ + lang: string; + /** Background colour for flattened icons @default "#fff" */ + background: string; + /** Theme color user for example in Android's task switcher @default "#fff" */ + theme_color: string; + /** Preferred display mode: "fullscreen", "standalone", "minimal-ui" or "browser" @default "standalone" */ + display: "fullscreen" | "standalone" | "minimal-ui" | "browser"; + /** Default orientation: "any", "natural", "portrait" or "landscape" @default "any" */ + orientation: "any" | "natural" | "portrait" | "landscape"; + /** Start URL when launching the application from a device @default "/?homescreen=1" */ + start_url: string; + /** Your application's version string @default "1.0" */ + version: string; + /** Print logs to console? @default false */ + logging: boolean; + /** + * Platform Options: + * - offset - offset in percentage + * - background: + * * false - use default + * * true - force use default, e.g. set background for Android icons + * * color - set background for the specified icons + */ + icons: Partial<{ + /* Create Android homescreen icon. */ + android: boolean | { offset: string; background: string }; + /* Create Apple touch icons. */ + appleIcon: boolean | { offset: string; background: string }; + /* Create Apple startup images. */ + appleStartup: boolean | { offset: string; background: string }; + /* Create Opera Coast icon. */ + coast: boolean | { offset: string; background: string }; + /* Create regular favicons. */ + favicons: boolean; + /* Create Firefox OS icons. */ + firefox: boolean | { offset: string; background: string }; + /* Create Windows 8 tile icons. */ + windows: boolean | { background: string }; + /* Create Yandex browser icon. */ + yandex: boolean | { background: string }; + }>; + } + + interface FavIconResponse { + images: Array<{ name: string; contents: Buffer }>; + files: Array<{ name: string; contents: Buffer }>; + html: string[]; + } + + type Callback = (error: Error | null, response: FavIconResponse) => void; + + /** You can programmatically access Favicons configuration (icon filenames, HTML, manifest files, etc) with this export */ + const config: Configuration; + + function stream(configuration?: Configuration): Duplex; } - -export interface FavIconResponse { - images: Array<{ name: string; contents: Buffer }>; - files: Array<{ name: string; contents: Buffer }>; - html: string[]; -} - -export type Callback = (error: Error | null, response: FavIconResponse) => void; - -/** You can programmatically access Favicons configuration (icon filenames, HTML, manifest files, etc) with this export */ -export const config: Configuration; - /** * Generate favicons * @param source Source image(s) @@ -82,12 +87,16 @@ export const config: Configuration; */ declare function favicons( source: string | Buffer | string[], - callback?: Callback + configuration?: Partial, +): Promise; +declare function favicons( + source: string | Buffer | string[], + callback?: favicons.Callback ): void; declare function favicons( source: string | Buffer | string[], - configuration?: Partial, - callback?: Callback + configuration?: Partial, + callback?: favicons.Callback ): void; -export default favicons; +export = favicons; diff --git a/types/feathersjs__feathers/feathersjs__feathers-tests.ts b/types/feathersjs__feathers/feathersjs__feathers-tests.ts index 7d0e961700..bf1cdf8aa7 100644 --- a/types/feathersjs__feathers/feathersjs__feathers-tests.ts +++ b/types/feathersjs__feathers/feathersjs__feathers-tests.ts @@ -9,7 +9,7 @@ interface Services { users: User; } -const app = feathers() as Application; +const app = feathers(); app.service('users').get(0).then(u => { const user: User = u; diff --git a/types/feathersjs__feathers/index.d.ts b/types/feathersjs__feathers/index.d.ts index 5948eadc27..4746b29ff7 100644 --- a/types/feathersjs__feathers/index.d.ts +++ b/types/feathersjs__feathers/index.d.ts @@ -12,7 +12,8 @@ import { EventEmitter } from 'events'; import * as self from '@feathersjs/feathers'; -declare const feathers: (() => Application) & typeof self; +// tslint:disable-next-line no-unnecessary-generics +declare const feathers: (() => Application) & typeof self; export default feathers; export const version: string; diff --git a/types/file-type/file-type-tests.ts b/types/file-type/file-type-tests.ts index 640d2c8fb0..d49a964829 100644 --- a/types/file-type/file-type-tests.ts +++ b/types/file-type/file-type-tests.ts @@ -1,6 +1,8 @@ import fileType = require("file-type"); +// $ExpectType FileTypeResult | null fileType(new Buffer([0xFF, 0xD8, 0xFF])); fileType(new Uint8Array([0xFF, 0xD8, 0xFF])); -const minimumBytes: number = fileType.minimumBytes; +// $ExpectType number +fileType.minimumBytes; diff --git a/types/file-type/index.d.ts b/types/file-type/index.d.ts index 2a0deee26a..c902dc384e 100644 --- a/types/file-type/index.d.ts +++ b/types/file-type/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for file-type 5.2 +// Type definitions for file-type 10.6 // Project: https://github.com/sindresorhus/file-type // Definitions by: KIM Jaesuck a.k.a. gim tcaesvk // BendingBender @@ -8,7 +8,17 @@ export = FileType; -declare function FileType(buf: Buffer | Uint8Array): FileType.FileTypeResult; +/** + * The file type is detected by checking the + * [magic number](http://en.wikipedia.org/wiki/Magic_number_(programming)#Magic_numbers_in_files) of the buffer. + * + * @param buf It only needs the first `.minimumBytes` bytes. The exception is detection of + * `docx`, `pptx`, and `xlsx` which potentially requires reading the whole file. + * @returns an Object with: + * - ext - One of the [supported file types](https://github.com/sindresorhus/file-type/blob/master/readme.md#supported-file-types) + * - mime - The [MIME type](http://en.wikipedia.org/wiki/Internet_media_type) + */ +declare function FileType(buf: Buffer | Uint8Array): FileType.FileTypeResult | null; declare namespace FileType { interface FileTypeResult { @@ -16,5 +26,9 @@ declare namespace FileType { mime: string; } + /** + * The minimum amount of bytes needed to detect a file type. Currently, + * it's 4100 bytes, but it can change, so don't hard-code it. + */ const minimumBytes: number; } diff --git a/types/file-type/tsconfig.json b/types/file-type/tsconfig.json index 499b81459c..1894b908af 100644 --- a/types/file-type/tsconfig.json +++ b/types/file-type/tsconfig.json @@ -6,7 +6,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ @@ -20,4 +20,4 @@ "index.d.ts", "file-type-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/find-versions/find-versions-tests.ts b/types/find-versions/find-versions-tests.ts index 81ea6ca974..e92e6d9848 100644 --- a/types/find-versions/find-versions-tests.ts +++ b/types/find-versions/find-versions-tests.ts @@ -1,3 +1,4 @@ import findVersions = require('find-versions'); -findVersions('node v1.0.0'); +findVersions('node v1.0.0'); // $ExpectType string[] +findVersions('1.0', { loose: true }); // $ExpectType string[] diff --git a/types/find-versions/index.d.ts b/types/find-versions/index.d.ts index 449c5a45c3..9531c1628f 100644 --- a/types/find-versions/index.d.ts +++ b/types/find-versions/index.d.ts @@ -1,7 +1,8 @@ -// Type definitions for find-versions 2.0 +// Type definitions for find-versions 3.0 // Project: https://github.com/sindresorhus/find-versions // Definitions by: Leonid Logvinov +// Chris Arnesen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare function findVersions(version: string): string[]; +declare function findVersions(version: string, options?: { loose: boolean }): string[]; export = findVersions; diff --git a/types/fined/fined-tests.ts b/types/fined/fined-tests.ts new file mode 100644 index 0000000000..5ee4e79bc6 --- /dev/null +++ b/types/fined/fined-tests.ts @@ -0,0 +1,18 @@ +import fined = require('fined'); + +// $ExpectType Result | null +fined({ path: 'path/to/file', extensions: ['.js', '.json'] }); + +const opts = { + name: '.app', + cwd: '.', + extensions: { + rc: 'default-rc-loader', + '.yml': 'default-yml-loader', + }, +}; + +fined({ path: '.' }, opts); +fined({ path: '~', extensions: { rc: 'some-special-rc-loader' } }, opts); +fined({ path: '~' }, {}); +fined({ path: '~' }, { extensions: '.ext' }); diff --git a/types/fined/index.d.ts b/types/fined/index.d.ts new file mode 100644 index 0000000000..107a40760c --- /dev/null +++ b/types/fined/index.d.ts @@ -0,0 +1,23 @@ +// Type definitions for fined 1.1 +// Project: https://github.com/js-cli/fined#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = fined; + +declare function fined(path: string | fined.PathSpec, opts?: fined.PathSpec): fined.Result | null; + +declare namespace fined { + interface PathSpec { + path?: string; + name?: string; + extensions?: string | string[] | { [extension: string]: string | null }; + cwd?: string; + findUp?: boolean; + } + + interface Result { + path: string; + extension: string | { [extension: string]: string }; + } +} diff --git a/types/fined/tsconfig.json b/types/fined/tsconfig.json new file mode 100644 index 0000000000..ce11eba9be --- /dev/null +++ b/types/fined/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "fined-tests.ts" + ] +} diff --git a/types/fined/tslint.json b/types/fined/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/fined/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/flagged-respawn/flagged-respawn-tests.ts b/types/flagged-respawn/flagged-respawn-tests.ts new file mode 100644 index 0000000000..12f949f9fb --- /dev/null +++ b/types/flagged-respawn/flagged-respawn-tests.ts @@ -0,0 +1,14 @@ +import flaggedRespawn = require('flagged-respawn'); + +const flags = ['--flag']; + +flaggedRespawn(flags, process.argv, (ready, child, argv) => { + // $ExpectType boolean + ready; + // $ExpectType Process + child; + // $ExpectType string[] + argv; +}); +flaggedRespawn(flags, process.argv, '--flag', () => {}); +flaggedRespawn(flags, process.argv, ['--flag'], () => {}); diff --git a/types/flagged-respawn/index.d.ts b/types/flagged-respawn/index.d.ts new file mode 100644 index 0000000000..eea62b2e8c --- /dev/null +++ b/types/flagged-respawn/index.d.ts @@ -0,0 +1,24 @@ +// Type definitions for flagged-respawn 1.0 +// Project: https://github.com/js-cli/js-flagged-respawn +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +export = flaggedRespawn; + +declare function flaggedRespawn( + flags: string[], + argv: string[], + callback: flaggedRespawn.Callback +): void; +declare function flaggedRespawn( + flags: string[], + argv: string[], + forcedFlags: string | string[], + callback: flaggedRespawn.Callback +): void; + +declare namespace flaggedRespawn { + type Callback = (ready: boolean, proc: NodeJS.Process, argv: string[]) => void; +} diff --git a/types/flagged-respawn/tsconfig.json b/types/flagged-respawn/tsconfig.json new file mode 100644 index 0000000000..91fce74324 --- /dev/null +++ b/types/flagged-respawn/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "flagged-respawn-tests.ts" + ] +} diff --git a/types/flagged-respawn/tslint.json b/types/flagged-respawn/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/flagged-respawn/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/fleximap/fleximap-tests.ts b/types/fleximap/fleximap-tests.ts new file mode 100644 index 0000000000..4ca0181662 --- /dev/null +++ b/types/fleximap/fleximap-tests.ts @@ -0,0 +1,27 @@ +import { FlexiMap } from "fleximap"; + +let flexiMap = new FlexiMap(); +flexiMap = new FlexiMap({ arr: [] }); +flexiMap = new FlexiMap([{ arr: [] }, { obj: {} }]); + +flexiMap.set('keyA', {arr: [], obj: {}}); +let result = flexiMap.get(['keyA', 'arr']); + +flexiMap.add(['keyB1', 'keyB2', 'keyB3'], 123); +result = flexiMap.get(['keyB1', 'keyB2']); + +const arr = []; +arr[5] = 'Hello world'; + +flexiMap.set(['keyC1', 'keyC2'], arr); +result = flexiMap.get(['keyC1', 'keyC2']); + +flexiMap.set(['itemsA', 0], 'hello'); +flexiMap.set(['itemsA', 2], 'world'); +flexiMap.remove(['itemsA', 0]); + +flexiMap.set(['itemsB', 0], 'a'); +flexiMap.set(['itemsB', 1], 'b'); +flexiMap.set(['itemsB', 2], 'c'); +let splicedItems = flexiMap.splice(['itemsB'], 1, 1); +splicedItems = flexiMap.splice(['itemsB'], 1, 0, 'b2'); diff --git a/types/fleximap/index.d.ts b/types/fleximap/index.d.ts new file mode 100644 index 0000000000..8481134ffe --- /dev/null +++ b/types/fleximap/index.d.ts @@ -0,0 +1,38 @@ +// Type definitions for fleximap 0.9 +// Project: https://github.com/SocketCluster/fleximap +// Definitions by: Daniel Rose +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +export type KeyChain = any; + +export class FlexiMap { + constructor(object?: any[] | object); + + get(keyChain: KeyChain): any; + getRange(keyChain: KeyChain, fromIndex: number, toIndex: number): any; + getRaw(keyChain: KeyChain): any; + getAll(): any[] | object; + + count(keyChain: KeyChain): number; + + hasImmediateKey(key: string): boolean; + hasKey(keyChain: KeyChain): boolean; + hasType(keyChain: KeyChain, type: any): boolean; + hasValue(keyChain: KeyChain, value: any): boolean; + hasObject(keyChain: KeyChain, object: object): boolean; + + set(keyChain: KeyChain, value: any): any; + + add(keyChain: KeyChain, value: any): number; + + concat(keyChain: KeyChain, value: any): any; + + remove(keyChain: KeyChain): any; + removeRange(keyChain: KeyChain, fromIndex: number, toIndex: number): any[]; + removeAll(): void; + + splice(keyChain: KeyChain, index: number, count: number, ...items: any[]): any[]; + + pop(keyChain: KeyChain): any[]; +} diff --git a/types/fleximap/tsconfig.json b/types/fleximap/tsconfig.json new file mode 100644 index 0000000000..710fa81c96 --- /dev/null +++ b/types/fleximap/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "fleximap-tests.ts" + ] +} diff --git a/types/fleximap/tslint.json b/types/fleximap/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/fleximap/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/fuzzy-search/fuzzy-search-tests.ts b/types/fuzzy-search/fuzzy-search-tests.ts new file mode 100644 index 0000000000..667cda446f --- /dev/null +++ b/types/fuzzy-search/fuzzy-search-tests.ts @@ -0,0 +1,27 @@ +import FuzzySearch = require('fuzzy-search'); + +const f = new FuzzySearch(['1', '2', '3']); + +new FuzzySearch([{ a: 1 }, { a: 2 }, { a: 3 }], ['a']); + +new FuzzySearch([{ a: 1 }, { a: 2 }, { a: 3 }], ['a'], {}); + +new FuzzySearch([{ a: 1 }, { a: 2 }, { a: 3 }], ['a'], { caseSensitive: true }); + +new FuzzySearch([{ a: 1 }, { a: 2 }, { a: 3 }], ['a'], { sort: true }); + +new FuzzySearch([{ a: 1 }, { a: 2 }, { a: 3 }], ['a'], { caseSensitive: true, sort: true }); + +let strArr: string[]; + +strArr = f.haystack; +// $ExpectType string[] +f.keys; +// $ExpectType Required +f.options; + +strArr = new FuzzySearch(['1', '2', '3']).search(); +strArr = new FuzzySearch(['1', '2', '3']).search('2'); + +// $ExpectType number +FuzzySearch.isMatch('1', '1', false); diff --git a/types/fuzzy-search/index.d.ts b/types/fuzzy-search/index.d.ts new file mode 100644 index 0000000000..8c3d5103ff --- /dev/null +++ b/types/fuzzy-search/index.d.ts @@ -0,0 +1,26 @@ +// Type definitions for fuzzy-search 2.1 +// Project: https://github.com/wouter2203/fuzzy-search#readme +// Definitions by: Alex Deas +// BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +declare class FuzzySearch { + haystack: T[]; + keys: string[]; + options: Required; + + static isMatch(item: string, query: string, caseSensitive: boolean): number; + + constructor(haystack: T[], keys?: string[], options?: FuzzySearch.Options); + search(needle?: string): T[]; +} + +declare namespace FuzzySearch { + interface Options { + caseSensitive?: boolean; + sort?: boolean; + } +} + +export = FuzzySearch; diff --git a/types/fuzzy-search/tsconfig.json b/types/fuzzy-search/tsconfig.json new file mode 100644 index 0000000000..c72f9609d0 --- /dev/null +++ b/types/fuzzy-search/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "fuzzy-search-tests.ts" + ] +} diff --git a/types/fuzzy-search/tslint.json b/types/fuzzy-search/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/fuzzy-search/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/gapi.auth2/gapi.auth2-tests.ts b/types/gapi.auth2/gapi.auth2-tests.ts index 1fc03f7f4f..229a18f5fc 100644 --- a/types/gapi.auth2/gapi.auth2-tests.ts +++ b/types/gapi.auth2/gapi.auth2-tests.ts @@ -144,7 +144,8 @@ function handleSignoutClick(event: MouseEvent) { // Load the API and make an API call. Display the results on the screen. function makeApiCall() { gapi.client.people.people.get({ - resourceName: 'people/me' + resourceName: 'people/me', + personFields: 'names' }).then((resp) => { const p = document.createElement('p'); const name = resp.result.names[0].givenName; diff --git a/types/gapi.people/gapi.people-tests.ts b/types/gapi.people/gapi.people-tests.ts index 65b6339765..349f956b39 100644 --- a/types/gapi.people/gapi.people-tests.ts +++ b/types/gapi.people/gapi.people-tests.ts @@ -64,6 +64,7 @@ var request = gapi.client.people.people.connections.list({ 'resourceName': 'people/me', 'pageSize': 10, + 'personFields': 'names' }); request.execute(function(resp) { diff --git a/types/gapi.people/index.d.ts b/types/gapi.people/index.d.ts index 851eab2c0b..d39dc0b875 100644 --- a/types/gapi.people/index.d.ts +++ b/types/gapi.people/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for Google People API 1.0 // Project: https://developers.google.com/people/ // Definitions by: Tanguy Krotoff +// Joshua O'Brien // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -13,7 +14,7 @@ declare namespace gapi.client.people { resourceName: string; // Query parameters - requestMask?: RequestMask; + personFields: string; } function get(parameters: GetParameters): HttpRequest; @@ -21,7 +22,7 @@ declare namespace gapi.client.people { interface GetBatchGetParameters { // Query parameters resourcesName?: string; - requestMask?: RequestMask; + personFields: string; } function getBatchGet(parameters: GetBatchGetParameters): HttpRequest; @@ -49,7 +50,7 @@ declare namespace gapi.client.people { pageSize?: number; sortOrder?: SortOrder; syncToken?: string; - requestMask?: RequestMask; + personFields: string; } interface Response { @@ -60,10 +61,6 @@ declare namespace gapi.client.people { } } - interface RequestMask { - includeField: string; - } - type SourceType = 'SOURCE_TYPE_UNSPECIFIED' | 'ACCOUNT' | 'PROFILE' | 'DOMAIN_PROFILE' | 'CONTACT'; interface Source { diff --git a/types/gapi/gapi-tests.ts b/types/gapi/gapi-tests.ts index 7c5308aaf9..0de37fdccb 100644 --- a/types/gapi/gapi-tests.ts +++ b/types/gapi/gapi-tests.ts @@ -20,7 +20,8 @@ https://developers.google.com/api-client-library/javascript/reference/referenced }).then(function() { // 3. Initialize and make the API request. return gapi.client.people.people.get({ - resourceName: 'people/me' + resourceName: 'people/me', + personFields: 'name' }); }).then(function(response) { console.log(response.result); diff --git a/types/gdal/gdal-tests.ts b/types/gdal/gdal-tests.ts new file mode 100644 index 0000000000..d30c83d571 --- /dev/null +++ b/types/gdal/gdal-tests.ts @@ -0,0 +1,78 @@ +import * as gdal from 'gdal'; + +// gdal.checksumImage(srcRasterBand, 0, 0, 512, 512); + +gdal.config.get('GDAL_DATA'); +gdal.config.set('GDAL_DATA', 'C:\\warmerda\\bld\\data'); + +/*gdal.contourGenerate({ + src: srcRasterBand, + dst: dstRasterBand +});*/ + +gdal.decToDMS(60, 'lat'); +gdal.decToDMS(60, 'lat', 2); + +/*gdal.fillNodata({ + +});*/ + +let creationOptionsArray: string[]; +creationOptionsArray = ['VRT_CREATION_OPTION=...']; +let creationOptionsObject: object; +creationOptionsObject = { + VRT_CREATION_OPTION: '...' +}; +gdal.open('C:\\datasets\\ogr.shp'); +gdal.open('C:\\datasets\\ogr.shp', 'r'); +gdal.open('C:\\datasets\\ogr.shp', 'r', 'ESRI Shapefile'); +gdal.open('C:\\datasets\\ogr.shp', 'r', ['ESRI Shapefile']); +gdal.open('C:\\datasets\\ogr.shp', 'r+'); +gdal.open('C:\\datasets\\ogr.shp', 'r+', 'ESRI Shapefile'); +gdal.open('C:\\datasets\\ogr.shp', 'r+', ['ESRI Shapefile']); +gdal.open('C:\\datasets\\raster.vrt', 'w', 'VRT'); +gdal.open('C:\\datasets\\raster.vrt', 'w', 'VRT', 512, 512, 3, 1, creationOptionsArray); +gdal.open('C:\\datasets\\raster.vrt', 'w', 'VRT', 512, 512, 3, 1, creationOptionsObject); +gdal.open('C:\\datasets\\raster.vrt', 'w', ['VRT']); +gdal.open('C:\\datasets\\raster.vrt', 'w', ['VRT'], 512, 512, 3, 1, creationOptionsArray); +gdal.open('C:\\datasets\\raster.vrt', 'w', ['VRT'], 512, 512, 3, 1, creationOptionsObject); + +/*let polygonizeOptions: gdal.PolygonizeOptions; +polygonizeOptions = { + src: srcRasterBand, + dst: dstRasterBand, + connectedness: 1, + mask: maskRasterBand, + pixValField: 1, + useFloats: true +}; +gdal.polygonize(polygonizeOptions); +gdal.polygonize({ + src: srcRasterBand, + dst: dstRasterBand, + pixValField: 1 +});*/ + +gdal.quiet(); + +/*let reprojectImageOptions: gdal.ReprojectImageOptions; +reprojectImageOptions = { + src: srcRasterBand, + dst: dstRasterBand, + s_srs: sourceSRS, + t_srs: targetSRS +}; +gdal.reprojectImage(reprojectImageOptions); +gdal.reprojectImage({ + +}); + +gdal.sieveFilter({ + +}); + +gdal.suggestedWarpOutput({ + +});*/ + +gdal.verbose(); diff --git a/types/gdal/index.d.ts b/types/gdal/index.d.ts new file mode 100644 index 0000000000..d6c76ba226 --- /dev/null +++ b/types/gdal/index.d.ts @@ -0,0 +1,707 @@ +// Type definitions for gdal 0.9 +// Project: https://github.com/naturalatlas/node-gdal#readme +// Definitions by: Andrei Digori +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 3.0 + +export as namespace gdal; + +/* Internal interfaces */ + +export type TypedArray = Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array; +export type Resampling = 'NEAREST' | 'GAUSS' | 'CUBIC' | 'AVERAGE' | 'MODE' | 'AVERAGE_MAGPHASE' | 'NONE'; + +export interface XY { + x: number; + y: number; +} + +export interface XYZ extends XY { + z: number; +} + +export interface EnvelopeBounds { + minX: number; + maxX: number; + minY: number; + maxY: number; +} + +export interface Envelope3DBounds extends EnvelopeBounds { + minZ: number; + maxZ: number; +} + +export interface RasterBandStatistics { + min: number; + max: number; + mean: number; + std_dev: number; +} + +export interface RasterBandPixelsWriteOptions { + buffer_width?: number; + buffer_height?: number; + pixel_space?: number; + line_space?: number; +} + +export interface RasterBandPixelsReadOptions { + buffer_width?: number; + buffer_height?: number; + pixel_space?: number; + line_space?: number; + data_type?: string; +} + +export interface ContourGenerateOptions { + src: RasterBand; + dst: Layer; + offset?: number; + interval?: number; + fixedLevels?: number[]; + nodata?: number; + idField?: number; + elevField?: number; +} + +export interface FillNoDataOptions { + src: RasterBand; + mask?: RasterBand; + searchDist: number; + smoothingIterations?: number; +} + +export interface PolygonizeOptions { + src: RasterBand; + dst: Layer; + mask?: RasterBand; + pixValField: number; + connectedness?: number; + useFloats?: boolean; +} + +export interface ReprojectImageOptions { + src: Dataset; + dst: Dataset; + s_srs: SpatialReference; + t_srs: SpatialReference; + resampling?: string; + cutline?: Geometry; + srcBands?: number[]; + dstBands?: number[]; + srcAlphaBand?: number; + dstAlphaBand?: number; + srcNodata?: number; + dstNodata?: number; + memoryLimit?: number; + maxError?: number; + multi?: boolean; + options?: string[] | object; +} + +export interface SieveFilterOptions { + src: RasterBand; + dst: RasterBand; + mask?: RasterBand; + threshold: number; + connectedness?: number; +} + +export interface SuggestedWarpOutputOptions { + src: Dataset; + s_srs: SpatialReference; + t_srs: SpatialReference; + maxError?: number; +} + +/* From API: https://naturalatlas.github.io/node-gdal/ */ + +/* Constants */ + +// CPL Error Codes +export const CPLE_AppDefined: number; +export const CPLE_AssertionFailed: number; +export const CPLE_FileIO: number; +export const CPLE_IllegalArg: number; +export const CPLE_None: number; +export const CPLE_NotSupported: number; +export const CPLE_NoWriteAccess: number; +export const CPLE_ObjectNull: number; +export const CPLE_OpenFailed: number; +export const CPLE_OutOfMemory: number; +export const CPLE_UserInterrupt: number; + +// CPL Error Levels +export const CE_Debug: number; +export const CE_Failure: number; +export const CE_Fatal: number; +export const CE_None: number; +export const CE_Warning: number; + +// DCAP +export const DCAP_CREATE: string; +export const DCAP_CREATECOPY: string; +export const DCAP_VIRTUALIO: string; + +// DMD +export const DMD_CREATIONDATATYPES: string; +export const DMD_CREATIONOPTIONLIST: string; +export const DMD_EXTENSION: string; +export const DMD_HELPTOPIC: string; +export const DMD_LONGNAME: string; +export const DMD_MIMETYPE: string; + +// GCI +export const GCI_AlphaBand: string; +export const GCI_BlackBand: string; +export const GCI_BlueBand: string; +export const GCI_CyanBand: string; +export const GCI_GrayIndex: string; +export const GCI_GreenBand: string; +export const GCI_HueBand: string; +export const GCI_LightnessBand: string; +export const GCI_MagentaBand: string; +export const GCI_PaletteIndex: string; +export const GCI_RedBand: string; +export const GCI_SaturationBand: string; +export const GCI_Undefined: string; +export const GCI_YCbCr_CbBand: string; +export const GCI_YCbCr_CrBand: string; +export const GCI_YCbCr_YBand: string; +export const GCI_YellowBand: string; + +// GDT +export const GDT_Byte: string; +export const GDT_CFloat32: string; +export const GDT_CFloat64: string; +export const GDT_CInt16: string; +export const GDT_CInt32: string; +export const GDT_Float32: string; +export const GDT_Float64: string; +export const GDT_Int16: string; +export const GDT_Int32: string; +export const GDT_UInt16: string; +export const GDT_UInt32: string; +export const GDT_Unknown: string; + +// GRA +export const GRA_Average: string; +export const GRA_Bilinear: string; +export const GRA_Cubic: string; +export const GRA_CubicSpline: string; +export const GRA_Lanczos: string; +export const GRA_Mode: string; +export const GRA_NearestNeighbor: string; + +// ODsC +export const ODrCCreateDataSource: string; +export const ODrCDeleteDataSource: string; +export const ODsCCreateGeomFieldAfterCreateLayer: string; +export const ODsCCreateLayer: string; +export const ODsCDeleteLayer: string; + +// OFT +export const OFTBinary: string; +export const OFTDate: string; +export const OFTDateTime: string; +export const OFTInteger: string; +export const OFTIntegerList: string; +export const OFTReal: string; +export const OFTRealList: string; +export const OFTString: string; +export const OFTStringList: string; +export const OFTTime: string; +export const OFTWideString: string; +export const OFTWideStringList: string; + +// OJ +export const OJLeft: string; +export const OJRight: string; +export const OJUndefined: string; + +// OLC +export const OLCAlterFieldDefn: string; +export const OLCCreateField: string; +export const OLCCreateGeomField: string; +export const OLCDeleteFeature: string; +export const OLCDeleteField: string; +export const OLCFastFeatureCount: string; +export const OLCFastGetExtent: string; +export const OLCFastSetNextByIndex: string; +export const OLCFastSpatialFilter: string; +export const OLCIgnoreFields: string; +export const OLCRandomRead: string; +export const OLCRandomWrite: string; +export const OLCReorderFields: string; +export const OLCSequentialWrite: string; +export const OLCStringsAsUTF8: string; +export const OLCTransactions: string; + +// wkbByteOrder +export const wkbNDR: string; +export const wkbXDR: string; + +// wkbGeometryType +export const wkb25DBit: number; +export const wkbGeometryCollection: number; +export const wkbGeometryCollection25D: number; +export const wkbLinearRing: string; +export const wkbLinearRing25D: number; +export const wkbLineString: number; +export const wkbLineString25D: number; +export const wkbMultiLineString: number; +export const wkbMultiLineString25D: number; +export const wkbMultiPoint: number; +export const wkbMultiPoint25D: number; +export const wkbMultiPolygon: number; +export const wkbMultiPolygon25D: number; +export const wkbNone: number; +export const wkbPoint: number; +export const wkbPoint25D: number; +export const wkbPolygon: number; +export const wkbPolygon25D: number; +export const wkbUnknown: number; + +// wkbVariant +export const wkbVariantIso: string; +export const wkbVariantOgc: string; +export const wkbVariantOldOgc: string; + +/* Classes and interfaces */ + +export class CoordinateTransformation { + constructor(source: SpatialReference, target: SpatialReference | Dataset); + transformPoint(x: number, y: number, z?: number): XYZ; +} + +export interface Dataset { + buildOverviews(resampling: Resampling, overviews: number[], bands?: number[]): void; + close(): void; + executeSQL(statement: string, spatial_filter?: Geometry, dialect?: string): Layer; + flush(): void; + getFileList(): string[]; + getGCPProjection(): string; + getGCPs(): object[]; + getMetadata(domain?: string): object; + setGCPs(gcps: object[], projection: string): void; + testCapability(capability: string): boolean; + + readonly bands: DatasetBands; + readonly description: string; + readonly driver: Driver; + geoTransform: number[]; + readonly layers: DatasetLayers; + readonly rasterSize: XY; + srs: SpatialReference; +} + +export interface DatasetBands { + count(): number; + create(dataType: number): RasterBand; + forEach(callback: (band: RasterBand, i: number) => void): void; + get(id: number): RasterBand; + map(callback: (band: RasterBand, i: number) => T): T[]; + + readonly ds: Dataset; +} + +export interface DatasetLayers { + copy(src_lyr_name: string, dst_lyr_name: string, options?: object | string[]): Layer; + count(): number; + create(name: string, srs: SpatialReference, geomType: number | Geometry, creation_options: string[] | object): Layer; + forEach(callback: (layer: Layer, i: number) => void): void; + get(key: string | number): Layer; + map(callback: (layer: Layer, i: number) => T): T[]; + remove(index: number): void; + + readonly ds: Dataset; +} + +export interface Driver { + copyFiles(name_old: string, name_new: string): void; + create(filename: string, x_size?: number, y_size?: number, band_count?: number, data_type?: number, creation_options?: string[] | object): Dataset; + createCopy(filename: string, src: Dataset, strict?: boolean, options?: string[] | object): Dataset; + deleteDataset(filename: string): void; + getMetadata(domain?: string): object; + open(path: string, mode?: 'r' | 'r+'): Dataset; + rename(new_name: string, old_name: string): void; + + readonly description: string; +} + +export class Envelope { + constructor(bounds: EnvelopeBounds); + contains(envelope: Envelope): boolean; + intersect(envelope: Envelope): void; + intersects(envelope: Envelope): boolean; + isEmpty(): boolean; + merge(envelope: Envelope): void; + toPolygon(): Polygon; +} + +export class Envelope3D extends Envelope { + constructor(bounds: Envelope3DBounds); +} + +export class Feature { + constructor(definition: Layer | FeatureDefn); + clone(): Feature; + destroy(): void; + equals(feature: Feature): boolean; + getFieldDefn(index: number): FieldDefn; + getGeometry(): Geometry; + setFrom(feature: Feature, index_map?: number[], forgiving?: boolean): void; + setGeometry(geometry: Geometry): void; + + readonly defn: FeatureDefn; + fid: number; + readonly fields: FeatureFields; +} + +export class FeatureDefn { + constructor(); + clone(): FeatureDefn; + + readonly fields: FeatureDefnFields; + geomIgnored: boolean; + geomType: number; + readonly name: string; + styleIgnored: boolean; +} + +export interface FeatureDefnFields { + add(field: FieldDefn | FieldDefn[]): void; + count(): number; + forEach(callback: (field: FieldDefn, i: number) => void): void; + get(key: string | number): FieldDefn; + getNames(): string[]; + indexOf(name: string): number; + map(callback: (field: FieldDefn, i: number) => T): T[]; + remove(key: string | number): void; + reorder(map: number[]): void; + + readonly featureDefn: FeatureDefn; +} + +export interface FeatureFields { + count(): number; + forEach(callback: (value: any, key: string) => void): void; + get(key: string | number): any; + getNames(): string[]; + indexOf(name: string): number; + map(callback: (value: any, key: string) => T): T[]; + reset(values: object, value: any): void; + set(key: string | number, value: any): void; + toArray(): any[]; + toJSON(): string; + toObject(): object; + + readonly feature: Feature; +} + +export class FieldDefn { + constructor(name: string, type: string); + + ignored: boolean; + justification: string; + name: string; + precision: number; + type: string; + width: number; +} + +export interface GDALDrivers { + count(): number; + forEach(callback: (driver: Driver, i: number) => void): void; + get(index: number | string): Driver; + getNames(): string[]; + map(callback: (driver: Driver, i: number) => T): T[]; +} + +export abstract class Geometry { + static create(type: number): Geometry; + static fromWKB(wkb: number, srs?: SpatialReference): Geometry; + static fromWKT(wkt: string, srs?: SpatialReference): Geometry; + static getConstructor(type: number): Geometry; + static getName(type: number): string; + + boundary(): Geometry; + buffer(distance: number, segments: number): Geometry; + centroid(): Point; + clone(): Geometry; + closeRings(): void; + contains(geometry: Geometry): boolean; + convexHull(): Geometry; + crosses(geometry: Geometry): boolean; + difference(geometry: Geometry): Geometry; + disjoint(geometry: Geometry): boolean; + distance(geometry: Geometry): number; + empty(): void; + equals(geometry: Geometry): boolean; + getEnvelope(): Envelope; + getEnvelope3D(): Envelope3D; + intersection(geometry: Geometry): Geometry; + intersects(geometry: Geometry): boolean; + isEmpty(): boolean; + isRing(): boolean; + isSimple(): boolean; + isValid(): boolean; + overlaps(geometry: Geometry): boolean; + segmentize(segment_length: number): number; + simplify(tolerance: number): Geometry; + simplifyPreserveTopology(tolerance: number): Geometry; + swapXY(): void; + symDifference(geometry: Geometry): Geometry; + toGML(): Geometry; + toJSON(): Geometry; + toKML(): Geometry; + toObject(): object; + touches(geometry: Geometry): boolean; + toWKB(byte_order?: string, variant?: string): Geometry; + toWKT(): Geometry; + transform(transformation: CoordinateTransformation): void; + transformTo(srs: SpatialReference): void; + union(geometry: Geometry): Geometry; + within(geometry: Geometry): boolean; + + readonly coordinateDimension: number; + readonly dimension: number; + readonly name: string; + srs: SpatialReference; + readonly wkbSize: number; + readonly wkbType: number; +} + +export class GeometryCollection extends Geometry { + getArea(): number; + getLength(): number; + + children: GeometryCollectionChildren; +} + +export interface GeometryCollectionChildren { + add(geometry: Geometry | Geometry[]): void; + count(): number; + forEach(callback: (geometry: Geometry, i: number) => void): void; + get(index: number): Geometry; + map(callback: (geometry: Geometry, i: number) => T): T[]; + remove(index: number): void; + toArray(): Geometry[]; + readonly layer: Layer; +} + +export interface Layer { + flush(): void; + getExtent(force?: boolean): Envelope; + getSpatialFilter(): Geometry; + setAttributeFilter(filter: string): void; + setSpatialFilter(filter: Geometry): void; + setSpatialFilter(minX: number, maxX: number, minY: number, maxY: number): void; + testCapability(capability: string): boolean; + readonly ds: Dataset; + readonly features: LayerFeatures; + readonly fidColumn: string; + readonly fields: LayerFields; + readonly geomColumn: string; + readonly geomType: number; + readonly name: string; + readonly srs: SpatialReference; +} + +export interface LayerFeatures { + add(feature: Feature): void; + count(force?: boolean): number; + first(): Feature; + forEach(callback: (feature: Feature, i: number) => void): void; + get(id: number): Feature; + map(callback: (feature: Feature, i: number) => T): T[]; + next(): Feature; + remove(id: number): void; + set(id: number, feature: Feature): void; + readonly layer: Layer; +} + +export interface LayerFields { + add(def: FieldDefn | FieldDefn[], approx?: boolean): void; + count(): number; + forEach(callback: (field: FieldDefn, i: number) => void): void; + fromJSON(object: object, approx_ok?: boolean): LayerFields; + get(field: string | number): FieldDefn; + getNames(): string[]; + indexOf(field: string): number; + map(callback: (field: FieldDefn, i: number) => T): T[]; + remove(field: string | number): void; + reorder(map: number[]): void; + readonly layer: Layer; +} + +export class LinearRing extends LineString { + getArea(): number; +} + +export class LineString extends Geometry { + addSubLineString(line: LineString, start?: number, end?: number): void; + getLength(): number; + value(distance: number): Point; + readonly points: LineStringPoints; +} + +export interface LineStringPoints { + add(point: Point | Point[]): void; + count(): number; + forEach(callback: (point: Point, i: number) => void): void; + get(index: number): Point; + map(callback: (point: Point, i: number) => T): T[]; + remove(index: number): void; + resize(count: number): void; + reverse(): void; + set(index: number, point: Point): void; + toArray(): Point[]; +} + +export class MultiLineString extends GeometryCollection { + polygonize(): Polygon; +} + +export class MultiPoint extends GeometryCollection {} + +export class MultiPolygon extends GeometryCollection { + getArea(): number; + unionCascaded(): Geometry; +} + +export class Point extends Geometry { + constructor(x: number, y: number, z?: number); + x: number; + y: number; + z: number; +} + +export class Polygon extends Geometry { + getArea(): number; + rings: PolygonRings; +} + +export interface PolygonRings { + add(ring: LinearRing | LinearRing[]): void; + count(): number; + forEach(callback: (ring: LinearRing, i: number) => void): void; + get(index: number): LinearRing; + map(callback: (ring: LinearRing, i: number) => T): T[]; + remove(index: number): void; + toArray(): LinearRing[]; + readonly layer: Layer; +} + +export interface RasterBand { + computeStatistics(allow_approximation: boolean): RasterBandStatistics; + createMaskBand(flags: number): void; + fill(real_value: number, imaginary_value?: number): void; + flush(): void; + getMaskBand(): RasterBand; + getMaskFlags(): number; + getMetadata(domain?: string): object; + getStatistics(allow_approximation: boolean, force: boolean): RasterBandStatistics; + setStatistics(min: number, max: number, mean: number, std_dev: number): void; + readonly blockSize: XY; + categoryNames: string[]; + colorInterpretation: string; + readonly dataType: string; + readonly description: string; + readonly ds: Dataset; + readonly hasArbitraryOverviews: boolean; + readonly id: number; + readonly maximum: number; + readonly minimum: number; + noDataValue: number; + offset: number; + readonly overviews: RasterBandOverviews; + readonly pixels: RasterBandPixels; + readonly readOnly: boolean; + scale: number; + readonly size: XY; + unitType: string; +} + +export interface RasterBandOverviews { + count(): number; + forEach(callback: (overviewBand: RasterBand, i: number) => void): void; + get(index: number): RasterBand; + getBySampleCount(samples: number): RasterBand; + map(callback: (overviewBand: RasterBand, i: number) => T): T[]; +} + +export interface RasterBandPixels { + get(x: number, y: number): number; + read(x: number, y: number, width: number, height: number, data?: TypedArray, options?: RasterBandPixelsReadOptions): TypedArray; + readBlock(x: number, y: number, data?: TypedArray): TypedArray; + set(x: number, y: number, value: number): void; + write(x: number, y: number, width: number, height: number, data: TypedArray, options?: RasterBandPixelsWriteOptions): void; + writeBlock(x: number, y: number, data: TypedArray): void; +} + +export class SpatialReference { + constructor(wkt?: string); + autoIdentifyEPSG(): void; + clone(): SpatialReference; + cloneGeogCS(): SpatialReference; + EPSGTreatsAsLatLong(): boolean; + EPSGTreatsAsNorthingEasting(): boolean; + getAngularUnits(): { value: any, unit: any }; + getAttrValue(node_name: string, attr_index?: number): string; + getAuthorityCode(target_key: string): string; + getAuthorityName(target_key: string): string; + getLinearUnits(): { value: any, unit: any }; + isCompound(): boolean; + isGeocentric(): boolean; + isGeographic(): boolean; + isLocal(): boolean; + isProjected(): boolean; + isSame(srs: SpatialReference): boolean; + isSameGeogCS(srs: SpatialReference): boolean; + isSameVertCS(srs: SpatialReference): boolean; + isVertical(): boolean; + morphFromESRI(): void; + morphToESRI(): void; + setWellKnownGeogCS(name: string): void; + toPrettyWKT(simplify?: boolean): string; + toProj4(): string; + toWKT(): string; + toXML(): string; + validate(): string; + static fromCRSURL(input: string): SpatialReference; + static fromEPSG(input: string): SpatialReference; + static fromEPSGA(input: number): SpatialReference; + static fromESRI(input: string[]): SpatialReference; + static fromMICoordSys(input: string): SpatialReference; + static fromProj4(input: string): SpatialReference; + static fromURL(url: string): SpatialReference; + static fromURN(input: string): SpatialReference; + static fromUserInput(input: string): SpatialReference; + static fromWKT(wkt: string): SpatialReference; + static fromWMSAUTO(input: string): SpatialReference; + static fromXML(input: string): SpatialReference; +} + +export namespace config { + function get(key: string): string; + function set(key: string, value: string): void; +} + +export const drivers: GDALDrivers; +export const lastError: { number: any, message: any, type: any }; +export const version: string; + +export function checksumImage(src: RasterBand, x?: number, y?: number, w?: number, h?: number): number; +export function contourGenerate(options: ContourGenerateOptions): void; +export function decToDMS(angle: number, axis: 'lat' | 'long', precision?: number): string; +export function fillNodata(options: FillNoDataOptions): void; +export function open(path: string, mode?: 'r' | 'r+' | 'w', drivers?: string | string[]): Dataset; +export function open(path: string, mode?: 'w', drivers?: string | string[], x_size?: number, y_size?: number, band_count?: number, data_type?: number, creation_options?: string[] | object): Dataset; +export function polygonize(options: PolygonizeOptions): void; +export function quiet(): void; +export function reprojectImage(options: ReprojectImageOptions): void; +export function sieveFilter(options: SieveFilterOptions): void; +export function suggestedWarpOutput(options: SuggestedWarpOutputOptions): { rasterSize: any, geoTransform: any }; +export function verbose(): void; diff --git a/types/gdal/tsconfig.json b/types/gdal/tsconfig.json new file mode 100644 index 0000000000..5c11132a33 --- /dev/null +++ b/types/gdal/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "gdal-tests.ts" + ] +} diff --git a/types/gdal/tslint.json b/types/gdal/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/gdal/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/ghauth/ghauth-tests.ts b/types/ghauth/ghauth-tests.ts new file mode 100644 index 0000000000..56bc0cd1b0 --- /dev/null +++ b/types/ghauth/ghauth-tests.ts @@ -0,0 +1,29 @@ +/// +import ghauth = require("ghauth"); +import { AuthOptions, TokenData } from "ghauth"; + +// Full +const authOptions1: AuthOptions = { + configName: "awesome", + noSave: true, + authUrl: "https://api.github.com/authorizations", + promptName: "GitHub", + scopes: ["user"], + note: "This token is for my awesome app", + userAgent: "My Awesome App", +}; + +ghauth(authOptions1, (err: Error, authData: TokenData) => { + authData.user; + authData.token; +}); + +// Required +const authOptions2: AuthOptions = { + configName: "awesome", +}; + +ghauth(authOptions2, (err: Error, authData: TokenData) => { + authData.user; + authData.token; +}); diff --git a/types/ghauth/index.d.ts b/types/ghauth/index.d.ts new file mode 100644 index 0000000000..3d91ab8ef5 --- /dev/null +++ b/types/ghauth/index.d.ts @@ -0,0 +1,49 @@ +// Type definitions for ghauth 3.2 +// Project: https://github.com/rvagg/ghauth +// Definitions by: Leko +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare function ghauth(authOptions: ghauth.AuthOptions, callback: (err: Error, tokenData: ghauth.TokenData) => void): void; + +declare namespace ghauth { + interface AuthOptions { + configName: string; + + /** + * @default false + */ + noSave?: boolean; + + /** + * @default "https://api.github.com/authorizations" + */ + authUrl?: string; + + /** + * @default "GitHub" + */ + promptName?: string; + + /** + * @default [] + */ + scopes?: ReadonlyArray; + + /** + * @default "Node.js command-line app with ghauth" + */ + note?: string; + + /** + * @default "Magic Node.js application that does magic things with ghauth" + */ + userAgent?: string; + } + + interface TokenData { + user: string; + token: string; + } +} + +export = ghauth; diff --git a/types/ghauth/tsconfig.json b/types/ghauth/tsconfig.json new file mode 100644 index 0000000000..0b946b4ae8 --- /dev/null +++ b/types/ghauth/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "ghauth-tests.ts" + ] +} diff --git a/types/ghauth/tslint.json b/types/ghauth/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/ghauth/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/gl-react-dom/GLViewDOM.d.ts b/types/gl-react-dom/GLViewDOM.d.ts index 8450a16a00..5ceef51ec8 100644 --- a/types/gl-react-dom/GLViewDOM.d.ts +++ b/types/gl-react-dom/GLViewDOM.d.ts @@ -4,10 +4,10 @@ export type SupportedImage = 'image/png' | 'image/jpeg' | 'image/bmp' | 'image/w export type ValidQuality = 0.0 | 0.1 | 0.2 | 0.3 | 0.4 | 0.5 | 0.6 | 0.7 | 0.8 | 0.9 | 1.0; export interface GLViewDOMProps { - onContextCreate: (gl: WebGLRenderingContext) => void; - onContextFailure: (e: Error) => void; - onContextLost: () => void; - onContextRestored: (gl: WebGLRenderingContext) => void; + onContextCreate?: (gl: WebGLRenderingContext) => void; + onContextFailure?: (e: Error) => void; + onContextLost?: () => void; + onContextRestored?: (gl: WebGLRenderingContext) => void; webglContextAttributes?: WebGLContextAttributes; pixelRatio?: number; width: number; diff --git a/types/gl-react-dom/gl-react-dom-tests.tsx b/types/gl-react-dom/gl-react-dom-tests.tsx new file mode 100644 index 0000000000..6d3852a156 --- /dev/null +++ b/types/gl-react-dom/gl-react-dom-tests.tsx @@ -0,0 +1,27 @@ +import * as React from 'react'; +import * as ReactDOM from 'react-dom'; +import { Surface } from 'gl-react-dom'; +import { Shaders, GLSL, Node } from 'gl-react'; + +const shaders = Shaders.create({ + Test: { + frag: GLSL` + precision highp float; + varying vec2 uv; + void main() { + gl_FragColor = vec4(uv.x, uv.y, 0.5, 1.0); + }` + } +}); + +const App = () => ( +
+ + + +
+); + +const element = document.createElement('div'); +document.body.appendChild(element); +ReactDOM.render(, element); diff --git a/types/gl-react-dom/tsconfig.json b/types/gl-react-dom/tsconfig.json index 9c4d38ca44..49a1ee91ff 100644 --- a/types/gl-react-dom/tsconfig.json +++ b/types/gl-react-dom/tsconfig.json @@ -1,6 +1,7 @@ { "files": [ - "index.d.ts" + "index.d.ts", + "gl-react-dom-tests.tsx" ], "compilerOptions": { "module": "commonjs", diff --git a/types/gl-react-expo/GLViewNative.d.ts b/types/gl-react-expo/GLViewNative.d.ts index 4f0270dd68..5320ccaaa2 100644 --- a/types/gl-react-expo/GLViewNative.d.ts +++ b/types/gl-react-expo/GLViewNative.d.ts @@ -3,7 +3,7 @@ import * as React from 'react'; // import { GLView as EXGLView } from 'expo'; export interface GLViewNativeProps { - onContextCreate: (gl: WebGLRenderingContext) => void; + onContextCreate?: (gl: WebGLRenderingContext) => void; style?: any; children?: any; } diff --git a/types/gl-react-expo/gl-react-expo-tests.tsx b/types/gl-react-expo/gl-react-expo-tests.tsx new file mode 100644 index 0000000000..2eb1fee9a9 --- /dev/null +++ b/types/gl-react-expo/gl-react-expo-tests.tsx @@ -0,0 +1,27 @@ +import * as React from 'react'; +import * as ReactDOM from 'react-dom'; +import { Surface } from 'gl-react-expo'; +import { Shaders, GLSL, Node } from 'gl-react'; + +const shaders = Shaders.create({ + Test: { + frag: GLSL` + precision highp float; + varying vec2 uv; + void main() { + gl_FragColor = vec4(uv.x, uv.y, 0.5, 1.0); + }` + } +}); + +const App = () => ( +
+ + + +
+); + +const element = document.createElement('div'); +document.body.appendChild(element); +ReactDOM.render(, element); diff --git a/types/gl-react-expo/tsconfig.json b/types/gl-react-expo/tsconfig.json index 9c4d38ca44..95487128f4 100644 --- a/types/gl-react-expo/tsconfig.json +++ b/types/gl-react-expo/tsconfig.json @@ -1,6 +1,7 @@ { "files": [ - "index.d.ts" + "index.d.ts", + "gl-react-expo-tests.tsx" ], "compilerOptions": { "module": "commonjs", diff --git a/types/gl-react-headless/GLViewHeadless.d.ts b/types/gl-react-headless/GLViewHeadless.d.ts index a94c1f9769..9b90b25958 100644 --- a/types/gl-react-headless/GLViewHeadless.d.ts +++ b/types/gl-react-headless/GLViewHeadless.d.ts @@ -1,10 +1,10 @@ import * as React from 'react'; export interface GLViewHeadlessProps { - onContextCreate: (gl: WebGLRenderingContext) => void; - onContextFailure: (e: Error) => void; - onContextLost: () => void; - onContextRestored: (gl: WebGLRenderingContext) => void; + onContextCreate?: (gl: WebGLRenderingContext) => void; + onContextFailure?: (e: Error) => void; + onContextLost?: () => void; + onContextRestored?: (gl: WebGLRenderingContext) => void; webglContextAttributes?: WebGLContextAttributes; pixelRatio?: number; width: number; diff --git a/types/gl-react-headless/gl-react-headless-tests.tsx b/types/gl-react-headless/gl-react-headless-tests.tsx new file mode 100644 index 0000000000..58f0cbc13b --- /dev/null +++ b/types/gl-react-headless/gl-react-headless-tests.tsx @@ -0,0 +1,27 @@ +import * as React from 'react'; +import * as ReactDOM from 'react-dom'; +import { Surface } from 'gl-react-headless'; +import { Shaders, GLSL, Node } from 'gl-react'; + +const shaders = Shaders.create({ + Test: { + frag: GLSL` + precision highp float; + varying vec2 uv; + void main() { + gl_FragColor = vec4(uv.x, uv.y, 0.5, 1.0); + }` + } +}); + +const App = () => ( +
+ + + +
+); + +const element = document.createElement('div'); +document.body.appendChild(element); +ReactDOM.render(, element); diff --git a/types/gl-react-headless/tsconfig.json b/types/gl-react-headless/tsconfig.json index 9c4d38ca44..8a7f2a4b22 100644 --- a/types/gl-react-headless/tsconfig.json +++ b/types/gl-react-headless/tsconfig.json @@ -1,6 +1,7 @@ { "files": [ - "index.d.ts" + "index.d.ts", + "gl-react-headless-tests.tsx" ], "compilerOptions": { "module": "commonjs", diff --git a/types/gl-react-native/GLViewNative.d.ts b/types/gl-react-native/GLViewNative.d.ts index 0a780d3aa7..b4a4c75bc1 100644 --- a/types/gl-react-native/GLViewNative.d.ts +++ b/types/gl-react-native/GLViewNative.d.ts @@ -1,8 +1,8 @@ import * as React from 'react'; export interface GLViewNativeProps { - onContextCreate: (gl: WebGLRenderingContext) => void; - onContextFailure: (e: Error) => void; + onContextCreate?: (gl: WebGLRenderingContext) => void; + onContextFailure?: (e: Error) => void; style?: any; children?: any; } diff --git a/types/gl-react-native/gl-react-native-tests.tsx b/types/gl-react-native/gl-react-native-tests.tsx new file mode 100644 index 0000000000..f74c9dc926 --- /dev/null +++ b/types/gl-react-native/gl-react-native-tests.tsx @@ -0,0 +1,27 @@ +import * as React from 'react'; +import * as ReactDOM from 'react-dom'; +import { Surface } from 'gl-react-native'; +import { Shaders, GLSL, Node } from 'gl-react'; + +const shaders = Shaders.create({ + Test: { + frag: GLSL` + precision highp float; + varying vec2 uv; + void main() { + gl_FragColor = vec4(uv.x, uv.y, 0.5, 1.0); + }` + } +}); + +const App = () => ( +
+ + + +
+); + +const element = document.createElement('div'); +document.body.appendChild(element); +ReactDOM.render(, element); diff --git a/types/gl-react-native/tsconfig.json b/types/gl-react-native/tsconfig.json index 9c4d38ca44..0ffab2bab3 100644 --- a/types/gl-react-native/tsconfig.json +++ b/types/gl-react-native/tsconfig.json @@ -1,6 +1,7 @@ { "files": [ - "index.d.ts" + "index.d.ts", + "gl-react-native-tests.tsx" ], "compilerOptions": { "module": "commonjs", diff --git a/types/gl-react/index.d.ts b/types/gl-react/index.d.ts index e1332fd964..84b82ddd2d 100644 --- a/types/gl-react/index.d.ts +++ b/types/gl-react/index.d.ts @@ -124,7 +124,7 @@ export interface Framebuffer { export interface NodeProps { shader: ShaderIdentifier | ShaderDefinition; uniformsOptions?: any; - uniforms: { [key: string]: any }; + uniforms?: { [key: string]: any }; ignoreUnusedUniforms?: string[] | boolean; sync?: boolean; width?: number; diff --git a/types/google-apps-script/google-apps-script.slides.d.ts b/types/google-apps-script/google-apps-script.slides.d.ts index 90e034ff60..3d1aac9227 100644 --- a/types/google-apps-script/google-apps-script.slides.d.ts +++ b/types/google-apps-script/google-apps-script.slides.d.ts @@ -836,9 +836,11 @@ declare namespace GoogleAppsScript { getNotesMaster(): NotesMaster; getNotesPageHeight(): Number; getNotesPageWidth(): Number; + getPageElementById(id: string): PageElement; getPageHeight(): Number; getPageWidth(): Number; getSelection(): Selection; + getSlideById(id: string): Slide; getSlides(): Slide[]; getUrl(): string; getViewers(): Base.User[]; diff --git a/types/google-cloud__kms/google-cloud__kms-tests.ts b/types/google-cloud__kms/google-cloud__kms-tests.ts new file mode 100644 index 0000000000..96ab80c7c1 --- /dev/null +++ b/types/google-cloud__kms/google-cloud__kms-tests.ts @@ -0,0 +1,117 @@ +import kms = require('@google-cloud/kms'); + +let kmsClientV1: kms.v1.KeyManagementServiceClient; +kmsClientV1 = new kms.v1.KeyManagementServiceClient(); + +const credentials = { + type: 'service_account', + project_id: '****', + private_key_id: '****', + private_key: '****', + client_email: '****', + client_id: '****', + auth_uri: 'https://accounts.google.com/o/oauth2/auth', + token_uri: 'https://oauth2.googleapis.com/token', + auth_provider_x509_cert_url: 'https://www.googleapis.com/oauth2/v1/certs', + client_x509_cert_url: '****' +}; + +let kmsClient: kms.KeyManagementServiceClient; +kmsClient = new kms.KeyManagementServiceClient({ credentials }); + +async function exampleListKeyRings() { + const locationPath = kmsClient.locationPath('[PROJECT_ID]', '[LOCATION]'); + const [ asyncKeyRings ] = await kmsClient.listKeyRings({parent: locationPath}); + if (asyncKeyRings.length > 0) { + const keyRing = asyncKeyRings[ 0 ]; + console.log(`KeyRing: ${keyRing.name}`); + } + + kmsClient.listKeyRings({parent: locationPath}, (err, [ callbackKeyRings ]) => { + if (callbackKeyRings.length > 0) { + const keyRing = callbackKeyRings[ 0 ]; + console.log(`KeyRing: ${keyRing.name}`); + } + }); + + kmsClient.listKeyRings({parent: locationPath}, { timeout: 1000 }, (err, [ callbackWithOptionsKeyRings ]) => { + if (callbackWithOptionsKeyRings.length > 0) { + const keyRing = callbackWithOptionsKeyRings[ 0 ]; + console.log(`KeyRing: ${keyRing.name}`); + } + }); +} + +async function exampleListCryptoKeys() { + const keyRingPath = kmsClient.keyRingPath('[PROJECT_ID]', '[LOCATION]', '[KEYRING_ID]'); + const [ asyncKeys ] = await kmsClient.listCryptoKeys({parent: keyRingPath}); + if (asyncKeys.length > 0) { + const key = asyncKeys[ 0 ]; + console.log(`CryptoKey: ${key.name} Version: ${key.primary.name}`); + } + + kmsClient.listCryptoKeys({parent: keyRingPath}, (err, [ callbackKeys ]) => { + if (callbackKeys.length > 0) { + const key = callbackKeys[ 0 ]; + console.log(`CryptoKey: ${key.name} Version: ${key.primary.name}`); + } + }); + + kmsClient.listCryptoKeys({parent: keyRingPath}, { timeout: 1000 }, (err, [ callbackWithOptionsKeys ]) => { + if (callbackWithOptionsKeys.length > 0) { + const key = callbackWithOptionsKeys[ 0 ]; + console.log(`CryptoKey: ${key.name} Version: ${key.primary.name}`); + } + }); +} + +async function exampleEncrypt() { + const formattedName = kmsClient.cryptoKeyPath('[PROJECT_ID]', '[LOCATION]', '[KEYRING_ID]', '[KEY_ID]'); + const unencryptedText = new Buffer('Hello World'); + + const [ asyncEncryptResult ] = await kmsClient.encrypt({ name: formattedName, plaintext: unencryptedText.toString('base64') }); + if (asyncEncryptResult != null) { + console.log(`Encrypted: ${asyncEncryptResult.ciphertext.toString('base64')}`); + } + + kmsClient.encrypt({ name: formattedName, plaintext: unencryptedText.toString('base64') }, (err, [ callbackEncryptResult ]) => { + if (callbackEncryptResult != null) { + console.log(`Encrypted: ${callbackEncryptResult.ciphertext.toString('base64')}`); + } + }); + + kmsClient.encrypt({ name: formattedName, plaintext: unencryptedText.toString('base64') }, { timeout: 1000 }, (err, [ callbackWithOptionsEncryptResult ]) => { + if (callbackWithOptionsEncryptResult != null) { + console.log(`Encrypted: ${callbackWithOptionsEncryptResult.ciphertext.toString('base64')}`); + } + }); +} + +async function exampleDecrypt() { + // Example pulling a file from Cloud Storage + // const secretsStorage = new Storage({ credentials }); + // const bucket = secretsStorage.bucket('[KMS_STORAGE_BUCKET]'); + // const filePath = '[PATH_TO_KMS_ENCRYPTED_FILE'; + // const file = bucket.file(filePath); + // const buffers = await file.download(); + // const buffer = buffers[ 0 ]; + + const buffer = new Buffer('[ENCRYPTED_SOURCE_BUFFER]'); + const formattedName = kmsClient.cryptoKeyPath('[PROJECT_ID]', '[LOCATION]', '[KEYRING_ID]', '[KEY_ID]'); + const [ asyncDecryptResult ] = await kmsClient.decrypt({name: formattedName, ciphertext: buffer.toString('base64') }); + if (asyncDecryptResult != null) { + console.log(`Decrypted: ${asyncDecryptResult.plaintext}`); + } + + kmsClient.decrypt({ name: formattedName, ciphertext: buffer.toString('base64') }, (err, [ callbackDecryptResult ]) => { + if (callbackDecryptResult != null) { + console.log(`Decrypted: ${callbackDecryptResult.plaintext}`); + } + }); + + kmsClient.decrypt({ name: formattedName, ciphertext: buffer.toString('base64') }, (err, [ callbackWithOptionsDecryptResult ]) => { + if (callbackWithOptionsDecryptResult != null) { + console.log(`Decrypted: ${callbackWithOptionsDecryptResult.plaintext}`); + } + }); +} diff --git a/types/google-cloud__kms/index.d.ts b/types/google-cloud__kms/index.d.ts new file mode 100644 index 0000000000..237c7115a0 --- /dev/null +++ b/types/google-cloud__kms/index.d.ts @@ -0,0 +1,273 @@ +// Type definitions for @google-cloud/kms 0.2 +// Project: https://github.com/googleapis/nodejs-kms +// Definitions by: Ben Talbot +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +/// + +import * as google_protobuf_timestamp_pb from "google-protobuf/google/protobuf/timestamp_pb"; + +export namespace v1 { + enum CryptoKeyVersionAlgorithm { + // Not specified. + CRYPTO_KEY_VERSION_ALGORITHM_UNSPECIFIED = 0, + + // Creates symmetric encryption keys. + GOOGLE_SYMMETRIC_ENCRYPTION = 1, + + // RSASSA-PSS 2048 bit key with a SHA256 digest. + RSA_SIGN_PSS_2048_SHA256 = 2, + + // RSASSA-PSS 3072 bit key with a SHA256 digest. + RSA_SIGN_PSS_3072_SHA256 = 3, + + // RSASSA-PSS 4096 bit key with a SHA256 digest. + RSA_SIGN_PSS_4096_SHA256 = 4, + + // RSASSA-PKCS1-v1_5 with a 2048 bit key and a SHA256 digest. + RSA_SIGN_PKCS1_2048_SHA256 = 5, + + // RSASSA-PKCS1-v1_5 with a 3072 bit key and a SHA256 digest. + RSA_SIGN_PKCS1_3072_SHA256 = 6, + + // RSASSA-PKCS1-v1_5 with a 4096 bit key and a SHA256 digest. + RSA_SIGN_PKCS1_4096_SHA256 = 7, + + // RSAES-OAEP 2048 bit key with a SHA256 digest. + RSA_DECRYPT_OAEP_2048_SHA256 = 8, + + // RSAES-OAEP 3072 bit key with a SHA256 digest. + RSA_DECRYPT_OAEP_3072_SHA256 = 9, + + // RSAES-OAEP 4096 bit key with a SHA256 digest. + RSA_DECRYPT_OAEP_4096_SHA256 = 10, + + // ECDSA on the NIST P-256 curve with a SHA256 digest. + EC_SIGN_P256_SHA256 = 12, + + // ECDSA on the NIST P-384 curve with a SHA384 digest. + EC_SIGN_P384_SHA384 = 13, + } + + enum CryptoKeyVersionState { + // Not specified. + CRYPTO_KEY_VERSION_STATE_UNSPECIFIED = 0, + + // This version is still being generated. It may not be used, enabled, + // disabled, or destroyed yet. Cloud KMS will automatically mark this + // version [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] as soon as the version is ready. + PENDING_GENERATION = 5, + + // This version may be used for cryptographic operations. + ENABLED = 1, + + // This version may not be used, but the key material is still available, + // and the version can be placed back into the [ENABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.ENABLED] state. + DISABLED = 2, + + // This version is destroyed, and the key material is no longer stored. + // A version may not leave this state once entered. + DESTROYED = 3, + + // This version is scheduled for destruction, and will be destroyed soon. + // Call + // [RestoreCryptoKeyVersion][google.cloud.kms.v1.KeyManagementService.RestoreCryptoKeyVersion] + // to put it back into the [DISABLED][google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionState.DISABLED] state. + DESTROY_SCHEDULED = 4, + } + + enum CryptoKeyVersionView { + // Default view for each [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion]. Does not include + // the [attestation][google.cloud.kms.v1.CryptoKeyVersion.attestation] field. + CRYPTO_KEY_VERSION_VIEW_UNSPECIFIED = 0, + + // Provides all fields in each [CryptoKeyVersion][google.cloud.kms.v1.CryptoKeyVersion], including the + // [attestation][google.cloud.kms.v1.CryptoKeyVersion.attestation]. + FULL = 1, + } + + enum ProtectionLevel { + // Not specified. + PROTECTION_LEVEL_UNSPECIFIED = 0, + + // Crypto operations are performed in software. + SOFTWARE = 1, + + // Crypto operations are performed in a Hardware Security Module. + HSM = 2, + } + + enum AttestationFormat { + ATTESTATION_FORMAT_UNSPECIFIED = 0, + + // Cavium HSM attestation compressed with gzip. Note that this format is + // defined by Cavium and subject to change at any time. + CAVIUM_V1_COMPRESSED = 3, + } + + interface KeyOperationAttestation { + format: AttestationFormat; + } + + interface CryptoKeyVersion { + name: string; + state: CryptoKeyVersionState; + protectionLevel: ProtectionLevel; + algorithm: CryptoKeyVersionAlgorithm; + attestation?: KeyOperationAttestation; + createTime: google_protobuf_timestamp_pb.Timestamp.AsObject; + generateTime: google_protobuf_timestamp_pb.Timestamp.AsObject; + destroyTime?: google_protobuf_timestamp_pb.Timestamp.AsObject; + destroyEventTime?: google_protobuf_timestamp_pb.Timestamp.AsObject; + } + + interface CryptoKeyVersionTemplate { + protectionLevel: ProtectionLevel; + algorithm: CryptoKeyVersionAlgorithm; + } + + enum CryptoKeyPurpose { + // Not specified. + CRYPTO_KEY_PURPOSE_UNSPECIFIED = 0, + + // [CryptoKeys][google.cloud.kms.v1.CryptoKey] with this purpose may be used with + // [Encrypt][google.cloud.kms.v1.KeyManagementService.Encrypt] and + // [Decrypt][google.cloud.kms.v1.KeyManagementService.Decrypt]. + ENCRYPT_DECRYPT = 1, + + // [CryptoKeys][google.cloud.kms.v1.CryptoKey] with this purpose may be used with + // [AsymmetricSign][google.cloud.kms.v1.KeyManagementService.AsymmetricSign] and + // [GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey]. + ASYMMETRIC_SIGN = 5, + + // [CryptoKeys][google.cloud.kms.v1.CryptoKey] with this purpose may be used with + // [AsymmetricDecrypt][google.cloud.kms.v1.KeyManagementService.AsymmetricDecrypt] and + // [GetPublicKey][google.cloud.kms.v1.KeyManagementService.GetPublicKey]. + ASYMMETRIC_DECRYPT = 6, + } + + interface CryptoKey { + name: string; + primary: CryptoKeyVersion; + purpose: CryptoKeyPurpose; + createTime: google_protobuf_timestamp_pb.Timestamp.AsObject; + nextRotationTime?: google_protobuf_timestamp_pb.Timestamp.AsObject; + versionTemplate: CryptoKeyVersionTemplate; + labels: { [s: string]: string; }; + } + + interface KeyRing { + name: string; + createTime: google_protobuf_timestamp_pb.Timestamp.AsObject; + } + + namespace KeyManagementServiceClient { + interface ConfigurationObject { + credentials?: { + client_email?: string; + private_key?: string + }; + email?: string; + keyFilename?: string; + port?: number; + projectId?: string; + promise?: any; + servicePath?: string; + } + + interface EncryptRequest { + name: string; + plaintext: string; + additionalAuthenticatedData?: string; + } + interface EncryptResponse { + name: string; + ciphertext: Buffer; + } + type EncryptCallback = (err: Error | null, apiResponse: [EncryptResponse, any, any]) => void; + + interface DecryptRequest { + name: string; + ciphertext: string; + additionalAuthenticatedData?: string; + } + interface DecryptResponse { + plaintext: Buffer; + } + type DecryptCallback = (err: Error | null, apiResponse: [DecryptResponse, any, any]) => void; + + interface ListKeyRingsRequest { + parent: string; + page_size?: number; + page_token?: string; + } + type ListKeyRingsCallback = (err: Error | null, apiResponse: [KeyRing[], any, any]) => void; + + interface ListCryptoKeysRequest { + parent: string; + page_size?: number; + page_token?: string; + } + type ListCryptoKeysCallback = (err: Error | null, apiResponse: [CryptoKey[], any, any]) => void; + } + + class KeyManagementServiceClient { + constructor(options?: KeyManagementServiceClient.ConfigurationObject); + + keyRingPath(project: string, location: string, keyRing: string): string; + cryptoKeyPathPath(project: string, location: string, keyRing: string, cryptoKeyPath: string): string; + locationPath(project: string, location: string): string; + cryptoKeyPath(project: string, location: string, keyRing: string, cryptoKey: string): string; + cryptoKeyVersionPath(project: string, location: string, keyRing: string, cryptoKey: string, cryptoKeyVersion: string): string; + + encrypt(request: KeyManagementServiceClient.EncryptRequest, gaxOpts?: GAX.CallOptions): Promise<[KeyManagementServiceClient.EncryptResponse, any, any]>; + encrypt(request: KeyManagementServiceClient.EncryptRequest, callback: KeyManagementServiceClient.EncryptCallback): void; + encrypt(request: KeyManagementServiceClient.EncryptRequest, gaxOpts: GAX.CallOptions, callback: KeyManagementServiceClient.EncryptCallback): void; + + decrypt(request: KeyManagementServiceClient.DecryptRequest, gaxOpts?: GAX.CallOptions): Promise<[KeyManagementServiceClient.DecryptResponse, any, any]>; + decrypt(request: KeyManagementServiceClient.DecryptRequest, callback: KeyManagementServiceClient.DecryptCallback): void; + decrypt(request: KeyManagementServiceClient.DecryptRequest, gaxOpts: GAX.CallOptions, callback: KeyManagementServiceClient.DecryptCallback): void; + + listKeyRings(request: KeyManagementServiceClient.ListKeyRingsRequest, gaxOpts?: GAX.CallOptions): Promise<[KeyRing[], any, any]>; + listKeyRings(request: KeyManagementServiceClient.ListKeyRingsRequest, callback: KeyManagementServiceClient.ListKeyRingsCallback): void; + listKeyRings(request: KeyManagementServiceClient.ListKeyRingsRequest, gaxOpts: GAX.CallOptions, callback: KeyManagementServiceClient.ListKeyRingsCallback): void; + + listCryptoKeys(request: KeyManagementServiceClient.ListCryptoKeysRequest, gaxOpts?: GAX.CallOptions): Promise<[CryptoKey[], any, any]>; + listCryptoKeys(request: KeyManagementServiceClient.ListCryptoKeysRequest, callback: KeyManagementServiceClient.ListCryptoKeysCallback): void; + listCryptoKeys(request: KeyManagementServiceClient.ListCryptoKeysRequest, gaxOpts: GAX.CallOptions, callback: KeyManagementServiceClient.ListCryptoKeysCallback): void; + } +} + +export class KeyManagementServiceClient extends v1.KeyManagementServiceClient { + constructor(options?: v1.KeyManagementServiceClient.ConfigurationObject); +} + +export namespace GAX { + /** https://googleapis.github.io/gax-nodejs/global.html#CallOptions */ + interface CallOptions { + timeout?: number; + retry?: RetryOptions; + autoPaginate?: boolean; + pageToken?: object; + isBundling?: boolean; + longrunning?: BackoffSettings; + promise?: PromiseConstructor; // FIXME Unsure if this is the correct type; remove this comment if it is + } + + /** https://googleapis.github.io/gax-nodejs/global.html#RetryOptions */ + interface RetryOptions { + retryCodes: string[]; + backoffSettings: BackoffSettings; + } + + /** https://googleapis.github.io/gax-nodejs/global.html#BackoffSettings */ + interface BackoffSettings { + initialRetryDelayMillis: number; + retryDelayMultiplier: number; + maxRetryDelayMillis: number; + initialRpcTimeoutMillis: number; + maxRpcTimeoutMillis: number; + totalTimeoutMillis: number; + } +} diff --git a/types/google-cloud__storage/tsconfig.json b/types/google-cloud__kms/tsconfig.json similarity index 80% rename from types/google-cloud__storage/tsconfig.json rename to types/google-cloud__kms/tsconfig.json index fe05cce995..bb1ba097cc 100644 --- a/types/google-cloud__storage/tsconfig.json +++ b/types/google-cloud__kms/tsconfig.json @@ -14,8 +14,8 @@ ], "types": [], "paths": { - "@google-cloud/storage": [ - "google-cloud__storage" + "@google-cloud/kms": [ + "google-cloud__kms" ] }, "noEmit": true, @@ -23,6 +23,6 @@ }, "files": [ "index.d.ts", - "google-cloud__storage-tests.ts" + "google-cloud__kms-tests.ts" ] } \ No newline at end of file diff --git a/types/google-cloud__kms/tslint.json b/types/google-cloud__kms/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/google-cloud__kms/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/google-cloud__storage/google-cloud__storage-tests.ts b/types/google-cloud__storage/google-cloud__storage-tests.ts deleted file mode 100644 index 1db3e73284..0000000000 --- a/types/google-cloud__storage/google-cloud__storage-tests.ts +++ /dev/null @@ -1,592 +0,0 @@ -// import file system i/o api -import * as fs from "fs"; - -// import Google Cloud Storage -import { - Acl, - Bucket, - Channel, - File, - ApiResponse, - BucketConfig, - BucketFileOptions, - BucketGetOptions, - BucketMetadata, - BucketPrivacyOptions, - BucketQuery, - ChannelConfig, - DownloadOptions, - FileMetadata, - FilePrivateOptions, - ReadStreamOptions, - ResumableUploadOptions, - SignedPolicy, - SignedPolicyOptions, - SignedUrlConfig, - WriteStreamOptions, - UploadOptions -} from "@google-cloud/storage"; -import Storage = require("@google-cloud/storage"); - -/** - * Test the storage service. - */ -export class TestStorage { - // constants - static BUCKET_CONFIG: BucketConfig = { - multiRegional: true - }; - - // import Storage class - static gcs = new Storage(); - - constructor() { - // nothing to do - } - - /** Returns the bucket. */ - bucket(name: string): Bucket { - return TestStorage.gcs.bucket(name); - } - - /** Create a new bucket. */ - createBucket(name: string, config?: BucketConfig): Promise<[Bucket, ApiResponse]> { - // overwrite default values with custom config - config = Object.assign(TestStorage.BUCKET_CONFIG, config); - - return TestStorage.gcs.createBucket(name, config); - } - - /** - * Query for buckets. - */ - getBuckets(query?: BucketQuery): Promise<[Bucket[]]> { - return TestStorage.gcs.getBuckets(query); - } -} - -/** The bucket API wrapper. */ -export class TestBucket { - // the bucket in the cloud - bucket: Bucket; - - /** Create a bucket. */ - create(config?: BucketConfig): Promise<[Bucket, ApiResponse]> { - return this.bucket.create(config); - } - - /** Create a channel that will be notified when objects in this bucket changes. */ - createChannel(id: string, config: ChannelConfig): Promise<[Channel, ApiResponse]> { - return this.bucket.createChannel(id, config); - } - - /** Delete the bucket. */ - delete(): Promise<[ApiResponse]> { - return this.bucket.delete(); - } - - /** Iterate over the bucket's files, calling file.delete() on each. */ - deleteFiles(query?: BucketQuery): Promise { - return this.bucket.deleteFiles(query); - } - - /** Check if the bucket exists. */ - exists(): Promise<[boolean]> { - return this.bucket.exists(); - } - - /** Create a File object. */ - file(name: string, options?: BucketFileOptions): File { - return this.bucket.file(name); - } - - /** Get a bucket if it exists. */ - get(options?: BucketGetOptions): Promise<[Bucket, ApiResponse]> { - return this.bucket.get(options); - } - - /** Get File objects for the files currently in the bucket */ - getFiles(query?: BucketQuery): Promise<[File[]]> { - return this.bucket.getFiles(query); - } - - /** Get File objects for the files currently in the bucket as a readable object stream. */ - getFilesStream(query?: BucketQuery): fs.ReadStream { - return this.bucket.getFilesStream(query); - } - - /** Get the bucket's metadata. */ - getMetadata(): Promise<[BucketMetadata, ApiResponse]> { - return this.bucket.getMetadata(); - } - - /** Make the bucket listing private. */ - makePrivate(options?: BucketPrivacyOptions): Promise<[File[]]> { - return this.bucket.makePrivate(options); - } - - /** Make the bucket publicly readable. */ - makePublic(options?: BucketPrivacyOptions): Promise<[File[]]> { - return this.bucket.makePublic(options); - } - - /** Set the bucket's metadata. */ - setMetadata(metadata?: BucketMetadata): Promise<[ApiResponse]> { - return this.bucket.setMetadata(metadata); - } - - /** Upload a file. */ - upload(localPath: string, options?: UploadOptions): Promise<[File]> { - return this.bucket.upload(localPath, options); - } -} - -/** The file API wrapper. */ -export class TestFile { - // the file in the cloud - file: File; - - /** - * Copy this file to another file. - * By default, this will copy the file to the same bucket, but you can choose to copy it to another - * Bucket by providing a Bucket or File object or a URL starting with "gs:// ". - */ - copy(destination: string | Bucket | File): Promise<[File, ApiResponse]> { - return this.file.copy(destination); - } - - /** Create a unique resumable upload session URI. This is the first step when performing a resumable upload. */ - createResumableUpload(options?: ResumableUploadOptions): Promise<[string]> { - return this.file.createResumableUpload(options); - } - - /** - * Create a readable stream to read the contents of the remote file. - * It can be piped to a writable stream or listened to for 'data' events to read a file's contents. - */ - createReadStream(options?: ReadStreamOptions): fs.ReadStream { - return this.file.createReadStream(options); - } - - /** Create a writable stream to overwrite the contents of the file in your bucket. */ - createWriteStream(options?: WriteStreamOptions): fs.WriteStream { - return this.file.createWriteStream(options); - } - - /** Delete the file. */ - delete(): Promise<[ApiResponse]> { - return this.file.delete(); - } - - /** Convenience method to download a file into memory or to a local destination. */ - download(options?: DownloadOptions): Promise<[Buffer]> { - return this.file.download(options); - } - - /** Check if the file exists. */ - exists(): Promise<[boolean]> { - return this.file.exists(); - } - - /** Get a file object and its metadata if it exists. */ - get(): Promise<[File, ApiResponse]> { - return this.file.get(); - } - - /** Get the file's metadata. */ - getMetadata(): Promise<[FileMetadata, ApiResponse]> { - return this.file.getMetadata(); - } - - /** Get a signed policy document to allow a user to upload data with a POST request */ - getSignedPolicy(options?: SignedPolicyOptions): Promise<[SignedPolicy]> { - return this.file.getSignedPolicy(options); - } - - /** Get a signed URL to allow limited time access to the file */ - getSignedUrl(config: SignedUrlConfig): Promise<[string]> { - return this.file.getSignedUrl(config); - } - - /** Make a file private to the project and remove all other permissions. */ - makePrivate(options?: FilePrivateOptions): Promise<[ApiResponse]> { - return this.file.makePrivate(options); - } - - /** Set a file to be publicly readable and maintain all previous permissions. */ - makePublic(): Promise<[ApiResponse]> { - return this.file.makePublic(); - } - - /** - * Move this file to another location. - * By default, this will move the file to the same bucket, but you can choose to move it to - * another Bucket by providing a Bucket or File object or a URL beginning with "gs:// ". - */ - move(destination: string | Bucket | File): Promise<[File, ApiResponse]> { - return this.file.move(destination); - } - - /** Write arbitrary data to a file. */ - save(data: string, options?: WriteStreamOptions): Promise { - return this.file.save(data); - } - - /** The Storage API allows you to use a custom key for server-side encryption. */ - setEncryptionKey(encryptionKey: string | Buffer): File { - return this.file.setEncryptionKey(encryptionKey); - } - - /** - * Merge the given metadata with the current remote file's metadata. - * This will set metadata if it was previously unset or update previously set metadata. - * To unset previously set metadata, set its value to null. - */ - setMetadata(metadata: FileMetadata): Promise<[ApiResponse]> { - return this.file.setMetadata(metadata); - } -} - -const testStorage = new TestStorage().bucket("examplebucketname"); - -testStorage.iam.getPolicy(); - -testStorage.iam.setPolicy({ - bindings: [ - { - role: "roles/storage.admin", - members: ['serviceAccount:myotherproject@appspot.gserviceaccount.com'] - } - ] - }); - -testStorage.iam.testPermissions('storage.buckets.delete'); - -testStorage.iam.testPermissions(['storage.buckets.delete', 'storage.buckets.get']); - -// Example from https://cloud.google.com/storage/docs/creating-buckets#storage-create-bucket-code_samples -{ - // Creates a client - const storage = new Storage(); - - const bucketName = 'Name of a bucket, e.g. my-bucket'; - - // Creates a new bucket - storage - .createBucket(bucketName, { - location: 'ASIA', - storageClass: 'COLDLINE', - }) - .then(() => { - console.log(`Bucket ${bucketName} created.`); - }) - .catch(err => { - console.error('ERROR:', err); - }); -} - -// Example from https://cloud.google.com/storage/docs/listing-buckets#storage-list-buckets-nodejs -{ - // Creates a client - const storage = new Storage(); - - // Lists all buckets in the current project - storage - .getBuckets() - .then(results => { - const buckets = results[0]; - - console.log('Buckets:'); - buckets.forEach(bucket => { - console.log(bucket.name); - }); - }) - .catch(err => { - console.error('ERROR:', err); - }); -} - -// Example from https://cloud.google.com/storage/docs/moving-buckets#storage-create-bucket-nodejs -{ - // Creates a client - const storage = new Storage(); - - const bucketName = 'Name of a bucket, e.g. my-bucket'; - - // Creates a new bucket - storage - .createBucket(bucketName, { - location: 'ASIA', - storageClass: 'COLDLINE', - }) - .then(() => { - console.log(`Bucket ${bucketName} created.`); - }) - .catch(err => { - console.error('ERROR:', err); - }); -} - -// Example from https://cloud.google.com/storage/docs/deleting-buckets -{ - // Creates a client - const storage = new Storage(); - - const bucketName = 'Name of a bucket, e.g. my-bucket'; - - // Deletes the bucket - storage - .bucket(bucketName) - .delete() - .then(() => { - console.log(`Bucket ${bucketName} deleted.`); - }) - .catch(err => { - console.error('ERROR:', err); - }); -} - -// Example from https://cloud.google.com/storage/docs/uploading-objects -{ - // Creates a client - const storage = new Storage(); - - const bucketName = 'Name of a bucket, e.g. my-bucket'; - const filename = 'Local file to upload, e.g. ./local/path/to/file.txt'; - - // Uploads a local file to the bucket - storage - .bucket(bucketName) - .upload(filename, { - // Support for HTTP requests made with `Accept-Encoding: gzip` - gzip: true, - metadata: { - // Enable long-lived HTTP caching headers - // Use only if the contents of the file will never change - // (If the contents will change, use cacheControl: 'no-cache') - cacheControl: 'public, max-age=31536000', - }, - }) - .then(() => { - console.log(`${filename} uploaded to ${bucketName}.`); - }) - .catch(err => { - console.error('ERROR:', err); - }); -} - -// Example from https://cloud.google.com/storage/docs/listing-objects -{ - // Creates a client - const storage = new Storage(); - - const bucketName = 'Name of a bucket, e.g. my-bucket'; - - // Lists files in the bucket - storage - .bucket(bucketName) - .getFiles() - .then(results => { - const files = results[0]; - - console.log('Files:'); - files.forEach(file => { - console.log(file.name); - }); - }) - .catch(err => { - console.error('ERROR:', err); - }); -} - -// Example from https://cloud.google.com/storage/docs/listing-objects -{ - // Creates a client - const storage = new Storage(); - - const bucketName = 'Name of a bucket, e.g. my-bucket'; - const prefix = 'Prefix by which to filter, e.g. public/'; - const delimiter = 'Delimiter to use, e.g. /'; - - /** - * This can be used to list all blobs in a "folder", e.g. "public/". - * - * The delimiter argument can be used to restrict the results to only the - * "files" in the given "folder". Without the delimiter, the entire tree under - * the prefix is returned. For example, given these blobs: - * - * /a/1.txt - * /a/b/2.txt - * - * If you just specify prefix = '/a', you'll get back: - * - * /a/1.txt - * /a/b/2.txt - * - * However, if you specify prefix='/a' and delimiter='/', you'll get back: - * - * /a/1.txt - */ - const options = { - prefix, - delimiter - }; - - // Lists files in the bucket, filtered by a prefix - storage - .bucket(bucketName) - .getFiles(options) - .then(results => { - const files = results[0]; - - console.log('Files:'); - files.forEach(file => { - console.log(file.name); - }); - }) - .catch(err => { - console.error('ERROR:', err); - }); -} - -// Example from https://cloud.google.com/storage/docs/downloading-objects#storage-download-object-nodejs -{ - // Creates a client - const storage = new Storage(); - - const bucketName = 'Name of a bucket, e.g. my-bucket'; - const srcFilename = 'Remote file to download, e.g. file.txt'; - const destFilename = 'Local destination for file, e.g. ./local/path/to/file.txt'; - - const options = { - // The path to which the file should be downloaded, e.g. "./file.txt" - destination: destFilename, - }; - - // Downloads the file - storage - .bucket(bucketName) - .file(srcFilename) - .download(options) - .then(() => { - console.log( - `gs://${bucketName}/${srcFilename} downloaded to ${destFilename}.` - ); - }) - .catch(err => { - console.error('ERROR:', err); - }); -} - -// Example from https://cloud.google.com/storage/docs/renaming-copying-moving-objects -{ - // Creates a client - const storage = new Storage(); - - const bucketName = 'Name of a bucket, e.g. my-bucket'; - const srcFilename = 'File to move, e.g. file.txt'; - const destFilename = 'Destination for file, e.g. moved.txt'; - - // Moves the file within the bucket - storage - .bucket(bucketName) - .file(srcFilename) - .move(destFilename) - .then(() => { - console.log( - `gs://${bucketName}/${srcFilename} moved to gs://${bucketName}/${destFilename}.` - ); - }) - .catch(err => { - console.error('ERROR:', err); - }); -} - -// Example from https://cloud.google.com/storage/docs/renaming-copying-moving-objects -{ - // Creates a client - const storage = new Storage(); - - const srcBucketName = 'Name of the source bucket, e.g. my-bucket'; - const srcFilename = 'Name of the source file, e.g. file.txt'; - const destBucketName = 'Name of the destination bucket, e.g. my-other-bucket'; - const destFilename = 'Destination name of file, e.g. file.txt'; - - // Copies the file to the other bucket - storage - .bucket(srcBucketName) - .file(srcFilename) - .copy(storage.bucket(destBucketName).file(destFilename)) - .then(() => { - console.log( - `gs://${srcBucketName}/${srcFilename} copied to gs://${destBucketName}/${destFilename}.` - ); - }) - .catch(err => { - console.error('ERROR:', err); - }); -} - -// Example from https://cloud.google.com/storage/docs/viewing-editing-metadata -{ - // Creates a client - const storage = new Storage(); - - const bucketName = 'Name of a bucket, e.g. my-bucket'; - const filename = 'File to access, e.g. file.txt'; - - // Gets the metadata for the file - storage - .bucket(bucketName) - .file(filename) - .getMetadata() - .then(results => { - const metadata = results[0]; - - console.log(`File: ${metadata.name}`); - console.log(`Bucket: ${metadata.bucket}`); - console.log(`Storage class: ${metadata.storageClass}`); - console.log(`Self link: ${metadata.selfLink}`); - console.log(`ID: ${metadata.id}`); - console.log(`Size: ${metadata.size}`); - console.log(`Updated: ${metadata.updated}`); - console.log(`Generation: ${metadata.generation}`); - console.log(`Metageneration: ${metadata.metageneration}`); - console.log(`Etag: ${metadata.etag}`); - console.log(`Owner: ${metadata.owner}`); - console.log(`Component count: ${metadata.component_count}`); - console.log(`Crc32c: ${metadata.crc32c}`); - console.log(`md5Hash: ${metadata.md5Hash}`); - console.log(`Cache-control: ${metadata.cacheControl}`); - console.log(`Content-type: ${metadata.contentType}`); - console.log(`Content-disposition: ${metadata.contentDisposition}`); - console.log(`Content-encoding: ${metadata.contentEncoding}`); - console.log(`Content-language: ${metadata.contentLanguage}`); - console.log(`Metadata: ${metadata.metadata}`); - console.log(`Media link: ${metadata.mediaLink}`); - }) - .catch(err => { - console.error('ERROR:', err); - }); -} - -// Example from https://cloud.google.com/storage/docs/deleting-objects -{ - // Creates a client - const storage = new Storage(); - - const bucketName = 'Name of a bucket, e.g. my-bucket'; - const filename = 'File to delete, e.g. file.txt'; - - // Deletes the file from the bucket - storage - .bucket(bucketName) - .file(filename) - .delete() - .then(() => { - console.log(`gs://${bucketName}/${filename} deleted.`); - }) - .catch(err => { - console.error('ERROR:', err); - }); -} diff --git a/types/google-cloud__storage/index.d.ts b/types/google-cloud__storage/index.d.ts deleted file mode 100644 index 2053abcc62..0000000000 --- a/types/google-cloud__storage/index.d.ts +++ /dev/null @@ -1,469 +0,0 @@ -// Type definitions for @google-cloud/storage 1.7 -// Project: https://github.com/googleapis/nodejs-storage -// Definitions by: Brian Love -// Nathan Brooker Perry -// Matt Welke -// Futa Ogawa -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 - -/// - -import { ReadStream, WriteStream } from "fs"; -import { CoreOptions } from "request"; - -type PromiseLibrary = () => PromiseLike; - -declare namespace Storage { - /** - * A bucket in the cloud. - */ - class Bucket { - constructor(storage: Storage, name: string); - acl: Acl; - combine(sources: string[] | File[], destination: string | File): Promise<[File, ApiResponse]>; - create(config?: BucketConfig): Promise<[Bucket, ApiResponse]>; - createChannel(id: string, config: ChannelConfig): Promise<[Channel, ApiResponse]>; - delete(): Promise<[ApiResponse]>; - deleteFiles(query?: BucketQuery): Promise; - exists(): Promise<[boolean]>; - file(name: string, options?: BucketFileOptions): File; - get(options?: BucketGetOptions): Promise<[Bucket, ApiResponse]>; - getFiles(query?: BucketQuery): Promise<[File[]]>; - getFilesStream(query?: BucketQuery): ReadStream; - getMetadata(): Promise<[BucketMetadata, ApiResponse]>; - id: string; - iam: Iam; - makePrivate(options?: BucketPrivacyOptions): Promise<[File[]]>; - makePublic(options?: BucketPrivacyOptions): Promise<[File[]]>; - metadata: BucketMetadata; - name: string; - setMetadata(metadata?: BucketMetadata): Promise<[ApiResponse]>; - upload(localPath: string, options?: UploadOptions): Promise<[File]>; - } - - /** - * Bucket configuration. - */ - interface BucketConfig { - coldline?: boolean; - dra?: boolean; - location?: string; - multiRegional?: boolean; - nearline?: boolean; - regional?: boolean; - versioning?: { - enabled?: boolean - }; - // Note: This is not documented, but it is used in examples (https://cloud.google.com/nodejs/docs/reference/storage/1.7.x/Storage) - storageClass?: 'COLDLINE' | 'DURABLE_REDUCED_AVAILABILITY' | 'MULTI_REGIONAL' | 'NEARLINE' | 'REGIONAL'; - } - - /** - * Options for getting a file. - */ - interface BucketFileOptions { - generation?: string | number; - } - - /** - * Options for getting a bucket. - */ - interface BucketGetOptions { - autoCreate?: boolean; - } - - /** - * Bucket metadata. - */ - interface BucketMetadata { - etag?: string; - id?: string; - kind?: string; - location?: string; - metageneration?: string; - name?: string; - projectNumber?: string; - selfLink?: string; - storageClass?: string; - timeCreated?: string; - updated?: string; - } - - /** - * The options for making the bucket private. - */ - interface BucketPrivacyOptions { - includeFiles?: boolean; - force?: boolean; - } - - /** - * Query a bucket. - */ - interface BucketQuery { - autoPaginate?: boolean; - delimiter?: string; - directory?: string; - prefix?: string; - maxApiCalls?: number; - maxResults?: number; - pageToken?: string; - userProject?: string; - versions?: boolean; - } - - /** - * Options for specifying the content length range. - */ - interface ContentLengthRange { - max?: number; - min?: number; - } - - /** - * A file in the cloud. - */ - class File { - constructor(bucket: Bucket, name: string, options?: BucketFileOptions); - acl: Acl; - copy(destination: string | Bucket | File): Promise<[File, ApiResponse]>; - createReadStream(options?: ReadStreamOptions): ReadStream; - createResumableUpload(options?: ResumableUploadOptions): Promise<[string]>; - createWriteStream(options?: WriteStreamOptions): WriteStream; - delete(): Promise<[ApiResponse]>; - download(options?: DownloadOptions): Promise<[Buffer]>; - exists(): Promise<[boolean]>; - get(): Promise<[File, ApiResponse]>; - getMetadata(): Promise<[FileMetadata, ApiResponse]>; - getSignedPolicy(options?: SignedPolicyOptions): Promise<[SignedPolicy]>; - getSignedUrl(config: SignedUrlConfig): Promise<[string]>; - makePrivate(options?: FilePrivateOptions): Promise<[ApiResponse]>; - makePublic(): Promise<[ApiResponse]>; - move(destination: string | Bucket | File): Promise<[File, ApiResponse]>; - name: string; - save(data: string | Buffer, options?: WriteStreamOptions): Promise; - setEncryptionKey(encryptionKey: string | Buffer): File; - setMetadata(metadata: FileMetadata): Promise<[ApiResponse]>; - metadata?: FileMetadata; - } - - /** - * Access controls on the object, containing one or more objectAccessControls Resources. - */ - interface AclFileMetadata { - bucket?: string; - domain?: string; - email?: string; - entity?: string; - entityId?: string; - etag?: string; - generation?: number; - id?: string; - kind?: string; - object?: string; - projectTeam?: ProjectTeam; - role?: string; - selfLink?: string; - } - - /** - * The project team associated with the entity, if any. - */ - interface ProjectTeam { - projectNumber?: string; - team?: string; - } - - /** - * Metadata of customer-supplied encryption key, if the object is encrypted by such a key. - */ - interface CustomerEncryption { - encryptionAlgorithm?: string; - keySha256?: string; - } - - /** - * User-defined metadata. - */ - interface CustomFileMetadata { - [key: string]: string; - } - - /** - * The owner of the object. This will always be the uploader of the object. - */ - interface Owner { - entity?: string; - entityId?: string; - } - - /** - * File metadata. - */ - interface FileMetadata { - acl?: AclFileMetadata[]; - bucket?: string; - cacheControl?: string; - componentCount?: number; - // Note: this property is accessed in one of the examples - component_count?: number; - contentDisposition?: string; - contentEncoding?: string; - contentLanguage?: string; - contentType?: string; - crc32c?: string; - customerEncryption?: CustomerEncryption; - etag?: string; - generation?: number; - id?: string; - kind?: string; - kmsKeyName?: string; - md5Hash?: string; - mediaLink?: string; - metadata?: CustomFileMetadata; - metageneration?: number; - name?: string; - owner?: Owner; - selfLink?: string; - size?: null | number; - storageClass?: string; - timeCreated?: string; - timeDeleted?: string; - timeStorageClassUpdated?: string; - updated?: string; - } - - /** - * Options when setting the file as private. - */ - interface FilePrivateOptions { - strict?: boolean; - } - - /** - * A signed policy allowing a user to upload a file with a POST. - */ - interface SignedPolicy { - base64?: string; - signature?: string; - string?: string; - } - - /** - * Options when obtaining the signed policy. - */ - interface SignedPolicyOptions { - acl?: string; - contentLengthRange?: ContentLengthRange; - equals?: string[] | [string[]]; - expires?: number | string; - max?: number; - min?: number; - startsWith?: string[] | [string[]]; - successRedirect?: string; - successStatus?: string; - } - - /** - * Options when obtaining a temporary signed URL for a file. - */ - interface SignedUrlConfig { - action: string; - cname?: string; - contentMd5?: string; - contentType?: string; - expires: any; - extensionHeaders?: { [key: string]: string }; - promptSaveAs?: string; - responseDisposition?: string; - responseType?: string; - } - - /** - * Options when obtaining a resumable upload URI. - */ - interface ResumableUploadOptions { - metadata?: FileMetadata; - origin?: string; - predefinedAcl?: string; - private?: boolean; - public?: boolean; - } - - /** - * Access control list for storage buckets and files. - */ - interface Acl extends AclActions { - default: AclEntity; - owners: AclEntity; - readers: AclEntity; - writers: AclEntity; - } - - /** - * Actions that can be performed on all ACL entities, including the root Acl. - */ - interface AclActions { - add(options: AclOptions): Promise<[Acl, ApiResponse]>; - delete(options: AclOptions): Promise<[Acl, ApiResponse]>; - get(options: AclOptions): Promise<[Acl, ApiResponse]>; - update(options: AclOptions): Promise<[Acl, ApiResponse]>; - } - - /** - * An object of convenience methods to add or delete reader ACL permissions for a given entity. - */ - interface AclEntity extends AclActions { - addAllAuthenticatedUsers(): Promise<[Acl, ApiResponse]>; - addAllUsers(): Promise<[Acl, ApiResponse]>; - addDomain(entity: string): Promise<[Acl, ApiResponse]>; - addGroup(entity: string): Promise<[Acl, ApiResponse]>; - addProject(entity: string): Promise<[Acl, ApiResponse]>; - addUser(entity: string): Promise<[Acl, ApiResponse]>; - deleteAllAuthenticatedUsers(): Promise<[Acl, ApiResponse]>; - deleteAllUsers(): Promise<[Acl, ApiResponse]>; - deleteDomain(entity: string): Promise<[Acl, ApiResponse]>; - deleteGroup(entity: string): Promise<[Acl, ApiResponse]>; - deleteProject(entity: string): Promise<[Acl, ApiResponse]>; - deleteUser(entity: string): Promise<[Acl, ApiResponse]>; - } - - /** - * ACL options. - */ - interface AclOptions { - entity?: string; - role?: string; - generation?: number; - } - - /** - * The response object. - */ - interface ApiResponse { - etag?: string; - id?: string; - kind?: string; - location?: string; - metageneration?: string; - name?: string; - projectNumber?: string; - selfLink?: string; - storageClass?: string; - timeCreated?: string; - updated?: string; - } - - interface Credentials { - client_email?: string; - private_key?: string; - } - - interface ConfigurationObject { - autoRetry?: boolean; - credentials?: Credentials; - email?: string; - keyFilename?: string; - maxRetries?: number; - projectId?: string; - promise?: PromiseLibrary; - } - - /** - * The options when downloading a file. - */ - interface DownloadOptions extends ReadStreamOptions { - destination?: string; - } - - /** - * Options when reading a file stream. - */ - interface ReadStreamOptions { - end?: number; - start?: number; - validation?: string | boolean; - } - - /** - * Options when uploading file to bucket. - */ - interface UploadOptions extends WriteStreamOptions { - destination?: string | File; - encryptionKey?: string; - kmsKeyName?: string; - requestOptions?: CoreOptions; - } - - /** - * Options when writing to a file stream. - */ - interface WriteStreamOptions { - contentType?: string; - gzip?: string | boolean; - metadata?: FileMetadata; - offset?: string; - predefinedAcl?: string; - private?: boolean; - public?: boolean; - resumable?: boolean; - uri?: string; - userProject?: string; - validation?: string | boolean; - } - - /** - * This class allows you interact with Google Cloud Storage. - */ - class Channel { - constructor(storage: Storage, id: string, resourceId: string); - stop(): Promise<[ApiResponse]>; - } - - /** - * Channel configuration. - */ - interface ChannelConfig { - address: string; - } - - /** - * This class allows you to get Identity Access Management information. - */ - class Iam { - getPolicy(): Promise; - setPolicy(policy: IamPolicy): Promise<[IamPolicy, ApiResponse]>; - testPermissions(permission: string | string[]): Promise<[{[key: string]: boolean}, ApiResponse]>; - } - - /** - * IAM policy - */ - interface IamPolicy { - bindings: IamBinding[]; - } - - interface IamBinding { - role: string; - members: string[]; - } -} - -/** - * The Storage class allows you interact with Google Cloud Storage. - */ -declare class Storage { - constructor(config?: Storage.ConfigurationObject); - acl: Storage.Acl; - bucket(name: string | Storage.Bucket): Storage.Bucket; - channel(id: string, resourceId: string): Storage.Channel; - createBucket(name: string, metadata?: Storage.BucketConfig): Promise<[Storage.Bucket, Storage.ApiResponse]>; - getBuckets(query?: Storage.BucketQuery): Promise<[Storage.Bucket[]]>; - getBucketsStream(query?: Storage.BucketQuery): Promise<[ReadStream]>; - Channel: (storage: Storage, id: string, resourceId: string) => Storage.Channel; - File: (bucket: Storage.Bucket, name: string, opts: Storage.BucketFileOptions) => Storage.File; - Bucket: (storage: Storage, name: string) => Storage.Bucket; -} - -export = Storage; diff --git a/types/google-cloud__storage/tslint.json b/types/google-cloud__storage/tslint.json deleted file mode 100644 index b3dfb39122..0000000000 --- a/types/google-cloud__storage/tslint.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "extends": "dtslint/dt.json", - "rules": { - // TODOs - "no-duplicate-imports": false, - "prefer-object-spread": false - } -} diff --git a/types/graphql-fields/graphql-fields-tests.ts b/types/graphql-fields/graphql-fields-tests.ts new file mode 100644 index 0000000000..811fe25ab2 --- /dev/null +++ b/types/graphql-fields/graphql-fields-tests.ts @@ -0,0 +1,8 @@ +import { GraphQLResolveInfo } from 'graphql'; +import graphqlFields = require('graphql-fields'); + +const info = ({} as any) as GraphQLResolveInfo; + +const fieldsWithSubFieldsArgs = graphqlFields(info, {}, { processArguments: true }); +const fieldsWithoutTypeName = graphqlFields(info, {}, { excludedFields: ['__typename'] }); +graphqlFields(info); diff --git a/types/graphql-fields/index.d.ts b/types/graphql-fields/index.d.ts new file mode 100644 index 0000000000..19e7f21dc4 --- /dev/null +++ b/types/graphql-fields/index.d.ts @@ -0,0 +1,18 @@ +// Type definitions for graphql-fields 1.3 +// Project: https://github.com/robrichard/graphql-fields#readme +// Definitions by: feinoujc +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.6 + +import { GraphQLResolveInfo } from 'graphql'; + +declare function graphqlFields(info: GraphQLResolveInfo, obj?: object, opts?: graphqlFields.Options): any; + +declare namespace graphqlFields { + interface Options { + processArguments?: boolean; + excludedFields?: string[]; + } +} + +export = graphqlFields; diff --git a/types/graphql-fields/tsconfig.json b/types/graphql-fields/tsconfig.json new file mode 100644 index 0000000000..826e200b41 --- /dev/null +++ b/types/graphql-fields/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "esnext.asynciterable" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "graphql-fields-tests.ts" + ] +} diff --git a/types/graphql-fields/tslint.json b/types/graphql-fields/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/graphql-fields/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/gridstack/tslint.json b/types/gridstack/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/gridstack/tslint.json +++ b/types/gridstack/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/gulp-json-validator/gulp-json-validator-tests.ts b/types/gulp-json-validator/gulp-json-validator-tests.ts new file mode 100644 index 0000000000..74a00f03da --- /dev/null +++ b/types/gulp-json-validator/gulp-json-validator-tests.ts @@ -0,0 +1,6 @@ +import gulpJsonValidator = require("gulp-json-validator"); + +gulpJsonValidator(); // $ExpectType ReadWriteStream +gulpJsonValidator({}); // $ExpectType ReadWriteStream +gulpJsonValidator({ allowDuplicatedKeys: true }); // $ExpectType ReadWriteStream +gulpJsonValidator({ allowDuplicatedKeys: false }); // $ExpectType ReadWriteStream diff --git a/types/gulp-json-validator/index.d.ts b/types/gulp-json-validator/index.d.ts new file mode 100644 index 0000000000..26e31d8b43 --- /dev/null +++ b/types/gulp-json-validator/index.d.ts @@ -0,0 +1,14 @@ +// Type definitions for gulp-json-validator 1.2 +// Project: https://github.com/jackyjieliu/gulp-json-validator +// Definitions by: Peter Safranek +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +interface GulpJsonValidatorOptions { + allowDuplicatedKeys?: boolean; +} + +declare function gulpJsonValidator(option?: GulpJsonValidatorOptions): NodeJS.ReadWriteStream; + +export = gulpJsonValidator; diff --git a/types/gulp-json-validator/tsconfig.json b/types/gulp-json-validator/tsconfig.json new file mode 100644 index 0000000000..76ee50c184 --- /dev/null +++ b/types/gulp-json-validator/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "gulp-json-validator-tests.ts" + ] +} diff --git a/types/gulp-json-validator/tslint.json b/types/gulp-json-validator/tslint.json new file mode 100644 index 0000000000..702f9354fc --- /dev/null +++ b/types/gulp-json-validator/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "file-name-casing": false + } +} diff --git a/types/hapi-auth-cookie/hapi-auth-cookie-tests.ts b/types/hapi-auth-cookie/hapi-auth-cookie-tests.ts new file mode 100644 index 0000000000..155bb928e3 --- /dev/null +++ b/types/hapi-auth-cookie/hapi-auth-cookie-tests.ts @@ -0,0 +1,33 @@ +import * as hapi from 'hapi'; +import * as auth from 'hapi-auth-cookie'; + +const server = new hapi.Server({ port: 8000 }); + +server.register({ + plugin: auth, +}); + +const options: auth.Options = { + clearInvalid: true, + cookie: 'session', + domain: '.typescript.org', + keepAlive: true, + password: 'abcdef', + redirectTo: '/login', + isSecure: true, + appendNext: false, + ttl: 259200000, + validateFunc: async () => { + return { valid: true }; + }, +}; + +server.auth.strategy('session', 'cookie', options); + +server.route({ method: 'get', path: '/', handler: async (request) => { + request.cookieAuth.set('key', 'value'); + request.cookieAuth.set({ user: request.params.user }); + request.cookieAuth.clear(); + request.cookieAuth.clear('key'); + request.cookieAuth.ttl(1000); +}}); diff --git a/types/hapi-auth-cookie/index.d.ts b/types/hapi-auth-cookie/index.d.ts new file mode 100644 index 0000000000..8184ffd2fe --- /dev/null +++ b/types/hapi-auth-cookie/index.d.ts @@ -0,0 +1,142 @@ +// Type definitions for hapi-auth-cookie 9.1 +// Project: https://github.com/hapijs/hapi-auth-cookie +// Definitions by: Silas Rech +// Simon Schick +// Matt Erickson +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import { Request, ResponseObject, Plugin, ResponseToolkit, AuthCredentials, ServerStateCookieOptions } from 'hapi'; + +declare module 'hapi' { + interface ServerAuth { + strategy(name: string, scheme: 'cookie', options?: hapiAuthCookie.Options): void; + } + + interface PluginSpecificConfiguration { + 'hapi-auth-cookie'?: { + redirectTo?: boolean; + }; + } + + interface Request { + cookieAuth: { + set(session: object): void; + set(key: string, value: object | string): void; + clear(key?: string): void; + ttl(milliseconds: number): void; + }; + } +} + +declare namespace hapiAuthCookie { + interface ValidateResponse { valid: boolean; credentials?: AuthCredentials; } + type ValidateFunction = (request?: Request, session?: object) => Promise; + type RedirectToFunction = (request?: Request) => void; + + /** + * Options passed to 'hapi.auth.strategy' when this plugin is used + */ + interface Options { + /** + * The cookie name. + * + * @default 'sid' + */ + cookie?: string; + + /** + * Used for Iron cookie encoding. + * Should be at least 32 characters long. + */ + password: string; + + /** + * Sets the cookie expires time in milliseconds. + * Required when 'keepAlive' is true. + * Defaults to single browser session (ends when browser closes). + */ + ttl?: number; + + /** + * Sets the cookie Domain value. + * Defaults to none. + */ + domain?: string; + + /** + * Sets the cookie path value. + * + * @default '/' + */ + path?: string; + + /** + * Any authentication cookie that fails validation will be marked as expired in the response and cleared. + * + * @default false + */ + clearInvalid?: boolean; + + /** + * Automatically sets the session cookie after validation to extend the current session for a new TTL duration. + * + * @default false + */ + keepAlive?: boolean; + + /** + * If false omitted. + * Other options Strict or Lax. + * + * @default 'Strict' + */ + isSameSite?: ServerStateCookieOptions['isSameSite']; + + /** + * If false, the cookie is allowed to be transmitted over insecure connections which exposes it to attacks. + * + * @default true + */ + isSecure?: boolean; + + /** + * If false, the cookie will not include the 'HttpOnly' flag. + * + * @default true + */ + isHttpOnly?: boolean; + + /** + * Login URI or function that returns a URI to redirect unauthenticated requests to. + * Note that it will only trigger when the authentication mode is 'required'. + * Defaults to no redirection. + */ + redirectTo?: string | RedirectToFunction; + + /** + * Only works if 'redirectTo' is true + * If set to true, a string, or an object, appends the current request path to the query component of the 'redirectTo' URI. + */ + appendNext?: boolean | string; + + /** + * An optional session validation function used to validate the content of the session cookie on each request. + * Used to verify that the internal session state is still valid (e.g. user account still exists). + */ + validateFunc?: ValidateFunction; + + /** + * A name to use with decorating the request object. + * Using multiple decorator names for separate authentication strategies could allow a developer to call the methods for the wrong strategy. + * Potentially resulting in unintended authorized access. + * + * @default 'cookieAuth' + */ + requestDecoratorName?: string; + } +} + +declare const hapiAuthCookie: Plugin; + +export = hapiAuthCookie; diff --git a/types/hapi-auth-cookie/tsconfig.json b/types/hapi-auth-cookie/tsconfig.json new file mode 100644 index 0000000000..ae04bf4a42 --- /dev/null +++ b/types/hapi-auth-cookie/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "hapi-auth-cookie-tests.ts" + ] +} diff --git a/types/hapi-auth-cookie/tslint.json b/types/hapi-auth-cookie/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/hapi-auth-cookie/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/hapi/index.d.ts b/types/hapi/index.d.ts index 3e323f8c44..ec2359ed5a 100644 --- a/types/hapi/index.d.ts +++ b/types/hapi/index.d.ts @@ -1428,7 +1428,7 @@ export interface RouteOptionsPreObject { /** * key name used to assign the response of the method to in request.pre and request.preResponses. */ - assign: string; + assign?: string; /** * A failAction value which determine what to do when a pre-handler method throws an error. If assign is specified and the failAction setting is not 'error', the error will be assigned. */ diff --git a/types/has-emoji/has-emoji-tests.ts b/types/has-emoji/has-emoji-tests.ts new file mode 100644 index 0000000000..f1453f4cf5 --- /dev/null +++ b/types/has-emoji/has-emoji-tests.ts @@ -0,0 +1,6 @@ +import hasEmoji = require('has-emoji'); + +// $ExpectType boolean +hasEmoji('Unicorn 🦄'); +// $ExpectType boolean +hasEmoji('Cat'); diff --git a/types/has-emoji/index.d.ts b/types/has-emoji/index.d.ts new file mode 100644 index 0000000000..2160e66497 --- /dev/null +++ b/types/has-emoji/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for has-emoji 1.0 +// Project: https://github.com/sindresorhus/has-emoji#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = hasEmoji; + +declare function hasEmoji(candidate: string): boolean; diff --git a/types/has-emoji/tsconfig.json b/types/has-emoji/tsconfig.json new file mode 100644 index 0000000000..646f983707 --- /dev/null +++ b/types/has-emoji/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "has-emoji-tests.ts" + ] +} diff --git a/types/has-emoji/tslint.json b/types/has-emoji/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/has-emoji/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/hibp/hibp-tests.ts b/types/hibp/hibp-tests.ts new file mode 100644 index 0000000000..cdcd1851bf --- /dev/null +++ b/types/hibp/hibp-tests.ts @@ -0,0 +1,17 @@ +import * as hibp from 'hibp'; + +hibp +.search('someAccountOrEmail') +.then(data => { + if (data.breaches || data.pastes) { + // Bummer... + console.log(data); + } else { + // Phew! We're clear. + console.log('Good news — no pwnage found!'); + } +}) +.catch(err => { + // Something went wrong. + console.log(err.message); +}); diff --git a/types/hibp/index.d.ts b/types/hibp/index.d.ts new file mode 100644 index 0000000000..27819f1c96 --- /dev/null +++ b/types/hibp/index.d.ts @@ -0,0 +1,97 @@ +// Type definitions for hibp 7.2 +// Project: https://github.com/wkovacs64/hibp +// Definitions by: Silas Rech +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +/// + +export interface BreachOptions { + domain?: string; + truncate?: boolean; +} + +export interface Breach { + Name: string; + Title: string; + Domain: string; + BreachDate: string; + AddedDate: string; + ModifiedDate: string; + PwnCount: number; + Description: string; + LogoPath: string; + DataClasses: string[]; + IsVerified: boolean; + IsFabricated: boolean; + IsSensitive: boolean; + IsRetired: boolean; + IsSpamList: boolean; +} + +export interface Paste { + Id: string; + Source: string; + Title: string; + Date: string; + EmailCount: number; +} + +export interface Range { + suffix: string; + count: number; +} + +/** + * Fetches data for a specific breach event. + */ +export function breach(breachName: string): Promise; + +/** + * Fetches breach data for a specific account. + */ +export function breachedAccount(account: string, options?: BreachOptions): Promise; + +/** + * Fetches all breach events in the system. + */ +export function breaches(options?: { domain?: string }): Promise; + +/** + * Fetches all data classes in the system. + */ +export function dataClasses(): Promise; + +/** + * Fetches paste data for a specific email address. + */ +export function pasteAccount(email: string): Promise; + +/** + * Fetches the number of times the the given password has been exposed in a breach (0 indicating no exposure). + * The password is given in plain text, but only the first 5 characters of its SHA-1 hash will be submitted to the API. + */ +export function pwnedPassword(password: string): Promise; + +/** + * Fetches the SHA-1 hash suffixes for the given 5-character SHA-1 hash prefix. + * + * When a password hash with the same first 5 characters is found in the Pwned Passwords repository, + * the API will respond with an HTTP 200 and include the suffix of every hash beginning with the specified prefix, + * followed by a count of how many times it appears in the data set. + * + * This function parses the response and returns a more structured format. + */ +export function pwnedPasswordRange(prefix: string): Promise; + +/** + * Fetches all breaches and all pastes associated with the provided account (email address or username). + * + * Note that the remote API does not support querying pastes by username (only email addresses), + * so in the event the provided account is not a valid email address, + * only breach data is queried and the "pastes" field of the resulting object will always be null. + * + * This is exactly how searching via the current web interface behaves, which this convenience method is designed to mimic. + * + */ +export function search(account: string, options?: BreachOptions): Promise<{ breaches?: Breach[], pastes?: Paste[] }>; diff --git a/types/hibp/tsconfig.json b/types/hibp/tsconfig.json new file mode 100644 index 0000000000..58ecb92a11 --- /dev/null +++ b/types/hibp/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "hibp-tests.ts" + ] +} diff --git a/types/hibp/tslint.json b/types/hibp/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/hibp/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/highcharts/modules/bullet.d.ts b/types/highcharts/modules/bullet.d.ts new file mode 100644 index 0000000000..98819c1963 --- /dev/null +++ b/types/highcharts/modules/bullet.d.ts @@ -0,0 +1,5 @@ +import { Static } from 'highcharts'; + +declare function HighchartsBullet(H: Static): Static; +export = HighchartsBullet; +export as namespace HighchartsBullet; diff --git a/types/highcharts/modules/heatmap.d.ts b/types/highcharts/modules/heatmap.d.ts new file mode 100644 index 0000000000..46ae5ff3e1 --- /dev/null +++ b/types/highcharts/modules/heatmap.d.ts @@ -0,0 +1,5 @@ +import { Static } from 'highcharts'; + +declare function HighchartsHeatMap(H: Static): Static; +export = HighchartsHeatMap; +export as namespace HighchartsHeatMap; diff --git a/types/highcharts/modules/solid-gauge.d.ts b/types/highcharts/modules/solid-gauge.d.ts new file mode 100644 index 0000000000..4fa17d62cd --- /dev/null +++ b/types/highcharts/modules/solid-gauge.d.ts @@ -0,0 +1,5 @@ +import { Static } from 'highcharts'; + +declare function HighchartsSolidGauge(H: Static): Static; +export = HighchartsSolidGauge; +export as namespace HighchartsSolidGauge; diff --git a/types/highcharts/modules/treemap.d.ts b/types/highcharts/modules/treemap.d.ts new file mode 100644 index 0000000000..25a2c58f2e --- /dev/null +++ b/types/highcharts/modules/treemap.d.ts @@ -0,0 +1,5 @@ +import { Static } from 'highcharts'; + +declare function HighchartsTreeMap(H: Static): Static; +export = HighchartsTreeMap; +export as namespace HighchartsTreeMap; diff --git a/types/highcharts/modules/wordcloud.d.ts b/types/highcharts/modules/wordcloud.d.ts new file mode 100644 index 0000000000..f6a9141057 --- /dev/null +++ b/types/highcharts/modules/wordcloud.d.ts @@ -0,0 +1,5 @@ +import { Static } from 'highcharts'; + +declare function HighchartsWordcloud(H: Static): Static; +export = HighchartsWordcloud; +export as namespace HighchartsWordcloud; diff --git a/types/highcharts/test/bullet.ts b/types/highcharts/test/bullet.ts new file mode 100644 index 0000000000..6a82c891bf --- /dev/null +++ b/types/highcharts/test/bullet.ts @@ -0,0 +1 @@ +HighchartsBullet(Highcharts); diff --git a/types/highcharts/test/heatmap.ts b/types/highcharts/test/heatmap.ts new file mode 100644 index 0000000000..d42454d447 --- /dev/null +++ b/types/highcharts/test/heatmap.ts @@ -0,0 +1 @@ +HighchartsHeatMap(Highcharts); diff --git a/types/highcharts/test/solid-gauge.ts b/types/highcharts/test/solid-gauge.ts new file mode 100644 index 0000000000..3d5c2245dc --- /dev/null +++ b/types/highcharts/test/solid-gauge.ts @@ -0,0 +1 @@ +HighchartsSolidGauge(Highcharts); diff --git a/types/highcharts/test/treemap.ts b/types/highcharts/test/treemap.ts new file mode 100644 index 0000000000..c7772a4dbf --- /dev/null +++ b/types/highcharts/test/treemap.ts @@ -0,0 +1 @@ +HighchartsTreeMap(Highcharts); diff --git a/types/highcharts/test/wordcloud.ts b/types/highcharts/test/wordcloud.ts new file mode 100644 index 0000000000..037d54eb7f --- /dev/null +++ b/types/highcharts/test/wordcloud.ts @@ -0,0 +1 @@ +HighchartsWordcloud(Highcharts); diff --git a/types/highcharts/tsconfig.json b/types/highcharts/tsconfig.json index e69f0eeb57..60bbecc1fa 100644 --- a/types/highcharts/tsconfig.json +++ b/types/highcharts/tsconfig.json @@ -18,23 +18,33 @@ "forceConsistentCasingInFileNames": true }, "files": [ - "index.d.ts", - "modules/map/index.d.ts", - "modules/boost.d.ts", - "modules/drilldown.d.ts", - "modules/exporting.d.ts", - "modules/no-data-to-display.d.ts", - "modules/offline-exporting.d.ts", "highcharts-more.d.ts", "highstock.d.ts", + "index.d.ts", "js/highcharts/index.d.ts", + "modules/boost.d.ts", + "modules/bullet.d.ts", + "modules/drilldown.d.ts", + "modules/exporting.d.ts", + "modules/heatmap.d.ts", + "modules/map/index.d.ts", + "modules/no-data-to-display.d.ts", + "modules/offline-exporting.d.ts", + "modules/solid-gauge.d.ts", + "modules/treemap.d.ts", + "modules/wordcloud.d.ts", "test/boost.ts", + "test/bullet.ts", "test/drilldown.ts", "test/exporting.ts", + "test/heatmap.ts", "test/highstock.ts", "test/index.ts", "test/more.ts", "test/no-data-to-display.ts", - "test/offline-exporting.ts" + "test/offline-exporting.ts", + "test/solid-gauge.ts", + "test/treemap.ts", + "test/wordcloud.ts" ] -} \ No newline at end of file +} diff --git a/types/highcharts/tslint.json b/types/highcharts/tslint.json index d6b6fde9be..113c45ef94 100644 --- a/types/highcharts/tslint.json +++ b/types/highcharts/tslint.json @@ -7,6 +7,7 @@ "no-declare-current-package": false, "no-object-literal-type-assertion": false, "no-self-import": false, - "no-unnecessary-generics": false + "no-unnecessary-generics": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/http-proxy-middleware/index.d.ts b/types/http-proxy-middleware/index.d.ts index b48214b8f6..09b80e21c4 100644 --- a/types/http-proxy-middleware/index.d.ts +++ b/types/http-proxy-middleware/index.d.ts @@ -18,7 +18,7 @@ declare function proxy(config: proxy.Config): proxy.Proxy; declare function proxy(contextOrUri: string | string[] | proxy.Filter, config: proxy.Config): proxy.Proxy; declare namespace proxy { - type Filter = (pathanme: string, req: http.IncomingMessage) => boolean; + type Filter = (pathname: string, req: http.IncomingMessage) => boolean; type Logger = (...args: any[]) => void; interface LogProvider { log: Logger; diff --git a/types/humanize-url/humanize-url-tests.ts b/types/humanize-url/humanize-url-tests.ts new file mode 100644 index 0000000000..7556cfb1c4 --- /dev/null +++ b/types/humanize-url/humanize-url-tests.ts @@ -0,0 +1,4 @@ +import humanizeUrl = require('humanize-url'); + +// $ExpectType string +humanizeUrl('https://www.sindresorhus.com/'); diff --git a/types/humanize-url/index.d.ts b/types/humanize-url/index.d.ts new file mode 100644 index 0000000000..c00f5c982f --- /dev/null +++ b/types/humanize-url/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for humanize-url 2.0 +// Project: https://github.com/sindresorhus/humanize-url#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = humanizeUrl; + +declare function humanizeUrl(url: string): string; diff --git a/types/humanize-url/tsconfig.json b/types/humanize-url/tsconfig.json new file mode 100644 index 0000000000..dd9fec46b6 --- /dev/null +++ b/types/humanize-url/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "humanize-url-tests.ts" + ] +} diff --git a/types/humanize-url/tslint.json b/types/humanize-url/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/humanize-url/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/hyper-aws4/hyper-aws4-tests.ts b/types/hyper-aws4/hyper-aws4-tests.ts new file mode 100644 index 0000000000..14caa34a9f --- /dev/null +++ b/types/hyper-aws4/hyper-aws4-tests.ts @@ -0,0 +1,12 @@ +import { sign, Request } from "hyper-aws4"; + +const signOption: Request = { + url: "https://us-west-1.hyper.sh/version", + method: "GET", + credential: { + accessKey: "6DPLADBPWYXDUVXLX34EJXBL", + secretKey: "2ldD1Yz0nzATl9vvagBwYTjglXBjVOWU8gV8aMm5" + } +}; + +sign(signOption); diff --git a/types/hyper-aws4/index.d.ts b/types/hyper-aws4/index.d.ts new file mode 100644 index 0000000000..bf2a0fafa8 --- /dev/null +++ b/types/hyper-aws4/index.d.ts @@ -0,0 +1,25 @@ +// Type definitions for hyper-aws4 1.1 +// Project: https://github.com/Tim-Zhang/hyper-aws4#readme +// Definitions by: BamButz +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export interface Credentials { + accessKey: string; + secretKey: string; +} + +export interface Header { + [header: string]: string; +} + +export type HttpMethods = "GET" | "POST" | "PUT" | "DELETE" | "PATCH"; + +export interface Request { + url: string; + method?: HttpMethods; + body?: string; + headers?: Header; + credential?: Credentials; +} + +export function sign(request: Request, credential?: Credentials): Header; diff --git a/types/hyper-aws4/tsconfig.json b/types/hyper-aws4/tsconfig.json new file mode 100644 index 0000000000..6df2d811c1 --- /dev/null +++ b/types/hyper-aws4/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "strictFunctionTypes": true + }, + "files": [ + "index.d.ts", + "hyper-aws4-tests.ts" + ] +} diff --git a/types/hyper-aws4/tslint.json b/types/hyper-aws4/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/hyper-aws4/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/icon-gen/icon-gen-tests.ts b/types/icon-gen/icon-gen-tests.ts new file mode 100644 index 0000000000..ca02834c04 --- /dev/null +++ b/types/icon-gen/icon-gen-tests.ts @@ -0,0 +1,43 @@ +import icongen = require('icon-gen'); + +icongen('./sample.svg', './icons', { report: true }) + .then(results => { + results[0]; + }) + .catch(err => { + throw err; + }); + +icongen('./sample.svg', './icons') + .then(results => { + results[0]; + }) + .catch(err => { + throw err; + }); + +icongen('./sample.svg', './icons', { + favicon: { + ico: [16, 24, 32, 48, 64], + name: 'favicon-', + sizes: [32, 57, 72, 96, 120, 128, 144, 152, 195, 228], + }, + report: false, +}) + .then(results => { + results[0]; + }) + .catch(err => { + throw err; + }); + +icongen('./sample.svg', './icons', { + favicon: {}, + report: false, +}) + .then(results => { + results[0]; + }) + .catch(err => { + throw err; + }); diff --git a/types/icon-gen/index.d.ts b/types/icon-gen/index.d.ts new file mode 100644 index 0000000000..e7bd6aaa69 --- /dev/null +++ b/types/icon-gen/index.d.ts @@ -0,0 +1,27 @@ +// Type definitions for icon-gen 2.0 +// Project: https://github.com/akabekobeko/npm-icon-gen#readme +// Definitions by: Florian Keller +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace icongen { + interface Options { + favicon?: { + ico: number[]; + name: string; + sizes: number[]; + } | {}; + icns?: { + name: string; + sizes: number[]; + } | {}; + ico?: { + name: string; + sizes: number[]; + } | {}; + report?: boolean; + } +} + +declare function icongen(src: string, dest: string, options?: icongen.Options): Promise; + +export = icongen; diff --git a/types/icon-gen/tsconfig.json b/types/icon-gen/tsconfig.json new file mode 100644 index 0000000000..6b83993922 --- /dev/null +++ b/types/icon-gen/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "icon-gen-tests.ts" + ] +} diff --git a/types/icon-gen/tslint.json b/types/icon-gen/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/icon-gen/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/iframe-resizer/iframe-resizer-tests.ts b/types/iframe-resizer/iframe-resizer-tests.ts index 218a7f71cd..2f459c16a7 100644 --- a/types/iframe-resizer/iframe-resizer-tests.ts +++ b/types/iframe-resizer/iframe-resizer-tests.ts @@ -1,9 +1,9 @@ -import { IFrameComponent, IFrameOptions, iframeResizer } from "iframe-resizer"; +import iframeResizer = require("iframe-resizer"); function testOne(): void { const iframe: HTMLIFrameElement = document.createElement('iframe'); - const options: IFrameOptions = {log: true}; - const components: IFrameComponent[] = iframeResizer(options, iframe); + const options: iframeResizer.IFrameOptions = {log: true}; + const components: iframeResizer.IFrameComponent[] = iframeResizer(options, iframe); if (components) { components.forEach(component => console.log(component.iFrameResizer)); } else { @@ -13,7 +13,7 @@ function testOne(): void { function testTwo(): void { const iframe: HTMLIFrameElement = document.createElement('iframe'); - const components: IFrameComponent[] = iframeResizer({ + const components: iframeResizer.IFrameComponent[] = iframeResizer({ initCallback: () => { console.log('Init'); }, diff --git a/types/iframe-resizer/index.d.ts b/types/iframe-resizer/index.d.ts index 6e67a5b592..5f3cb19c7d 100644 --- a/types/iframe-resizer/index.d.ts +++ b/types/iframe-resizer/index.d.ts @@ -3,275 +3,315 @@ // Definitions by: Armin Baljic // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// tslint:disable-next-line:interface-name -export interface IFrameObject { - close(): void; - moveToAnchor(anchor: string): void; - resize(): void; - sendMessage(message: any, targetOrigin?: string): void; +declare namespace iframeResizer { + // tslint:disable-next-line:interface-name + interface IFrameObject { + close(): void; + + moveToAnchor(anchor: string): void; + + resize(): void; + + sendMessage( + message: any, + targetOrigin?: string + ): void; + } + + // tslint:disable-next-line:interface-name + interface IFrameComponent extends HTMLIFrameElement { + iFrameResizer: IFrameObject; + } + + // tslint:disable-next-line:interface-name + interface IFrameOptions { + /** + * When enabled changes to the Window size or the DOM will cause the iFrame to resize to the new content size. + * Disable if using size method with custom dimensions. + */ + autoResize?: boolean; + /** + * Override the body background style in the iFrame. + */ + bodyBackground?: string; + /** + * Override the default body margin style in the iFrame. A string can be any valid value for the + * CSS margin attribute, for example '8px 3em'. A number value is converted into px. + */ + bodyMargin?: number | string; + /** + * Override the default body padding style in the iFrame. A string can be any valid value for the + * CSS margin attribute, for example '8px 3em'. A number value is converted into px. + */ + bodyPadding?: number | string; + /** + * When set to true, only allow incoming messages from the domain listed in the src property of the iFrame tag. + * If your iFrame navigates between different domains, ports or protocols; then you will need to + * provide an array of URLs or disable this option. + */ + checkOrigin?: boolean | string[]; + /** + * When enabled in page linking inside the iFrame and from the iFrame to the parent page will be enabled. + */ + inPageLinks?: boolean; + /** + * Height calculation method. + */ + heightCalculationMethod?: HeightCalculationMethod; + /** + * Set iFrame Id + */ + id?: string; + /** + * In browsers that don't support mutationObserver, such as IE10, the library falls back to using + * setInterval, to check for changes to the page size. + */ + interval?: number; + /** + * Setting the log option to true will make the scripts in both the host page and the iFrame output + * everything they do to the JavaScript console so you can see the communication between the two scripts. + */ + log?: boolean; + /** + * Set maximum height of iFrame. + */ + maxHeight?: number; + /** + * Set maximum width of iFrame. + */ + maxWidth?: number; + /** + * Set minimum height of iFrame. + */ + minHeight?: number; + /** + * Set minimum width of iFrame. + */ + minWidth?: number; + /** + * Listen for resize events from the parent page, or the iFrame. Select the 'child' value if the iFrame + * can be resized independently of the browser window. Selecting this value can cause issues with some + * height calculation methods on mobile devices. + */ + resizeFrom?: 'parent' | 'child'; + /** + * Enable scroll bars in iFrame. + */ + scrolling?: boolean | 'auto'; + /** + * Resize iFrame to content height. + */ + sizeHeight?: boolean; + /** + * Resize iFrame to content width. + */ + sizeWidth?: boolean; + /** + * Set the number of pixels the iFrame content size has to change by, before triggering a resize of the iFrame. + */ + tolerance?: number; + /** + * Width calculation method. + */ + widthCalculationMethod?: WidthCalculationMethod; + + /** + * Called when iFrame is closed via parentIFrame.close() or iframe.iframeResizer.close() methods. + */ + closedCallback?(iframeId: string): void; + + /** + * Initial setup callback function. + */ + initCallback?(iframe: IFrameComponent): void; + + /** + * Receive message posted from iFrame with the parentIFrame.sendMessage() method. + */ + messageCallback?(data: IFrameMessageData): void; + + /** + * Function called after iFrame resized. Passes in messageData object containing the iFrame, height, width + * and the type of event that triggered the iFrame to resize. + */ + resizedCallback?(data: IFrameResizedData): void; + + /** + * Called before the page is repositioned after a request from the iFrame, due to either an in page link, + * or a direct request from either parentIFrame.scrollTo() or parentIFrame.scrollToOffset(). + * If this callback function returns false, it will stop the library from repositioning the page, so that + * you can implement your own animated page scrolling instead. + */ + scrollCallback?(data: IFrameScrollData): boolean; + } + + // tslint:disable-next-line:interface-name + interface IFramePageOptions { + /** + * This option allows you to restrict the domain of the parent page, + * to prevent other sites mimicking your parent page. + */ + targetOrigin?: string; + + /** + * Receive message posted from the parent page with the iframe.iFrameResizer.sendMessage() method. + */ + messageCallback?(message: any): void; + + /** + * This function is called once iFrame-Resizer has been initialized after receiving a call from the parent page. + */ + readyCallback?(): void; + + /** + * These option can be used to override the option set in the parent page + */ + heightCalculationMethod?: HeightCalculationMethod | (() => number); + /** + * These option can be used to override the option set in the parent page + */ + widthCalculationMethod?: WidthCalculationMethod | (() => number); + } + + type HeightCalculationMethod = 'bodyOffset' | 'bodyScroll' | 'documentElementOffset' | 'documentElementScroll' | + 'max' | 'min' | 'grow' | 'lowestElement' | 'taggedElement'; + + type WidthCalculationMethod = 'bodyOffset' | 'bodyScroll' | 'documentElementOffset' | 'documentElementScroll' | + 'max' | 'min' | 'scroll' | 'rightMostElement' | 'taggedElement'; + + // tslint:disable-next-line:interface-name + interface IFramePage { + /** + * Turn autoResizing of the iFrame on and off. Returns bool of current state. + */ + autoResize(resize?: boolean): boolean; + + /** + * Remove the iFrame from the parent page. + */ + close(): void; + + /** + * Returns the ID of the iFrame that the page is contained in. + */ + getId(): string; + + /** + * Ask the containing page for its positioning coordinates. + * + * Your callback function will be recalled when the parent page is scrolled or resized. + * + * Pass false to disable the callback. + */ + getPageInfo(callback: ((data: PageInfo) => void) | false): void; + + /** + * Scroll the parent page to the coordinates x and y + */ + scrollTo( + x: number, + y: number + ): void; + + /** + * Scroll the parent page to the coordinates x and y relative to the position of the iFrame. + */ + scrollToOffset( + x: number, + y: number + ): void; + + /** + * Send data to the containing page, message can be any data type that can be serialized into JSON. The `targetOrigin` + * option is used to restrict where the message is sent to; to stop an attacker mimicking your parent page. + * See the MDN documentation on postMessage for more details. + */ + sendMessage( + message: any, + targetOrigin?: string + ): void; + + /** + * Change the method use to workout the height of the iFrame. + */ + setHeightCalculationMethod(method: HeightCalculationMethod): void; + + /** + * Change the method use to workout the width of the iFrame. + */ + setWidthCalculationMethod(method: WidthCalculationMethod): void; + + /** + * Set default target origin. + */ + setTargetOrigin(targetOrigin: string): void; + + /** + * Manually force iFrame to resize. To use passed arguments you need first to disable the `autoResize` option to + * prevent auto resizing and enable the `sizeWidth` option if you wish to set the width. + */ + size( + customHeight?: string, + customWidth?: string + ): void; + } + + interface PageInfo { + /** + * The height of the iframe in pixels + */ + iframeHeight: number; + /** + * The width of the iframe in pixels + */ + iframeWidth: number; + /** + * The height of the viewport in pixels + */ + clientHeight: number; + /** + * The width of the viewport in pixels + */ + clientWidth: number; + /** + * The number of pixels between the left edge of the containing page and the left edge of the iframe + */ + offsetLeft: number; + /** + * The number of pixels between the top edge of the containing page and the top edge of the iframe + */ + offsetTop: number; + /** + * The number of pixels between the left edge of the iframe and the left edge of the iframe viewport + */ + scrollLeft: number; + /** + * The number of pixels between the top edge of the iframe and the top edge of the iframe viewport + */ + scrollTop: number; + } + + // tslint:disable-next-line:interface-name + interface IFrameResizedData { + iframe: IFrameComponent; + height: number; + width: number; + type: string; + } + + // tslint:disable-next-line:interface-name + interface IFrameMessageData { + iframe: IFrameComponent; + message: any; + } + + // tslint:disable-next-line:interface-name + interface IFrameScrollData { + x: number; + y: number; + } } -// tslint:disable-next-line:interface-name -export interface IFrameComponent extends HTMLIFrameElement { - iFrameResizer: IFrameObject; -} - -// tslint:disable-next-line:interface-name -export interface IFrameOptions { - /** - * When enabled changes to the Window size or the DOM will cause the iFrame to resize to the new content size. - * Disable if using size method with custom dimensions. - */ - autoResize?: boolean; - /** - * Override the body background style in the iFrame. - */ - bodyBackground?: string; - /** - * Override the default body margin style in the iFrame. A string can be any valid value for the - * CSS margin attribute, for example '8px 3em'. A number value is converted into px. - */ - bodyMargin?: number | string; - /** - * Override the default body padding style in the iFrame. A string can be any valid value for the - * CSS margin attribute, for example '8px 3em'. A number value is converted into px. - */ - bodyPadding?: number | string; - /** - * When set to true, only allow incoming messages from the domain listed in the src property of the iFrame tag. - * If your iFrame navigates between different domains, ports or protocols; then you will need to - * provide an array of URLs or disable this option. - */ - checkOrigin?: boolean | string[]; - /** - * When enabled in page linking inside the iFrame and from the iFrame to the parent page will be enabled. - */ - inPageLinks?: boolean; - /** - * Height calculation method. - */ - heightCalculationMethod?: HeightCalculationMethod; - /** - * Set iFrame Id - */ - id?: string; - /** - * In browsers that don't support mutationObserver, such as IE10, the library falls back to using - * setInterval, to check for changes to the page size. - */ - interval?: number; - /** - * Setting the log option to true will make the scripts in both the host page and the iFrame output - * everything they do to the JavaScript console so you can see the communication between the two scripts. - */ - log?: boolean; - /** - * Set maximum height of iFrame. - */ - maxHeight?: number; - /** - * Set maximum width of iFrame. - */ - maxWidth?: number; - /** - * Set minimum height of iFrame. - */ - minHeight?: number; - /** - * Set minimum width of iFrame. - */ - minWidth?: number; - /** - * Listen for resize events from the parent page, or the iFrame. Select the 'child' value if the iFrame - * can be resized independently of the browser window. Selecting this value can cause issues with some - * height calculation methods on mobile devices. - */ - resizeFrom?: 'parent' | 'child'; - /** - * Enable scroll bars in iFrame. - */ - scrolling?: boolean | 'auto'; - /** - * Resize iFrame to content height. - */ - sizeHeight?: boolean; - /** - * Resize iFrame to content width. - */ - sizeWidth?: boolean; - /** - * Set the number of pixels the iFrame content size has to change by, before triggering a resize of the iFrame. - */ - tolerance?: number; - /** - * Width calculation method. - */ - widthCalculationMethod?: WidthCalculationMethod; - /** - * Called when iFrame is closed via parentIFrame.close() or iframe.iframeResizer.close() methods. - */ - closedCallback?(iframeId: string): void; - /** - * Initial setup callback function. - */ - initCallback?(iframe: IFrameComponent): void; - /** - * Receive message posted from iFrame with the parentIFrame.sendMessage() method. - */ - messageCallback?(data: IFrameMessageData): void; - /** - * Function called after iFrame resized. Passes in messageData object containing the iFrame, height, width - * and the type of event that triggered the iFrame to resize. - */ - resizedCallback?(data: IFrameResizedData): void; - /** - * Called before the page is repositioned after a request from the iFrame, due to either an in page link, - * or a direct request from either parentIFrame.scrollTo() or parentIFrame.scrollToOffset(). - * If this callback function returns false, it will stop the library from repositioning the page, so that - * you can implement your own animated page scrolling instead. - */ - scrollCallback?(data: IFrameScrollData): boolean; -} - -// tslint:disable-next-line:interface-name -export interface IFramePageOptions { - /** - * This option allows you to restrict the domain of the parent page, - * to prevent other sites mimicking your parent page. - */ - targetOrigin?: string; - /** - * Receive message posted from the parent page with the iframe.iFrameResizer.sendMessage() method. - */ - messageCallback?(message: any): void; - /** - * This function is called once iFrame-Resizer has been initialized after receiving a call from the parent page. - */ - readyCallback?(): void; - /** - * These option can be used to override the option set in the parent page - */ - heightCalculationMethod?: HeightCalculationMethod | (() => number); - /** - * These option can be used to override the option set in the parent page - */ - widthCalculationMethod?: WidthCalculationMethod | (() => number); -} - -export type HeightCalculationMethod = 'bodyOffset' | 'bodyScroll' | 'documentElementOffset' | 'documentElementScroll' | - 'max' | 'min' | 'grow' | 'lowestElement' | 'taggedElement'; - - export type WidthCalculationMethod = 'bodyOffset' | 'bodyScroll' | 'documentElementOffset' | 'documentElementScroll' | - 'max' | 'min' | 'scroll' | 'rightMostElement' | 'taggedElement'; - -// tslint:disable-next-line:interface-name -export interface IFramePage { - /** - * Turn autoResizing of the iFrame on and off. Returns bool of current state. - */ - autoResize(resize?: boolean): boolean; - /** - * Remove the iFrame from the parent page. - */ - close(): void; - /** - * Returns the ID of the iFrame that the page is contained in. - */ - getId(): string; - /** - * Ask the containing page for its positioning coordinates. - * - * Your callback function will be recalled when the parent page is scrolled or resized. - * - * Pass false to disable the callback. - */ - getPageInfo(callback: ((data: PageInfo) => void) | false): void; - /** - * Scroll the parent page to the coordinates x and y - */ - scrollTo(x: number, y: number): void; - /** - * Scroll the parent page to the coordinates x and y relative to the position of the iFrame. - */ - scrollToOffset(x: number, y: number): void; - /** - * Send data to the containing page, message can be any data type that can be serialized into JSON. The `targetOrigin` - * option is used to restrict where the message is sent to; to stop an attacker mimicking your parent page. - * See the MDN documentation on postMessage for more details. - */ - sendMessage(message: any, targetOrigin?: string): void; - /** - * Change the method use to workout the height of the iFrame. - */ - setHeightCalculationMethod(method: HeightCalculationMethod): void; - /** - * Change the method use to workout the width of the iFrame. - */ - setWidthCalculationMethod(method: WidthCalculationMethod): void; - /** - * Set default target origin. - */ - setTargetOrigin(targetOrigin: string): void; - /** - * Manually force iFrame to resize. To use passed arguments you need first to disable the `autoResize` option to - * prevent auto resizing and enable the `sizeWidth` option if you wish to set the width. - */ - size(customHeight?: string, customWidth?: string): void; -} - -export interface PageInfo { - /** - * The height of the iframe in pixels - */ - iframeHeight: number; - /** - * The width of the iframe in pixels - */ - iframeWidth: number; - /** - * The height of the viewport in pixels - */ - clientHeight: number; - /** - * The width of the viewport in pixels - */ - clientWidth: number; - /** - * The number of pixels between the left edge of the containing page and the left edge of the iframe - */ - offsetLeft: number; - /** - * The number of pixels between the top edge of the containing page and the top edge of the iframe - */ - offsetTop: number; - /** - * The number of pixels between the left edge of the iframe and the left edge of the iframe viewport - */ - scrollLeft: number; - /** - * The number of pixels between the top edge of the iframe and the top edge of the iframe viewport - */ - scrollTop: number; -} - -// tslint:disable-next-line:interface-name -export interface IFrameResizedData { - iframe: IFrameComponent; - height: number; - width: number; - type: string; -} - -// tslint:disable-next-line:interface-name -export interface IFrameMessageData { - iframe: IFrameComponent; - message: any; -} - -// tslint:disable-next-line:interface-name -export interface IFrameScrollData { - x: number; - y: number; -} - -export function iframeResizer(options: IFrameOptions, target: string | HTMLElement): IFrameComponent[]; +declare function iframeResizer(options: iframeResizer.IFrameOptions, target: string | HTMLElement): iframeResizer.IFrameComponent[]; +export = iframeResizer; +export as namespace iframeResizer; diff --git a/types/imap-simple/index.d.ts b/types/imap-simple/index.d.ts index 3bde57c113..398bcb6a26 100644 --- a/types/imap-simple/index.d.ts +++ b/types/imap-simple/index.d.ts @@ -1,6 +1,7 @@ -// Type definitions for imap-simple v3.1.0 +// Type definitions for imap-simple v4.2.0 // Project: https://github.com/chadxz/imap-simple // Definitions by: Jeffery Grajkowski +// Ilari Aarnio // Definitions: https://github.com/psnider/DefinitelyTyped/imap-simple /// @@ -42,6 +43,18 @@ export class ImapSimple extends NodeJS.EventEmitter { openBox(boxName: string, callback: (err: Error, boxName: string) => void): void; openBox(boxName: string): Promise; + /** Create a mailbox, calling the provided callback with signature (err, boxName), or resolves the returned promise with boxName. */ + addBox(boxName: string, callback: (err: Error, boxName: string) => void): void; + addBox(boxName: string): Promise; + + /** Delete a mailbox, calling the provided callback with signature (err, boxName), or resolves the returned promise with boxName. */ + delBox(boxName: string, callback: (err: Error, boxName: string) => void): void; + delBox(boxName: string): Promise; + + /** Returns the full list of mailboxes (folders). Upon success, either the provided callback will be called with signature (err, boxes), or the returned promise will be resolved with boxes. Boxes is the exact object returned from the node-imap getBoxes() result. */ + getBoxes(callback: (err: Error, boxes: Imap.MailBoxes) => void): void; + getBoxes(): Promise; + /** Search for and retrieve mail in the previously opened mailbox. */ search(searchCriteria: any[], fetchOptions: Imap.FetchOptions, callback: (err: Error, messages: Message[]) => void): void; search(searchCriteria: any[], fetchOptions: Imap.FetchOptions): Promise; @@ -57,6 +70,10 @@ export class ImapSimple extends NodeJS.EventEmitter { addMessageLabel(source: string | string[], label: string | string[], callback: (err: Error) => void): void; addMessageLabel(source: string | string[], label: string | string[]): Promise; + /** Appends the argument message to the currently open mailbox or another mailbox. Message is a RFC-822 compatible MIME message. Valid options are mailbox, flags and date. When completed, either calls the provided callback with signature (err), or resolves the returned promise. */ + append(message: any, options: Imap.AppendOptions, callback: (err: Error) => void): void; + append(message: any, options: Imap.AppendOptions): Promise; + /** Moves the specified message(s) in the currently open mailbox to another mailbox. source corresponds to a node-imap MessageSource which specifies the messages to be moved. When completed, either calls the provided callback with signature (err), or resolves the returned promise. */ moveMessage(source: string | string[], boxName: string, callback: (err: Error) => void): void; moveMessage(source: string | string[], boxName: string): Promise; @@ -66,8 +83,8 @@ export class ImapSimple extends NodeJS.EventEmitter { addFlags(source: string | string[], flag: string | string[]): Promise; /** Removes the provided flag(s) from the specified message(s). uid is the uid of the message you want to remove the flag from or an array of uids. flag is either a string or array of strings indicating the flags to remove. */ - delFlags(source: string | string[], flag: string | string[], callback: (err: Error) => void): void; - delFlags(source: string | string[], flag: string | string[]): Promise; + delFlags(uid: string | string[], flag: string | string[], callback: (err: Error) => void): void; + delFlags(uid: string | string[], flag: string | string[]): Promise; } export namespace errors { diff --git a/types/intercom-client/Lead.d.ts b/types/intercom-client/Lead.d.ts new file mode 100644 index 0000000000..aa4e4a2cfa --- /dev/null +++ b/types/intercom-client/Lead.d.ts @@ -0,0 +1,49 @@ +import { Company } from "./Company"; +import { Avatar, LocationData, Segment, SocialProfile, Tag } from './User'; + +export type LeadIdentifier = { "id": string } | { "user_id": string }; + +export interface Lead { + "type": "contact", + readonly "id": string, + "user_id": string | null, + "email": string | null, + "phone": string | null, + "name": string | null, + readonly "updated_at": number, + "last_seen_ip": string | null, + "unsubscribed_from_emails": boolean, + "last_request_at": number | null, + readonly "created_at": number, + "user_agent_data": string | null, + "custom_attributes": { + [key: string]: any + }, + "avatar": Avatar, + "location_data": LocationData | {}, + "social_profiles": { + "type": "social_profile.list", + "social_profiles": SocialProfile[] + }, + "companies": { + "type": "company.list", + "companies": Company[] + }, + "segments": { + "type": "segment.list", + "segments": Segment[] + + }, + "tags": { + "type": "tag.list", + "tags": Tag[] + }, + "referrer": string | null, +} + +export interface List { + "type": "user.list", + "total_count": number, + "contacts": Lead[], + "pages": { "next"?: string, "page": number, "per_page": number, "total_pages": number } +} diff --git a/types/intercom-client/index.d.ts b/types/intercom-client/index.d.ts index b776165c55..8c81fd989c 100644 --- a/types/intercom-client/index.d.ts +++ b/types/intercom-client/index.d.ts @@ -6,6 +6,7 @@ /// import { List as UserList, User, UserIdentifier } from './User'; +import { List as LeadList, Lead, LeadIdentifier } from './Lead'; import { CompanyIdentifier, List as CompanyList, Company } from './Company'; import { TagIdentifier, List as TagList, Tag, TagOper } from './Tag'; import { List as EventList, Event, ListParam as EventListParam } from './Event'; @@ -33,6 +34,8 @@ export class Client { companies: Companies; tags: Tags; events: Events; + contacts: Leads; + leads: Leads; } export class ApiResponse extends IncomingMessage { @@ -51,17 +54,46 @@ export class Users { find(identifier: UserIdentifier): Promise>; find(identifier: UserIdentifier, cb: callback>): void; - list(): Promise>; - list(cb: callback>): void; + list(): Promise>; + list(cb: callback>): void; listBy(params: {tag_id?: string, segment_id?: string}): Promise>; listBy(params: {tag_id?: string, segment_id?: string}, cb: callback>): void; scroll: Scroll; - archive(): Promise; + archive(identifier: UserIdentifier): Promise>; + archive(identifier: UserIdentifier, cb: callback>): void; + + requestPermanentDeletion(id: string): Promise<{ id: number }>; + requestPermanentDeletion(id: string, cb: callback<{ id: number }>): void; + + requestPermanentDeletionByParams(identifier: UserIdentifier): Promise<{ id: number }>; + requestPermanentDeletionByParams(identifier: UserIdentifier, cb: callback<{ id: number }>): void; +} + +export class Leads { + create(lead: Partial): Promise>; + create(lead: Partial, cb: callback>): void; + + update(lead: UserIdentifier & Partial): Promise>; + update(lead: UserIdentifier & Partial, cb: callback>): void; + + list(): Promise>; + list(cb: callback>): void; + + listBy(params: { email?: string, tag_id?: string, segment_id?: string }): Promise>; + listBy(params: { email?: string, tag_id?: string, segment_id?: string }, cb: callback>): void; + + find(identifier: LeadIdentifier): Promise> + find(identifier: LeadIdentifier, cb: callback>): void; + + delete(id: string): Promise>; + delete(id: string, cb: callback>): void; + + convert(params: { contact: LeadIdentifier, user: UserIdentifier }): Promise>; + convert(params: { contact: LeadIdentifier, user: UserIdentifier }, cb: callback>): void; - requestPermanentDeletion(): Promise<{id: number}>; } export class Companies { diff --git a/types/internal-ip/index.d.ts b/types/internal-ip/index.d.ts index a82dd8c913..1bed7e9059 100644 --- a/types/internal-ip/index.d.ts +++ b/types/internal-ip/index.d.ts @@ -1,7 +1,12 @@ -// Type definitions for internal-ip 2.0 +// Type definitions for internal-ip 3.0 // Project: https://github.com/sindresorhus/internal-ip#readme // Definitions by: BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -export function v6(): Promise; -export function v4(): Promise; +export const v6: IPGetterFn; +export const v4: IPGetterFn; + +export interface IPGetterFn { // tslint:disable-line:interface-name + (): Promise; + sync(): string | null; +} diff --git a/types/internal-ip/internal-ip-tests.ts b/types/internal-ip/internal-ip-tests.ts index e94ec9f510..1b383de2f3 100644 --- a/types/internal-ip/internal-ip-tests.ts +++ b/types/internal-ip/internal-ip-tests.ts @@ -1,10 +1,15 @@ import * as internalIp from 'internal-ip'; -let str: string; internalIp.v6().then(ip => { - str = ip; + // $ExpectType string | null + ip; }); +// $ExpectType string | null +internalIp.v6.sync(); internalIp.v4().then(ip => { - str = ip; + // $ExpectType string | null + ip; }); +// $ExpectType string | null +internalIp.v4.sync(); diff --git a/types/internal-ip/tsconfig.json b/types/internal-ip/tsconfig.json index 746718e07c..99d54932e0 100644 --- a/types/internal-ip/tsconfig.json +++ b/types/internal-ip/tsconfig.json @@ -20,4 +20,4 @@ "index.d.ts", "internal-ip-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/internal-ip/v2/index.d.ts b/types/internal-ip/v2/index.d.ts new file mode 100644 index 0000000000..a82dd8c913 --- /dev/null +++ b/types/internal-ip/v2/index.d.ts @@ -0,0 +1,7 @@ +// Type definitions for internal-ip 2.0 +// Project: https://github.com/sindresorhus/internal-ip#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export function v6(): Promise; +export function v4(): Promise; diff --git a/types/internal-ip/v2/internal-ip-tests.ts b/types/internal-ip/v2/internal-ip-tests.ts new file mode 100644 index 0000000000..e94ec9f510 --- /dev/null +++ b/types/internal-ip/v2/internal-ip-tests.ts @@ -0,0 +1,10 @@ +import * as internalIp from 'internal-ip'; + +let str: string; +internalIp.v6().then(ip => { + str = ip; +}); + +internalIp.v4().then(ip => { + str = ip; +}); diff --git a/types/internal-ip/v2/tsconfig.json b/types/internal-ip/v2/tsconfig.json new file mode 100644 index 0000000000..bae5b7feb8 --- /dev/null +++ b/types/internal-ip/v2/tsconfig.json @@ -0,0 +1,28 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "paths": { + "internal-ip": [ + "internal-ip/v2" + ] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "internal-ip-tests.ts" + ] +} diff --git a/types/internal-ip/v2/tslint.json b/types/internal-ip/v2/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/internal-ip/v2/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/interpret/index.d.ts b/types/interpret/index.d.ts new file mode 100644 index 0000000000..de51c842f8 --- /dev/null +++ b/types/interpret/index.d.ts @@ -0,0 +1,26 @@ +// Type definitions for interpret 1.1 +// Project: https://github.com/tkellen/node-interpret +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +export interface Hook { + (m: { extensions: string } | NodeModule): any; + install(m?: { extension: string; [key: string]: any }): void; +} + +export type RegisterFn = (hook: Hook) => void; + +export interface ExtensionDescriptor { + module: string; + register: RegisterFn; +} + +export type Extension = string | ExtensionDescriptor | Array; +export interface Extensions { + [extension: string]: Extension | null; +} + +export const extensions: Extensions; +export const jsVariants: Extensions; diff --git a/types/interpret/interpret-tests.ts b/types/interpret/interpret-tests.ts new file mode 100644 index 0000000000..2ac4cc0081 --- /dev/null +++ b/types/interpret/interpret-tests.ts @@ -0,0 +1,50 @@ +import { extensions, jsVariants, Extensions } from 'interpret'; + +// $ExpectType Extensions +extensions; +// $ExpectType Extensions +jsVariants; + +const myExts: Extensions = { + '.babel.js': [ + { + module: 'babel-register', + register(hook) { + hook({ extensions: '.js' }); + }, + }, + ], + '.co': 'coco', + '.coffee': ['coffeescript/register', 'coffee-script/register', 'coffeescript', 'coffee-script'], + '.esm.js': { + module: 'esm', + register(hook) { + const esmLoader = hook(module); + require.extensions['.js'] = esmLoader('module')._extensions['.js']; + }, + }, + '.js': null, + '.jsx': [ + { + module: 'node-jsx', + register(hook) { + hook.install({ extension: '.jsx', harmony: true }); + }, + }, + ], + '.toml': { + module: 'toml-require', + register(hook) { + hook.install(); + }, + }, + '.ts': [ + 'typescript-require', + { + module: '@babel/register', + register(hook) { + hook({ extensions: '.ts' }); + }, + }, + ], +}; diff --git a/types/interpret/tsconfig.json b/types/interpret/tsconfig.json new file mode 100644 index 0000000000..970cf59fd9 --- /dev/null +++ b/types/interpret/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "interpret-tests.ts" + ] +} diff --git a/types/interpret/tslint.json b/types/interpret/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/interpret/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/intl-tel-input/v13/tslint.json b/types/intl-tel-input/v13/tslint.json index b6afb8acee..d2632b3e92 100644 --- a/types/intl-tel-input/v13/tslint.json +++ b/types/intl-tel-input/v13/tslint.json @@ -75,6 +75,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/intro.js/index.d.ts b/types/intro.js/index.d.ts index ec27d19439..40603bed1d 100644 --- a/types/intro.js/index.d.ts +++ b/types/intro.js/index.d.ts @@ -7,7 +7,11 @@ declare namespace IntroJs { interface Step { intro: string; element?: string|HTMLElement|Element; - position?: string; + position?: "top"|"left"|"right"|"bottom"|"bottom-left-aligned"|"bottom-middle-aligned"|"bottom-right-aligned"|"auto"; + tooltipClass?: string; + highlightClass?: string; + scrollTo?: "off"|"tooltip"|"element"; + disableInteraction?: boolean; } interface Hint { diff --git a/types/intro.js/intro.js-tests.ts b/types/intro.js/intro.js-tests.ts index d40fbe3f36..44b2f238d3 100644 --- a/types/intro.js/intro.js-tests.ts +++ b/types/intro.js/intro.js-tests.ts @@ -31,13 +31,22 @@ intro.setOptions({ position: 'left' }, { - element : '#step4', - intro : "Another step.", - position: 'bottom' + element : '#step4', + intro : "Another step.", + position : 'bottom', + tooltipClass : 'step4Class', + highlightClass: '' }, { - element: '#step5', - intro : 'Get it, use it.' + element : '#step4', + intro : "Another step.", + position: 'bottom', + scrollTo: 'tooltip' + }, + { + element : '#step5', + intro : 'Get it, use it.', + disableInteraction: true } ], hints: [ diff --git a/types/iri/index.d.ts b/types/iri/index.d.ts new file mode 100644 index 0000000000..93183bcfad --- /dev/null +++ b/types/iri/index.d.ts @@ -0,0 +1,89 @@ +// Type definitions for iri 1.3 +// Project: https://github.com/awwright/node-iri +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export class IRI { + /** + * The constructor takes a single argument, a URI or IRI string: + */ + constructor(iri: string); + /** + * Returns UTF-16 IRI + */ + toString(): string; + /** + * Returns the IRI without the fragment component. Useful for dereferencing URLs on a network. + */ + defrag(): IRI; + /** + * IRIs with a fragment are not absolute. + */ + isAbsolute(): boolean; + /** + * Resolves the IRI against itself, having the effect of stripping the fragment and checking that the supplied IRI is valid (absolute). + */ + toAbsolute(): IRI; + /** + * Resolves the IRI against itself, having the effect of stripping the fragment and checking that the supplied IRI is valid (absolute). + */ + authority(): string | null; + /** + * Returns the fragment component of the IRI. + */ + fragment(): string | null; + /** + * Returns the hier-part of the IRI, the hierarchial component: Everything between the scheme and query, including leading `//` for the host, if it exists. + */ + hierpart(): string; + /** + * Returns the host component of the URI, either a domain name or string-formatted IP address. Excludes port number and username/password. + */ + host(): string; + /** + * Returns the path component of the hier-part. Does not include the authority/host, query, or fragment. + */ + path(): string; + /** + * Returns the port component of the authority as a string, or `null` if there is no port. + */ + port(): string | null; + /** + * Returns the query component of the IRI including leading "?", or `null` if there is no query component. + */ + query(): string | null; + /** + * Resolve the provided URI/IRI reference against this IRI. + */ + resolveReference(ref: string | IRI): IRI; + /** + * Returns the scheme of the IRI, e.g. "https", "file", or "urn". + */ + scheme(): string | null; + /** + * Returns the username/password component of the IRI. + */ + userinfo(): string | null; + /** + * Returns a URI formatted string with only 7-bit characters. + */ + toURIString(): string; + /** + * Decodes URI-encoded UTF-8 characters and returns a unicode string (Strings in ECMAScript/JavaScript are UTF-16). + */ + toIRIString(): string; + /** + * Returns a new IRI object with URI-encoded UTF-8 characters decoded. + */ + toIRI(): IRI; +} + +/** + * Returns an iri.IRI object with UTF-8 escaped characterd decoded. + */ +export function fromURI(uri: string): IRI; + +/** + * Returns an IRI string decoded from the given URI. + */ +export function toIRIString(uri: string): string; diff --git a/types/iri/iri-tests.ts b/types/iri/iri-tests.ts new file mode 100644 index 0000000000..97a460e02c --- /dev/null +++ b/types/iri/iri-tests.ts @@ -0,0 +1,43 @@ +import { IRI, fromURI, toIRIString } from 'iri'; + +const iri = new IRI('iri'); +// $ExpectType string +iri.toString(); +// $ExpectType IRI +iri.defrag(); +// $ExpectType boolean +iri.isAbsolute(); +// $ExpectType IRI +iri.toAbsolute(); +// $ExpectType string | null +iri.authority(); +// $ExpectType string | null +iri.fragment(); +// $ExpectType string +iri.hierpart(); +// $ExpectType string +iri.host(); +// $ExpectType string +iri.path(); +// $ExpectType string | null +iri.port(); +// $ExpectType string | null +iri.query(); +// $ExpectType IRI +iri.resolveReference('ref'); +iri.resolveReference(iri); +// $ExpectType string | null +iri.scheme(); +// $ExpectType string | null +iri.userinfo(); +// $ExpectType string +iri.toURIString(); +// $ExpectType string +iri.toIRIString(); +// $ExpectType IRI +iri.toIRI(); + +// $ExpectType IRI +fromURI('u'); +// $ExpectType string +toIRIString('u'); diff --git a/types/iri/tsconfig.json b/types/iri/tsconfig.json new file mode 100644 index 0000000000..09b1e0069e --- /dev/null +++ b/types/iri/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "iri-tests.ts" + ] +} diff --git a/types/iri/tslint.json b/types/iri/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/iri/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/jasmine/index.d.ts b/types/jasmine/index.d.ts index e9dba1e2cd..fdfe29607c 100644 --- a/types/jasmine/index.d.ts +++ b/types/jasmine/index.d.ts @@ -80,18 +80,21 @@ declare function afterAll(action: (done: DoneFn) => void, timeout?: number): voi /** * Create an expectation for a spec. + * @checkReturnValue see https://tsetse.info/check-return-value * @param spy */ declare function expect(spy: Function): jasmine.Matchers; /** * Create an expectation for a spec. + * @checkReturnValue see https://tsetse.info/check-return-value * @param actual */ declare function expect(actual: ArrayLike): jasmine.ArrayLikeMatchers; /** * Create an expectation for a spec. + * @checkReturnValue see https://tsetse.info/check-return-value * @param actual Actual computed value to test expectations against. */ declare function expect(actual: T): jasmine.Matchers; @@ -639,6 +642,7 @@ declare namespace jasmine { calls: Calls; mostRecentCall: { args: any[]; }; argsForCall: any[]; + withArgs(...args: any[]): Spy; } type SpyObj = T & { diff --git a/types/jasmine/jasmine-tests.ts b/types/jasmine/jasmine-tests.ts index ba8763ce3d..92f9a21db8 100644 --- a/types/jasmine/jasmine-tests.ts +++ b/types/jasmine/jasmine-tests.ts @@ -469,6 +469,40 @@ describe("A spy, when configured with an alternate implementation", () => { }); }); +describe("A spy, when configured with alternate implementations for specified arguments", () => { + var foo: any, bar: any, fetchedBar: any; + + beforeEach(() => { + foo = { + setBar: (value: any) => { + bar = value; + }, + getBar: () => { + return bar; + } + }; + + spyOn(foo, "getBar") + .withArgs(1, "2") + .and.callFake(() => 1002); + + foo.setBar(123); + fetchedBar = foo.getBar(1, "2"); + }); + + it("tracks that the spy was called", () => { + expect(foo.getBar).toHaveBeenCalled(); + }); + + it("should not effect other functions", () => { + expect(bar).toEqual(123); + }); + + it("when called returns the requested value", () => { + expect(fetchedBar).toEqual(1002); + }); +}); + describe("A spy, when configured to throw a value", () => { var foo: any, bar: any; diff --git a/types/jest-when/index.d.ts b/types/jest-when/index.d.ts index af62a95830..f484502f4d 100644 --- a/types/jest-when/index.d.ts +++ b/types/jest-when/index.d.ts @@ -8,6 +8,11 @@ export interface PartialMockInstance { mockReturnValue: jest.MockInstance['mockReturnValue']; + mockReturnValueOnce: jest.MockInstance['mockReturnValueOnce']; + mockResolvedValue: jest.MockInstance['mockResolvedValue']; + mockResolvedValueOnce: jest.MockInstance['mockResolvedValueOnce']; + mockRejectedValue: jest.MockInstance['mockRejectedValue']; + mockRejectedValueOnce: jest.MockInstance['mockRejectedValueOnce']; } export interface When { diff --git a/types/joi/index.d.ts b/types/joi/index.d.ts index 096847a82c..404e0339ef 100644 --- a/types/joi/index.d.ts +++ b/types/joi/index.d.ts @@ -504,6 +504,11 @@ export interface NumberSchema extends AnySchema { */ integer(): this; + /** + * Allows the number to be outside of JavaScript's safety range (Number.MIN_SAFE_INTEGER & Number.MAX_SAFE_INTEGER). + */ + unsafe(enabled?: boolean): this; + /** * Specifies the maximum number of decimal places where: * @param limit - the maximum number of decimal places allowed. diff --git a/types/joi/joi-tests.ts b/types/joi/joi-tests.ts index 716fc70c16..e21310396b 100644 --- a/types/joi/joi-tests.ts +++ b/types/joi/joi-tests.ts @@ -618,6 +618,7 @@ numSchema = numSchema.greater(ref); numSchema = numSchema.less(num); numSchema = numSchema.less(ref); numSchema = numSchema.integer(); +numSchema = numSchema.unsafe(); numSchema = numSchema.precision(num); numSchema = numSchema.multiple(num); numSchema = numSchema.positive(); diff --git a/types/jquery-focus-exit/index.d.ts b/types/jquery-focus-exit/index.d.ts index 8787136a4e..d4da0a1f18 100644 --- a/types/jquery-focus-exit/index.d.ts +++ b/types/jquery-focus-exit/index.d.ts @@ -14,7 +14,7 @@ export interface FocusElements { declare global { interface JQuery { focusExit(options?: { debug: boolean }): JQuery; - on(event: 'focusExit', handler: ((event: JQuery.Event, data: FocusElements) => void)): JQuery; - one(event: 'focusin', handler: ((event: JQuery.Event) => void)): JQuery; + on(event: 'focusExit', handler: ((event: JQuery.TriggeredEvent, data: FocusElements) => void)): JQuery; + one(event: 'focusin', handler: ((event: JQuery.TriggeredEvent) => void)): JQuery; } } diff --git a/types/jquery-mouse-exit/index.d.ts b/types/jquery-mouse-exit/index.d.ts index f0ba17996e..651a7b3f85 100644 --- a/types/jquery-mouse-exit/index.d.ts +++ b/types/jquery-mouse-exit/index.d.ts @@ -18,6 +18,6 @@ export type FocusElements = Partial<{ declare global { interface JQuery { mouseExit(options?: Options): JQuery; - on(event: 'mouseExit', handler: ((event: JQuery.Event, data: FocusElements) => void)): JQuery; + on(event: 'mouseExit', handler: ((event: JQuery.TriggeredEvent, data: FocusElements) => void)): JQuery; } } diff --git a/types/jquery.colorpicker/tslint.json b/types/jquery.colorpicker/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/jquery.colorpicker/tslint.json +++ b/types/jquery.colorpicker/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/jquery.fancytree/tslint.json b/types/jquery.fancytree/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/jquery.fancytree/tslint.json +++ b/types/jquery.fancytree/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/jquery.pjax/tslint.json b/types/jquery.pjax/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/jquery.pjax/tslint.json +++ b/types/jquery.pjax/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/jquery/JQuery.d.ts b/types/jquery/JQuery.d.ts index 7453457953..cbcc12d956 100644 --- a/types/jquery/JQuery.d.ts +++ b/types/jquery/JQuery.d.ts @@ -530,7 +530,10 @@ $( document ).ajaxComplete(function( event, request, settings ) { }); ``` */ - ajaxComplete(handler: (this: Document, event: JQuery.Event, jqXHR: JQuery.jqXHR, ajaxOptions: JQuery.AjaxSettings) => void | false): this; + ajaxComplete(handler: (this: Document, + event: JQuery.TriggeredEvent, + jqXHR: JQuery.jqXHR, + ajaxOptions: JQuery.AjaxSettings) => void | false): this; /** * Register a handler to be called when Ajax requests complete with an error. This is an Ajax Event. * @param handler The function to be invoked. @@ -543,7 +546,11 @@ $( document ).ajaxError(function( event, request, settings ) { }); ``` */ - ajaxError(handler: (this: Document, event: JQuery.Event, jqXHR: JQuery.jqXHR, ajaxSettings: JQuery.AjaxSettings, thrownError: string) => void | false): this; + ajaxError(handler: (this: Document, + event: JQuery.TriggeredEvent, + jqXHR: JQuery.jqXHR, + ajaxSettings: JQuery.AjaxSettings, + thrownError: string) => void | false): this; /** * Attach a function to be executed before an Ajax request is sent. This is an Ajax Event. * @param handler The function to be invoked. @@ -556,7 +563,10 @@ $( document ).ajaxSend(function( event, request, settings ) { }); ``` */ - ajaxSend(handler: (this: Document, event: JQuery.Event, jqXHR: JQuery.jqXHR, ajaxOptions: JQuery.AjaxSettings) => void | false): this; + ajaxSend(handler: (this: Document, + event: JQuery.TriggeredEvent, + jqXHR: JQuery.jqXHR, + ajaxOptions: JQuery.AjaxSettings) => void | false): this; /** * Register a handler to be called when the first Ajax request begins. This is an Ajax Event. * @param handler The function to be invoked. @@ -595,7 +605,11 @@ $( document ).ajaxSuccess(function( event, request, settings ) { }); ``` */ - ajaxSuccess(handler: (this: Document, event: JQuery.Event, jqXHR: JQuery.jqXHR, ajaxOptions: JQuery.AjaxSettings, data: JQuery.PlainObject) => void | false): this; + ajaxSuccess(handler: (this: Document, + event: JQuery.TriggeredEvent, + jqXHR: JQuery.jqXHR, + ajaxOptions: JQuery.AjaxSettings, + data: JQuery.PlainObject) => void | false): this; /** * Perform a custom animation of a set of CSS properties. * @param properties An object of CSS properties and values that the animation will move toward. @@ -1329,9 +1343,12 @@ $( "p" ).before( $( "b" ) ); * * **Solution**: Change the method call to use `.on()` or `.off()`, the documentation for the old methods include specific instructions. In general, the `.bind()` and `.unbind()` methods can be renamed directly to `.on()` and `.off()` respectively since the argument orders are identical. */ - bind(eventType: string, - eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; + bind( + eventType: TType, + eventData: TData, + handler: JQuery.TypeEventHandler + ): this; /** * Attach a handler to an event for the elements. * @param eventType A string containing one or more DOM event types, such as "click" or "submit," or custom event names. @@ -1458,8 +1475,13 @@ $( "button" ).click(function() { ``` */ - bind(eventType: string, - handler_preventBubble: JQuery.EventHandler | JQuery.EventHandlerBase> | false | null | undefined): this; + bind( + eventType: TType, + handler_preventBubble: JQuery.TypeEventHandler | + false | + null | + undefined + ): this; /** * Attach a handler to an event for the elements. * @param events An object containing one or more DOM event types and functions to execute for them. @@ -1485,7 +1507,7 @@ $( "div.test" ).bind({ }); ``` */ - bind(events: JQuery.PlainObject | JQuery.EventHandlerBase> | false>): this; + bind(events: JQuery.TypeEventHandlers): this; /** * Bind an event handler to the "blur" JavaScript event, or trigger that event on an element. * @param eventData An object containing data that will be passed to the event handler. @@ -1499,7 +1521,7 @@ $( "div.test" ).bind({ * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ blur(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to the "blur" JavaScript event, or trigger that event on an element. * @param handler A function to execute each time the event is triggered. @@ -1515,7 +1537,8 @@ $( "div.test" ).bind({ $( "p" ).blur(); ``` */ - blur(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; + blur(handler?: JQuery.TypeEventHandler | + false): this; /** * Bind an event handler to the "change" JavaScript event, or trigger that event on an element. * @param eventData An object containing data that will be passed to the event handler. @@ -1529,7 +1552,7 @@ $( "p" ).blur(); * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ change(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to the "change" JavaScript event, or trigger that event on an element. * @param handler A function to execute each time the event is triggered. @@ -1588,7 +1611,8 @@ $( "input[type='text']" ).change(function() { }); ``` */ - change(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; + change(handler?: JQuery.TypeEventHandler | + false): this; /** * Get the children of each element in the set of matched elements, optionally filtered by a selector. * @param selector A string containing a selector expression to match elements against. @@ -1841,7 +1865,7 @@ $( "#stop" ).click(function() { * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ click(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to the "click" JavaScript event, or trigger that event on an element. * @param handler A function to execute each time the event is triggered. @@ -1891,7 +1915,8 @@ $( "p" ).click(function() { $( "p" ).click(); ``` */ - click(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; + click(handler?: JQuery.TypeEventHandler | + false): this; /** * Create a deep copy of the set of matched elements. * @param withDataAndEvents A Boolean indicating whether event handlers and data should be copied along with the elements. The @@ -2065,7 +2090,7 @@ $( "#frameDemo" ).contents().find( "a" ).css( "background-color", "#BADA55" ); ``` */ - contents(): JQuery; + contents(): JQuery; /** * Bind an event handler to the "contextmenu" JavaScript event, or trigger that event on an element. * @param eventData An object containing data that will be passed to the event handler. @@ -2079,7 +2104,7 @@ $( "#frameDemo" ).contents().find( "a" ).css( "background-color", "#BADA55" ); * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ contextmenu(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to the "contextmenu" JavaScript event, or trigger that event on an element. * @param handler A function to execute each time the event is triggered. @@ -2133,7 +2158,8 @@ div.contextmenu(function() { ``` */ - contextmenu(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; + contextmenu(handler?: JQuery.TypeEventHandler | + false): this; /** * Set one or more CSS properties for the set of matched elements. * @param propertyName A CSS property name. @@ -2594,7 +2620,7 @@ $( "button" ).click(function() { * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ dblclick(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to the "dblclick" JavaScript event, or trigger that event on an element. * @param handler A function to execute each time the event is triggered. @@ -2648,7 +2674,8 @@ divdbl.dblclick(function() { ``` */ - dblclick(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; + dblclick(handler?: JQuery.TypeEventHandler | + false): this; /** * Set a timer to delay execution of subsequent items in the queue. * @param duration An integer indicating the number of milliseconds to delay execution of the next item in the queue. @@ -2713,10 +2740,13 @@ $( "button" ).click(function() { * * **Solution**: Change the method call to use `.on()` or `.off()`, the documentation for the old methods include specific instructions. In general, the `.bind()` and `.unbind()` methods can be renamed directly to `.on()` and `.off()` respectively since the argument orders are identical. */ - delegate(selector: JQuery.Selector, - eventType: string, - eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; + delegate( + selector: JQuery.Selector, + eventType: TType, + eventData: TData, + handler: JQuery.TypeEventHandler + ): this; /** * Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements. * @param selector A selector to filter the elements that trigger the event. @@ -2828,9 +2858,12 @@ $( "button" ).click(function() { ``` */ - delegate(selector: JQuery.Selector, - eventType: string, - handler: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; + delegate( + selector: JQuery.Selector, + eventType: TType, + handler: JQuery.TypeEventHandler | + false + ): this; /** * Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements. * @param selector A selector to filter the elements that trigger the event. @@ -2844,7 +2877,8 @@ $( "button" ).click(function() { * **Solution**: Change the method call to use `.on()` or `.off()`, the documentation for the old methods include specific instructions. In general, the `.bind()` and `.unbind()` methods can be renamed directly to `.on()` and `.off()` respectively since the argument orders are identical. */ delegate(selector: JQuery.Selector, - events: JQuery.PlainObject | JQuery.EventHandlerBase> | false>): this; + events: JQuery.TypeEventHandlers + ): this; /** * Execute the next function on the queue for the matched elements. * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. @@ -4264,7 +4298,7 @@ $( "p span" ).first().addClass( "highlight" ); * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ focus(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to the "focus" JavaScript event, or trigger that event on an element. * @param handler A function to execute each time the event is triggered. @@ -4316,7 +4350,8 @@ $( document ).ready(function() { }); ``` */ - focus(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; + focus(handler?: JQuery.TypeEventHandler | + false): this; /** * Bind an event handler to the "focusin" event. * @param eventData An object containing data that will be passed to the event handler. @@ -4330,7 +4365,7 @@ $( document ).ready(function() { * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ focusin(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to the "focusin" event. * @param handler A function to execute each time the event is triggered. @@ -4370,7 +4405,8 @@ $( "p" ).focusin(function() { ``` */ - focusin(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; + focusin(handler?: JQuery.TypeEventHandler | + false): this; /** * Bind an event handler to the "focusout" JavaScript event. * @param eventData An object containing data that will be passed to the event handler. @@ -4384,7 +4420,7 @@ $( "p" ).focusin(function() { * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ focusout(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to the "focusout" JavaScript event. * @param handler A function to execute each time the event is triggered. @@ -4445,7 +4481,8 @@ $( "p" ) ``` */ - focusout(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; + focusout(handler?: JQuery.TypeEventHandler | + false): this; /** * Retrieve one of the elements matched by the jQuery object. * @param index A zero-based integer indicating which element to retrieve. @@ -4888,12 +4925,11 @@ $( "button" ).click(function() { */ hide(duration_complete_options?: JQuery.Duration | ((this: TElement) => void) | JQuery.EffectsOptions): this; /** - * Bind one or two handlers to the matched elements, to be executed when the mouse pointer enters and leaves the elements. - * @param handlerInOut A function to execute when the mouse pointer enters or leaves the element. + * Bind two handlers to the matched elements, to be executed when the mouse pointer enters and leaves the elements. + * @param handlerIn A function to execute when the mouse pointer enters the element. * @param handlerOut A function to execute when the mouse pointer leaves the element. * @see \`{@link https://api.jquery.com/hover/ }\` * @since 1.0 - * @since 1.4 * @deprecated ​ Deprecated. * * **Cause**: The `.hover()` method is a shorthand for the use of the `mouseover`/`mouseout` events. It is often a poor user interface choice because it does not allow for any small amounts of delay between when the mouse enters or exits an area and when the event fires. This can make it quite difficult to use with UI widgets such as drop-down menus. For more information on the problems of hovering, see the \`{@link http://cherne.net/brian/resources/jquery.hoverIntent.html hoverIntent plugin}\`. @@ -4961,6 +4997,21 @@ $( "td" ).hover( ```javascript $( "td" ).off( "mouseenter mouseleave" ); ``` + */ + hover(handlerIn: JQuery.TypeEventHandler | + false, + handlerOut: JQuery.TypeEventHandler | + false): this; + /** + * Bind a single handler to the matched elements, to be executed when the mouse pointer enters or leaves the elements. + * @param handlerInOut A function to execute when the mouse pointer enters or leaves the element. + * @see \`{@link https://api.jquery.com/hover/ }\` + * @since 1.4 + * @deprecated ​ Deprecated. + * + * **Cause**: The `.hover()` method is a shorthand for the use of the `mouseover`/`mouseout` events. It is often a poor user interface choice because it does not allow for any small amounts of delay between when the mouse enters or exits an area and when the event fires. This can make it quite difficult to use with UI widgets such as drop-down menus. For more information on the problems of hovering, see the \`{@link http://cherne.net/brian/resources/jquery.hoverIntent.html hoverIntent plugin}\`. + * + * **Solution**: Review uses of `.hover()` to determine if they are appropriate, and consider use of plugins such as `hoverIntent` as an alternative. The direct replacement for `.hover(fn1, fn2)`, is `.on("mouseenter", fn1).on("mouseleave", fn2)`. * @example ​ ````Slide the next sibling LI up or down on hover, and toggle a class. ```html @@ -5016,10 +5067,8 @@ $( "li" ) ``` */ - // HACK: The type parameter T is not used but ensures the 'event' callback parameter is typed correctly. - // tslint:disable-next-line:no-unnecessary-generics - hover(handlerInOut: JQuery.EventHandler | JQuery.EventHandlerBase> | false, - handlerOut?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; + hover(handlerInOut: JQuery.TypeEventHandler | + false): this; /** * Set the HTML contents of each element in the set of matched elements. * @param htmlString_function _@param_ `htmlString_function` @@ -5833,7 +5882,7 @@ $( "li" ).click(function() { * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ keydown(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to the "keydown" JavaScript event, or trigger that event on an element. * @param handler A function to execute each time the event is triggered. @@ -5905,7 +5954,8 @@ $( "#other" ).click(function() { ``` */ - keydown(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; + keydown(handler?: JQuery.TypeEventHandler | + false): this; /** * Bind an event handler to the "keypress" JavaScript event, or trigger that event on an element. * @param eventData An object containing data that will be passed to the event handler. @@ -5919,7 +5969,7 @@ $( "#other" ).click(function() { * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ keypress(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to the "keypress" JavaScript event, or trigger that event on an element. * @param handler A function to execute each time the event is triggered. @@ -5991,7 +6041,8 @@ $( "#other" ).click(function() { ``` */ - keypress(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; + keypress(handler?: JQuery.TypeEventHandler | + false): this; /** * Bind an event handler to the "keyup" JavaScript event, or trigger that event on an element. * @param eventData An object containing data that will be passed to the event handler. @@ -6005,7 +6056,7 @@ $( "#other" ).click(function() { * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ keyup(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to the "keyup" JavaScript event, or trigger that event on an element. * @param handler A function to execute each time the event is triggered. @@ -6078,7 +6129,8 @@ $( "#other").click(function() { ``` */ - keyup(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; + keyup(handler?: JQuery.TypeEventHandler | + false): this; /** * Reduce the set of matched elements to the final one in the set. * @see \`{@link https://api.jquery.com/last/ }\` @@ -6367,7 +6419,7 @@ $( "input" ).click(function() { * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ mousedown(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to the "mousedown" JavaScript event, or trigger that event on an element. * @param handler A function to execute each time the event is triggered. @@ -6405,7 +6457,8 @@ $( "p" ) ``` */ - mousedown(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; + mousedown(handler?: JQuery.TypeEventHandler | + false): this; /** * Bind an event handler to be fired when the mouse enters an element, or trigger that handler on an element. * @param eventData An object containing data that will be passed to the event handler. @@ -6419,7 +6472,7 @@ $( "p" ) * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ mouseenter(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to be fired when the mouse enters an element, or trigger that handler on an element. * @param handler A function to execute each time the event is triggered. @@ -6500,7 +6553,8 @@ $( "div.enterleave" ) ``` */ - mouseenter(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; + mouseenter(handler?: JQuery.TypeEventHandler | + false): this; /** * Bind an event handler to be fired when the mouse leaves an element, or trigger that handler on an element. * @param eventData An object containing data that will be passed to the event handler. @@ -6514,7 +6568,7 @@ $( "div.enterleave" ) * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ mouseleave(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to be fired when the mouse leaves an element, or trigger that handler on an element. * @param handler A function to execute each time the event is triggered. @@ -6593,7 +6647,8 @@ $( "div.enterleave" ) ``` */ - mouseleave(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; + mouseleave(handler?: JQuery.TypeEventHandler | + false): this; /** * Bind an event handler to the "mousemove" JavaScript event, or trigger that event on an element. * @param eventData An object containing data that will be passed to the event handler. @@ -6607,7 +6662,7 @@ $( "div.enterleave" ) * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ mousemove(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to the "mousemove" JavaScript event, or trigger that event on an element. * @param handler A function to execute each time the event is triggered. @@ -6671,7 +6726,8 @@ $( "div" ).mousemove(function( event ) { ``` */ - mousemove(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; + mousemove(handler?: JQuery.TypeEventHandler | + false): this; /** * Bind an event handler to the "mouseout" JavaScript event, or trigger that event on an element. * @param eventData An object containing data that will be passed to the event handler. @@ -6685,7 +6741,7 @@ $( "div" ).mousemove(function( event ) { * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ mouseout(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to the "mouseout" JavaScript event, or trigger that event on an element. * @param handler A function to execute each time the event is triggered. @@ -6766,7 +6822,8 @@ $( "div.enterleave" ) ``` */ - mouseout(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; + mouseout(handler?: JQuery.TypeEventHandler | + false): this; /** * Bind an event handler to the "mouseover" JavaScript event, or trigger that event on an element. * @param eventData An object containing data that will be passed to the event handler. @@ -6780,7 +6837,7 @@ $( "div.enterleave" ) * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ mouseover(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to the "mouseover" JavaScript event, or trigger that event on an element. * @param handler A function to execute each time the event is triggered. @@ -6861,7 +6918,8 @@ $( "div.enterleave" ) ``` */ - mouseover(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; + mouseover(handler?: JQuery.TypeEventHandler | + false): this; /** * Bind an event handler to the "mouseup" JavaScript event, or trigger that event on an element. * @param eventData An object containing data that will be passed to the event handler. @@ -6875,7 +6933,7 @@ $( "div.enterleave" ) * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ mouseup(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to the "mouseup" JavaScript event, or trigger that event on an element. * @param handler A function to execute each time the event is triggered. @@ -6913,7 +6971,8 @@ $( "p" ) ``` */ - mouseup(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; + mouseup(handler?: JQuery.TypeEventHandler | + false): this; /** * Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector. * @param selector A string containing a selector expression to match elements against. @@ -7245,7 +7304,12 @@ $( "body" ).on( "click", "p", foo ); $( "body" ).off( "click", "p", foo ); ``` */ - off(events: string, selector: JQuery.Selector, handler: JQuery.EventHandlerBase> | false): this; + off( + events: TType, + selector: JQuery.Selector, + handler: JQuery.TypeEventHandler | + false + ): this; /** * Remove an event handler. * @param events One or more space-separated event types and optional namespaces, or just namespaces, such as @@ -7275,7 +7339,12 @@ $( "form" ).on( "keypress.validator", "input[type='text']", validate ); $( "form" ).off( ".validator" ); ``` */ - off(events: string, selector_handler?: JQuery.Selector | JQuery.EventHandlerBase> | false): this; + off( + events: TType, + selector_handler?: JQuery.Selector | + JQuery.TypeEventHandler | + false + ): this; /** * Remove an event handler. * @param events An object where the string keys represent one or more space-separated event types and optional @@ -7284,7 +7353,8 @@ $( "form" ).off( ".validator" ); * @see \`{@link https://api.jquery.com/off/ }\` * @since 1.7 */ - off(events: JQuery.PlainObject> | false>, selector?: JQuery.Selector): this; + off(events: JQuery.TypeEventHandlers, + selector?: JQuery.Selector): this; /** * Remove an event handler. * @param event A jQuery.Event object. @@ -7295,7 +7365,7 @@ $( "form" ).off( ".validator" ); $( "p" ).off(); ``` */ - off(event?: JQuery.Event): this; + off(event?: JQuery.TriggeredEvent): this; /** * Set the current coordinates of every element in the set of matched elements, relative to the document. * @param coordinates_function _@param_ `coordinates_function` @@ -7468,10 +7538,30 @@ $( "*", document.body ).click(function( event ) { * @see \`{@link https://api.jquery.com/on/ }\` * @since 1.7 */ - on(events: string, - selector: JQuery.Selector | null, - data: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; + on( + events: TType, + selector: JQuery.Selector, + data: TData, + handler: JQuery.TypeEventHandler + ): this; + /** + * Attach an event handler function for one or more events to the selected elements. + * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". + * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the + * selector is null or omitted, the event is always triggered when it reaches the selected element. + * @param data Data to be passed to the handler in event.data when an event is triggered. + * @param handler A function to execute when the event is triggered. + * @see \`{@link https://api.jquery.com/on/ }\` + * @since 1.7 + */ + on( + events: TType, + selector: null | undefined, + data: TData, + handler: JQuery.TypeEventHandler + ): this; /** * Attach an event handler function for one or more events to the selected elements. * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". @@ -7484,7 +7574,7 @@ $( "*", document.body ).click(function( event ) { * @deprecated ​ Deprecated. Use \`{@link JQuery.Event }\` in place of \`{@link JQueryEventObject }\`. */ on(events: string, - selector: JQuery.Selector | null, + selector: JQuery.Selector | null | undefined, data: any, handler: ((event: JQueryEventObject) => void)): this; /** @@ -7547,14 +7637,41 @@ $( "body" ).on( "click", "a", function( event ) { }); ``` */ - on(events: string, - selector: JQuery.Selector, - handler: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; + on( + events: TType, + selector: JQuery.Selector, + handler: JQuery.TypeEventHandler | + false + ): this; /** * Attach an event handler function for one or more events to the selected elements. * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". - * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the - * selector is null or omitted, the event is always triggered when it reaches the selected element. + * @param data Data to be passed to the handler in event.data when an event is triggered. + * @param handler A function to execute when the event is triggered. + * @see \`{@link https://api.jquery.com/on/ }\` + * @since 1.7 + * @example ​ ````Pass data to the event handler, which is specified here by name: +```javascript +function myHandler( event ) { + alert( event.data.foo ); +} +$( "p" ).on( "click", { foo: "bar" }, myHandler ); +``` + */ + on( + events: TType, + data: TData, + handler: JQuery.TypeEventHandler + ): this; + /** + * Attach an event handler function for one or more events to the selected elements. + * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". + * @param selector_data _@param_ `selector_data` + *
+ * * `selector` — A selector string to filter the descendants of the selected elements that trigger the event. If the + * selector is null or omitted, the event is always triggered when it reaches the selected element.
+ * * `data` — Data to be passed to the handler in event.data when an event is triggered. * @param handler A function to execute when the event is triggered. * @see \`{@link https://api.jquery.com/on/ }\` * @since 1.7 @@ -7609,37 +7726,6 @@ $( "body" ).on( "click", "a", function( event ) { event.preventDefault(); }); ``` - */ - on(events: string, - selector: JQuery.Selector, - // tslint:disable-next-line:unified-signatures - handler: ((event: JQueryEventObject) => void)): this; - /** - * Attach an event handler function for one or more events to the selected elements. - * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". - * @param data Data to be passed to the handler in event.data when an event is triggered. - * @param handler A function to execute when the event is triggered. - * @see \`{@link https://api.jquery.com/on/ }\` - * @since 1.7 - * @example ​ ````Pass data to the event handler, which is specified here by name: -```javascript -function myHandler( event ) { - alert( event.data.foo ); -} -$( "p" ).on( "click", { foo: "bar" }, myHandler ); -``` - */ - on(events: string, - data: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; - /** - * Attach an event handler function for one or more events to the selected elements. - * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". - * @param data Data to be passed to the handler in event.data when an event is triggered. - * @param handler A function to execute when the event is triggered. - * @see \`{@link https://api.jquery.com/on/ }\` - * @since 1.7 - * @deprecated ​ Deprecated. Use \`{@link JQuery.Event }\` in place of \`{@link JQueryEventObject }\`. * @example ​ ````Pass data to the event handler, which is specified here by name: ```javascript function myHandler( event ) { @@ -7649,8 +7735,7 @@ $( "p" ).on( "click", { foo: "bar" }, myHandler ); ``` */ on(events: string, - // tslint:disable-next-line:unified-signatures - data: any, + selector_data: any, handler: ((event: JQueryEventObject) => void)): this; /** * Attach an event handler function for one or more events to the selected elements. @@ -7743,8 +7828,11 @@ $( "#cart" ).on( "mouseenter mouseleave", function( event ) { }); ``` */ - on(events: string, - handler: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; + on( + events: TType, + handler: JQuery.TypeEventHandler | + false + ): this; /** * Attach an event handler function for one or more events to the selected elements. * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". @@ -7837,7 +7925,6 @@ $( "#cart" ).on( "mouseenter mouseleave", function( event ) { ``` */ on(events: string, - // tslint:disable-next-line:unified-signatures handler: ((event: JQueryEventObject) => void)): this; /** * Attach an event handler function for one or more events to the selected elements. @@ -7849,9 +7936,26 @@ $( "#cart" ).on( "mouseenter mouseleave", function( event ) { * @see \`{@link https://api.jquery.com/on/ }\` * @since 1.7 */ - on(events: JQuery.PlainObject | JQuery.EventHandlerBase> | false>, - selector: JQuery.Selector | null, - data: TData): this; + on( + events: JQuery.TypeEventHandlers, + selector: JQuery.Selector, + data: TData + ): this; + /** + * Attach an event handler function for one or more events to the selected elements. + * @param events An object in which the string keys represent one or more space-separated event types and optional + * namespaces, and the values represent a handler function to be called for the event(s). + * @param selector A selector string to filter the descendants of the selected elements that will call the handler. If + * the selector is null or omitted, the handler is always called when it reaches the selected element. + * @param data Data to be passed to the handler in event.data when an event occurs. + * @see \`{@link https://api.jquery.com/on/ }\` + * @since 1.7 + */ + on( + events: JQuery.TypeEventHandlers, + selector: null | undefined, + data: TData + ): this; /** * Attach an event handler function for one or more events to the selected elements. * @param events An object in which the string keys represent one or more space-separated event types and optional @@ -7861,9 +7965,9 @@ $( "#cart" ).on( "mouseenter mouseleave", function( event ) { * @see \`{@link https://api.jquery.com/on/ }\` * @since 1.7 */ - on(events: JQuery.PlainObject | JQuery.EventHandlerBase> | false>, - // tslint:disable-next-line:unified-signatures - selector: JQuery.Selector): this; + on(events: JQuery.TypeEventHandlers, + selector: JQuery.Selector + ): this; /** * Attach an event handler function for one or more events to the selected elements. * @param events An object in which the string keys represent one or more space-separated event types and optional @@ -7872,8 +7976,10 @@ $( "#cart" ).on( "mouseenter mouseleave", function( event ) { * @see \`{@link https://api.jquery.com/on/ }\` * @since 1.7 */ - on(events: JQuery.PlainObject | JQuery.EventHandlerBase> | false>, - data: TData): this; + on( + events: JQuery.TypeEventHandlers, + data: TData + ): this; /** * Attach an event handler function for one or more events to the selected elements. * @param events An object in which the string keys represent one or more space-separated event types and optional @@ -7922,7 +8028,7 @@ $( "div.test" ).on({ ``` */ - on(events: JQuery.PlainObject | JQuery.EventHandlerBase> | false>): this; + on(events: JQuery.TypeEventHandlers): this; /** * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". @@ -7933,10 +8039,30 @@ $( "div.test" ).on({ * @see \`{@link https://api.jquery.com/one/ }\` * @since 1.7 */ - one(events: string, - selector: JQuery.Selector | null, - data: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; + one( + events: TType, + selector: JQuery.Selector, + data: TData, + handler: JQuery.TypeEventHandler + ): this; + /** + * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. + * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". + * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the + * selector is null or omitted, the event is always triggered when it reaches the selected element. + * @param data Data to be passed to the handler in event.data when an event is triggered. + * @param handler A function to execute when the event is triggered. + * @see \`{@link https://api.jquery.com/one/ }\` + * @since 1.7 + */ + one( + events: TType, + selector: null | undefined, + data: TData, + handler: JQuery.TypeEventHandler + ): this; /** * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". @@ -7947,9 +8073,12 @@ $( "div.test" ).on({ * @see \`{@link https://api.jquery.com/one/ }\` * @since 1.7 */ - one(events: string, + one( + events: TType, selector: JQuery.Selector, - handler: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; + handler: JQuery.TypeEventHandler | + false + ): this; /** * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". @@ -7958,9 +8087,12 @@ $( "div.test" ).on({ * @see \`{@link https://api.jquery.com/one/ }\` * @since 1.7 */ - one(events: string, - data: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; + one( + events: TType, + data: TData, + handler: JQuery.TypeEventHandler + ): this; /** * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". @@ -8049,8 +8181,11 @@ $(".target").one("click mouseenter", function() { ``` */ - one(events: string, - handler: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; + one( + events: TType, + handler: JQuery.TypeEventHandler| + false + ): this; /** * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. * @param events An object in which the string keys represent one or more space-separated event types and optional @@ -8061,9 +8196,26 @@ $(".target").one("click mouseenter", function() { * @see \`{@link https://api.jquery.com/one/ }\` * @since 1.7 */ - one(events: JQuery.PlainObject | JQuery.EventHandlerBase> | false>, - selector: JQuery.Selector | null, - data: TData): this; + one( + events: JQuery.TypeEventHandlers, + selector: JQuery.Selector, + data: TData + ): this; + /** + * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. + * @param events An object in which the string keys represent one or more space-separated event types and optional + * namespaces, and the values represent a handler function to be called for the event(s). + * @param selector A selector string to filter the descendants of the selected elements that will call the handler. If + * the selector is null or omitted, the handler is always called when it reaches the selected element. + * @param data Data to be passed to the handler in event.data when an event occurs. + * @see \`{@link https://api.jquery.com/one/ }\` + * @since 1.7 + */ + one( + events: JQuery.TypeEventHandlers, + selector: null | undefined, + data: TData + ): this; /** * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. * @param events An object in which the string keys represent one or more space-separated event types and optional @@ -8073,8 +8225,7 @@ $(".target").one("click mouseenter", function() { * @see \`{@link https://api.jquery.com/one/ }\` * @since 1.7 */ - one(events: JQuery.PlainObject | JQuery.EventHandlerBase> | false>, - // tslint:disable-next-line:unified-signatures + one(events: JQuery.TypeEventHandlers, selector: JQuery.Selector): this; /** * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. @@ -8084,8 +8235,10 @@ $(".target").one("click mouseenter", function() { * @see \`{@link https://api.jquery.com/one/ }\` * @since 1.7 */ - one(events: JQuery.PlainObject | JQuery.EventHandlerBase> | false>, - data: TData): this; + one( + events: JQuery.TypeEventHandlers, + data: TData + ): this; /** * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. * @param events An object in which the string keys represent one or more space-separated event types and optional @@ -8093,7 +8246,7 @@ $(".target").one("click mouseenter", function() { * @see \`{@link https://api.jquery.com/one/ }\` * @since 1.7 */ - one(events: JQuery.PlainObject | JQuery.EventHandlerBase> | false>): this; + one(events: JQuery.TypeEventHandlers): this; /** * Set the CSS outer height of each element in the set of matched elements. * @param value_function _@param_ `value_function` @@ -9851,7 +10004,7 @@ $( "button" ).on( "click", function() { * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ resize(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to the "resize" JavaScript event, or trigger that event on an element. * @param handler A function to execute each time the event is triggered. @@ -9869,7 +10022,8 @@ $( window ).resize(function() { }); ``` */ - resize(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; + resize(handler?: JQuery.TypeEventHandler | + false): this; /** * Bind an event handler to the "scroll" JavaScript event, or trigger that event on an element. * @param eventData An object containing data that will be passed to the event handler. @@ -9883,7 +10037,7 @@ $( window ).resize(function() { * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ scroll(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to the "scroll" JavaScript event, or trigger that event on an element. * @param handler A function to execute each time the event is triggered. @@ -9933,7 +10087,8 @@ $( window ).scroll(function() { ``` */ - scroll(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; + scroll(handler?: JQuery.TypeEventHandler | + false): this; /** * Set the current horizontal position of the scroll bar for each of the set of matched elements. * @param value An integer indicating the new position to set the scroll bar to. @@ -10107,7 +10262,7 @@ $( "p:last" ).text( "scrollTop:" + p.scrollTop() ); * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ select(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to the "select" JavaScript event, or trigger that event on an element. * @param handler A function to execute each time the event is triggered. @@ -10156,7 +10311,8 @@ $( ":input" ).select(function() { $( "input" ).select(); ``` */ - select(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; + select(handler?: JQuery.TypeEventHandler | + false): this; /** * Encode a set of form elements as a string for submission. * @see \`{@link https://api.jquery.com/serialize/ }\` @@ -11127,7 +11283,7 @@ $( "#toggle" ).on( "click", function() { * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. */ submit(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; + handler: JQuery.TypeEventHandler): this; /** * Bind an event handler to the "submit" JavaScript event, or trigger that event on an element. * @param handler A function to execute each time the event is triggered. @@ -11196,7 +11352,8 @@ $( "form" ).submit(function() { $( "form:first" ).submit(); ``` */ - submit(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; + submit(handler?: JQuery.TypeEventHandler | + false): this; /** * Set the content of each element in the set of matched elements to the specified text. * @param text_function _@param_ `text_function` @@ -11704,7 +11861,7 @@ $( "body" ).trigger({ }); ``` */ - trigger(eventType_event: string | JQuery.Event, extraParameters?: any[] | JQuery.PlainObject | string | number | boolean): this; + trigger(eventType_event: string | JQuery.Event, extraParameters?: any[] | JQuery.PlainObject | string | number | boolean): this; /** * Execute all handlers attached to an element for an event. * @param eventType_event _@param_ `eventType_event` @@ -11747,7 +11904,7 @@ $( "input" ).focus(function() { ``` */ - triggerHandler(eventType_event: string | JQuery.Event, extraParameters?: any[] | JQuery.PlainObject | string | number | boolean): any; + triggerHandler(eventType_event: string | JQuery.Event, extraParameters?: any[] | JQuery.PlainObject | string | number | boolean): any; /** * Remove a previously-attached event handler from the elements. * @param event A string containing one or more DOM event types, such as "click" or "submit," or custom event names. @@ -11815,7 +11972,11 @@ $( "p" ).bind( "click", foo ); // ... Now foo will be called when paragraphs are $( "p" ).unbind( "click", foo ); // ... foo will no longer be called. ``` */ - unbind(event: string, handler: JQuery.EventHandlerBase> | false): this; + unbind( + event: TType, + handler: JQuery.TypeEventHandler | + false + ): this; /** * Remove a previously-attached event handler from the elements. * @param event A string containing one or more DOM event types, such as "click" or "submit," or custom event names. @@ -11836,7 +11997,7 @@ $( "p" ).unbind(); $( "p" ).unbind( "click" ); ``` */ - unbind(event?: string | JQuery.Event): this; + unbind(event?: string | JQuery.TriggeredEvent): this; /** * Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements. * @param selector A selector which will be used to filter the event results. @@ -11906,12 +12067,19 @@ $( "body" ).delegate( "p", "click", foo ); $( "body" ).undelegate( "p", "click", foo ); ``` */ - undelegate(selector: JQuery.Selector, eventType: string, handler: JQuery.EventHandlerBase> | false): this; + undelegate( + selector: JQuery.Selector, + eventType: TType, + handler: JQuery.TypeEventHandler | + false + ): this; /** * Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements. * @param selector A selector which will be used to filter the event results. - * @param eventTypes A string containing a JavaScript event type, such as "click" or "keydown" - * An object of one or more event types and previously bound functions to unbind from them. + * @param eventType_events _@param_ `eventType_events` + *
+ * * `eventType` — A string containing a JavaScript event type, such as "click" or "keydown"
+ * * `events` — An object of one or more event types and previously bound functions to unbind from them. * @see \`{@link https://api.jquery.com/undelegate/ }\` * @since 1.4.2 * @since 1.4.3 @@ -11921,7 +12089,9 @@ $( "body" ).undelegate( "p", "click", foo ); * * **Solution**: Change the method call to use `.on()` or `.off()`, the documentation for the old methods include specific instructions. In general, the `.bind()` and `.unbind()` methods can be renamed directly to `.on()` and `.off()` respectively since the argument orders are identical. */ - undelegate(selector: JQuery.Selector, eventTypes: string | JQuery.PlainObject> | false>): this; + undelegate(selector: JQuery.Selector, + eventType_events: string | + JQuery.TypeEventHandlers): this; /** * Remove a handler from the event for all elements which match the current selector, based upon a specific set of root elements. * @param namespace A selector which will be used to filter the event results. diff --git a/types/jquery/JQueryStatic.d.ts b/types/jquery/JQueryStatic.d.ts index 20d3a9e8c5..4ba7653e69 100644 --- a/types/jquery/JQueryStatic.d.ts +++ b/types/jquery/JQueryStatic.d.ts @@ -148,21 +148,26 @@ $( "div", xml.responseXML ); $( document.body ).css( "background", "black" ); ``` */ - // Using a unified signature is not possible due to a TypeScript 2.4 bug (DefinitelyTyped#27810) - (element: T): JQuery; + // NOTE: `HTMLSelectElement` is both an Element and an Array-Like Object but jQuery treats it as an Element. + (element: HTMLSelectElement): JQuery; /** * Return a collection of matched elements either found in the DOM based on passed argument(s) or created by passing an HTML string. - * @param elementArray An array containing a set of DOM elements to wrap in a jQuery object. + * @param element_elementArray _@param_ `element_elementArray` + *
+ * * `element` — A DOM element to wrap in a jQuery object.
+ * * `elementArray` — An array containing a set of DOM elements to wrap in a jQuery object. * @see \`{@link https://api.jquery.com/jQuery/ }\` * @since 1.0 + * @example ​ ````Set the background color of the page to black. +```javascript +$( document.body ).css( "background", "black" ); +``` * @example ​ ````Hide all the input elements within a form. ```javascript $( myForm.elements ).hide(); ``` */ - // Using a unified signature is not possible due to a TypeScript 2.4 bug (DefinitelyTyped#27810) - // tslint:disable-next-line:unified-signatures - (elementArray: T[]): JQuery; + (element_elementArray: T | ArrayLike): JQuery; /** * Return a collection of matched elements either found in the DOM based on passed argument(s) or created by passing an HTML string. * @param selection An existing jQuery object to clone. diff --git a/types/jquery/jquery-tests.ts b/types/jquery/jquery-tests.ts index 515715bf14..9e4dea80ee 100644 --- a/types/jquery/jquery-tests.ts +++ b/types/jquery/jquery-tests.ts @@ -160,6 +160,9 @@ function JQueryStatic() { // $ExpectType JQuery $([new HTMLSelectElement()]); + // $ExpectType JQuery + $(document.querySelectorAll('p')); + // https://github.com/DefinitelyTyped/DefinitelyTyped/issues/19597#issuecomment-378218432 function issue_19597_378218432() { const myDiv = $(document.createElement('div')); @@ -2430,7 +2433,7 @@ function JQuery() { $(document).ajaxComplete(function(event, jqXHR, ajaxOptions) { // $ExpectType Document this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; // $ExpectType jqXHR jqXHR; @@ -2446,7 +2449,7 @@ function JQuery() { $(document).ajaxError(function(event, jqXHR, ajaxSettings, thrownError) { // $ExpectType Document this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; // $ExpectType jqXHR jqXHR; @@ -2464,7 +2467,7 @@ function JQuery() { $(document).ajaxSend(function(event, jqXHR, ajaxOptions) { // $ExpectType Document this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; // $ExpectType jqXHR jqXHR; @@ -2500,7 +2503,7 @@ function JQuery() { $(document).ajaxSuccess(function(event, jqXHR, ajaxOptions, data) { // $ExpectType Document this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; // $ExpectType jqXHR jqXHR; @@ -3883,21 +3886,11 @@ function JQuery() { function events() { // [bind() overloads] https://github.com/jquery/api.jquery.com/issues/1048 function bind() { - interface J1 { kind: 'J1'; } - // $ExpectType JQuery $('p').bind('myEvent', 'myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').bind('myEvent', 'myData', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }); @@ -3905,77 +3898,51 @@ function JQuery() { $('p').bind('myEvent', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').bind('myEvent', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }); // $ExpectType JQuery $('p').bind('myEvent', false); + // $ExpectType JQuery + $('p').bind('myEvent', null); + + // $ExpectType JQuery + $('p').bind('myEvent', undefined); + // $ExpectType JQuery $('p').bind({ myEvent1: false, myEvent2(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }, - myEvent3(this: J1, event) { - // $ExpectType J1 + click(event) { + // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType ClickEvent event; } }); - - // $ExpectType JQuery - $('p').bind('myEvent', null); - - // $ExpectType JQuery - $('p').bind('myEvent', undefined); - } + } function delegate() { - interface J1 { kind: 'J1'; } - // $ExpectType JQuery $('table').delegate('td', 'myEvent', 'myData', function(event) { - // $ExpectType HTMLElement + // $ExpectType any this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('table').delegate('td', 'myEvent', 'myData', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }); // $ExpectType JQuery $('table').delegate('td', 'myEvent', function(event) { - // $ExpectType HTMLElement + // $ExpectType any this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('table').delegate('td', 'myEvent', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }); @@ -3984,44 +3951,37 @@ function JQuery() { // $ExpectType JQuery $('table').delegate('td', { - myEvent1(event) { - // $ExpectType HTMLElement + myEvent1: false, + myEvent2(event) { + // $ExpectType any this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }, - myEvent2: false, - myEvent3(this: J1, event) { - // $ExpectType J1 + click(event) { + // $ExpectType any this; - // $ExpectType Event + // $ExpectType ClickEvent event; } }); } function off() { - function defaultContext_defaultData(this: HTMLElement, event: JQuery.Event) { } + function defaultData(this: HTMLElement, event: JQuery.TriggeredEvent) { } - function defaultContext_customData(this: HTMLElement, event: JQuery.Event) { } + function customData(this: HTMLElement, event: JQuery.TriggeredEvent) { } - function customContext_defaultData(this: J1, event: JQuery.Event) { } - - function customContext_customData(this: J1, event: JQuery.Event) { } - - interface J1 { kind: 'J1'; } + function specificEventType(this: HTMLElement, event: JQuery.MouseDownEvent) { } // $ExpectType JQuery - $('table').off('myEvent', 'td', defaultContext_defaultData); + $('table').off('myEvent', 'td', defaultData); // $ExpectType JQuery - $('table').off('myEvent', 'td', defaultContext_customData); + $('table').off('myEvent', 'td', customData); // $ExpectType JQuery - $('table').off('myEvent', 'td', customContext_defaultData); - - // $ExpectType JQuery - $('table').off('myEvent', 'td', customContext_customData); + $('table').off('mousedown', 'td', specificEventType); // $ExpectType JQuery $('table').off('myEvent', 'td', false); @@ -4030,16 +3990,13 @@ function JQuery() { $('table').off('myEvent', 'td'); // $ExpectType JQuery - $('table').off('myEvent', defaultContext_defaultData); + $('table').off('myEvent', defaultData); // $ExpectType JQuery - $('table').off('myEvent', defaultContext_customData); + $('table').off('myEvent', customData); // $ExpectType JQuery - $('table').off('myEvent', customContext_defaultData); - - // $ExpectType JQuery - $('table').off('myEvent', customContext_customData); + $('table').off('mousedown', specificEventType); // $ExpectType JQuery $('table').off('myEvent', false); @@ -4050,52 +4007,30 @@ function JQuery() { // $ExpectType JQuery $('table').off({ myEvent1: false, - defaultContext_defaultData, - defaultContext_customData, - customContext_defaultData, - customContext_customData + defaultData, + customData }, 'td'); // $ExpectType JQuery $('table').off({ myEvent1: false, - defaultContext_defaultData, - defaultContext_customData, - customContext_defaultData, - customContext_customData + defaultData, + customData }); + const ev: JQuery.TriggeredEvent = undefined!; // $ExpectType JQuery - $('table').off($.Event('myEvent')); + $('table').off(ev); // $ExpectType JQuery $('table').off(); } function on() { - interface J1 { kind: 'J1'; } - - // $ExpectType JQuery $('table').on('myEvent', 'td', 'myData', function(event) { - // $ExpectType HTMLElement + // $ExpectType any this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('table').on('myEvent', 'td', 'myData', function(event: JQueryEventObject) { - // $ExpectType HTMLElement - this; - // $ExpectType JQueryEventObject - event; - }); - - // $ExpectType JQuery - $('table').on('myEvent', 'td', 'myData', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }); @@ -4103,12 +4038,29 @@ function JQuery() { $('table').on('myEvent', null, 'myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType TriggeredEvent + event; + }); + + // $ExpectType JQuery + $('table').on('myEvent', undefined, 'myData', function(event) { + // $ExpectType HTMLElement + this; + // $ExpectType TriggeredEvent + event; + }); + + // $ExpectType JQuery + $('table').on('myEvent', 'td', 'myData', function(event: JQueryEventObject) { + // $ExpectType any + this; + // $ExpectType JQueryEventObject event; }); // $ExpectType JQuery $('table').on('myEvent', null, 'myData', function(event: JQueryEventObject) { + // TODO: Why is this HTMLElement? The callback signature doesn't even have `this` declared. // $ExpectType HTMLElement this; // $ExpectType JQueryEventObject @@ -4116,34 +4068,19 @@ function JQuery() { }); // $ExpectType JQuery - $('table').on('myEvent', null, 'myData', function(this: J1, event) { - // $ExpectType J1 + $('table').on('myEvent', undefined, 'myData', function(event: JQueryEventObject) { + // TODO: Why is this HTMLElement? The callback signature doesn't even have `this` declared. + // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType JQueryEventObject event; }); // $ExpectType JQuery $('table').on('myEvent', 'td', function(event) { - // $ExpectType HTMLElement + // $ExpectType any this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('table').on('myEvent', 'td', function(event: JQueryEventObject) { - // $ExpectType HTMLElement - this; - // $ExpectType JQueryEventObject - event; - }); - - // $ExpectType JQuery - $('table').on('myEvent', 'td', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }); @@ -4154,7 +4091,15 @@ function JQuery() { $('table').on('myEvent', 3, function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType TriggeredEvent + event; + }); + + // $ExpectType JQuery + $('table').on('myEvent', 'td', function(event: JQueryEventObject) { + // $ExpectType any + this; + // $ExpectType JQueryEventObject event; }); @@ -4167,20 +4112,15 @@ function JQuery() { }); // $ExpectType JQuery - $('table').on('myEvent', 3, function(this: J1, event) { - // $ExpectType J1 + $('table').on('myEvent', function(event) { + // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }); // $ExpectType JQuery - $('table').on('myEvent', function(event) { - // $ExpectType HTMLElement - this; - // $ExpectType Event - event; - }); + $('table').on('myEvent', false); // $ExpectType JQuery $('table').on('myEvent', function(event: JQueryEventObject) { @@ -4214,30 +4154,19 @@ function JQuery() { event; }); - // $ExpectType JQuery - $('table').on('myEvent', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('table').on('myEvent', false); - // $ExpectType JQuery $('table').on({ myEvent1: false, myEvent2(event) { - // $ExpectType HTMLElement + // $ExpectType any this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }, - myEvent3(this: J1, event) { - // $ExpectType J1 + click(event) { + // $ExpectType any this; - // $ExpectType Event + // $ExpectType ClickEvent event; } }, 'td', 'myData'); @@ -4248,13 +4177,13 @@ function JQuery() { myEvent2(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }, - myEvent3(this: J1, event) { - // $ExpectType J1 + click(event) { + // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType ClickEvent event; } }, null, 'myData'); @@ -4265,13 +4194,30 @@ function JQuery() { myEvent2(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }, - myEvent3(this: J1, event) { - // $ExpectType J1 + click(event) { + // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType ClickEvent + event; + } + }, undefined, 'myData'); + + // $ExpectType JQuery + $('table').on({ + myEvent1: false, + myEvent2(event) { + // $ExpectType any + this; + // $ExpectType TriggeredEvent + event; + }, + click(event) { + // $ExpectType any + this; + // $ExpectType ClickEvent event; } }, 'td'); @@ -4282,13 +4228,13 @@ function JQuery() { myEvent2(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }, - myEvent3(this: J1, event) { - // $ExpectType J1 + click(event) { + // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType ClickEvent event; } }, 3); @@ -4299,34 +4245,37 @@ function JQuery() { myEvent2(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }, - myEvent3(this: J1, event) { - // $ExpectType J1 + click(event) { + // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType ClickEvent event; } }); + + // https://github.com/DefinitelyTyped/DefinitelyTyped/issues/31124 + function issue_31124(el: Element, mouseX: number) { + $(el) + .on("mousedown touchstart", (evt) => { + // tslint:disable-next-line:prefer-conditional-expression + if (evt.type === "mousedown") { + mouseX = (evt.originalEvent as MouseEvent).clientX; + } else { + mouseX = (evt.originalEvent as TouchEvent).touches[0].clientX; + } + }); + } } function one() { - interface J1 { kind: 'J1'; } - // $ExpectType JQuery $('table').one('myEvent', 'td', 'myData', function(event) { - // $ExpectType HTMLElement + // $ExpectType any this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('table').one('myEvent', 'td', 'myData', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }); @@ -4334,31 +4283,23 @@ function JQuery() { $('table').one('myEvent', null, 'myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }); // $ExpectType JQuery - $('table').one('myEvent', null, 'myData', function(this: J1, event) { - // $ExpectType J1 + $('table').one('myEvent', undefined, 'myData', function(event) { + // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }); // $ExpectType JQuery $('table').one('myEvent', 'td', function(event) { - // $ExpectType HTMLElement + // $ExpectType any this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('table').one('myEvent', 'td', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }); @@ -4369,15 +4310,7 @@ function JQuery() { $('table').one('myEvent', 3, function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('table').one('myEvent', 3, function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }); @@ -4385,15 +4318,7 @@ function JQuery() { $('table').one('myEvent', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('table').one('myEvent', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }); @@ -4404,15 +4329,15 @@ function JQuery() { $('table').one({ myEvent1: false, myEvent2(event) { - // $ExpectType HTMLElement + // $ExpectType any this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }, - myEvent3(this: J1, event) { - // $ExpectType J1 + click(event) { + // $ExpectType any this; - // $ExpectType Event + // $ExpectType ClickEvent event; } }, 'td', 'myData'); @@ -4423,13 +4348,13 @@ function JQuery() { myEvent2(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }, - myEvent3(this: J1, event) { - // $ExpectType J1 + click(event) { + // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType ClickEvent event; } }, null, 'myData'); @@ -4440,13 +4365,30 @@ function JQuery() { myEvent2(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }, - myEvent3(this: J1, event) { - // $ExpectType J1 + click(event) { + // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType ClickEvent + event; + } + }, undefined, 'myData'); + + // $ExpectType JQuery + $('table').one({ + myEvent1: false, + myEvent2(event) { + // $ExpectType any + this; + // $ExpectType TriggeredEvent + event; + }, + click(event) { + // $ExpectType any + this; + // $ExpectType ClickEvent event; } }, 'td'); @@ -4457,13 +4399,13 @@ function JQuery() { myEvent2(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }, - myEvent3(this: J1, event) { - // $ExpectType J1 + click(event) { + // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType ClickEvent event; } }, 3); @@ -4474,13 +4416,13 @@ function JQuery() { myEvent2(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }, - myEvent3(this: J1, event) { - // $ExpectType J1 + click(event) { + // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType ClickEvent event; } }); @@ -4551,27 +4493,20 @@ function JQuery() { } function unbind() { - function defaultContext_defaultData(this: HTMLElement, event: JQuery.Event) { } + function defaultData(this: HTMLElement, event: JQuery.TriggeredEvent) { } - function defaultContext_customData(this: HTMLElement, event: JQuery.Event) { } + function customData(this: HTMLElement, event: JQuery.TriggeredEvent) { } - function customContext_defaultData(this: J1, event: JQuery.Event) { } - - function customContext_customData(this: J1, event: JQuery.Event) { } - - interface J1 { kind: 'J1'; } + function specificEventType(this: HTMLElement, event: JQuery.MouseDownEvent) { } // $ExpectType JQuery - $('p').unbind('myEvent', defaultContext_defaultData); + $('p').unbind('myEvent', defaultData); // $ExpectType JQuery - $('p').unbind('myEvent', defaultContext_customData); + $('p').unbind('myEvent', customData); // $ExpectType JQuery - $('p').unbind('myEvent', customContext_defaultData); - - // $ExpectType JQuery - $('p').unbind('myEvent', customContext_customData); + $('p').unbind('mousedown', specificEventType); // $ExpectType JQuery $('p').unbind('myEvent', false); @@ -4579,35 +4514,29 @@ function JQuery() { // $ExpectType JQuery $('p').unbind('myEvent'); + const ev: JQuery.TriggeredEvent = undefined!; // $ExpectType JQuery - $('p').unbind($.Event('myEvent')); + $('p').unbind(ev); // $ExpectType JQuery $('p').unbind(); } function undelegate() { - function defaultContext_defaultData(this: HTMLElement, event: JQuery.Event) { } + function defaultData(this: HTMLElement, event: JQuery.TriggeredEvent) { } - function defaultContext_customData(this: HTMLElement, event: JQuery.Event) { } + function customData(this: HTMLElement, event: JQuery.TriggeredEvent) { } - function customContext_defaultData(this: J1, event: JQuery.Event) { } - - function customContext_customData(this: J1, event: JQuery.Event) { } - - interface J1 { kind: 'J1'; } + function specificEventType(this: HTMLElement, event: JQuery.MouseDownEvent) { } // $ExpectType JQuery - $('table').undelegate('td', 'click', defaultContext_defaultData); + $('table').undelegate('td', 'click', defaultData); // $ExpectType JQuery - $('table').undelegate('td', 'click', defaultContext_customData); + $('table').undelegate('td', 'click', customData); // $ExpectType JQuery - $('table').undelegate('td', 'click', customContext_defaultData); - - // $ExpectType JQuery - $('table').undelegate('td', 'click', customContext_customData); + $('table').undelegate('td', 'mousedown', specificEventType); // $ExpectType JQuery $('table').undelegate('td', 'click', false); @@ -4618,10 +4547,8 @@ function JQuery() { // $ExpectType JQuery $('table').undelegate('td', { myEvent1: false, - defaultContext_defaultData, - defaultContext_customData, - customContext_defaultData, - customContext_customData + defaultData, + customData }); // $ExpectType JQuery @@ -4632,21 +4559,11 @@ function JQuery() { } function blur() { - interface J1 { kind: 'J1'; } - // $ExpectType JQuery $('p').blur('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').blur('myData', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType BlurEvent event; }); @@ -4654,15 +4571,7 @@ function JQuery() { $('p').blur(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').blur(function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType BlurEvent event; }); @@ -4674,21 +4583,11 @@ function JQuery() { } function change() { - interface J1 { kind: 'J1'; } - // $ExpectType JQuery $('p').change('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').change('myData', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType ChangeEvent event; }); @@ -4696,15 +4595,7 @@ function JQuery() { $('p').change(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').change(function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType ChangeEvent event; }); @@ -4716,21 +4607,11 @@ function JQuery() { } function click() { - interface J1 { kind: 'J1'; } - // $ExpectType JQuery $('p').click('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').click('myData', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType ClickEvent event; }); @@ -4738,15 +4619,7 @@ function JQuery() { $('p').click(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').click(function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType ClickEvent event; }); @@ -4758,21 +4631,11 @@ function JQuery() { } function contextmenu() { - interface J1 { kind: 'J1'; } - // $ExpectType JQuery $('p').contextmenu('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').contextmenu('myData', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType ContextMenuEvent event; }); @@ -4780,15 +4643,7 @@ function JQuery() { $('p').contextmenu(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').contextmenu(function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType ContextMenuEvent event; }); @@ -4800,21 +4655,11 @@ function JQuery() { } function dblclick() { - interface J1 { kind: 'J1'; } - // $ExpectType JQuery $('p').dblclick('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').dblclick('myData', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType DoubleClickEvent event; }); @@ -4822,15 +4667,7 @@ function JQuery() { $('p').dblclick(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').dblclick(function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType DoubleClickEvent event; }); @@ -4842,21 +4679,11 @@ function JQuery() { } function focus() { - interface J1 { kind: 'J1'; } - // $ExpectType JQuery $('p').focus('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').focus('myData', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType FocusEvent event; }); @@ -4864,15 +4691,7 @@ function JQuery() { $('p').focus(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').focus(function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType FocusEvent event; }); @@ -4884,21 +4703,11 @@ function JQuery() { } function focusin() { - interface J1 { kind: 'J1'; } - // $ExpectType JQuery $('p').focusin('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').focusin('myData', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType FocusInEvent event; }); @@ -4906,15 +4715,7 @@ function JQuery() { $('p').focusin(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').focusin(function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType FocusInEvent event; }); @@ -4926,21 +4727,11 @@ function JQuery() { } function focusout() { - interface J1 { kind: 'J1'; } - // $ExpectType JQuery $('p').focusout('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').focusout('myData', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType FocusOutEvent event; }); @@ -4948,15 +4739,7 @@ function JQuery() { $('p').focusout(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').focusout(function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType FocusOutEvent event; }); @@ -4968,21 +4751,11 @@ function JQuery() { } function keydown() { - interface J1 { kind: 'J1'; } - // $ExpectType JQuery $('p').keydown('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').keydown('myData', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType KeyDownEvent event; }); @@ -4990,15 +4763,7 @@ function JQuery() { $('p').keydown(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').keydown(function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType KeyDownEvent event; }); @@ -5010,21 +4775,11 @@ function JQuery() { } function keypress() { - interface J1 { kind: 'J1'; } - // $ExpectType JQuery $('p').keypress('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').keypress('myData', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType KeyPressEvent event; }); @@ -5032,15 +4787,7 @@ function JQuery() { $('p').keypress(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').keypress(function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType KeyPressEvent event; }); @@ -5052,21 +4799,11 @@ function JQuery() { } function keyup() { - interface J1 { kind: 'J1'; } - // $ExpectType JQuery $('p').keyup('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').keyup('myData', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType KeyUpEvent event; }); @@ -5074,15 +4811,7 @@ function JQuery() { $('p').keyup(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').keyup(function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType KeyUpEvent event; }); @@ -5094,21 +4823,11 @@ function JQuery() { } function mousedown() { - interface J1 { kind: 'J1'; } - // $ExpectType JQuery $('p').mousedown('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').mousedown('myData', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType MouseDownEvent event; }); @@ -5116,15 +4835,7 @@ function JQuery() { $('p').mousedown(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').mousedown(function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType MouseDownEvent event; }); @@ -5136,21 +4847,11 @@ function JQuery() { } function mouseenter() { - interface J1 { kind: 'J1'; } - // $ExpectType JQuery $('p').mouseenter('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').mouseenter('myData', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType MouseEnterEvent event; }); @@ -5158,15 +4859,7 @@ function JQuery() { $('p').mouseenter(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').mouseenter(function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType MouseEnterEvent event; }); @@ -5178,21 +4871,11 @@ function JQuery() { } function mouseleave() { - interface J1 { kind: 'J1'; } - // $ExpectType JQuery $('p').mouseleave('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').mouseleave('myData', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType MouseLeaveEvent event; }); @@ -5200,15 +4883,7 @@ function JQuery() { $('p').mouseleave(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').mouseleave(function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType MouseLeaveEvent event; }); @@ -5220,21 +4895,11 @@ function JQuery() { } function mousemove() { - interface J1 { kind: 'J1'; } - // $ExpectType JQuery $('p').mousemove('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').mousemove('myData', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType MouseMoveEvent event; }); @@ -5242,15 +4907,7 @@ function JQuery() { $('p').mousemove(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').mousemove(function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType MouseMoveEvent event; }); @@ -5262,21 +4919,11 @@ function JQuery() { } function mouseout() { - interface J1 { kind: 'J1'; } - // $ExpectType JQuery $('p').mouseout('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').mouseout('myData', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType MouseOutEvent event; }); @@ -5284,15 +4931,7 @@ function JQuery() { $('p').mouseout(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').mouseout(function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType MouseOutEvent event; }); @@ -5304,21 +4943,11 @@ function JQuery() { } function mouseover() { - interface J1 { kind: 'J1'; } - // $ExpectType JQuery $('p').mouseover('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').mouseover('myData', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType MouseOverEvent event; }); @@ -5326,15 +4955,7 @@ function JQuery() { $('p').mouseover(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').mouseover(function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType MouseOverEvent event; }); @@ -5346,21 +4967,11 @@ function JQuery() { } function mouseup() { - interface J1 { kind: 'J1'; } - // $ExpectType JQuery $('p').mouseup('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').mouseup('myData', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType MouseUpEvent event; }); @@ -5368,15 +4979,7 @@ function JQuery() { $('p').mouseup(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').mouseup(function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType MouseUpEvent event; }); @@ -5388,21 +4991,11 @@ function JQuery() { } function resize() { - interface J1 { kind: 'J1'; } - // $ExpectType JQuery $('p').resize('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').resize('myData', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType ResizeEvent event; }); @@ -5410,15 +5003,7 @@ function JQuery() { $('p').resize(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').resize(function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType ResizeEvent event; }); @@ -5430,21 +5015,11 @@ function JQuery() { } function scroll() { - interface J1 { kind: 'J1'; } - // $ExpectType JQuery $('p').scroll('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').scroll('myData', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType ScrollEvent event; }); @@ -5452,15 +5027,7 @@ function JQuery() { $('p').scroll(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').scroll(function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType ScrollEvent event; }); @@ -5472,21 +5039,11 @@ function JQuery() { } function select() { - interface J1 { kind: 'J1'; } - // $ExpectType JQuery $('p').select('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').select('myData', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType SelectEvent event; }); @@ -5494,15 +5051,7 @@ function JQuery() { $('p').select(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').select(function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType SelectEvent event; }); @@ -5514,21 +5063,11 @@ function JQuery() { } function submit() { - interface J1 { kind: 'J1'; } - // $ExpectType JQuery $('p').submit('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').submit('myData', function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType SubmitEvent event; }); @@ -5536,15 +5075,7 @@ function JQuery() { $('p').submit(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').submit(function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType SubmitEvent event; }); @@ -5556,32 +5087,16 @@ function JQuery() { } function hover() { - interface J1 { kind: 'J1'; } - interface J2 { kind: 'J2'; } - // $ExpectType JQuery $('p').hover(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType MouseEnterEvent event; }, function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').hover(function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event - event; - }, function(event) { - // $ExpectType HTMLElement - this; - // $ExpectType Event + // $ExpectType MouseLeaveEvent event; }); @@ -5589,41 +5104,7 @@ function JQuery() { $('p').hover(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }, function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').hover(function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event - event; - }, function(this: J2, event) { - // $ExpectType J2 - this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').hover(function(event) { - // $ExpectType HTMLElement - this; - // $ExpectType Event - event; - }, false); - - // $ExpectType JQuery - $('p').hover(function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType MouseEnterEvent event; }, false); @@ -5631,15 +5112,7 @@ function JQuery() { $('p').hover(false, function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').hover(false, function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event + // $ExpectType MouseLeaveEvent event; }); @@ -5650,16 +5123,23 @@ function JQuery() { $('p').hover(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType MouseEnterEvent | MouseLeaveEvent event; - }); - // $ExpectType JQuery - $('p').hover(function(this: J1, event) { - // $ExpectType J1 - this; - // $ExpectType Event - event; + switch (event.type) { + case 'mouseover': + // $ExpectType MouseEnterEvent + event; + break; + case 'mouseout': + // $ExpectType MouseLeaveEvent + event; + break; + default: + // $ExpectType never + event; + break; + } }); // $ExpectType JQuery @@ -8398,51 +7878,186 @@ function JQuery_Effects() { function JQuery_Event() { function call_signature() { - // $ExpectType Event & Coordinates + // $ExpectType Event & Coordinates $.Event('keydown', $('p').offset()); - - // $ExpectType Event & { type: string; } - $.Event({ - type: 'keydown' - }); } function constructor() { - // $ExpectType Event & Coordinates + // $ExpectType Event & Coordinates new $.Event('keydown', $('p').offset()); - - // $ExpectType Event & { type: string; } - new $.Event({ - type: 'keydown' - }); } // https://stackoverflow.com/questions/49892574/trigger-a-jquery-3-event-with-ctrlkey-set function stackoverflow_49892574() { - const event = $.Event("keydown"); + const event = $.Event("keydown"); event.which = 77; event.ctrlKey = true; $(window).trigger(event); } } +function JQuery_TypeEventHandlers() { + const events: JQuery.TypeEventHandlers = { + change(event) { + // $ExpectType HTMLElement + this; + // $ExpectType ChangeEvent + event; + }, + resize(event) { + // $ExpectType HTMLElement + this; + // $ExpectType ResizeEvent + event; + }, + scroll(event) { + // $ExpectType HTMLElement + this; + // $ExpectType ScrollEvent + event; + }, + select(event) { + // $ExpectType HTMLElement + this; + // $ExpectType SelectEvent + event; + }, + submit(event) { + // $ExpectType HTMLElement + this; + // $ExpectType SubmitEvent + event; + }, + click(event) { + // $ExpectType HTMLElement + this; + // $ExpectType ClickEvent + event; + }, + contextmenu(event) { + // $ExpectType HTMLElement + this; + // $ExpectType ContextMenuEvent + event; + }, + dblclick(event) { + // $ExpectType HTMLElement + this; + // $ExpectType DoubleClickEvent + event; + }, + mousedown(event) { + // $ExpectType HTMLElement + this; + // $ExpectType MouseDownEvent + event; + }, + mouseenter(event) { + // $ExpectType HTMLElement + this; + // $ExpectType MouseEnterEvent + event; + }, + mouseleave(event) { + // $ExpectType HTMLElement + this; + // $ExpectType MouseLeaveEvent + event; + }, + mousemove(event) { + // $ExpectType HTMLElement + this; + // $ExpectType MouseMoveEvent + event; + }, + mouseout(event) { + // $ExpectType HTMLElement + this; + // $ExpectType MouseOutEvent + event; + }, + mouseover(event) { + // $ExpectType HTMLElement + this; + // $ExpectType MouseOverEvent + event; + }, + mouseup(event) { + // $ExpectType HTMLElement + this; + // $ExpectType MouseUpEvent + event; + }, + keydown(event) { + // $ExpectType HTMLElement + this; + // $ExpectType KeyDownEvent + event; + }, + keypress(event) { + // $ExpectType HTMLElement + this; + // $ExpectType KeyPressEvent + event; + }, + keyup(event) { + // $ExpectType HTMLElement + this; + // $ExpectType KeyUpEvent + event; + }, + touchcancel(event) { + // $ExpectType HTMLElement + this; + // $ExpectType TouchCancelEvent + event; + }, + touchend(event) { + // $ExpectType HTMLElement + this; + // $ExpectType TouchEndEvent + event; + }, + touchmove(event) { + // $ExpectType HTMLElement + this; + // $ExpectType TouchMoveEvent + event; + }, + touchstart(event) { + // $ExpectType HTMLElement + this; + // $ExpectType TouchStartEvent + event; + }, + blur(event) { + // $ExpectType HTMLElement + this; + // $ExpectType BlurEvent + event; + }, + focus(event) { + // $ExpectType HTMLElement + this; + // $ExpectType FocusEvent + event; + }, + focusin(event) { + // $ExpectType HTMLElement + this; + // $ExpectType FocusInEvent + event; + }, + focusout(event) { + // $ExpectType HTMLElement + this; + // $ExpectType FocusOutEvent + event; + } + }; +} + function JQuery_EventExtensions() { - function fixHooks() { - jQuery.event.fixHooks.drop = { - props: ['dataTransfer'], - filter(event, originalEvent) { - // $ExpectType Event - event; - // $ExpectType Event - originalEvent; - }, - }; - - // Weak type test. This may be removed if the TypeScript requirement is increased to 2.4+. - // $ExpectError - jQuery.event.fixHooks.drop = ['dataTransfer']; - } - function special() { jQuery.event.special.multiclick = { noBubble: true, @@ -8455,7 +8070,7 @@ function JQuery_EventExtensions() { data; // $ExpectType string namespaces; - // $ExpectType EventHandler + // $ExpectType EventHandlerBase> eventHandle; return false; @@ -8481,7 +8096,7 @@ function JQuery_EventExtensions() { trigger(event, data) { // $ExpectType EventTarget this; - // $ExpectType Event + // $ExpectType Event event; // $ExpectType any data; @@ -8489,7 +8104,7 @@ function JQuery_EventExtensions() { return false; }, _default(event, data) { - // $ExpectType Event + // $ExpectType TriggeredEvent event; // $ExpectType any data; @@ -8497,7 +8112,7 @@ function JQuery_EventExtensions() { return false; }, handle(event, data) { - // $ExpectType Event & { handleObj: HandleObject; } + // $ExpectType TriggeredEvent & { handleObj: HandleObject; } event; // $ExpectType any data; @@ -8505,7 +8120,7 @@ function JQuery_EventExtensions() { preDispatch(event) { // $ExpectType EventTarget this; - // $ExpectType Event + // $ExpectType Event event; return false; @@ -8513,7 +8128,7 @@ function JQuery_EventExtensions() { postDispatch(event) { // $ExpectType EventTarget this; - // $ExpectType Event + // $ExpectType Event event; } }; diff --git a/types/jquery/misc.d.ts b/types/jquery/misc.d.ts index 7b09b6a4dc..ebba2f7a31 100644 --- a/types/jquery/misc.d.ts +++ b/types/jquery/misc.d.ts @@ -3981,49 +3981,97 @@ $( "input" ).click(function() { // This should be a class but doesn't work correctly under the JQuery namespace. Event should be an inner class of jQuery. - // Static members + /** + * jQuery's event system normalizes the event object according to W3C standards. The event object is guaranteed to be passed to the event handler (no checks for window.event required). It normalizes the target, relatedTarget, which, metaKey and pageX/Y properties and provides both stopPropagation() and preventDefault() methods. + * + * Those properties are all documented, and accompanied by examples, on the \`{@link http://api.jquery.com/category/events/event-object/ Event object}\` page. + * + * The standard events in the Document Object Model are: `blur`, `focus`, `load`, `resize`, `scroll`, `unload`, `beforeunload`, `click`, `dblclick`, `mousedown`, `mouseup`, `mousemove`, `mouseover`, `mouseout`, `mouseenter`, `mouseleave`, `change`, `select`, `submit`, `keydown`, `keypress`, and `keyup`. Since the DOM event names have predefined meanings for some elements, using them for other purposes is not recommended. jQuery's event model can trigger an event by any name on an element, and it is propagated up the DOM tree to which that element belongs, if any. + * @see \`{@link https://api.jquery.com/category/events/event-object/ }\` + */ interface EventStatic { - // tslint:disable-next-line:no-unnecessary-generics - (event: string, properties?: T): Event & T; - // tslint:disable-next-line:no-unnecessary-generics - (properties: T): Event & T; - // tslint:disable-next-line:no-unnecessary-generics - new (event: string, properties?: T): Event & T; - // tslint:disable-next-line:no-unnecessary-generics - new (properties: T): Event & T; + /** + * The jQuery.Event constructor is exposed and can be used when calling trigger. The new operator is optional. + * + * Check \`{@link https://api.jquery.com/trigger/ trigger}\`'s documentation to see how to combine it with your own event object. + * @see \`{@link https://api.jquery.com/category/events/event-object/ }\` + * @since 1.6 + * @example +```javascript +//Create a new jQuery.Event object without the "new" operator. +var e = jQuery.Event( "click" ); +​ +// trigger an artificial click event +jQuery( "body" ).trigger( e ); +``` + * @example +```javascript +// Create a new jQuery.Event object with specified event properties. +var e = jQuery.Event( "keydown", { keyCode: 64 } ); +​ +// trigger an artificial keydown event with keyCode 64 +jQuery( "body" ).trigger( e ); +``` + */ + (event: string, properties?: T): Event & T; + /** + * The jQuery.Event constructor is exposed and can be used when calling trigger. The new operator is optional. + * + * Check \`{@link https://api.jquery.com/trigger/ trigger}\`'s documentation to see how to combine it with your own event object. + * @see \`{@link https://api.jquery.com/category/events/event-object/ }\` + * @since 1.6 + * @example +```javascript +//Create a new jQuery.Event object without the "new" operator. +var e = jQuery.Event( "click" ); +​ +// trigger an artificial click event +jQuery( "body" ).trigger( e ); +``` + * @example +```javascript +// Create a new jQuery.Event object with specified event properties. +var e = jQuery.Event( "keydown", { keyCode: 64 } ); +​ +// trigger an artificial keydown event with keyCode 64 +jQuery( "body" ).trigger( e ); +``` + */ + new (event: string, properties?: T): Event & T; } - // Instance members + /** + * jQuery's event system normalizes the event object according to W3C standards. The event object is guaranteed to be passed to the event handler (no checks for window.event required). It normalizes the target, relatedTarget, which, metaKey and pageX/Y properties and provides both stopPropagation() and preventDefault() methods. + * + * Those properties are all documented, and accompanied by examples, on the \`{@link http://api.jquery.com/category/events/event-object/ Event object}\` page. + * + * The standard events in the Document Object Model are: `blur`, `focus`, `load`, `resize`, `scroll`, `unload`, `beforeunload`, `click`, `dblclick`, `mousedown`, `mouseup`, `mousemove`, `mouseover`, `mouseout`, `mouseenter`, `mouseleave`, `change`, `select`, `submit`, `keydown`, `keypress`, and `keyup`. Since the DOM event names have predefined meanings for some elements, using them for other purposes is not recommended. jQuery's event model can trigger an event by any name on an element, and it is propagated up the DOM tree to which that element belongs, if any. + * @see \`{@link https://api.jquery.com/category/events/event-object/ }\` + * @see \`{@link TriggeredEvent }\` + */ interface Event { // region Copied properties // #region Copied properties - // region Event - // #region Event + // Event - bubbles?: boolean; - cancelable?: boolean; - eventPhase?: number; + bubbles: boolean | undefined; + cancelable: boolean | undefined; + eventPhase: number | undefined; - // #endregion + // UIEvent - // region UIEvent - // #region UIEvent + detail: number | undefined; + view: Window | undefined; - detail?: number; - view?: Window; + // MouseEvent - // #endregion - - // region MouseEvent - // #region MouseEvent - - button?: number; - buttons?: number; - clientX?: number; - clientY?: number; - offsetX?: number; - offsetY?: number; + button: number | undefined; + buttons: number | undefined; + clientX: number | undefined; + clientY: number | undefined; + offsetX: number | undefined; + offsetY: number | undefined; /** * The mouse position relative to the left edge of the document. * @see \`{@link https://api.jquery.com/event.pageX/ }\` @@ -4059,7 +4107,7 @@ $( document ).on( "mousemove", function( event ) { ``` */ - pageX: number; + pageX: number | undefined; /** * The mouse position relative to the top edge of the document. * @see \`{@link https://api.jquery.com/event.pageY/ }\` @@ -4095,49 +4143,93 @@ $( document ).on( "mousemove", function( event ) { ``` */ - pageY: number; - screenX?: number; - screenY?: number; + pageY: number | undefined; + screenX: number | undefined; + screenY: number | undefined; /** @deprecated */ - toElement?: Element; + toElement: Element | undefined; - // #endregion + // PointerEvent - // region PointerEvent - // #region PointerEvent + pointerId: number | undefined; + pointerType: string | undefined; - pointerId?: number; - pointerType?: string; - - // #endregion - - // region KeyboardEvent - // #region KeyboardEvent + // KeyboardEvent /** @deprecated */ - char?: string; + char: string | undefined; /** @deprecated */ - charCode?: number; - key?: string; + charCode: number | undefined; + key: string | undefined; /** @deprecated */ - keyCode?: number; + keyCode: number | undefined; - // #endregion + // TouchEvent - // region TouchEvent - // #region TouchEvent + changedTouches: TouchList | undefined; + targetTouches: TouchList | undefined; + touches: TouchList | undefined; - changedTouches?: TouchList; - targetTouches?: TouchList; - touches?: TouchList; + // MouseEvent, KeyboardEvent - // #endregion + /** + * For key or mouse events, this property indicates the specific key or button that was pressed. + * @see \`{@link https://api.jquery.com/event.which/ }\` + * @since 1.1.3 + * @deprecated ​ Deprecated since 3.3. See \`{@link https://github.com/jquery/api.jquery.com/issues/821 }\`. + * @example ​ ````Log which key was depressed. +```html + + + + + event.which demo + + + +​ + +
+​ + +​ + + +``` + * @example ​ ````Log which mouse button was depressed. +```html + + + + + event.which demo + + + +​ + +
+​ + +​ + + +``` + */ + which: number | undefined; - // region MouseEvent, KeyboardEvent, TouchEvent - // #region MouseEvent, KeyboardEvent, TouchEvent + // MouseEvent, KeyboardEvent, TouchEvent - altKey?: boolean; - ctrlKey?: boolean; + altKey: boolean | undefined; + ctrlKey: boolean | undefined; /** * Indicates whether the META key was pressed when the event fired. * @see \`{@link https://api.jquery.com/event.metaKey/ }\` @@ -4174,77 +4266,11 @@ $( "#checkMetaKey" ).click(function( event ) { ``` */ - metaKey: boolean; - shiftKey?: boolean; + metaKey: boolean | undefined; + shiftKey: boolean | undefined; // #endregion - // #endregion - - /** - * The namespace specified when the event was triggered. - * @see \`{@link https://api.jquery.com/event.namespace/ }\` - * @since 1.4.3 - * @example ​ ````Determine the event namespace used. -```html - - - - - event.namespace demo - - - -​ - -

-​ - -​ - - -``` - */ - namespace: string; - /** - * The last value returned by an event handler that was triggered by this event, unless the value was undefined. - * @see \`{@link https://api.jquery.com/event.result/ }\` - * @since 1.3 - * @example ​ ````Display previous handler's return value -```html - - - - - event.result demo - - - -​ - -

-​ - -​ - - -``` - */ - result: any; /** * The difference in milliseconds between the time the browser created the event and January 1, 1970. * @see \`{@link https://api.jquery.com/event.timeStamp/ }\` @@ -4301,58 +4327,6 @@ $( "a" ).click(function( event ) { ``` */ type: string; - /** - * For key or mouse events, this property indicates the specific key or button that was pressed. - * @see \`{@link https://api.jquery.com/event.which/ }\` - * @since 1.1.3 - * @example ​ ````Log which key was depressed. -```html - - - - - event.which demo - - - -​ - -
-​ - -​ - - -``` - * @example ​ ````Log which mouse button was depressed. -```html - - - - - event.which demo - - - -​ - -
-​ - -​ - - -``` - */ - which: number; /** * Returns whether event.preventDefault() was ever called on this event object. * @see \`{@link https://api.jquery.com/event.isDefaultPrevented/ }\` @@ -4545,11 +4519,17 @@ $( "p" ).click(function( event ) { stopPropagation(): void; } - // Generic members - interface Event< - TTarget = EventTarget, - TData = null - > { + // #endregion + + /** + * Base type for jQuery events that have been triggered (including events triggered on plain objects). + */ + interface TriggeredEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends Event { /** * The current DOM element within the event bubbling phase. * @see \`{@link https://api.jquery.com/event.currentTarget/ }\` @@ -4560,51 +4540,8 @@ $( "p" ).click(function( event ) { alert( event.currentTarget === this ); // true }); ``` - */ - currentTarget: TTarget; - /** - * An optional object of data passed to an event method when the current executing handler is bound. - * @see \`{@link https://api.jquery.com/event.data/ }\` - * @since 1.1 - * @example ​ ````Within a for loop, pass the value of i to the .on() method so that the current iteration's value is preserved. -```html - - - - - event.data demo - - - -​ - - - - - -​ -
-​ - -​ - - -``` - */ - data: TData; + */ + currentTarget: TCurrentTarget; /** * The element where the currently-called jQuery event handler was attached. * @see \`{@link https://api.jquery.com/event.delegateTarget/ }\` @@ -4615,21 +4552,8 @@ $( ".box" ).on( "click", "button", function( event ) { $( event.delegateTarget ).css( "background-color", "red" ); }); ``` - */ - delegateTarget: TTarget; - originalEvent: _Event; - /** - * The other DOM element involved in the event, if any. - * @see \`{@link https://api.jquery.com/event.relatedTarget/ }\` - * @since 1.1.4 - * @example ​ ````On mouseout of anchors, alert the element type being entered. -```javascript -$( "a" ).mouseout(function( event ) { - alert( event.relatedTarget.nodeName ); // "DIV" -}); -``` - */ - relatedTarget: TTarget | null; + */ + delegateTarget: TDelegateTarget; /** * The DOM element that initiated the event. * @see \`{@link https://api.jquery.com/event.target/ }\` @@ -4707,37 +4631,1728 @@ $( "ul" ).click( handler ).find( "ul" ).hide(); ``` - */ + */ target: TTarget; + + /** + * An optional object of data passed to an event method when the current executing handler is bound. + * @see \`{@link https://api.jquery.com/event.data/ }\` + * @since 1.1 + * @example ​ ````Within a for loop, pass the value of i to the .on() method so that the current iteration's value is preserved. +```html + + + + + event.data demo + + + +​ + + + + + +​ +
+​ + +​ + + +``` + */ + data: TData; + + /** + * The namespace specified when the event was triggered. + * @see \`{@link https://api.jquery.com/event.namespace/ }\` + * @since 1.4.3 + * @example ​ ````Determine the event namespace used. +```html + + + + + event.namespace demo + + + +​ + +

+​ + +​ + + +``` + */ + namespace?: string; + originalEvent?: _Event; + /** + * The last value returned by an event handler that was triggered by this event, unless the value was undefined. + * @see \`{@link https://api.jquery.com/event.result/ }\` + * @since 1.3 + * @example ​ ````Display previous handler's return value +```html + + + + + event.result demo + + + +​ + +

+​ + +​ + + +``` + */ + result?: any; } - interface EventLike { - type: string; + // region Event + // #region Event + + interface EventBase< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends TriggeredEvent { + /** + * The other DOM element involved in the event, if any. + * @see \`{@link https://api.jquery.com/event.relatedTarget/ }\` + * @since 1.1.4 + * @example ​ ````On mouseout of anchors, alert the element type being entered. +```javascript +$( "a" ).mouseout(function( event ) { + alert( event.relatedTarget.nodeName ); // "DIV" +}); +``` + */ + relatedTarget?: undefined; + + // Event + + bubbles: boolean; + cancelable: boolean; + eventPhase: number; + + // UIEvent + + detail: undefined; + view: undefined; + + // MouseEvent + + button: undefined; + buttons: undefined; + clientX: undefined; + clientY: undefined; + offsetX: undefined; + offsetY: undefined; + /** + * The mouse position relative to the left edge of the document. + * @see \`{@link https://api.jquery.com/event.pageX/ }\` + * @since 1.0.4 + * @example ​ ````Show the mouse position relative to the left and top edges of the document (within this iframe). +```html + + + + + event.pageX demo + + + + +​ +
+​ + +​ + + +``` + */ + pageX: undefined; + /** + * The mouse position relative to the top edge of the document. + * @see \`{@link https://api.jquery.com/event.pageY/ }\` + * @since 1.0.4 + * @example ​ ````Show the mouse position relative to the left and top edges of the document (within this iframe). +```html + + + + + event.pageY demo + + + + +​ +
+​ + +​ + + +``` + */ + pageY: undefined; + screenX: undefined; + screenY: undefined; + /** @deprecated */ + toElement: undefined; + + // PointerEvent + + pointerId: undefined; + pointerType: undefined; + + // KeyboardEvent + + /** @deprecated */ + char: undefined; + /** @deprecated */ + charCode: undefined; + key: undefined; + /** @deprecated */ + keyCode: undefined; + + // TouchEvent + + changedTouches: undefined; + targetTouches: undefined; + touches: undefined; + + // MouseEvent, KeyboardEvent + + /** + * For key or mouse events, this property indicates the specific key or button that was pressed. + * @see \`{@link https://api.jquery.com/event.which/ }\` + * @since 1.1.3 + * @deprecated ​ Deprecated since 3.3. See \`{@link https://github.com/jquery/api.jquery.com/issues/821 }\`. + * @example ​ ````Log which key was depressed. +```html + + + + + event.which demo + + + +​ + +
+​ + +​ + + +``` + * @example ​ ````Log which mouse button was depressed. +```html + + + + + event.which demo + + + +​ + +
+​ + +​ + + +``` + */ + which: undefined; + + // MouseEvent, KeyboardEvent, TouchEvent + + altKey: undefined; + ctrlKey: undefined; + /** + * Indicates whether the META key was pressed when the event fired. + * @see \`{@link https://api.jquery.com/event.metaKey/ }\` + * @since 1.0.4 + * @example ​ ````Determine whether the META key was pressed when the event fired. +```html + + + + + event.metaKey demo + + + + +​ + +
+​ + +​ + + +``` + */ + metaKey: undefined; + shiftKey: undefined; + + originalEvent?: _Event; + } + + interface ChangeEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends EventBase { + type: 'change'; + } + + interface ResizeEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends EventBase { + type: 'resize'; + } + + interface ScrollEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends EventBase { + type: 'scroll'; + } + + interface SelectEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends EventBase { + type: 'select'; + } + + interface SubmitEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends EventBase { + type: 'submit'; } // #endregion - interface EventHandler extends EventHandlerBase> { } + // region UIEvent + // #region UIEvent + + interface UIEventBase< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends TriggeredEvent { + // Event + + bubbles: boolean; + cancelable: boolean; + eventPhase: number; + + // UIEvent + + detail: number; + view: Window; + + originalEvent?: _UIEvent; + } + + // region MouseEvent + // #region MouseEvent + + interface MouseEventBase< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends UIEventBase { + /** + * The other DOM element involved in the event, if any. + * @see \`{@link https://api.jquery.com/event.relatedTarget/ }\` + * @since 1.1.4 + * @example ​ ````On mouseout of anchors, alert the element type being entered. +```javascript +$( "a" ).mouseout(function( event ) { + alert( event.relatedTarget.nodeName ); // "DIV" +}); +``` + */ + relatedTarget?: EventTarget | null; + + // MouseEvent + + button: number; + buttons: number; + clientX: number; + clientY: number; + offsetX: number; + offsetY: number; + /** + * The mouse position relative to the left edge of the document. + * @see \`{@link https://api.jquery.com/event.pageX/ }\` + * @since 1.0.4 + * @example ​ ````Show the mouse position relative to the left and top edges of the document (within this iframe). +```html + + + + + event.pageX demo + + + + +​ +
+​ + +​ + + +``` + */ + pageX: number; + /** + * The mouse position relative to the top edge of the document. + * @see \`{@link https://api.jquery.com/event.pageY/ }\` + * @since 1.0.4 + * @example ​ ````Show the mouse position relative to the left and top edges of the document (within this iframe). +```html + + + + + event.pageY demo + + + + +​ +
+​ + +​ + + +``` + */ + pageY: number; + screenX: number; + screenY: number; + /** @deprecated */ + toElement: Element; + + // PointerEvent + + pointerId: undefined; + pointerType: undefined; + + // KeyboardEvent + + /** @deprecated */ + char: undefined; + /** @deprecated */ + charCode: undefined; + key: undefined; + /** @deprecated */ + keyCode: undefined; + + // TouchEvent + + changedTouches: undefined; + targetTouches: undefined; + touches: undefined; + + // MouseEvent, KeyboardEvent + + /** + * For key or mouse events, this property indicates the specific key or button that was pressed. + * @see \`{@link https://api.jquery.com/event.which/ }\` + * @since 1.1.3 + * @deprecated ​ Deprecated since 3.3. See \`{@link https://github.com/jquery/api.jquery.com/issues/821 }\`. + * @example ​ ````Log which key was depressed. +```html + + + + + event.which demo + + + +​ + +
+​ + +​ + + +``` + * @example ​ ````Log which mouse button was depressed. +```html + + + + + event.which demo + + + +​ + +
+​ + +​ + + +``` + */ + which: number; + + // MouseEvent, KeyboardEvent, TouchEvent + + altKey: boolean; + ctrlKey: boolean; + /** + * Indicates whether the META key was pressed when the event fired. + * @see \`{@link https://api.jquery.com/event.metaKey/ }\` + * @since 1.0.4 + * @example ​ ````Determine whether the META key was pressed when the event fired. +```html + + + + + event.metaKey demo + + + + +​ + +
+​ + +​ + + +``` + */ + metaKey: boolean; + shiftKey: boolean; + + originalEvent?: _MouseEvent; + } + + interface ClickEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends MouseEventBase { + /** + * The other DOM element involved in the event, if any. + * @see \`{@link https://api.jquery.com/event.relatedTarget/ }\` + * @since 1.1.4 + * @example ​ ````On mouseout of anchors, alert the element type being entered. + ```javascript + $( "a" ).mouseout(function( event ) { + alert( event.relatedTarget.nodeName ); // "DIV" + }); + ``` + */ + relatedTarget?: null; + + type: 'click'; + } + + interface ContextMenuEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends MouseEventBase { + /** + * The other DOM element involved in the event, if any. + * @see \`{@link https://api.jquery.com/event.relatedTarget/ }\` + * @since 1.1.4 + * @example ​ ````On mouseout of anchors, alert the element type being entered. + ```javascript + $( "a" ).mouseout(function( event ) { + alert( event.relatedTarget.nodeName ); // "DIV" + }); + ``` + */ + relatedTarget?: null; + + type: 'contextmenu'; + } + + interface DoubleClickEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends MouseEventBase { + /** + * The other DOM element involved in the event, if any. + * @see \`{@link https://api.jquery.com/event.relatedTarget/ }\` + * @since 1.1.4 + * @example ​ ````On mouseout of anchors, alert the element type being entered. + ```javascript + $( "a" ).mouseout(function( event ) { + alert( event.relatedTarget.nodeName ); // "DIV" + }); + ``` + */ + relatedTarget?: null; + + type: 'dblclick'; + } + + interface MouseDownEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends MouseEventBase { + /** + * The other DOM element involved in the event, if any. + * @see \`{@link https://api.jquery.com/event.relatedTarget/ }\` + * @since 1.1.4 + * @example ​ ````On mouseout of anchors, alert the element type being entered. + ```javascript + $( "a" ).mouseout(function( event ) { + alert( event.relatedTarget.nodeName ); // "DIV" + }); + ``` + */ + relatedTarget?: null; + + type: 'mousedown'; + } + + interface MouseEnterEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends MouseEventBase { + // Special handling by jQuery. + type: 'mouseover'; + } + + interface MouseLeaveEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends MouseEventBase { + // Special handling by jQuery. + type: 'mouseout'; + } + + interface MouseMoveEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends MouseEventBase { + /** + * The other DOM element involved in the event, if any. + * @see \`{@link https://api.jquery.com/event.relatedTarget/ }\` + * @since 1.1.4 + * @example ​ ````On mouseout of anchors, alert the element type being entered. + ```javascript + $( "a" ).mouseout(function( event ) { + alert( event.relatedTarget.nodeName ); // "DIV" + }); + ``` + */ + relatedTarget?: null; + + type: 'mousemove'; + } + + interface MouseOutEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends MouseEventBase { + type: 'mouseout'; + } + + interface MouseOverEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends MouseEventBase { + type: 'mouseover'; + } + + interface MouseUpEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends MouseEventBase { + /** + * The other DOM element involved in the event, if any. + * @see \`{@link https://api.jquery.com/event.relatedTarget/ }\` + * @since 1.1.4 + * @example ​ ````On mouseout of anchors, alert the element type being entered. + ```javascript + $( "a" ).mouseout(function( event ) { + alert( event.relatedTarget.nodeName ); // "DIV" + }); + ``` + */ + relatedTarget?: null; + + type: 'mouseup'; + } + + // #endregion + + // region KeyboardEvent + // #region KeyboardEvent + + interface KeyboardEventBase< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends UIEventBase { + /** + * The other DOM element involved in the event, if any. + * @see \`{@link https://api.jquery.com/event.relatedTarget/ }\` + * @since 1.1.4 + * @example ​ ````On mouseout of anchors, alert the element type being entered. +```javascript +$( "a" ).mouseout(function( event ) { + alert( event.relatedTarget.nodeName ); // "DIV" +}); +``` + */ + relatedTarget?: undefined; + + // MouseEvent + + button: undefined; + buttons: undefined; + clientX: undefined; + clientY: undefined; + offsetX: undefined; + offsetY: undefined; + /** + * The mouse position relative to the left edge of the document. + * @see \`{@link https://api.jquery.com/event.pageX/ }\` + * @since 1.0.4 + * @example ​ ````Show the mouse position relative to the left and top edges of the document (within this iframe). +```html + + + + + event.pageX demo + + + + +​ +
+​ + +​ + + +``` + */ + pageX: undefined; + /** + * The mouse position relative to the top edge of the document. + * @see \`{@link https://api.jquery.com/event.pageY/ }\` + * @since 1.0.4 + * @example ​ ````Show the mouse position relative to the left and top edges of the document (within this iframe). +```html + + + + + event.pageY demo + + + + +​ +
+​ + +​ + + +``` + */ + pageY: undefined; + screenX: undefined; + screenY: undefined; + /** @deprecated */ + toElement: undefined; + + // PointerEvent + + pointerId: undefined; + pointerType: undefined; + + // KeyboardEvent + + /** @deprecated */ + char: string | undefined; + /** @deprecated */ + charCode: number; + key: string; + /** @deprecated */ + keyCode: number; + + // TouchEvent + + changedTouches: undefined; + targetTouches: undefined; + touches: undefined; + + // MouseEvent, KeyboardEvent + + /** + * For key or mouse events, this property indicates the specific key or button that was pressed. + * @see \`{@link https://api.jquery.com/event.which/ }\` + * @since 1.1.3 + * @deprecated ​ Deprecated since 3.3. See \`{@link https://github.com/jquery/api.jquery.com/issues/821 }\`. + * @example ​ ````Log which key was depressed. +```html + + + + + event.which demo + + + +​ + +
+​ + +​ + + +``` + * @example ​ ````Log which mouse button was depressed. +```html + + + + + event.which demo + + + +​ + +
+​ + +​ + + +``` + */ + which: number; + + // MouseEvent, KeyboardEvent, TouchEvent + + altKey: boolean; + ctrlKey: boolean; + /** + * Indicates whether the META key was pressed when the event fired. + * @see \`{@link https://api.jquery.com/event.metaKey/ }\` + * @since 1.0.4 + * @example ​ ````Determine whether the META key was pressed when the event fired. +```html + + + + + event.metaKey demo + + + + +​ + +
+​ + +​ + + +``` + */ + metaKey: boolean; + shiftKey: boolean; + + originalEvent?: _KeyboardEvent; + } + + interface KeyDownEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends KeyboardEventBase { + type: 'keydown'; + } + + interface KeyPressEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends KeyboardEventBase { + type: 'keypress'; + } + + interface KeyUpEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends KeyboardEventBase { + type: 'keyup'; + } + + // #endregion + + // region TouchEvent + // #region TouchEvent + + interface TouchEventBase< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends UIEventBase { + /** + * The other DOM element involved in the event, if any. + * @see \`{@link https://api.jquery.com/event.relatedTarget/ }\` + * @since 1.1.4 + * @example ​ ````On mouseout of anchors, alert the element type being entered. +```javascript +$( "a" ).mouseout(function( event ) { + alert( event.relatedTarget.nodeName ); // "DIV" +}); +``` + */ + relatedTarget?: undefined; + + // MouseEvent + + button: undefined; + buttons: undefined; + clientX: undefined; + clientY: undefined; + offsetX: undefined; + offsetY: undefined; + /** + * The mouse position relative to the left edge of the document. + * @see \`{@link https://api.jquery.com/event.pageX/ }\` + * @since 1.0.4 + * @example ​ ````Show the mouse position relative to the left and top edges of the document (within this iframe). +```html + + + + + event.pageX demo + + + + +​ +
+​ + +​ + + +``` + */ + pageX: undefined; + /** + * The mouse position relative to the top edge of the document. + * @see \`{@link https://api.jquery.com/event.pageY/ }\` + * @since 1.0.4 + * @example ​ ````Show the mouse position relative to the left and top edges of the document (within this iframe). +```html + + + + + event.pageY demo + + + + +​ +
+​ + +​ + + +``` + */ + pageY: undefined; + screenX: undefined; + screenY: undefined; + /** @deprecated */ + toElement: undefined; + + // PointerEvent + + pointerId: undefined; + pointerType: undefined; + + // KeyboardEvent + + /** @deprecated */ + char: undefined; + /** @deprecated */ + charCode: undefined; + key: undefined; + /** @deprecated */ + keyCode: undefined; + + // TouchEvent + + changedTouches: TouchList; + targetTouches: TouchList; + touches: TouchList; + + // MouseEvent, KeyboardEvent + + /** + * For key or mouse events, this property indicates the specific key or button that was pressed. + * @see \`{@link https://api.jquery.com/event.which/ }\` + * @since 1.1.3 + * @deprecated ​ Deprecated since 3.3. See \`{@link https://github.com/jquery/api.jquery.com/issues/821 }\`. + * @example ​ ````Log which key was depressed. +```html + + + + + event.which demo + + + +​ + +
+​ + +​ + + +``` + * @example ​ ````Log which mouse button was depressed. +```html + + + + + event.which demo + + + +​ + +
+​ + +​ + + +``` + */ + which: undefined; + + // MouseEvent, KeyboardEvent, TouchEvent + + altKey: boolean; + ctrlKey: boolean; + /** + * Indicates whether the META key was pressed when the event fired. + * @see \`{@link https://api.jquery.com/event.metaKey/ }\` + * @since 1.0.4 + * @example ​ ````Determine whether the META key was pressed when the event fired. +```html + + + + + event.metaKey demo + + + + +​ + +
+​ + +​ + + +``` + */ + metaKey: boolean; + shiftKey: boolean; + + originalEvent?: _TouchEvent; + } + + interface TouchCancelEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends TouchEventBase { + type: 'touchcancel'; + } + + interface TouchEndEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends TouchEventBase { + type: 'touchend'; + } + + interface TouchMoveEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends TouchEventBase { + type: 'touchmove'; + } + + interface TouchStartEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends TouchEventBase { + type: 'touchstart'; + } + + // #endregion + + // region FocusEvent + // #region FocusEvent + + interface FocusEventBase< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends UIEventBase { + /** + * The other DOM element involved in the event, if any. + * @see \`{@link https://api.jquery.com/event.relatedTarget/ }\` + * @since 1.1.4 + * @example ​ ````On mouseout of anchors, alert the element type being entered. +```javascript +$( "a" ).mouseout(function( event ) { + alert( event.relatedTarget.nodeName ); // "DIV" +}); +``` + */ + relatedTarget?: EventTarget | null; + + // MouseEvent + + button: undefined; + buttons: undefined; + clientX: undefined; + clientY: undefined; + offsetX: undefined; + offsetY: undefined; + /** + * The mouse position relative to the left edge of the document. + * @see \`{@link https://api.jquery.com/event.pageX/ }\` + * @since 1.0.4 + * @example ​ ````Show the mouse position relative to the left and top edges of the document (within this iframe). +```html + + + + + event.pageX demo + + + + +​ +
+​ + +​ + + +``` + */ + pageX: undefined; + /** + * The mouse position relative to the top edge of the document. + * @see \`{@link https://api.jquery.com/event.pageY/ }\` + * @since 1.0.4 + * @example ​ ````Show the mouse position relative to the left and top edges of the document (within this iframe). +```html + + + + + event.pageY demo + + + + +​ +
+​ + +​ + + +``` + */ + pageY: undefined; + screenX: undefined; + screenY: undefined; + /** @deprecated */ + toElement: undefined; + + // PointerEvent + + pointerId: undefined; + pointerType: undefined; + + // KeyboardEvent + + /** @deprecated */ + char: undefined; + /** @deprecated */ + charCode: undefined; + key: undefined; + /** @deprecated */ + keyCode: undefined; + + // TouchEvent + + changedTouches: undefined; + targetTouches: undefined; + touches: undefined; + + // MouseEvent, KeyboardEvent + + /** + * For key or mouse events, this property indicates the specific key or button that was pressed. + * @see \`{@link https://api.jquery.com/event.which/ }\` + * @since 1.1.3 + * @deprecated ​ Deprecated since 3.3. See \`{@link https://github.com/jquery/api.jquery.com/issues/821 }\`. + * @example ​ ````Log which key was depressed. +```html + + + + + event.which demo + + + +​ + +
+​ + +​ + + +``` + * @example ​ ````Log which mouse button was depressed. +```html + + + + + event.which demo + + + +​ + +
+​ + +​ + + +``` + */ + which: undefined; + + // MouseEvent, KeyboardEvent, TouchEvent + + altKey: undefined; + ctrlKey: undefined; + /** + * Indicates whether the META key was pressed when the event fired. + * @see \`{@link https://api.jquery.com/event.metaKey/ }\` + * @since 1.0.4 + * @example ​ ````Determine whether the META key was pressed when the event fired. +```html + + + + + event.metaKey demo + + + + +​ + +
+​ + +​ + + +``` + */ + metaKey: undefined; + shiftKey: undefined; + + originalEvent?: _FocusEvent; + } + + interface BlurEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends FocusEventBase { + type: 'blur'; + } + + interface FocusEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends FocusEventBase { + type: 'focus'; + } + + interface FocusInEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends FocusEventBase { + type: 'focusin'; + } + + interface FocusOutEvent< + TDelegateTarget = any, + TData = any, + TCurrentTarget = any, + TTarget = any + > extends FocusEventBase { + type: 'focusout'; + } + + // #endregion + + // #endregion + + interface TypeToTriggeredEventMap< + TDelegateTarget, + TData, + TCurrentTarget, + TTarget + > { + // Event + + change: ChangeEvent; + resize: ResizeEvent; + scroll: ScrollEvent; + select: SelectEvent; + submit: SubmitEvent; + + // UIEvent + + // MouseEvent + + click: ClickEvent; + contextmenu: ContextMenuEvent; + dblclick: DoubleClickEvent; + mousedown: MouseDownEvent; + mouseenter: MouseEnterEvent; + mouseleave: MouseLeaveEvent; + mousemove: MouseMoveEvent; + mouseout: MouseOutEvent; + mouseover: MouseOverEvent; + mouseup: MouseUpEvent; + + // KeyboardEvent + + keydown: KeyDownEvent; + keypress: KeyPressEvent; + keyup: KeyUpEvent; + + // TouchEvent + + touchcancel: TouchCancelEvent; + touchend: TouchEndEvent; + touchmove: TouchMoveEvent; + touchstart: TouchStartEvent; + + // FocusEvent + + blur: BlurEvent; + focus: FocusEvent; + focusin: FocusInEvent; + focusout: FocusOutEvent; + + [type: string]: TriggeredEvent; + } // Extra parameters can be passed from trigger() type EventHandlerBase = (this: TContext, t: T, ...args: any[]) => any; + type EventHandler< + TCurrentTarget, + TData = undefined + > = EventHandlerBase>; + + type TypeEventHandler< + TDelegateTarget, + TData, + TCurrentTarget, + TTarget, + TType extends keyof TypeToTriggeredEventMap + > = EventHandlerBase[TType]>; + + interface TypeEventHandlers< + TDelegateTarget, + TData, + TCurrentTarget, + TTarget + > extends _TypeEventHandlers { + // No idea why it's necessary to include `object` in the union but otherwise TypeScript complains that + // derived types of Event are not assignable to Event. + [type: string]: TypeEventHandler | + false | + undefined | + object; + } + + type _TypeEventHandlers< + TDelegateTarget, + TData, + TCurrentTarget, + TTarget + > = { + [TType in keyof TypeToTriggeredEventMap]?: + TypeEventHandler | + false | + object; + }; + // region Event extensions // #region Event extensions interface EventExtensions { - /** - * jQuery defines an \`{@link https://api.jquery.com/category/events/event-object/ Event object}\` that represents a cross-browser subset of the information available when an event occurs. The `jQuery.event.props` property is an array of string names for properties that are always copied when jQuery processes a native browser event. (Events fired in code by `.trigger()` do not use this list, since the code can construct a `jQuery.Event` object with the needed values and trigger using that object.) - * - * To add a property name to this list, use `jQuery.event.props.push( "newPropertyName" )`. However, be aware that every event processed by jQuery will now attempt to copy this property name from the native browser event to jQuery's constructed event. If the property does not exist for that event type, it will get an undefined value. Adding many properties to this list can significantly reduce event delivery performance, so for infrequently-needed properties it is more efficient to use the value directly from `event.originalEvent` instead. If properties must be copied, you are strongly advised to use `jQuery.event.fixHooks` as of version 1.7. - * @see \`{@link https://learn.jquery.com/events/event-extensions/#jquery-event-props-array }\` - */ - props: string[]; - /** - * The `fixHooks` interface provides a per-event-type way to extend or normalize the event object that jQuery creates when it processes a _native_ browser event. - * @see \`{@link https://learn.jquery.com/events/event-extensions/#jquery-event-fixhooks-object }\` - */ - fixHooks: FixHooks; /** * The jQuery special event hooks are a set of per-event-name functions and properties that allow code to control the behavior of event processing within jQuery. The mechanism is similar to `fixHooks` in that the special event information is stored in `jQuery.event.special.NAME`, where `NAME` is the name of the special event. Event names are case sensitive. * @@ -4747,75 +6362,6 @@ $( "ul" ).click( handler ).find( "ul" ).hide(); special: SpecialEventHooks; } - // region Fix hooks - // #region Fix hooks - - // Workaround for TypeScript 2.3 which does not have support for weak types handling. - type FixHook = { - /** - * Strings representing properties that should be copied from the browser's event object to the jQuery event object. If omitted, no additional properties are copied beyond the standard ones that jQuery copies and normalizes (e.g. `event.target` and `event.relatedTarget`). - */ - props: string[]; - } | { - /** - * jQuery calls this function after it constructs the `jQuery.Event` object, copies standard properties from `jQuery.event.props`, and copies the `fixHooks`-specific props (if any) specified above. The function can create new properties on the event object or modify existing ones. The second argument is the browser's native event object, which is also available in `event.originalEvent`. - * - * Note that for all events, the browser's native event object is available in `event.originalEvent`; if the jQuery event handler examines the properties there instead of jQuery's normalized `event` object, there is no need to create a `fixHooks` entry to copy or modify the properties. - * @example ​ ````For example, to set a hook for the "drop" event that copies the `dataTransfer` property, assign an object to `jQuery.event.fixHooks.drop`: -```javascript -jQuery.event.fixHooks.drop = { - props: [ "dataTransfer" ] -}; -``` - -Since fixHooks is an advanced feature and rarely used externally, jQuery does not include code or -interfaces to deal with conflict resolution. If there is a chance that some other code may be assigning -`fixHooks` to the same events, the code should check for an existing hook and take appropriate measures. -A simple solution might look like this: - -```javascript -if ( jQuery.event.fixHooks.drop ) { - throw new Error( "Someone else took the jQuery.event.fixHooks.drop hook!" ); -} - -jQuery.event.fixHooks.drop = { - props: [ "dataTransfer" ] -}; -``` - -When there are known cases of different plugins wanting to attach to the drop hook, this solution might be more appropriate: - -```javascript -var existingHook = jQuery.event.fixHooks.drop; - -if ( !existingHook ) { - jQuery.event.fixHooks.drop = { - props: [ "dataTransfer" ] - }; -} else { - if ( existingHook.props ) { - existingHook.props.push( "dataTransfer" ); - } else { - existingHook.props = [ "dataTransfer" ]; - } -} -``` - */ - filter(event: Event, originalEvent: _Event): void; - } | { - [key: string]: never; - }; - - /** - * The `fixHooks` interface provides a per-event-type way to extend or normalize the event object that jQuery creates when it processes a _native_ browser event. - * @see \`{@link https://learn.jquery.com/events/event-extensions/#jquery-event-fixhooks-object }\` - */ - interface FixHooks { - [event: string]: FixHook; - } - - // #endregion - // region Special event hooks // #region Special event hooks @@ -4879,13 +6425,13 @@ if ( !existingHook ) { * The trigger hook is called early in the process of triggering an event, just after the `jQuery.Event` object is constructed and before any handlers have been called. It can process the triggered event in any way, for example by calling `event.stopPropagation()` or `event.preventDefault()` before returning. If the hook returns `false`, jQuery does not perform any further event triggering actions and returns immediately. Otherwise, it performs the normal trigger processing, calling any event handlers for the element and bubbling the event (unless propagation is stopped in advance or `noBubble` was specified for the special event) to call event handlers attached to parent elements. * @see \`{@link https://learn.jquery.com/events/event-extensions/#trigger-function-event-jquery-event-data-object }\` */ - trigger(this: TTarget, event: Event, data: TData): void | false; + trigger(this: TTarget, event: Event, data: TData): void | false; } | { /** * When the `.trigger()` method finishes running all the event handlers for an event, it also looks for and runs any method on the target object by the same name unless of the handlers called `event.preventDefault()`. So, `.trigger( "submit" )` will execute the `submit()` method on the element if one exists. When a `_default` hook is specified, the hook is called just prior to checking for and executing the element's default method. If this hook returns the value `false` the element's default method will be called; otherwise it is not. * @see \`{@link https://learn.jquery.com/events/event-extensions/#_default-function-event-jquery-event-data-object }\` */ - _default(event: Event, data: TData): void | false; + _default(event: TriggeredEvent, data: TData): void | false; } | { /** * jQuery calls a handle hook when the event has occurred and jQuery would normally call the user's event handler specified by `.on()` or another event binding method. If the hook exists, jQuery calls it _instead_ of that event handler, passing it the event and any data passed from `.trigger()` if it was not a native event. The `this` keyword is the DOM element being handled, and `event.handleObj` property has the detailed event information. @@ -4893,11 +6439,11 @@ if ( !existingHook ) { * Based in the information it has, the handle hook should decide whether to call the original handler function which is in `event.handleObj.handler`. It can modify information in the event object before calling the original handler, but _must restore_ that data before returning or subsequent unrelated event handlers may act unpredictably. In most cases, the handle hook should return the result of the original handler, but that is at the discretion of the hook. The handle hook is unique in that it is the only special event function hook that is called under its original special event name when the type is mapped using `bindType` and `delegateType`. For that reason, it is almost always an error to have anything other than a handle hook present if the special event defines a `bindType` and `delegateType`, since those other hooks will never be called. * @see \`{@link https://learn.jquery.com/events/event-extensions/#handle-function-event-jquery-event-data-object }\` */ - handle(this: TTarget, event: Event & { handleObj: HandleObject; }, ...data: TData[]): void; + handle(this: TTarget, event: TriggeredEvent & { handleObj: HandleObject; }, ...data: TData[]): void; } | { - preDispatch(this: TTarget, event: Event): false | void; + preDispatch(this: TTarget, event: Event): false | void; } | { - postDispatch(this: TTarget, event: Event): void; + postDispatch(this: TTarget, event: Event): void; } | { [key: string]: never; }; @@ -4989,8 +6535,12 @@ if ( !existingHook ) { declare const jQuery: JQueryStatic; declare const $: JQueryStatic; -// Used by JQuery.Event type _Event = Event; +type _UIEvent = UIEvent; +type _MouseEvent = MouseEvent; +type _KeyboardEvent = KeyboardEvent; +type _TouchEvent = TouchEvent; +type _FocusEvent = FocusEvent; // region ES5 compatibility // #region ES5 compatibility diff --git a/types/jquery/test/example-tests.ts b/types/jquery/test/example-tests.ts index 7ecb1733a7..77d412f8e1 100644 --- a/types/jquery/test/example-tests.ts +++ b/types/jquery/test/example-tests.ts @@ -384,7 +384,7 @@ function examples() { } function bind_2() { - function handler(event: JQuery.Event) { + function handler(event: JQuery.TriggeredEvent) { alert(event.data.foo); } @@ -830,7 +830,7 @@ function examples() { var len = kids.addClass('hilite').length; $('#results span:first').text(len); - $('#results span:last').text(event.target.tagName); + $('#results span:last').text((event.target as Element).tagName); event.preventDefault(); }); @@ -1578,7 +1578,7 @@ function examples() { function event_related_target_0() { $('a').mouseout(function(event) { - alert(( event.relatedTarget).nodeName); // "DIV" + alert((event.relatedTarget as HTMLElement).nodeName); // "DIV" }); } @@ -1614,12 +1614,12 @@ function examples() { function event_target_0() { $('body').click(function(event) { - $('#log').html('clicked: ' + event.target.nodeName); + $('#log').html('clicked: ' + (event.target as Node).nodeName); }); } function event_target_1() { - function handler(event: JQuery.Event) { + function handler(event: JQuery.TriggeredEvent) { var target = $(event.target); if (target.is('li')) { target.children().toggle(); @@ -3018,10 +3018,10 @@ function examples() { function jQuery_proxy_0() { var me = { type: 'zombie', - test: function(event: JQuery.Event) { + test: function(event: JQuery.TriggeredEvent) { // Without proxy, `this` would refer to the event target // use event.target to reference that element. - var element = event.target; + var element = event.target as Element; $(element).css('background-color', 'red'); // With proxy, `this` refers to the me object encapsulating @@ -3033,7 +3033,7 @@ function examples() { var you = { type: 'person', - test: function(event: JQuery.Event) { + test: function(event: JQuery.TriggeredEvent) { $('#log').append(this.type + ' '); }, }; @@ -3075,7 +3075,7 @@ function examples() { type: 'dog', // Note that event comes *after* one and two - test: function(one: typeof you, two: typeof they, event: JQuery.Event) { + test: function(one: typeof you, two: typeof they, event: JQuery.TriggeredEvent) { $('#log') // `one` maps to `you`, the 1st additional @@ -3796,7 +3796,7 @@ function examples() { } function on_1() { - function myHandler(event: JQuery.Event) { + function myHandler(event: JQuery.TriggeredEvent) { alert(event.data.foo); } diff --git a/types/jquery/test/learn-tests.ts b/types/jquery/test/learn-tests.ts index 8ef5eb2cfa..b1a0353b4e 100644 --- a/types/jquery/test/learn-tests.ts +++ b/types/jquery/test/learn-tests.ts @@ -21,24 +21,6 @@ jQuery("a").greenify(); // Makes all the links green. // Events -function fixHooks() { - function setHook() { - jQuery.event.fixHooks.drop = { - props: ["dataTransfer"] - }; - } - - function conflictResolution() { - if (jQuery.event.fixHooks.drop) { - throw new Error("Someone else took the jQuery.event.fixHooks.drop hook!"); - } - - jQuery.event.fixHooks.drop = { - props: ["dataTransfer"] - }; - } -} - function special() { function defineSpecialEvent() { jQuery.event.special.pushy = { @@ -53,7 +35,7 @@ function special() { bindType: "click", handle(event) { const handleObj = event.handleObj; - const targetData = jQuery.data(event.target); + const targetData = jQuery.data(event.target as Element); let ret = null; // If a multiple of the click count, run the handler diff --git a/types/jquery/test/longdesc-tests.ts b/types/jquery/test/longdesc-tests.ts index bb3bb4c83c..e1ee36a575 100644 --- a/types/jquery/test/longdesc-tests.ts +++ b/types/jquery/test/longdesc-tests.ts @@ -538,7 +538,7 @@ function longdesc() { $('#foo').slideUp(300).delay(800).fadeIn(400); } - function delegate_0(elements: HTMLElement[], selector: string, events: any, data: any, handler: JQuery.EventHandler) { + function delegate_0(elements: HTMLElement[], selector: string, events: string, data: any, handler: JQuery.TypeEventHandler) { // jQuery 1.4.3+ $(elements).delegate(selector, events, data, handler); // jQuery 1.7+ @@ -886,7 +886,7 @@ function longdesc() { var currentRequests: JQuery.PlainObject = {}; $.ajaxPrefilter(function(options, originalOptions, jqXHR) { - if (( options).abortOnRetry) { + if ((options as any).abortOnRetry) { if (currentRequests[options.url!]) { currentRequests[options.url!].abort(); } @@ -1297,7 +1297,7 @@ function longdesc() { return $.css(elem, borderRadius!); }, set: function(elem, value) { - ( elem.style)[borderRadius!] = value; + (elem.style as any)[borderRadius!] = value; }, }; } @@ -2016,7 +2016,7 @@ function longdesc() { } function on_3() { - function greet(event: JQuery.Event) { + function greet(event: JQuery.TriggeredEvent) { alert('Hello ' + event.data.name); } diff --git a/types/jsforce/api/chatter.d.ts b/types/jsforce/api/chatter.d.ts index 4e0982ca24..c712187559 100644 --- a/types/jsforce/api/chatter.d.ts +++ b/types/jsforce/api/chatter.d.ts @@ -41,6 +41,8 @@ export class Request implements Promise { then(onfulfilled?: ((value: T) => (PromiseLike | TResult1)) | null | undefined, onrejected?: ((reason: any) => (PromiseLike | TResult2)) | null | undefined): Promise; + finally(onfinally?: () => void): Promise; + thenCall(callback?: (err: Error, records: T) => void): Query; readonly [Symbol.toStringTag]: 'Promise'; diff --git a/types/jsforce/api/metadata.d.ts b/types/jsforce/api/metadata.d.ts index 15f0fe249e..c6aec12e7e 100644 --- a/types/jsforce/api/metadata.d.ts +++ b/types/jsforce/api/metadata.d.ts @@ -124,6 +124,8 @@ export class AsyncResultLocator extends EventEmitter implements Promise { then(onfulfilled?: ((value: T) => (PromiseLike | TResult1)) | null | undefined, onrejected?: ((reason: any) => (PromiseLike | TResult2)) | null | undefined): Promise; + finally(onfinally?: () => void): Promise; + readonly [Symbol.toStringTag]: "Promise"; } diff --git a/types/json-server/index.d.ts b/types/json-server/index.d.ts new file mode 100644 index 0000000000..c52a4b220e --- /dev/null +++ b/types/json-server/index.d.ts @@ -0,0 +1,72 @@ +// Type definitions for json-server 0.14 +// Project: https://github.com/typicode/json-server +// Definitions by: Jeremy Bensimon +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +import { NextHandleFunction } from 'connect'; +import { Application, RequestHandler, Router } from 'express'; + +/** + * Returns an Express server. + */ +export function create(): Application; + +/** + * Returns middlewares used by JSON Server. + */ +export function defaults(options?: MiddlewaresOptions): RequestHandler[]; + +/** + * Returns JSON Server router. + * @param source Either a path to a json file (e.g. `'db.json'`) or an object in memory + * @param options Set foreign key suffix (default: `'Id'`) + */ +export function router(source: string | object, options?: { foreignKeySuffix: string }): Router; + +/** + * Add custom rewrite rules. + */ +export function rewriter(rules: { [rule: string]: string }): Router; + +/** + * Returns body-parser middleware used by JSON Server router. + * + * @returns + * ``` + * [bodyParser.json({ limit: '10mb', extended: false }), bodyParser.urlencoded({ extended: false })] + * ``` + */ +export const bodyParser: [NextHandleFunction, NextHandleFunction]; + +export interface MiddlewaresOptions { + /** + * Path to static files + * @default "public" (if folder exists) + */ + static?: string; + + /** + * Enable logger middleware + * @default true + */ + logger?: boolean; + + /** + * Enable body-parser middleware + * @default true + */ + bodyParser?: boolean; + + /** + * Disable CORS + * @default false + */ + noCors?: boolean; + + /** + * Accept only GET requests + * @default false + */ + readOnly?: boolean; +} diff --git a/types/json-server/json-server-tests.ts b/types/json-server/json-server-tests.ts new file mode 100644 index 0000000000..d68484b1ff --- /dev/null +++ b/types/json-server/json-server-tests.ts @@ -0,0 +1,41 @@ +import * as jsonServer from 'json-server'; + +const server = jsonServer.create(); + +const inMemoryDbRouter = jsonServer.router({ todos: [] as any[], users: [] as any[] }); + +const router = jsonServer.router('db.json', { foreignKeySuffix: '_id' }); + +const middlewaresOptions: jsonServer.MiddlewaresOptions = { + bodyParser: true, + logger: false, + noCors: true, + readOnly: true, + static: 'assets', +}; + +const middlewares = jsonServer.defaults(middlewaresOptions); + +const rewriter = jsonServer.rewriter({ + '/api/*': '/$1', + '/blog/:resource/:id/show': '/:resource/:id', +}); + +server.use(jsonServer.bodyParser); + +server.use((req, res, next) => { + if (req.method === 'POST') { + req.body.createdAt = Date.now(); + } + next(); +}); + +server.use(rewriter); + +server.use(middlewares); + +server.use(router); + +server.listen(3000, () => { + console.log('JSON Server is running'); +}); diff --git a/types/json-server/tsconfig.json b/types/json-server/tsconfig.json new file mode 100644 index 0000000000..e923ac1d7a --- /dev/null +++ b/types/json-server/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "json-server-tests.ts"] +} diff --git a/types/json-server/tslint.json b/types/json-server/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/json-server/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/json_ml/index.d.ts b/types/json_ml/index.d.ts new file mode 100644 index 0000000000..7cab812880 --- /dev/null +++ b/types/json_ml/index.d.ts @@ -0,0 +1,15 @@ +// Type definitions for json_ml 0.0 +// Project: https://github.com/59naga/json-ml +// Definitions by: Alan Plum +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 3.0 + +/// + +export type Node = string | [string, ...any[]]; +export function parse(xml: string, trim?: boolean): Node[]; +export function stringify( + object: Node[], + replacer?: ((node: Cheerio) => any) | null, + indent?: number +): string; diff --git a/types/json_ml/json_ml-tests.ts b/types/json_ml/json_ml-tests.ts new file mode 100644 index 0000000000..05ca64da4a --- /dev/null +++ b/types/json_ml/json_ml-tests.ts @@ -0,0 +1,20 @@ +/// +import { Node, parse, stringify } from "json_ml"; + +const nodes: Node[] = parse( + '
  • First Item
  • Second Item
  • ThirdItem
' +); +stringify(nodes, el => (el.is("li") ? null : el), 2); + +stringify( + [ + [ + "ul", + ["li", { style: "color: red" }], + ["li", { title: "Some hover text", style: "color: green" }], + ["li", ["span", { class: "code-example-third" }]] + ] + ], + null, + 2 +); diff --git a/types/json_ml/tsconfig.json b/types/json_ml/tsconfig.json new file mode 100644 index 0000000000..951405762a --- /dev/null +++ b/types/json_ml/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "json_ml-tests.ts"] +} diff --git a/types/json_ml/tslint.json b/types/json_ml/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/json_ml/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/karma-chai-sinon/index.d.ts b/types/karma-chai-sinon/index.d.ts index 0b14373a99..9a14f659e2 100644 --- a/types/karma-chai-sinon/index.d.ts +++ b/types/karma-chai-sinon/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/tubalmartin/karma-chai-sinon // Definitions by: Václav Ostrožlík // Definitions: https://github.com/borisyankov/DefinitelyTyped -// TypeScript Version: 3.0 +// TypeScript Version: 2.8 /// import Sinon = require('sinon'); diff --git a/types/kendo-ui/tslint.json b/types/kendo-ui/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/kendo-ui/tslint.json +++ b/types/kendo-ui/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/koa-log/index.d.ts b/types/koa-log/index.d.ts new file mode 100644 index 0000000000..3e97ea155f --- /dev/null +++ b/types/koa-log/index.d.ts @@ -0,0 +1,33 @@ +// Type definitions for koa-log 2.1 +// Project: https://github.com/vicanso/koa-log#readme +// Definitions by: Uladzimir Havenchyk +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import * as Koa from 'koa'; + +declare function koaLog(type: string): Koa.Middleware; + +declare namespace koaLog { + namespace morgan { + function cookie(ctx: Koa.BaseContext, key: string): string; + + function date(ctx: Koa.BaseContext, format: string): string; + + function format(name: string): string; + + function length(ctx: Koa.BaseContext): number | undefined; + + function method(ctx: Koa.BaseContext): string; + + function referrer(ctx: Koa.BaseContext): string; + + function status(ctx: Koa.BaseContext): number; + + function token(name: string, fn: (ctx: Koa.BaseContext) => string): void; + + function url(ctx: Koa.BaseContext): string; + } +} + +export = koaLog; diff --git a/types/koa-log/koa-log-tests.ts b/types/koa-log/koa-log-tests.ts new file mode 100644 index 0000000000..070ceabfe9 --- /dev/null +++ b/types/koa-log/koa-log-tests.ts @@ -0,0 +1,10 @@ +import Koa = require('koa'); +import koaLogger = require('koa-log'); + +koaLogger.morgan.token('request-body', (ctx: Koa.BaseContext) => JSON.stringify(ctx.request.body)); +koaLogger.morgan.token('response-body', (ctx: Koa.BaseContext) => JSON.stringify(ctx.body)); + +const app = new Koa(); +app.use( + koaLogger(':status :method :url took :response-time ms :request-body :response-body') +); diff --git a/types/koa-log/tsconfig.json b/types/koa-log/tsconfig.json new file mode 100644 index 0000000000..2e32dbc373 --- /dev/null +++ b/types/koa-log/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "koa-log-tests.ts" + ] +} diff --git a/types/koa-log/tslint.json b/types/koa-log/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/koa-log/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/ldap-filters/index.d.ts b/types/ldap-filters/index.d.ts new file mode 100644 index 0000000000..46e1c24fa8 --- /dev/null +++ b/types/ldap-filters/index.d.ts @@ -0,0 +1,60 @@ +// Type definitions for ldap-filters 2.2 +// Project: https://github.com/tapmodo/node-ldap-filters +// Definitions by: Alan Plum +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +interface Filter { + toString(indent?: boolean | number): string; + simplify(): Filter; + match(data: object): boolean; +} + +declare namespace Filter { + let escape_chars: string[]; + let indent: number; + let indent_char: string; + let collapse_not: boolean; + + function escape(value: string): string; + function unescape(value: string): string; + function parse(input: string): Filter; + function matchString(data: string | string[], filter: Filter): boolean; + function matchSubstring(data: string | string[], filter: Filter): boolean; + function matchApprox(data: string | string[], filter: Filter): boolean; + function matchGTE(data: string | string[], filter: Filter): boolean; + function matchLTE(data: string | string[], filter: Filter): boolean; + function attribute(name: string): Attribute; + function AND(filters: Filter[]): Group; + function OR(filters: Filter[]): Group; + function NOT(filter: Filter): GroupNot; + + interface Group { + type: string; + comp: string; + filters: Filter[]; + toString(indent?: boolean | number): string; + match(data: object): boolean; + } + + interface GroupNot extends Group { + simplify(): Filter; + } + + interface Attribute { + name: string; + escapeChars: string[]; + escape(value: string): string; + present(): Filter; + raw(value: string): Filter; + equalTo(value: string): Filter; + endsWith(value: string): Filter; + startsWith(value: string): Filter; + contains(value: string): Filter; + approx(value: string): Filter; + lte(value: string): Filter; + gte(value: string): Filter; + } +} + +export = Filter; diff --git a/types/ldap-filters/ldap-filters-tests.ts b/types/ldap-filters/ldap-filters-tests.ts new file mode 100644 index 0000000000..5111af785e --- /dev/null +++ b/types/ldap-filters/ldap-filters-tests.ts @@ -0,0 +1,28 @@ +/// + +import Filter = require("ldap-filters"); + +Filter.collapse_not = false; + +const output = Filter.AND([ + Filter.attribute("givenName").equalTo("jenny"), + Filter.attribute("sn").equalTo("jensen") +]); + +console.log(output.toString()); + +Filter.parse("(&(givenName=jenny)(sn=jensen))"); + +Filter.parse("(&(uid=jenny))").simplify(); + +const filter = Filter.parse( + "(&(givenName=jenny)(sn=jensen)(|(c=us)(st=ontario)))" +); + +filter.toString(); +filter.toString(true); +filter.toString(2); + +const parsed = Filter.parse("(&(givenName~=jeni)(sn=jensen))"); +const data = { givenName: "Jenny", sn: "Jensen" }; +console.log(parsed.match(data)); diff --git a/types/ldap-filters/tsconfig.json b/types/ldap-filters/tsconfig.json new file mode 100644 index 0000000000..9d4f5aa560 --- /dev/null +++ b/types/ldap-filters/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "ldap-filters-tests.ts"] +} diff --git a/types/ldap-filters/tslint.json b/types/ldap-filters/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/ldap-filters/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/liftoff/index.d.ts b/types/liftoff/index.d.ts new file mode 100644 index 0000000000..91316ead82 --- /dev/null +++ b/types/liftoff/index.d.ts @@ -0,0 +1,203 @@ +// Type definitions for liftoff 2.5 +// Project: https://github.com/js-cli/js-liftoff#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import { Extensions, Extension, ExtensionDescriptor } from 'interpret'; +import { PathSpec } from 'fined'; +import { EventEmitter } from 'events'; + +export = Liftoff; + +declare class Liftoff extends EventEmitter { + /** + * Create an instance of Liftoff to invoke your application. + */ + constructor(options?: Liftoff.Options); + + /** + * Launches your application with provided options, builds an environment, + * and invokes your callback, passing the calculated environment as the first argument. + */ + launch( + opts: Liftoff.LaunchOptions, + callback: (this: this, env: Liftoff.LiftoffEnv) => void + ): void; + + addListener( + event: 'require', + listener: (name: string, module: ExtensionDescriptor) => void + ): this; + addListener(event: 'requireFail', listener: (name: string, err: any) => void): this; + addListener(event: 'respawn', listener: (flags: string[], child: NodeJS.Process) => void): this; + on(event: 'require', listener: (name: string, module: ExtensionDescriptor) => void): this; + on(event: 'requireFail', listener: (name: string, err: any) => void): this; + on(event: 'respawn', listener: (flags: string[], child: NodeJS.Process) => void): this; + once(event: 'require', listener: (name: string, module: ExtensionDescriptor) => void): this; + once(event: 'requireFail', listener: (name: string, err: any) => void): this; + once(event: 'respawn', listener: (flags: string[], child: NodeJS.Process) => void): this; + prependListener( + event: 'require', + listener: (name: string, module: ExtensionDescriptor) => void + ): this; + prependListener(event: 'requireFail', listener: (name: string, err: any) => void): this; + prependListener( + event: 'respawn', + listener: (flags: string[], child: NodeJS.Process) => void + ): this; + prependOnceListener( + event: 'require', + listener: (name: string, module: ExtensionDescriptor) => void + ): this; + prependOnceListener(event: 'requireFail', listener: (name: string, err: any) => void): this; + prependOnceListener( + event: 'respawn', + listener: (flags: string[], child: NodeJS.Process) => void + ): this; + removeListener( + event: 'require', + listener: (name: string, module: ExtensionDescriptor) => void + ): this; + removeListener(event: 'requireFail', listener: (name: string, err: any) => void): this; + removeListener( + event: 'respawn', + listener: (flags: string[], child: NodeJS.Process) => void + ): this; + off(event: 'require', listener: (name: string, module: ExtensionDescriptor) => void): this; + off(event: 'requireFail', listener: (name: string, err: any) => void): this; + off(event: 'respawn', listener: (flags: string[], child: NodeJS.Process) => void): this; + removeAllListeners(event?: 'require' | 'requireFail' | 'respawn'): this; + listeners(event: 'require' | 'requireFail' | 'respawn'): Function[]; // tslint:disable-line:ban-types + rawListeners(event: 'require' | 'requireFail' | 'respawn'): Function[]; // tslint:disable-line:ban-types + emit(event: 'require', name: string, module: ExtensionDescriptor): boolean; + emit(event: 'requireFail', name: string, err: any): boolean; + emit(event: 'respawn', flags: string[], child: NodeJS.Process): boolean; + eventNames(): Array<'require' | 'requireFail' | 'respawn'>; + listenerCount(type: 'require' | 'requireFail' | 'respawn'): number; +} + +declare namespace Liftoff { + interface Options { + /** + * Sugar for setting processTitle, moduleName, configName automatically. + * @default null + */ + name?: string; + /** + * Sets which module your application expects to find locally when being run. + * @default null + */ + moduleName?: string; + /** + * Sets the name of the configuration file Liftoff will attempt to find. Case-insensitive. + * @default null + */ + configName?: string; + /** + * Set extensions to include when searching for a configuration file. + * If an external module is needed to load a given extension (e.g. .coffee), + * the module name should be specified as the value for the key. + * @default {".js":null,".json":null} + */ + extensions?: Extensions; + /** + * Any flag specified here will be applied to node, not your program. + * Useful for supporting invocations like myapp --harmony command, + * where --harmony should be passed to node, not your program. + * This functionality is implemented using flagged-respawn. + * To support all v8flags, see `v8flags`. + * @default null + */ + v8flags?: string[] | ((cb: (err: any, flags: string[]) => void) => void); + /** + * Sets what the process title will be. + * @default null + */ + processTitle?: string; + /** + * A method to handle bash/zsh/whatever completions. + * @default null + */ + completions?: (completion: string) => any; + /** + * An object of configuration files to find. Each property is keyed by the + * default basename of the file being found, and the value is an object + * of path arguments keyed by unique names. + * @default null + */ + configFiles?: { + [extension: string]: { [locationName: string]: string | PathSpec }; + }; + } + + interface LaunchOptions { + /** + * Change the current working directory for this launch. Relative paths are calculated against `process.cwd()`. + * @default process.cwd() + */ + cwd?: string; + + /** + * Don't search for a config, use the one provided. + * **Note**: Liftoff will assume the current working directory is the directory containing the config file + * unless an alternate location is explicitly specified using `cwd`. + * @default null + */ + configPath?: string; + + /** + * A string or array of modules to attempt requiring from the local + * working directory before invoking the launch callback. + * @default null + */ + require?: string | any[]; + + /** + * Allows you to force node or V8 flags during the launch. + * This is useful if you need to make sure certain flags will always be enabled + * or if you need to enable flags that don't show up in `opts.v8flags` + * (as these flags aren't validated against opts.v8flags). + * @default null + */ + forcedFlags?: string | string[] | ((env: LiftoffEnv) => string | string[]); + + completion?: string; + } + + interface LiftoffEnv { + /** + * the current working directory + */ + cwd: string; + /** + * an array of modules that liftoff tried to pre-load + */ + require: string[]; + /** + * the config files searched for + */ + configNameSearch: string[]; + /** + * the full path to your configuration file (if found) + */ + configPath: string | undefined; + /** + * the base directory of your configuration file (if found) + */ + configBase: string | undefined; + /** + * the full path to the local module your project relies on (if found) + */ + modulePath: string | undefined; + /** + * the contents of the local module's package.json (if found) + */ + modulePackage: { [key: string]: any } | undefined; + /** + * an object of filepaths for each found config file (filepath values will be null if not found) + */ + configFiles: { [extensions: string]: { [path: string]: string | null } } | undefined; + } +} diff --git a/types/liftoff/liftoff-tests.ts b/types/liftoff/liftoff-tests.ts new file mode 100644 index 0000000000..bfc960eb62 --- /dev/null +++ b/types/liftoff/liftoff-tests.ts @@ -0,0 +1,182 @@ +import Liftoff = require('liftoff'); +import v8flags = require('v8flags'); + +new Liftoff({ + name: 'hacker', + processTitle: 'hacker', + moduleName: 'hacker', + configName: 'hackerfile', + extensions: { + '.js': null, + '.json': null, + '.coffee': 'coffee-script/register', + }, + v8flags: ['--harmony'], +}); +new Liftoff({ + name: 'hacker', + processTitle: 'hacker', + moduleName: 'hacker', + configName: 'hackerfile', + extensions: { + '.js': null, + '.json': null, + '.coffee': 'coffee-script/register', + }, + v8flags, +}); +new Liftoff({ name: 'hacker' }); +new Liftoff({ + name: 'myapp', + extensions: { + '.js': null, + '.json': null, + '.coffee': 'coffee-script/register', + }, +}); +new Liftoff({ + name: 'myapp', + configName: '.myapp', + extensions: { + rc: null, + }, +}); +new Liftoff({ + name: 'myapp', + extensions: require('interpret').jsVariants, +}); +new Liftoff({ + v8flags: ['--trace-deprecation'], +}); +new Liftoff({ + v8flags(cb) { + cb(null, ['--trace-deprecation']); + }, +}); +new Liftoff({ + name: 'hacker', + configFiles: { + '.hacker': { + cwd: '.', + }, + }, +}); +new Liftoff({ + name: 'hacker', + configFiles: { + '.hacker': { + home: { + path: '~', + extensions: { + rc: null, + }, + }, + }, + }, +}); +new Liftoff({ + name: 'hacker', + configFiles: { + '.hacker': { + up: { + path: '.', + findUp: true, + }, + }, + }, +}); +new Liftoff({ + name: 'hacker', + configFiles: { + hacker: { + override: { + path: '.', + name: '.override', + }, + }, + }, +}); +new Liftoff({ + name: 'hacker', + configFiles: { + '.hacker': { + home: { + path: '.', + cwd: '~', + }, + }, + }, +}); + +new Liftoff().launch( + { + cwd: '', + configPath: '', + require: '', + completion: '', + }, + env => { + // $ExpectType LiftoffEnv + env; + + // $ExpectType string + env.cwd; + // $ExpectType string[] + env.require; + // $ExpectType string[] + env.configNameSearch; + // $ExpectType string | undefined + env.configPath; + // $ExpectType string | undefined + env.configBase; + // $ExpectType string | undefined + env.modulePath; + // $ExpectType { [key: string]: any; } | undefined + env.modulePackage; + // $ExpectType { [extensions: string]: { [path: string]: string | null; }; } | undefined + env.configFiles; + } +); +new Liftoff().launch({ cwd: '' }, () => {}); +new Liftoff().launch({ configPath: '' }, () => {}); +new Liftoff().launch({ require: '' }, () => {}); +new Liftoff().launch({ forcedFlags: ['--trace-deprecation'] }, () => {}); +new Liftoff().launch({ forcedFlags: '--trace-deprecation' }, () => {}); +new Liftoff().launch( + { + forcedFlags: env => { + // $ExpectType LiftoffEnv + env; + return ['--trace-deprecation']; + }, + }, + () => {} +); +new Liftoff().launch( + { + forcedFlags: env => { + return '--trace-deprecation'; + }, + }, + () => {} +); +new Liftoff().launch({ completion: '' }, () => {}); + +new Liftoff().on('require', (name, module) => { + // $ExpectType string + name; + // $ExpectType ExtensionDescriptor + module; +}); +new Liftoff().on('requireFail', (name, err) => { + // $ExpectType string + name; + // $ExpectType any + err; +}); +new Liftoff().on('respawn', (flags, child) => { + // $ExpectType string[] + flags; + // $ExpectType Process + child; +}); diff --git a/types/liftoff/tsconfig.json b/types/liftoff/tsconfig.json new file mode 100644 index 0000000000..771c8ce2ed --- /dev/null +++ b/types/liftoff/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "liftoff-tests.ts" + ] +} diff --git a/types/liftoff/tslint.json b/types/liftoff/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/liftoff/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/list-stream/index.d.ts b/types/list-stream/index.d.ts new file mode 100644 index 0000000000..2b3fd1da28 --- /dev/null +++ b/types/list-stream/index.d.ts @@ -0,0 +1,33 @@ +// Type definitions for list-stream 1.0 +// Project: https://github.com/rvagg/list-stream +// Definitions by: Christian Sporer +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.7 + +/// + +import { Duplex, DuplexOptions } from "stream"; + +interface ListStreamMethod { + (callback?: (err: Error, data: any[]) => void): ListStream; + (options?: DuplexOptions, callback?: (err: Error, data: any[]) => void): ListStream; +} + +interface ListStreamConstructor extends ListStreamMethod { + new(callback?: (err: Error, data: any[]) => void): ListStream; + new(options?: DuplexOptions, callback?: (err: Error, data: any[]) => void): ListStream; + + obj: ListStreamMethod; +} + +declare let ListStream: ListStreamConstructor; + +interface ListStream extends Duplex { + append(chunk: any): void; + duplicate(): ListStream; + end(): void; + get(index: number): any; + length: number; +} + +export = ListStream; diff --git a/types/list-stream/list-stream-tests.ts b/types/list-stream/list-stream-tests.ts new file mode 100644 index 0000000000..8b6ae25435 --- /dev/null +++ b/types/list-stream/list-stream-tests.ts @@ -0,0 +1,2 @@ +import "./test/import-tests"; +import "./test/require-tests"; diff --git a/types/list-stream/test/import-tests.ts b/types/list-stream/test/import-tests.ts new file mode 100644 index 0000000000..3648097ad6 --- /dev/null +++ b/types/list-stream/test/import-tests.ts @@ -0,0 +1,54 @@ +import ListStream from "list-stream"; + +let chunk: any = "chunk"; +let listStream: ListStream; +let num = 1; + +listStream = ListStream((err: Error, data: any[]) => { + if (err) { throw err; } + console.log(data.length); + for (const date of data) { + console.log(date); + } +}); +listStream = ListStream({ objectMode: true }, (err: Error, data: any[]) => { + if (err) { throw err; } + console.log(data.length); + for (const date of data) { + console.log(date); + } +}); +listStream = new ListStream((err: Error, data: any[]) => { + if (err) { throw err; } + console.log(data.length); + for (const date of data) { + console.log(date); + } +}); +listStream = new ListStream({ objectMode: true }, (err: Error, data: any[]) => { + if (err) { throw err; } + console.log(data.length); + for (const date of data) { + console.log(date); + } +}); +listStream = ListStream.obj((err: Error, data: any[]) => { + if (err) { throw err; } + console.log(data.length); + for (const date of data) { + console.log(date); + } +}); + +listStream = ListStream.obj(); +listStream.write({ key: "value" }); + +listStream.append(chunk); + +listStream = listStream.duplicate(); + +listStream.end(); + +chunk = listStream.get(num); + +num = listStream.length; diff --git a/types/list-stream/test/require-tests.ts b/types/list-stream/test/require-tests.ts new file mode 100644 index 0000000000..8966e1e5a3 --- /dev/null +++ b/types/list-stream/test/require-tests.ts @@ -0,0 +1,54 @@ +import ListStream = require("list-stream"); + +let chunk: any = "chunk"; +let listStream: ListStream; +let num = 1; + +listStream = ListStream((err: Error, data: any[]) => { + if (err) { throw err; } + console.log(data.length); + for (const date of data) { + console.log(date); + } +}); +listStream = ListStream({ objectMode: true }, (err: Error, data: any[]) => { + if (err) { throw err; } + console.log(data.length); + for (const date of data) { + console.log(date); + } +}); +listStream = new ListStream((err: Error, data: any[]) => { + if (err) { throw err; } + console.log(data.length); + for (const date of data) { + console.log(date); + } +}); +listStream = new ListStream({ objectMode: true }, (err: Error, data: any[]) => { + if (err) { throw err; } + console.log(data.length); + for (const date of data) { + console.log(date); + } +}); +listStream = ListStream.obj((err: Error, data: any[]) => { + if (err) { throw err; } + console.log(data.length); + for (const date of data) { + console.log(date); + } +}); + +listStream = ListStream.obj(); +listStream.write({ key: "value" }); + +listStream.append(chunk); + +listStream = listStream.duplicate(); + +listStream.end(); + +chunk = listStream.get(num); + +num = listStream.length; diff --git a/types/list-stream/tsconfig.json b/types/list-stream/tsconfig.json new file mode 100644 index 0000000000..00fe9a2e23 --- /dev/null +++ b/types/list-stream/tsconfig.json @@ -0,0 +1,26 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "esModuleInterop": true + }, + "files": [ + "test/import-tests.ts", + "test/require-tests.ts", + "index.d.ts", + "list-stream-tests.ts" + ] +} diff --git a/types/list-stream/tslint.json b/types/list-stream/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/list-stream/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/lodash/common/lang.d.ts b/types/lodash/common/lang.d.ts index 9afe554b28..723388c9cc 100644 --- a/types/lodash/common/lang.d.ts +++ b/types/lodash/common/lang.d.ts @@ -1020,7 +1020,7 @@ declare module "../index" { // isMatchWith - type isMatchWithCustomizer = (value: any, other: any, indexOrKey: PropertyName) => boolean; + type isMatchWithCustomizer = (value: any, other: any, indexOrKey: PropertyName, object: object, source: object) => boolean; interface LoDashStatic { /** diff --git a/types/lodash/lodash-tests.ts b/types/lodash/lodash-tests.ts index 4f7f229fe6..9d2547dcf4 100644 --- a/types/lodash/lodash-tests.ts +++ b/types/lodash/lodash-tests.ts @@ -4205,7 +4205,7 @@ fp.now(); // $ExpectType number // _.isMatchWith { - const testIsMatchCustiomizerFn = (value: any, other: any, indexOrKey: number|string|symbol) => true; + const testIsMatchCustiomizerFn = (value: any, other: any, indexOrKey: number|string|symbol, object: object, source: object) => true; _.isMatchWith({}, {}, testIsMatchCustiomizerFn); // $ExpectType boolean _({}).isMatchWith({}, testIsMatchCustiomizerFn); // $ExpectType boolean diff --git a/types/ltx/index.d.ts b/types/ltx/index.d.ts index 33311a3175..1c313c5541 100644 --- a/types/ltx/index.d.ts +++ b/types/ltx/index.d.ts @@ -1,17 +1,17 @@ -// Type definitions for ltx 2.6 +// Type definitions for ltx 2.8 // Project: github.com/node-xmpp/ltx/ // Definitions by: PJakcson +// BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.1 -export {Element } from './lib/Element'; -export {nameEqual, attrsEqual, childrenEqual, equal} from './lib/equal'; -export {isNode, isElement, isText} from './lib/is'; -export {clone} from './lib/clone'; -export {createElement} from './lib/createElement'; -export {escapeXML, unescapeXML, escapeXMLText, unescapeXMLText} from './lib/escape'; -export {Parser} from './lib/Parser'; -export {parse} from './lib/parse'; -export {tag} from './lib/tag'; -export {tagString} from './lib/tagString'; -export {stringify} from './lib/stringify'; +export * from './lib/Element'; +export * from './lib/equal'; +export * from './lib/is'; +export * from './lib/clone'; +export * from './lib/createElement'; +export * from './lib/escape'; +export * from './lib/Parser'; +export * from './lib/parse'; +export * from './lib/tag'; +export * from './lib/tagString'; +export * from './lib/stringify'; diff --git a/types/ltx/lib/Element.d.ts b/types/ltx/lib/Element.d.ts index 203eaa93b6..7f0d3de62e 100644 --- a/types/ltx/lib/Element.d.ts +++ b/types/ltx/lib/Element.d.ts @@ -1,21 +1,26 @@ +import { clone } from './clone'; + +export type Node = Element | TextNode; +export type TextNode = string | number; + /** * Element * * Attributes are in the element.attrs object. Children is a list of * either other Elements or Strings for text content. - **/ -export declare class Element { + */ +export class Element { name: string; - parent: Element; + parent: Element | null; children: Element[]; - attrs: any; + attrs: { [attrName: string]: any }; - constructor(name: string, attrs?: any); + constructor(name: string, attrs?: string | { [attrName: string]: any }); /** * if (element.is('message', 'jabber:client')) ... - **/ - is(name: string, xmlns?: any): boolean; + */ + is(name: string, xmlns?: string): boolean; /** * without prefix. @@ -24,50 +29,44 @@ export declare class Element { /** * retrieves the namespace of the current element, upwards recursively - **/ - getNS(): any; + */ + getNS(): string | undefined; /** * find the namespace to the given prefix, upwards recursively - **/ - findNS(prefix: string): any; + */ + findNS(prefix: string): string | undefined; /** * Recursiverly gets all xmlns defined, in the form of {url:prefix} - **/ - getXmlns(): any; + */ + getXmlns(): { [key: string]: string }; - setAttrs(attrs: any): void; + setAttrs(attrs: string | { [attrName: string]: any }): void; /** - * xmlns can be null, returns the matching attribute. - **/ - getAttr(name: string, xmlns?: any): any; + * returns the matching attribute. + */ + getAttr(name: string, xmlns?: string): any; - /** - * xmlns can be null - **/ - getChild(name: string, xmlns?: any): Element; + getChild(name: string, xmlns?: string): Element | undefined; - /** - * xmlns can be null - **/ - getChildren(name: string, xmlns?: any): Element[]; + getChildren(name: string, xmlns?: string): Element[]; - /** - * xmlns and recursive can be null - **/ - getChildByAttr(attr: any, val: any, xmlns?: any, recursive?: any): Element; + getChildByAttr( + attr: string, + val: any, + xmlns?: string, + recursive?: boolean + ): Element | undefined; + getChildrenByAttr(attr: string, val: any, xmlns?: string, recursive?: boolean): Element[]; - /** - * xmlns and recursive can be null - **/ - getChildrenByAttr(attr: any, val: any, xmlns?: any, recursive?: any): Element[]; + getChildrenByFilter(filter: (child: Node) => boolean, recursive?: boolean): Element[]; getText(): string; - getChildText(name: string, xmlns?: any): string; + getChildText(name: string, xmlns?: string): string | null; /** * Return all direct descendents that are Elements. @@ -77,37 +76,39 @@ export declare class Element { getChildElements(): Element[]; /** returns uppermost parent */ - root(): Element; + root(): Element | this; - tree(): Element; + tree(): Element | this; /** just parent or itself */ - up(): Element; + up(): Element | this; /** create child node and return it */ - c(name: string, attrs?: any): Element; + c(name: string, attrs?: { [key: string]: any }): Element; + + cnode(child: T): T; /** add text node and return element */ - t(text: string): Element; + t(text: TextNode): this; /** * Either: * el.remove(childEl) * el.remove('author', 'urn:...') */ - remove(el: Element, xmlns?: any): Element; + remove(el: Element | string, xmlns?: string): this; - clone(): Element; + clone: typeof clone; - text(val: string): string; + text(val?: string): string; - attr(attr: any, val: any): any; + attr(attr: string, val?: any): any; toString(): string; - toJSON(): any; + toJSON(): ElementJson; - write(writer: any): void; + write(writer: (part: string) => void): void; nameEquals(el: Element): boolean; @@ -117,3 +118,9 @@ export declare class Element { equals(el: Element): boolean; } + +export interface ElementJson { + name: string; + attrs: { [attrName: string]: any }; + children: Array; +} diff --git a/types/ltx/lib/Parser.d.ts b/types/ltx/lib/Parser.d.ts index 083e3ace66..463029286f 100644 --- a/types/ltx/lib/Parser.d.ts +++ b/types/ltx/lib/Parser.d.ts @@ -1,5 +1,15 @@ /// import { EventEmitter } from 'events'; -export declare class Parser extends EventEmitter { - constructor(options?: any); +import { Element } from './Element'; + +export class Parser extends EventEmitter { + constructor(options?: ParserOptions); + + write(data: string): void; + end(data: string): void; +} + +export interface ParserOptions { + Parser?: typeof Parser; + Element?: typeof Element; } diff --git a/types/ltx/lib/clone.d.ts b/types/ltx/lib/clone.d.ts index 41193a3f40..15369e00d5 100644 --- a/types/ltx/lib/clone.d.ts +++ b/types/ltx/lib/clone.d.ts @@ -1 +1,3 @@ -export declare function clone(el: any): any; +import { Element } from './Element'; + +export function clone(el: T): T; diff --git a/types/ltx/lib/createElement.d.ts b/types/ltx/lib/createElement.d.ts index c372f11150..21527ae1b6 100644 --- a/types/ltx/lib/createElement.d.ts +++ b/types/ltx/lib/createElement.d.ts @@ -1,2 +1,6 @@ -import { Element } from './Element'; -export declare function createElement(name: string, attrs: any): Element; +import { Element, Node } from './Element'; +export function createElement( + name: string, + attrs?: string | { [attrName: string]: any }, + ...children: Node[] +): Element; diff --git a/types/ltx/lib/equal.d.ts b/types/ltx/lib/equal.d.ts index 520555e098..f7548c526b 100644 --- a/types/ltx/lib/equal.d.ts +++ b/types/ltx/lib/equal.d.ts @@ -1,4 +1,6 @@ -export declare function nameEqual(a: any, b: any): boolean; -export declare function attrsEqual(a: any, b: any): boolean; -export declare function childrenEqual(a: any, b: any): boolean; -export declare function equal(a: any, b: any): boolean; +import { Element } from './Element'; + +export function nameEqual(a: Element, b: Element): boolean; +export function attrsEqual(a: Element, b: Element): boolean; +export function childrenEqual(a: Element, b: Element): boolean; +export function equal(a: Element, b: Element): boolean; diff --git a/types/ltx/lib/escape.d.ts b/types/ltx/lib/escape.d.ts index 4bc45c223a..d390e860ed 100644 --- a/types/ltx/lib/escape.d.ts +++ b/types/ltx/lib/escape.d.ts @@ -1,4 +1,4 @@ -export declare function escapeXML(s: string): string; -export declare function unescapeXML(s: string): string; -export declare function escapeXMLText(s: string): string; -export declare function unescapeXMLText(s: string): string; +export function escapeXML(s: string): string; +export function unescapeXML(s: string): string; +export function escapeXMLText(s: string): string; +export function unescapeXMLText(s: string): string; diff --git a/types/ltx/lib/is.d.ts b/types/ltx/lib/is.d.ts index 6515d23f80..e62d919267 100644 --- a/types/ltx/lib/is.d.ts +++ b/types/ltx/lib/is.d.ts @@ -1,3 +1,5 @@ -export declare function isNode(el: any): boolean; -export declare function isElement(el: any): boolean; -export declare function isText(el: any): boolean; +import { Element, Node } from './Element'; + +export function isNode(el: any): el is Node; +export function isElement(el: any): el is Element; +export function isText(el: any): el is string; diff --git a/types/ltx/lib/parse.d.ts b/types/ltx/lib/parse.d.ts index cc4073113a..0e0a9b17cb 100644 --- a/types/ltx/lib/parse.d.ts +++ b/types/ltx/lib/parse.d.ts @@ -1 +1,4 @@ -export declare function parse(data: any, options?: any): any; +import { ParserOptions, Parser } from './Parser'; +import { Element } from './Element'; + +export function parse(data: string, options?: ParserOptions | Parser): Element; diff --git a/types/ltx/lib/stringify.d.ts b/types/ltx/lib/stringify.d.ts index 770f7d324f..9913f2318c 100644 --- a/types/ltx/lib/stringify.d.ts +++ b/types/ltx/lib/stringify.d.ts @@ -1 +1,3 @@ -export declare function stringify(el: any, indent: any, level: any): string; +import { Element } from './Element'; + +export function stringify(el: Element, indent?: number, level?: number): string; diff --git a/types/ltx/lib/tag.d.ts b/types/ltx/lib/tag.d.ts index 8bbcb6fe7b..11a9784bf0 100644 --- a/types/ltx/lib/tag.d.ts +++ b/types/ltx/lib/tag.d.ts @@ -1 +1,3 @@ -export declare function tag(d: any): any; +import { Element } from './Element'; + +export function tag(literals: string[], ...substitutions: string[]): Element; diff --git a/types/ltx/lib/tagString.d.ts b/types/ltx/lib/tagString.d.ts index 44036ce037..619ccbdb23 100644 --- a/types/ltx/lib/tagString.d.ts +++ b/types/ltx/lib/tagString.d.ts @@ -1 +1 @@ -export declare function tagString(d: any): string; +export function tagString(literals: string[], ...substitutions: string[]): string; diff --git a/types/ltx/ltx-tests.ts b/types/ltx/ltx-tests.ts index 522b7673c8..a7342ef54b 100644 --- a/types/ltx/ltx-tests.ts +++ b/types/ltx/ltx-tests.ts @@ -1,21 +1,147 @@ import * as ltx from 'ltx'; -ltx.parse(''); +let el: ltx.Element = null as any; +let maybeEl: ltx.Element | undefined = null as any; +let els: ltx.Element[] = []; +let bool: boolean; +const any: any = null; +let str: string = null as any; -const getChildTextElement = ltx.parse('body text') as ltx.Element; -if (getChildTextElement.getChildText('child') !== 'body text') { - throw new Error("body does not match"); +el = ltx.clone(el); + +bool = ltx.nameEqual(el, el); +bool = ltx.attrsEqual(el, el); +bool = ltx.childrenEqual(el, el); +bool = ltx.equal(el, el); + +el = ltx.createElement('el'); +el = ltx.createElement('el', 'xml'); +el = ltx.createElement('el', { foo: 'bar' }); +el = ltx.createElement('el', { foo: 'bar' }, el); +el = ltx.createElement('el', { foo: 'bar' }, 'hi'); + +if (ltx.isNode(any)) { + // $ExpectType Node + any; +} +if (ltx.isElement(any)) { + // $ExpectType Element + any; +} +if (ltx.isText(any)) { + // $ExpectType string + any; } -const p = new ltx.Parser(); +str = ltx.escapeXML(str); +str = ltx.unescapeXML(str); +str = ltx.escapeXMLText(str); +str = ltx.unescapeXMLText(str); + +el = ltx.parse(''); +el = ltx.parse('', (null as any) as ltx.Parser); +el = ltx.parse('', { Parser: (null as any) as typeof ltx.Parser }); +el = ltx.parse('', { Element: (null as any) as typeof ltx.Element }); + +el = ltx.tag(['document'], 'foo'); +str = ltx.tagString(['document'], 'foo'); + +str = ltx.stringify(el); +str = ltx.stringify(el, 1); +str = ltx.stringify(el, 1, 1); + +const getChildTextElement = ltx.parse('body text'); +if (getChildTextElement.getChildText('child') !== 'body text') { + throw new Error('body does not match'); +} + +let p: ltx.Parser; +p = new ltx.Parser(); +p = new ltx.Parser({ Parser: (null as any) as typeof ltx.Parser }); +p = new ltx.Parser({ Element: (null as any) as typeof ltx.Element }); p.on('tree', (ignored: any) => {}); - p.on('error', (ignored: any) => {}); -const el = new ltx.Element('root').c('children'); -el.c('child', {age: 5}).t('Hello').up() - .c('child', {age: 7}).t('Hello').up() - .c('child', {age: 99}).t('Hello').up(); +el = new ltx.Element('root').c('children'); -el.root().toString(); +bool = el.is('el'); +bool = el.is('el', 'ns'); +str = el.getName(); +let s: string | undefined = el.getNS(); +s = el.findNS('ns'); +const xmlns: { [key: string]: string } = el.getXmlns(); +el.setAttrs('ho'); +el.setAttrs({ my: 'attr' }); +el.getAttr('ho'); +el.getAttr('ho', 'ns'); +maybeEl = el.getChild('el'); +maybeEl = el.getChild('el', 'ns'); +els = el.getChildren('el'); +els = el.getChildren('el', 'ns'); +maybeEl = el.getChildByAttr('my', 'attr'); +maybeEl = el.getChildByAttr('my', 'attr', 'ns'); +maybeEl = el.getChildByAttr('my', 'attr', 'ns', true); +els = el.getChildrenByAttr('my', 'attr'); +els = el.getChildrenByAttr('my', 'attr', 'ns'); +els = el.getChildrenByAttr('my', 'attr', 'ns', true); +els = el.getChildrenByFilter(child => { + // $ExpectType Node + child; + return true; +}); +els = el.getChildrenByFilter(child => { + // $ExpectType Node + child; + return true; +}, true); +str = el.getText(); +let maybeS: string | null = el.getChildText('hi'); +maybeS = el.getChildText('hi', 'ns'); +els = el.getChildElements(); + +class MyEl extends ltx.Element { + foo: 'bar'; +} +let myEl = new MyEl('el'); + +// $ExpectType Element | MyEl +myEl.root(); +// $ExpectType Element | MyEl +myEl.tree(); +// $ExpectType Element | MyEl +myEl.up(); + +el = el.c('hi'); +el = el.c('hi', { my: 'attr' }); +myEl = myEl.cnode(myEl); +myEl = myEl.t('hi'); +myEl = myEl.t(1); +myEl = myEl.remove(el); +myEl = myEl.remove('el'); +myEl = myEl.remove('el', 'ns'); +myEl = myEl.clone(myEl); +str = el.text(); +str = el.text('val'); +el.attr('my'); +el.attr('my', 'attr'); +str = el.toString(); +const json: ltx.ElementJson = el.toJSON(); +el.write(part => { + // $ExpectType string + part; +}); +bool = el.nameEquals(el); +bool = el.attrsEquals(el); +bool = el.childrenEquals(el); +bool = el.equals(el); + +el.c('child', { age: 5 }) + .t('Hello') + .up() + .c('child', { age: 7 }) + .t('Hello') + .up() + .c('child', { age: 99 }) + .t('Hello') + .up(); diff --git a/types/ltx/tslint.json b/types/ltx/tslint.json index 5bb1e8735d..f93cf8562a 100644 --- a/types/ltx/tslint.json +++ b/types/ltx/tslint.json @@ -1,9 +1,3 @@ { - "extends": "dtslint/dt.json", - "rules": { - // All are TODOs - "jsdoc-format": false, - "no-consecutive-blank-lines": false, - "strict-export-declare-modifiers": false - } + "extends": "dtslint/dt.json" } diff --git a/types/lunr/index.d.ts b/types/lunr/index.d.ts index da87ae95d8..415c7c1d8f 100644 --- a/types/lunr/index.d.ts +++ b/types/lunr/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for lunr.js 2.1 +// Type definitions for lunr.js 2.3 // Project: https://github.com/olivernn/lunr.js -// Definitions by: Sean Tan +// Definitions by: Sean Tan , Andrés Pérez // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -127,9 +127,14 @@ declare namespace lunr { * All fields should be added before adding documents to the index. Adding fields after * a document has been indexed will have no effect on already indexed documents. * + * Fields can be boosted at build time. This allows terms within that field to have more + * importance when ranking search results. Use a field boost to specify that matches + * within one field are more important than other fields. + * * @param field - The name of a field to index in all documents. + * @param attributes - Optional attributes associated with this field. */ - field(field: string): void; + field(field: string, attributes?: object): void; /** * A parameter to tune the amount of field length normalisation that is applied when @@ -160,9 +165,13 @@ declare namespace lunr { * it should have all fields defined for indexing, though null or undefined values will not * cause errors. * + * Entire documents can be boosted at build time. Applying a boost to a document indicates that + * this document should rank higher in search results than other documents. + * * @param doc - The document to add to the index. + * @param attributes - Optional attributes associated with this document. */ - add(doc: object): void; + add(doc: object, attributes?: object): void; /** * Builds the index, creating an instance of lunr.Index. diff --git a/types/lunr/lunr-tests.ts b/types/lunr/lunr-tests.ts index ade45cae64..a14fd1947f 100644 --- a/types/lunr/lunr-tests.ts +++ b/types/lunr/lunr-tests.ts @@ -4,11 +4,18 @@ function basic_test() { const index = lunr(function() { this.field("title"); this.field("body"); + this.field("content", { + boost: 2, + extractor: (doc: object) => "oof" + }); this.ref("id"); this.add({ id: 1, title: "Foo", body: "Foo foo foo!" + }, + { + boost: 2 }); this.add({ id: 2, diff --git a/types/mailgun-js/index.d.ts b/types/mailgun-js/index.d.ts index 0c6ef0eef3..7c6284059e 100644 --- a/types/mailgun-js/index.d.ts +++ b/types/mailgun-js/index.d.ts @@ -50,6 +50,8 @@ declare namespace Mailgun { getType(): string; } + type AttachmentData = string | Buffer | NodeJS.ReadWriteStream | Attachment; + interface MailgunExport { new (options: ConstructorParams): Mailgun; (options: ConstructorParams): Mailgun; @@ -64,7 +66,8 @@ declare namespace Mailgun { subject?: string; text?: string; html?: string; - attachment?: string | Buffer | NodeJS.ReadWriteStream | Attachment; + attachment?: AttachmentData | ReadonlyArray; + inline?: AttachmentData | ReadonlyArray; } interface BatchData extends SendData { diff --git a/types/mailgun-js/mailgun-js-tests.ts b/types/mailgun-js/mailgun-js-tests.ts index e06e683248..0d830308d1 100644 --- a/types/mailgun-js/mailgun-js-tests.ts +++ b/types/mailgun-js/mailgun-js-tests.ts @@ -25,7 +25,15 @@ const exampleSendData: mailgunFactory.messages.SendData = { attachment: new mailgun.Attachment({ data: "filepath", filename: "my_custom_name.png" - }) + }), + inline: [ + new mailgun.Attachment({ + data: "filepath", + filename: "my_custom_name_2.png" + }), + "my_custom_file_3.png", + Buffer.from("plain text") + ] }; mailgun.messages().send(exampleSendData, (err, body) => {}); diff --git a/types/mapbox-gl/index.d.ts b/types/mapbox-gl/index.d.ts index 91fb68cd96..149d433a89 100644 --- a/types/mapbox-gl/index.d.ts +++ b/types/mapbox-gl/index.d.ts @@ -232,7 +232,7 @@ declare namespace mapboxgl { /** * The max number of pixels a user can shift the mouse pointer during a click for it to be * considered a valid click (as opposed to a mouse drag). - * + * * @default 3 */ clickTolerance?: number; @@ -242,7 +242,7 @@ declare namespace mapboxgl { * and Vector Tile web workers (this information is normally inaccessible from the main * Javascript thread). Information will be returned in a `resourceTiming` property of * relevant `data` events. - * + * * @default false */ collectResourceTiming?: boolean; @@ -250,7 +250,7 @@ declare namespace mapboxgl { /** * If `true`, symbols from multiple sources can collide with each other during collision * detection. If `false`, collision detection is run separately for the symbols in each source. - * + * * @default true */ crossSourceCollisions?: boolean; @@ -278,7 +278,7 @@ declare namespace mapboxgl { * Controls the duration of the fade-in/fade-out animation for label collisions, in milliseconds. * This setting affects all symbol layers. This setting does not affect the duration of runtime * styling transitions or raster tile cross-fading. - * + * * @default 300 */ fadeDuration?: number; @@ -297,14 +297,14 @@ declare namespace mapboxgl { * 'CJK Unified Ideographs' and 'Hangul Syllables' ranges. In these ranges, font settings from * the map's style will be ignored, except for font-weight keywords (light/regular/medium/bold). * The purpose of this option is to avoid bandwidth-intensive glyph server requests. - * + * * @default null */ localIdeographFontFamily?: string; /** * A string representing the position of the Mapbox wordmark on the map. - * + * * @default "bottom-left" */ logoPosition?: 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right'; @@ -324,14 +324,14 @@ declare namespace mapboxgl { /** * The initial pitch (tilt) of the map, measured in degrees away from the plane of the * screen (0-60). - * + * * @default 0 */ pitch?: number; /** * If `false`, the map's pitch (tilt) control with "drag to rotate" interaction will be disabled. - * + * * @default true */ pitchWithRotate?: boolean; @@ -339,14 +339,14 @@ declare namespace mapboxgl { /** * If `false`, the map won't attempt to re-request tiles once they expire per their HTTP * `cacheControl`/`expires` headers. - * + * * @default true */ refreshExpiredTiles?: boolean; /** * If `true`, multiple copies of the world will be rendered, when zoomed out. - * + * * @default true */ renderWorldCopies?: boolean; @@ -363,7 +363,7 @@ declare namespace mapboxgl { /** * A callback run before the Map makes a request for an external URL. The callback can be * used to modify the url, set headers, or set the credentials property for cross-origin requests. - * + * * @default null */ transformRequest?: TransformRequestFunction; @@ -377,13 +377,13 @@ declare namespace mapboxgl { /** * The maximum number of tiles stored in the tile cache for a given source. If omitted, the * cache will be dynamically sized based on the current viewport. - * + * * @default null */ maxTileCacheSize?: number; } - export type ResourceType = + export type ResourceType = | 'Unknown' | 'Style' | 'Source' @@ -692,7 +692,7 @@ declare namespace mapboxgl { clusterMaxZoom?: number; lineMetrics?: boolean; - + generateId?: boolean; } @@ -1071,7 +1071,7 @@ declare namespace mapboxgl { export interface MapSourceDataEvent extends MapboxEvent { dataType: 'source'; isSourceLoaded: boolean; - source: Style; + source: Source; sourceId: string; sourceDataType: 'metadata' | 'content'; tile: any; @@ -1319,6 +1319,7 @@ declare namespace mapboxgl { 'fill-extrusion-height-transition'?: Transition; 'fill-extrusion-base'?: number | StyleFunction | Expression; 'fill-extrusion-base-transition'?: Transition; + 'fill-extrusion-vertical-gradient'?: boolean; } export interface LineLayout { @@ -1476,13 +1477,13 @@ declare namespace mapboxgl { } export interface HeatmapPaint { - 'heatmap-radius'?: number | Expression; + 'heatmap-radius'?: number | StyleFunction | Expression; 'heatmap-radius-transition'?: Transition; 'heatmap-weight'?: number | StyleFunction | Expression; - 'heatmap-intensity'?: number | Expression; + 'heatmap-intensity'?: number | StyleFunction | Expression; 'heatmap-intensity-transition'?: Transition; - 'heatmap-color'?: string | Expression; - 'heatmap-opacity'?: number | Expression; + 'heatmap-color'?: string | StyleFunction | Expression; + 'heatmap-opacity'?: number | StyleFunction | Expression; 'heatmap-opacity-transition'?: Transition; } diff --git a/types/mapbox-gl/mapbox-gl-tests.ts b/types/mapbox-gl/mapbox-gl-tests.ts index 422b255900..d119c76bd5 100644 --- a/types/mapbox-gl/mapbox-gl-tests.ts +++ b/types/mapbox-gl/mapbox-gl-tests.ts @@ -465,10 +465,10 @@ expectType(mapboxgl.Point.convert(pointlike)); expectType((url: string) => ({ url })); expectType((url: string, resourceType: mapboxgl.ResourceType) => ({ - url, - credentials: 'same-origin', - headers: { 'Accept-Encoding': 'compress' }, - method: 'POST', + url, + credentials: 'same-origin', + headers: { 'Accept-Encoding': 'compress' }, + method: 'POST', collectResourceTiming: true, })); diff --git a/types/marked/index.d.ts b/types/marked/index.d.ts index d558348db9..7eddfb4919 100644 --- a/types/marked/index.d.ts +++ b/types/marked/index.d.ts @@ -1,8 +1,9 @@ -// Type definitions for Marked 0.4 +// Type definitions for Marked 0.5 // Project: https://github.com/markedjs/marked // Definitions by: William Orr // BendingBender // CrossR +// Mike Wickett // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export as namespace marked; @@ -34,6 +35,15 @@ declare namespace marked { */ function lexer(src: string, options?: MarkedOptions): TokensList; + /** + * @param src String of markdown source to be compiled + * @param links Array of links + * @param options Hash of options + * @return String of compiled HTML + */ + + function inlineLexer(src: string, links: string[], options?: MarkedOptions): string; + /** * Compiles markdown to HTML. * diff --git a/types/match-media-mock/match-media-mock-tests.ts b/types/match-media-mock/match-media-mock-tests.ts index dc35cff40b..25fe411dd1 100644 --- a/types/match-media-mock/match-media-mock-tests.ts +++ b/types/match-media-mock/match-media-mock-tests.ts @@ -7,7 +7,7 @@ matchMediaMock('(max-width: 991px)').matches // false matchMediaMock('(max-width: 1240px)').matches // true const mediaQueryList = matchMediaMock('(max-width: 991px)'); -const listener = (mql: MediaQueryList) => { }; +const listener = function (this: MediaQueryList) { }; mediaQueryList.addListener(listener) mediaQueryList.removeListener(listener) diff --git a/types/matcher/index.d.ts b/types/matcher/index.d.ts new file mode 100644 index 0000000000..08e4e91f8f --- /dev/null +++ b/types/matcher/index.d.ts @@ -0,0 +1,16 @@ +// Type definitions for matcher 1.1 +// Project: https://github.com/sindresorhus/matcher#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = matcher; + +declare function matcher(inputs: string[], patterns: string[], options?: matcher.Options): string[]; + +declare namespace matcher { + function isMatch(input: string, pattern: string, options?: Options): boolean; + + interface Options { + caseSensitive?: boolean; + } +} diff --git a/types/matcher/matcher-tests.ts b/types/matcher/matcher-tests.ts new file mode 100644 index 0000000000..fbadf58e1e --- /dev/null +++ b/types/matcher/matcher-tests.ts @@ -0,0 +1,10 @@ +import matcher = require('matcher'); + +// $ExpectType string[] +matcher(['foo', 'bar', 'moo'], ['*oo', '!foo']); +matcher(['foo', 'bar', 'moo'], ['!*oo']); +matcher(['foo', 'bar', 'moo'], ['!*oo'], { caseSensitive: true }); + +// $ExpectType boolean +matcher.isMatch('unicorn', 'uni*'); +matcher.isMatch('UNICORN', 'UNI*', { caseSensitive: true }); diff --git a/types/matcher/tsconfig.json b/types/matcher/tsconfig.json new file mode 100644 index 0000000000..efa5f37200 --- /dev/null +++ b/types/matcher/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "matcher-tests.ts" + ] +} diff --git a/types/matcher/tslint.json b/types/matcher/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/matcher/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/materialize-css/autoinit.d.ts b/types/materialize-css/autoinit.d.ts new file mode 100644 index 0000000000..c3e9009b1d --- /dev/null +++ b/types/materialize-css/autoinit.d.ts @@ -0,0 +1,6 @@ +declare namespace M { + /** + * Automatically initialize components. + */ + function AutoInit(context?: Element): void; +} diff --git a/types/materialize-css/index.d.ts b/types/materialize-css/index.d.ts index f8502cafb4..3be768a216 100644 --- a/types/materialize-css/index.d.ts +++ b/types/materialize-css/index.d.ts @@ -9,6 +9,7 @@ /// /// +/// /// /// /// diff --git a/types/mathjs/index.d.ts b/types/mathjs/index.d.ts index 6cb49323fa..a8ec6114eb 100644 --- a/types/mathjs/index.d.ts +++ b/types/mathjs/index.d.ts @@ -3,6 +3,7 @@ // Definitions by: Ilya Shestakov , // Andy Patterson , // Brad Besserman +// Pawel Krol // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -2571,6 +2572,23 @@ declare namespace math { * ‘string’, ‘Array’, ‘Date’. */ typeof(x: any): string; + + /** + * Import functions from an object or a module + * To avoid errors when using one of the imported functions extend module like this: + * + * @example + * // imported_math_functions.ts + * declare module 'mathjs' { + * interface MathJsStatic { + * hello(a: number): number; + * } + * } + * + * @param object An object with functions to be imported. + * @param options An object with import options. + */ + import(object: ImportObject | ImportObject[], options: ImportOptions): void; } interface Matrix { @@ -4542,4 +4560,14 @@ declare namespace math { */ typeof(): MathJsChain; } + + interface ImportOptions { + override?: boolean; + silent?: boolean; + wrap?: boolean; + } + + interface ImportObject { + [key: string]: any; + } } diff --git a/types/mathjs/mathjs-tests.ts b/types/mathjs/mathjs-tests.ts index babfa3ff37..0d21be817e 100644 --- a/types/mathjs/mathjs-tests.ts +++ b/types/mathjs/mathjs-tests.ts @@ -1,3 +1,6 @@ +// Import needed for mathjs.import functionality (declaring/extending module) +import * as math from 'mathjs'; + /* Basic usage examples */ @@ -392,3 +395,27 @@ JSON serialization/deserialization const parsed = JSON.parse(stringified, math.json.reviver); parsed.bigNumber === math.bignumber('1.5'); // true } + +/* +Extend functionality with import + */ + +declare module 'mathjs' { + interface MathJsStatic { + testFun(): number; + value: number; + } +} + +{ + const testFun = () => 5; + + math.import({ + testFun, + value: 10 + }, {}); + + math.testFun(); + + const a = math.value * 2; +} diff --git a/types/mcrypt/index.d.ts b/types/mcrypt/index.d.ts new file mode 100644 index 0000000000..945cb88e59 --- /dev/null +++ b/types/mcrypt/index.d.ts @@ -0,0 +1,31 @@ +// Type definitions for mcrypt 0.1 +// Project: https://github.com/tugrul/node-mcrypt +// Definitions by: Alan Plum +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +/// + +export function getAlgorithmNames(): string[]; +export function getModeNames(): string[]; + +export class MCrypt { + constructor(algorithm: string, mode: string); + open(key: string | Buffer, iv?: string | Buffer): void; + encrypt(plaintext: string | Buffer): Buffer; + decrypt(ciphertext: Buffer): Buffer; + generateIv(): Buffer; + validateKeySize(validate: boolean): void; + validateIvSize(validate: boolean): void; + selfTest(): boolean; + isBlockAlgorithmMode(): boolean; + isBlockAlgorithm(): boolean; + isBlockMode(): boolean; + getBlockSize(): number; + getKeySize(): number; + getSupportedKeySizes(): number[]; + getIvSize(): number; + hasIv(): boolean; + getAlgorithmName(): string; + getModeName(): string; +} diff --git a/types/mcrypt/mcrypt-tests.ts b/types/mcrypt/mcrypt-tests.ts new file mode 100644 index 0000000000..66614e08e3 --- /dev/null +++ b/types/mcrypt/mcrypt-tests.ts @@ -0,0 +1,51 @@ +import { getAlgorithmNames, getModeNames, MCrypt } from "mcrypt"; + +let plaintext: Buffer; +let ciphertext: Buffer; + +for (const algo of getAlgorithmNames()) { + console.log(algo.toUpperCase()); +} +for (const mode of getModeNames()) { + console.log(mode.toUpperCase()); +} + +const desEcb = new MCrypt("des", "ecb"); +desEcb.open("madepass"); + +ciphertext = desEcb.encrypt("too many secrets"); +console.log(ciphertext.toString("base64")); + +plaintext = desEcb.decrypt(ciphertext); +console.log(plaintext.toString()); + +const blowfishCfb = new MCrypt("blowfish", "cfb"); +const iv = blowfishCfb.generateIv(); +blowfishCfb.open("somekey", iv); +ciphertext = blowfishCfb.encrypt("sometext"); +console.log(Buffer.concat([iv, ciphertext]).toString("base64")); + +const bfEcb = new MCrypt("blowfish", "ecb"); +bfEcb.validateKeySize(false); +bfEcb.open("typeconfig.sys^_-"); + +const rjCbc = new MCrypt("rijndael-256", "cbc"); +rjCbc.validateIvSize(false); +rjCbc.open("$verysec$retkey$", "foobar"); + +console.log(blowfishCfb.getBlockSize() * 8); +console.log(blowfishCfb.getKeySize() * 8); +console.log(blowfishCfb.getSupportedKeySizes().map(v => v * 8)); +console.log(blowfishCfb.getIvSize() * 8); +console.log(blowfishCfb.getAlgorithmName().toUpperCase()); +console.log(blowfishCfb.getModeName().toUpperCase()); + +function assertBool(value: boolean) { + return value; +} + +assertBool(blowfishCfb.selfTest()); +assertBool(blowfishCfb.isBlockAlgorithmMode()); +assertBool(blowfishCfb.isBlockAlgorithm()); +assertBool(blowfishCfb.isBlockMode()); +assertBool(blowfishCfb.hasIv()); diff --git a/types/mcrypt/tsconfig.json b/types/mcrypt/tsconfig.json new file mode 100644 index 0000000000..1bb1454ce5 --- /dev/null +++ b/types/mcrypt/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "mcrypt-tests.ts"] +} diff --git a/types/mcrypt/tslint.json b/types/mcrypt/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/mcrypt/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/mdast/index.d.ts b/types/mdast/index.d.ts index d7761bd38f..c1fcadec97 100644 --- a/types/mdast/index.d.ts +++ b/types/mdast/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/syntax-tree/mdast // Definitions by: Jun Lu // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.4 +// TypeScript Version: 3.0 import { Parent as UnistParent, Literal as UnistLiteral, Node } from 'unist'; diff --git a/types/mem-fs/index.d.ts b/types/mem-fs/index.d.ts index 4b1d8c4d14..6ab2c43c88 100644 --- a/types/mem-fs/index.d.ts +++ b/types/mem-fs/index.d.ts @@ -10,13 +10,13 @@ import { Transform } from 'stream'; import * as File from 'vinyl'; export interface Store extends EventEmitter { - add: (file: File, content: string) => void; - each: (callback: (file: File, index: number) => void) => void; get: (filepath: string) => File; + add: (file: File) => this; + each: (callback: (file: File, index: number) => void) => this; stream: () => Transform; } -export function create(...args: any[]): Store; +export function create(): Store; export namespace memFs { } diff --git a/types/mem-fs/mem-fs-tests.ts b/types/mem-fs/mem-fs-tests.ts index 9605c65ef7..3b20f30891 100644 --- a/types/mem-fs/mem-fs-tests.ts +++ b/types/mem-fs/mem-fs-tests.ts @@ -3,6 +3,6 @@ import * as fs from 'mem-fs'; const store: fs.Store = fs.create(); const file = store.get('hello'); -store.add(file, 'hahahahah'); - -store.each(file => console.dir(store.get(file.path))); +const file2 = store.add(file) + .each(file => console.dir(store.get(file.path))) + .get('test'); diff --git a/types/memoize-one/index.d.ts b/types/memoize-one/index.d.ts index 71f785e73c..e8ec195875 100644 --- a/types/memoize-one/index.d.ts +++ b/types/memoize-one/index.d.ts @@ -1,9 +1,9 @@ -// Type definitions for memoize-one 3.1 +// Type definitions for memoize-one 4.1 // Project: https://github.com/alexreardon/memoize-one#readme // Definitions by: Karol Majewski , Frank Li // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare function memoizeOne any>(resultFn: T, isEqual?: EqualityFn): T; -export type EqualityFn = (a: any, b: any) => boolean; +export type EqualityFn = (a: any, b: any, index: number) => boolean; export default memoizeOne; diff --git a/types/memoize-one/memoize-one-tests.ts b/types/memoize-one/memoize-one-tests.ts index 4feddf6e57..a9c565b500 100644 --- a/types/memoize-one/memoize-one-tests.ts +++ b/types/memoize-one/memoize-one-tests.ts @@ -3,6 +3,7 @@ import memoizeOne, { EqualityFn } from 'memoize-one'; declare function add(a: number, b: number): number ; declare function lousyEqualityFn(a: any, b: any): boolean; declare function strictEqualityFn(a: T, b: T): boolean; +declare function equalityFnWithIndex(a: T, b: T, index: number): boolean; /** * Accepts a second argument. @@ -10,17 +11,18 @@ declare function strictEqualityFn(a: T, b: T): boolean; memoizeOne(add); // $ExpectType (a: number, b: number) => number memoizeOne(add, lousyEqualityFn); // $ExpectType (a: number, b: number) => number memoizeOne(add, strictEqualityFn); // $ExpectType (a: number, b: number) => number +memoizeOne(add, equalityFnWithIndex); // $ExpectType (a: number, b: number) => number /** - * The second argument can be, but doesn't have to be stritly typed. + * The second argument can be, but doesn't have to be strictly typed. */ memoizeOne(add, (a, b) => a === b); // $ExpectType (a: number, b: number) => number memoizeOne(add, (a: string, b: string) => a === b); // $ExpectType (a: number, b: number) => number /** - * Function passed as the second argument accepts exactly two arguments. + * Function passed as the second argument accepts no more than three arguments. */ -memoizeOne(add, (a: number, b: number, c: number) => a === b || c); // $ExpectError +memoizeOne(add, (a: number, b: number, c: number, d: number) => Boolean(a && b && c && d)); // $ExpectError /** * Function passed as the second argument returns a boolean. diff --git a/types/memoize-one/v3/index.d.ts b/types/memoize-one/v3/index.d.ts new file mode 100644 index 0000000000..71f785e73c --- /dev/null +++ b/types/memoize-one/v3/index.d.ts @@ -0,0 +1,9 @@ +// Type definitions for memoize-one 3.1 +// Project: https://github.com/alexreardon/memoize-one#readme +// Definitions by: Karol Majewski , Frank Li +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare function memoizeOne any>(resultFn: T, isEqual?: EqualityFn): T; +export type EqualityFn = (a: any, b: any) => boolean; + +export default memoizeOne; diff --git a/types/memoize-one/v3/memoize-one-tests.ts b/types/memoize-one/v3/memoize-one-tests.ts new file mode 100644 index 0000000000..f163add16e --- /dev/null +++ b/types/memoize-one/v3/memoize-one-tests.ts @@ -0,0 +1,33 @@ +import memoizeOne, { EqualityFn } from 'memoize-one'; + +declare function add(a: number, b: number): number ; +declare function lousyEqualityFn(a: any, b: any): boolean; +declare function strictEqualityFn(a: T, b: T): boolean; + +/** + * Accepts a second argument. + */ +memoizeOne(add); // $ExpectType (a: number, b: number) => number +memoizeOne(add, lousyEqualityFn); // $ExpectType (a: number, b: number) => number +memoizeOne(add, strictEqualityFn); // $ExpectType (a: number, b: number) => number + +/** + * The second argument can be, but doesn't have to be strictly typed. + */ +memoizeOne(add, (a, b) => a === b); // $ExpectType (a: number, b: number) => number +memoizeOne(add, (a: string, b: string) => a === b); // $ExpectType (a: number, b: number) => number + +/** + * Function passed as the second argument accepts exactly two arguments. + */ +memoizeOne(add, (a: number, b: number, c: number) => a === b || c); // $ExpectError + +/** + * Function passed as the second argument returns a boolean. + */ +memoizeOne(add, (a: string, b: string) => 0); // $ExpectError + +/** + * The `EqualityFn` type is publicly accessible. + */ +const simpleIsEqual: EqualityFn = (x: number, y: number): boolean => (x === y); diff --git a/types/memoize-one/v3/tsconfig.json b/types/memoize-one/v3/tsconfig.json new file mode 100644 index 0000000000..728bd3ee58 --- /dev/null +++ b/types/memoize-one/v3/tsconfig.json @@ -0,0 +1,26 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "types": [], + "paths": { + "memoize-one": [ "memoize-one/v3" ] + }, + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "memoize-one-tests.ts" + ] +} diff --git a/types/memoize-one/v3/tslint.json b/types/memoize-one/v3/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/memoize-one/v3/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/mirrorx/index.d.ts b/types/mirrorx/index.d.ts index 443712c325..e2fa0ee465 100644 --- a/types/mirrorx/index.d.ts +++ b/types/mirrorx/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/mirrorjs/mirror // Definitions by: Aaronphy // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.8 +// TypeScript Version: 3.0 import * as H from 'history'; diff --git a/types/mochaccino/index.d.ts b/types/mochaccino/index.d.ts index 4dbc62b7d9..3d5d9570a8 100644 --- a/types/mochaccino/index.d.ts +++ b/types/mochaccino/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/pawelgalazka/mochaccino#readme // Definitions by: Thomas-P // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 3.0 +// TypeScript Version: 2.8 import * as Sinon from 'sinon'; export interface Expect { not: Expect; diff --git a/types/mockingoose/index.d.ts b/types/mockingoose/index.d.ts new file mode 100644 index 0000000000..a1597bd4e5 --- /dev/null +++ b/types/mockingoose/index.d.ts @@ -0,0 +1,40 @@ +// Type definitions for mockingoose 2.11 +// Project: https://github.com/alonronin/mockingoose#readme +// Definitions by: Hiroshi Ioka +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +type Op = + | 'find' + | 'findOne' + | 'count' + | 'countDocuments' + | 'estimatedDocumentCount' + | 'distinct' + | 'findOneAndUpdate' + | 'findOneAndRemove' + | 'remove' + | 'update' + | 'deleteOne' + | 'deleteMany' + | 'save'; + +declare class Mock { + toReturn(expected: any, op?: Op): this; + reset(op: Op): this; + toJSON(): any; +} + +interface Target { + __mocks: any; + resetAll(): void; + toJSON(): any; +} + +type Proxy = Target & { + [index: string]: Mock; +}; + +declare const mockingoose: Proxy; + +export default mockingoose; diff --git a/types/mockingoose/mockingoose-tests.ts b/types/mockingoose/mockingoose-tests.ts new file mode 100644 index 0000000000..09a00ad274 --- /dev/null +++ b/types/mockingoose/mockingoose-tests.ts @@ -0,0 +1,9 @@ +import mockingoose from 'mockingoose'; + +mockingoose.User + .toReturn({ name: 'name' }) + .toReturn({ name: 'a name too' }, 'findOne') + .toReturn({ name: 'another name' }, 'save') + .reset('find'); + +mockingoose.resetAll(); diff --git a/types/mockingoose/tsconfig.json b/types/mockingoose/tsconfig.json new file mode 100644 index 0000000000..a6f171944a --- /dev/null +++ b/types/mockingoose/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "mockingoose-tests.ts" + ] +} diff --git a/types/mockingoose/tslint.json b/types/mockingoose/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/mockingoose/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/mongodb/index.d.ts b/types/mongodb/index.d.ts index b31a8dd7b9..feb12923aa 100644 --- a/types/mongodb/index.d.ts +++ b/types/mongodb/index.d.ts @@ -19,6 +19,7 @@ // Mikael Lirbank // Hector Ribes // Florian Richter +// Erik Christensen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -44,10 +45,7 @@ export class MongoClient extends EventEmitter { static connect(uri: string, callback: MongoCallback): void; static connect(uri: string, options?: MongoClientOptions): Promise; static connect(uri: string, options: MongoClientOptions, callback: MongoCallback): void; - /** - * @deprecated - * http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html#connect - */ + /** http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html#connect */ connect(): Promise; connect(callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html#close */ @@ -589,7 +587,7 @@ export class Db extends EventEmitter { indexInformation(name: string, options?: { full?: boolean, readPreference?: ReadPreference | string }): Promise; indexInformation(name: string, options: { full?: boolean, readPreference?: ReadPreference | string }, callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#listCollections */ - listCollections(filter?: Object, options?: { batchSize?: number, readPreference?: ReadPreference | string }): CommandCursor; + listCollections(filter?: Object, options?: { nameOnly?: boolean, batchSize?: number, readPreference?: ReadPreference | string, session?: ClientSession }): CommandCursor; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#profilingInfo */ /** @deprecated Query the system.profile collection directly. */ profilingInfo(callback: MongoCallback): void; @@ -679,7 +677,7 @@ export interface CollectionCreateOptions extends CommonOptions { indexOptionDefaults?: object; viewOn?: string; pipeline?: any[]; - collation?: object; + collation?: CollationDocument; } /** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#collection */ @@ -737,7 +735,7 @@ export interface IndexOptions extends CommonOptions { * Creates a partial index based on the given filter object (MongoDB 3.2 or higher) */ partialFilterExpression?: any; - collation?: Object; + collation?: CollationDocument; default_language?: string } @@ -839,9 +837,9 @@ export interface Collection { createIndex(fieldOrSpec: string | any, options?: IndexOptions): Promise; createIndex(fieldOrSpec: string | any, options: IndexOptions, callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#createIndexes and http://docs.mongodb.org/manual/reference/command/createIndexes/ */ - createIndexes(indexSpecs: Object[], callback: MongoCallback): void; - createIndexes(indexSpecs: Object[], options?: { session?: ClientSession }): Promise; - createIndexes(indexSpecs: Object[], options: { session?: ClientSession }, callback: MongoCallback): void; + createIndexes(indexSpecs: IndexSpecification[], callback: MongoCallback): void; + createIndexes(indexSpecs: IndexSpecification[], options?: { session?: ClientSession }): Promise; + createIndexes(indexSpecs: IndexSpecification[], options: { session?: ClientSession }, callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#deleteMany */ deleteMany(filter: FilterQuery, callback: MongoCallback): void; deleteMany(filter: FilterQuery, options?: CommonOptions): Promise; @@ -888,9 +886,9 @@ export interface Collection { findOneAndReplace(filter: FilterQuery, replacement: Object, options?: FindOneAndReplaceOption): Promise>; findOneAndReplace(filter: FilterQuery, replacement: Object, options: FindOneAndReplaceOption, callback: MongoCallback>): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#findOneAndUpdate */ - findOneAndUpdate(filter: FilterQuery, update: Object, callback: MongoCallback>): void; - findOneAndUpdate(filter: FilterQuery, update: Object, options?: FindOneAndUpdateOption): Promise>; - findOneAndUpdate(filter: FilterQuery, update: Object, options: FindOneAndUpdateOption, callback: MongoCallback>): void; + findOneAndUpdate(filter: FilterQuery, update: UpdateQuery | TSchema, callback: MongoCallback>): void; + findOneAndUpdate(filter: FilterQuery, update: UpdateQuery | TSchema, options?: FindOneAndUpdateOption): Promise>; + findOneAndUpdate(filter: FilterQuery, update: UpdateQuery | TSchema, options: FindOneAndUpdateOption, callback: MongoCallback>): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#geoHaystackSearch */ geoHaystackSearch(x: number, y: number, callback: MongoCallback): void; geoHaystackSearch(x: number, y: number, options?: GeoHaystackSearchOptions): Promise; @@ -1294,11 +1292,12 @@ export interface CollectionAggregationOptions { * Allow driver to bypass schema validation in MongoDB 3.2 or higher. */ bypassDocumentValidation?: boolean; + hint?: string | object; raw?: boolean; promoteLongs?: boolean; promoteValues?: boolean; promoteBuffers?: boolean; - collation?: Object; + collation?: CollationDocument; comment?: string session?: ClientSession; @@ -1560,7 +1559,7 @@ export interface FindOneOptions { readPreference?: ReadPreference | string; partial?: boolean; maxTimeMs?: number; - collation?: Object; + collation?: CollationDocument; session?: ClientSession; } @@ -1681,7 +1680,7 @@ export class Cursor extends Readable { close(): Promise; close(callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#collation */ - collation(value: Object): Cursor; + collation(value: CollationDocument): Cursor; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#comment */ comment(value: string): Cursor; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#count */ @@ -1827,24 +1826,30 @@ export class AggregationCursor extends Readable { unwind(field: string): AggregationCursor; } +/** http://mongodb.github.io/node-mongodb-native/3.1/api/CommandCursor.html#~resultCallback */ +export type CommandCursorResult = any | void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/CommandCursor.html */ export class CommandCursor extends Readable { + /** http://mongodb.github.io/node-mongodb-native/3.1/api/CommandCursor.html#hasNext */ + hasNext(): Promise; + /** http://mongodb.github.io/node-mongodb-native/3.1/api/CommandCursor.html#hasNext */ + hasNext(callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/CommandCursor.html#batchSize */ batchSize(value: number): CommandCursor; /** http://mongodb.github.io/node-mongodb-native/3.1/api/CommandCursor.html#clone */ clone(): CommandCursor; /** http://mongodb.github.io/node-mongodb-native/3.1/api/CommandCursor.html#close */ - close(): Promise; - close(callback: MongoCallback): void; + close(): Promise; + close(callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/CommandCursor.html#each */ - each(callback: MongoCallback): void; + each(callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/CommandCursor.html#isClosed */ isClosed(): boolean; /** http://mongodb.github.io/node-mongodb-native/3.1/api/CommandCursor.html#maxTimeMS */ maxTimeMS(value: number): CommandCursor; /** http://mongodb.github.io/node-mongodb-native/3.1/api/CommandCursor.html#next */ - next(): Promise; - next(callback: MongoCallback): void; + next(): Promise; + next(callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/CommandCursor.html#read */ read(size: number): string | Buffer | void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/CommandCursor.html#rewind */ @@ -1986,7 +1991,7 @@ export interface ChangeStreamOptions { maxAwaitTimeMS?: number; resumeAfter?: Object; batchSize?: number; - collation?: Object; + collation?: CollationDocument; readPreference?: ReadPreference; } @@ -2067,3 +2072,39 @@ export class Logger { */ static setLevel(level: string): void } + +/** https://docs.mongodb.com/manual/reference/collation/#collation-document-fields */ +export interface CollationDocument { + locale: string; + strength?: number; + caseLevel?: boolean; + caseFirst?: string; + numericOrdering?: boolean; + alternate?: string; + maxVariable?: string; + backwards?: boolean; + normalization?: boolean; + +} + +/** https://docs.mongodb.com/manual/reference/command/createIndexes/ */ +export interface IndexSpecification { + key: object; + name?: string; + background?: boolean; + unique?: boolean; + partialFilterExpression?: object; + sparse?: boolean; + expireAfterSeconds?: number; + storageEngine?: object; + weights?: object; + default_language?: string; + language_override?: string; + textIndexVersion?: number; + '2dsphereIndexVersion'?: number; + bits?: number; + min?: number; + max?: number; + bucketSize?: number; + collation?: CollationDocument; +} diff --git a/types/mongoose/index.d.ts b/types/mongoose/index.d.ts index 3672b75b8f..87ce57f05c 100644 --- a/types/mongoose/index.d.ts +++ b/types/mongoose/index.d.ts @@ -280,6 +280,16 @@ declare module "mongoose" { collection?: string ): U; + /** + * Removes the model named `name` from this connection, if it exists. You can + * use this function to clean up any models you created in your tests to + * prevent OverwriteModelErrors. + * + * @param name if string, the name of the model to remove. If regexp, removes all models whose name matches the regexp. + * @returns this + */ + deleteModel(name: string | RegExp): Connection; + /** Returns an array of model names created on this connection. */ modelNames(): string[]; @@ -414,6 +424,7 @@ declare module "mongoose" { */ autoIndex?: boolean; }; + autoIndex?: boolean; } /** See the node-mongodb-native driver instance for options that it understands. */ @@ -511,7 +522,7 @@ declare module "mongoose" { /** * section error/notFound.js * https://mongoosejs.com/docs/api.html#mongooseerror_MongooseError.DocumentNotFoundError - * + * * An instance of this error class will be returned when `save()` fails * because the underlying * document was not found. The constructor takes one parameter, the @@ -524,7 +535,7 @@ declare module "mongoose" { /** * section error/cast.js * https://mongoosejs.com/docs/api.html#mongooseerror_MongooseError.CastError - * + * * An instance of this error class will be returned when mongoose failed to * cast a value. */ @@ -544,7 +555,7 @@ declare module "mongoose" { /** * section error/validation.js * https://mongoosejs.com/docs/api.html#mongooseerror_MongooseError.ValidationError - * + * * An instance of this error class will be returned when [validation](http://mongoosejs.com/docs/validation.html) failed. */ export class ValidationError extends Error { @@ -565,7 +576,7 @@ declare module "mongoose" { /** * section error/validator.js * https://mongoosejs.com/docs/api.html#mongooseerror_MongooseError.ValidatorError - * + * * A `ValidationError` has a hash of `errors` that contain individual `ValidatorError` instances */ export class ValidatorError extends Error { @@ -585,7 +596,7 @@ declare module "mongoose" { /** * section error/version.js * https://mongoosejs.com/docs/api.html#mongooseerror_MongooseError.VersionError - * + * * An instance of this error class will be returned when you call `save()` after * the document in the database was changed in a potentially unsafe way. See * the [`versionKey` option](http://mongoosejs.com/docs/guide.html#versionKey) for more information. @@ -600,7 +611,7 @@ declare module "mongoose" { /** * section error/parallelSave.js * https://mongoosejs.com/docs/api.html#mongooseerror_MongooseError.ParallelSaveError - * + * * An instance of this error class will be returned when you call `save()` multiple * times on the same document in parallel. See the [FAQ](http://mongoosejs.com/docs/faq.html) for more * information. @@ -612,7 +623,7 @@ declare module "mongoose" { /** * section error/overwriteModel.js * https://mongoosejs.com/docs/api.html#mongooseerror_MongooseError.OverwriteModelError - * + * * Thrown when a model with the given name was already registered on the connection. * See [the FAQ about `OverwriteModelError`](http://mongoosejs.com/docs/faq.html#overwrite-model-error). */ @@ -623,7 +634,7 @@ declare module "mongoose" { /** * section error/missingSchema.js * https://mongoosejs.com/docs/api.html#mongooseerror_MongooseError.MissingSchemaError - * + * * Thrown when you try to access a model that has not been registered yet */ export class MissingSchemaError extends Error { @@ -633,7 +644,7 @@ declare module "mongoose" { /** * section error/divergentArray.js * https://mongoosejs.com/docs/api.html#mongooseerror_MongooseError.DivergentArrayError - * + * * An instance of this error will be returned if you used an array projection * and then modified the array in an unsafe way. */ @@ -2011,6 +2022,30 @@ declare module "mongoose" { */ or(array: any[]): this; + /** + * Make this query throw an error if no documents match the given `filter`. + * This is handy for integrating with async/await, because `orFail()` saves you + * an extra `if` statement to check if no document was found. + * + * Example: + * + * // Throws if no doc returned + * await Model.findOne({ foo: 'bar' }).orFail(); + * + * // Throws if no document was updated + * await Model.updateOne({ foo: 'bar' }, { name: 'test' }).orFail(); + * + * // Throws "No docs found!" error if no docs match `{ foo: 'bar' }` + * await Model.find({ foo: 'bar' }).orFail(new Error('No docs found!')); + * + * // Throws "Not found" error if no document was found + * await Model.findOneAndUpdate({ foo: 'bar' }, { name: 'test' }). + * orFail(() => Error('Not found')); + * + * @param err optional error to throw if no docs match `filter` + */ + orFail(err?: Error | (() => Error)): this; + /** Specifies a $polygon condition */ polygon(...coordinatePairs: number[][]): this; polygon(path: string, ...coordinatePairs: number[][]): this; diff --git a/types/mongoose/mongoose-tests.ts b/types/mongoose/mongoose-tests.ts index f713ba8538..7d23e6be6b 100644 --- a/types/mongoose/mongoose-tests.ts +++ b/types/mongoose/mongoose-tests.ts @@ -27,7 +27,8 @@ const connection2: Promise = mongoose.connect(connectUri, { bufferCommands: false, useNewUrlParser: true, useFindAndModify: true, - useCreateIndex: true + useCreateIndex: true, + autoIndex: true }); const connection3: null = mongoose.connect(connectUri, function (error) { error.stack; @@ -145,6 +146,7 @@ conn1.close(function (err) {}); conn1.close(true, function (err) {}); conn1.collection('name').$format(999); conn1.model('myModel', new mongoose.Schema({}), 'myCol').find(); +conn1.deleteModel('myModel'); conn1.models.myModel.findOne().exec(); interface IStatics { staticMethod1: (a: number) => string; @@ -1079,6 +1081,7 @@ query.find().where('age').in([20, 21]); query.find().in('age', [20, 21]); query.nor([{ color: 'green' }, { status: 'ok' }]).nor([]); query.or([{ color: 'red' }, { status: 'emergency' }]).or([]); +query.find({ color: 'blue' }).orFail(); query.where('loc').within().polygon([10,20], [13, 25], [7,15]); query.polygon('loc', [10,20], [13, 25], [7,15]); query.findOne().populate('owner').exec(function (err, kitten) { diff --git a/types/mongoose/v4/index.d.ts b/types/mongoose/v4/index.d.ts index ee3cd4c045..d8a9feb085 100644 --- a/types/mongoose/v4/index.d.ts +++ b/types/mongoose/v4/index.d.ts @@ -329,6 +329,16 @@ declare module "mongoose" { collection?: string ): U; + /** + * Removes the model named `name` from this connection, if it exists. You can + * use this function to clean up any models you created in your tests to + * prevent OverwriteModelErrors. + * + * @param name if string, the name of the model to remove. If regexp, removes all models whose name matches the regexp. + * @returns this + */ + deleteModel(name: string | RegExp): Connection; + /** Returns an array of model names created on this connection. */ modelNames(): string[]; diff --git a/types/mongoose/v4/mongoose-tests.ts b/types/mongoose/v4/mongoose-tests.ts index b2d2a834fd..633d3438a8 100644 --- a/types/mongoose/v4/mongoose-tests.ts +++ b/types/mongoose/v4/mongoose-tests.ts @@ -133,6 +133,7 @@ conn1.openSet('mongodb://localhost/test', 'db', { conn1.close().catch(function (err) {}); conn1.collection('name').$format(999); conn1.model('myModel', new mongoose.Schema({}), 'myCol').find(); +conn1.deleteModel('myModel'); interface IStatics { staticMethod1: (a: number) => string; } diff --git a/types/multi-progress/index.d.ts b/types/multi-progress/index.d.ts new file mode 100644 index 0000000000..31dd11b710 --- /dev/null +++ b/types/multi-progress/index.d.ts @@ -0,0 +1,48 @@ +// Type definitions for multi-progress 2.0 +// Project: https://github.com/pitaj/multi-progress +// Definitions by: David Brett +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import * as ProgressBar from 'progress'; +import { Stream } from 'stream'; + +export as namespace MultiProgress; + +export = MultiProgress; + +declare class MultiProgress { + /** + * Create a new @see MultiProgress with the given stream, or stderr by default + * @param stream A stream to write the progress bars to + */ + constructor(stream?: Stream) + + /** + * Add a new bar + */ + newBar: (format: string, options: ProgressBar.ProgressBarOptions) => ProgressBar; + + /** + * Close all bars + */ + terminate: () => void; + + /** + * Render the given progress bar + */ + move: (index: number) => void; + + /** + * Move the bar indicated by index forward the number of steps indicated by value + */ + tick: (index: number, value: number, options?: any) => void; + + /** + * Update the bar indicated by index to the value given + */ + update: (index: number, value: number, options?: any) => void; +} + +declare namespace MultiProgress {} diff --git a/types/multi-progress/multi-progress-tests.ts b/types/multi-progress/multi-progress-tests.ts new file mode 100644 index 0000000000..b14806b7c5 --- /dev/null +++ b/types/multi-progress/multi-progress-tests.ts @@ -0,0 +1,18 @@ +/** + * Example from https://github.com/pitaj/multi-progress + */ + +// require the library +import * as MultiProgress from 'multi-progress'; + +// spawn an instance with the optional stream to write to +// use of `new` is optional +const multi = new MultiProgress(process.stderr); + +// create a progress bar +const bar = multi.newBar(' downloading [:bar] :percent :etas', { + complete: '=', + incomplete: ' ', + width: 30, + total: 20 +}); diff --git a/types/multi-progress/tsconfig.json b/types/multi-progress/tsconfig.json new file mode 100644 index 0000000000..3f0dc36371 --- /dev/null +++ b/types/multi-progress/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "multi-progress-tests.ts" + ] +} \ No newline at end of file diff --git a/types/multi-progress/tslint.json b/types/multi-progress/tslint.json new file mode 100644 index 0000000000..1a60b8a5dd --- /dev/null +++ b/types/multi-progress/tslint.json @@ -0,0 +1,4 @@ +{ + "extends": "dtslint/dt.json", + "rules": { } +} diff --git a/types/netease-captcha/index.d.ts b/types/netease-captcha/index.d.ts new file mode 100644 index 0000000000..fbdfb03e7d --- /dev/null +++ b/types/netease-captcha/index.d.ts @@ -0,0 +1,73 @@ +// Type definitions for netease-captcha 2.1 +// Project: https://cstaticdun.126.net/load.min.js +// Definitions by: Minjie Shen +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +interface Window { + initNECaptcha?: NeteaseCaptcha.InitFunction; +} + +declare namespace NeteaseCaptcha { + type InitFunction = (config: Config, onLoad?: onLoad, onError?: onError) => void; + + interface Config { + /** + * Verification code id + */ + captchaId: string; + + /** + * Selector string or HTMLElement to render widget into + */ + element: string | HTMLElement; + + /** + * Defaults to 'float' on desktop, and 'popup' on mobile + */ + mode?: 'float' | 'embed' | 'popup'; + + /** + * Defaults to page protocol + */ + protocol?: 'http' | 'https'; + + /** + * Defaults to 'auto' + */ + width?: number | string; + + /** + * Defaults to 'zh-CN' + */ + lang?: 'zh-CN' | 'en'; + + onReady?(instance: Instance): void; + + onVerify?(error: any, data: Data): void; + } + + interface Instance { + /** + * Refresh the instance to get new verification information + */ + refresh(): void; + + /** + * Destroy the current instance + */ + destroy(): void; + + /** + * Available when the mode is set to 'popup' - opens the popup to accept verification + */ + popUp?(): void; + } + + interface Data { + validate: string; + } + + type onLoad = (instance: Instance) => void; + + type onError = (error: any) => void; +} diff --git a/types/netease-captcha/netease-captcha-tests.ts b/types/netease-captcha/netease-captcha-tests.ts new file mode 100644 index 0000000000..ee73302cc1 --- /dev/null +++ b/types/netease-captcha/netease-captcha-tests.ts @@ -0,0 +1,23 @@ +const config: NeteaseCaptcha.Config = { + captchaId: 'FAKE ID', + element: '#captcha', + mode: 'popup', + protocol: 'https', + width: '200px', + lang: 'en', + onVerify: (error: any, data?: NeteaseCaptcha.Data) => { + console.log(error, data); + } + }; + +const onLoad: NeteaseCaptcha.onLoad = (instance: NeteaseCaptcha.Instance) => { + instance.refresh(); + instance.destroy(); + if (instance.popUp) { + instance.popUp(); + } +}; + +if (window.initNECaptcha) { + window.initNECaptcha(config, onLoad); +} diff --git a/types/netease-captcha/tsconfig.json b/types/netease-captcha/tsconfig.json new file mode 100644 index 0000000000..11afad945f --- /dev/null +++ b/types/netease-captcha/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6", "dom"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "netease-captcha-tests.ts" + ] +} diff --git a/types/netease-captcha/tslint.json b/types/netease-captcha/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/netease-captcha/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/next-redux-saga/index.d.ts b/types/next-redux-saga/index.d.ts index b7575fba16..0366868d97 100644 --- a/types/next-redux-saga/index.d.ts +++ b/types/next-redux-saga/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/bmealhouse/next-redux-saga // Definitions by: Leo Cavalcante // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.8 +// TypeScript Version: 3.0 import { ComponentType } from "react"; diff --git a/types/next-redux-wrapper/index.d.ts b/types/next-redux-wrapper/index.d.ts index 16af858743..10fa2d44d1 100644 --- a/types/next-redux-wrapper/index.d.ts +++ b/types/next-redux-wrapper/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Steve // Jungwoo-An // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.8 +// TypeScript Version: 3.0 /// @@ -19,6 +19,8 @@ declare namespace nextReduxWrapper { interface Options { storeKey?: string; debug?: boolean; + serializeState?: any; + deserializeState?: any; } interface StoreCreatorOptions extends Options { diff --git a/types/ng-cordova/tslint.json b/types/ng-cordova/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/ng-cordova/tslint.json +++ b/types/ng-cordova/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/ng-flow/tslint.json b/types/ng-flow/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/ng-flow/tslint.json +++ b/types/ng-flow/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/ng-grid/tslint.json b/types/ng-grid/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/ng-grid/tslint.json +++ b/types/ng-grid/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/node-forge/index.d.ts b/types/node-forge/index.d.ts index 1a2b028a90..d2fcddc2d9 100644 --- a/types/node-forge/index.d.ts +++ b/types/node-forge/index.d.ts @@ -67,6 +67,8 @@ declare module "node-forge" { function privateKeyFromPem(pem: PEM): PrivateKey; function certificateToPem(cert: Certificate, maxline?: number): PEM; function certificateFromPem(pem: PEM, computeHash?: boolean, strict?: boolean): Certificate; + function createCaStore(): CAStore; + function verifyCertificateChain(caStore: CAStore, chain: Certificate[], customVerifyCallback?: (verified: boolean | string, depth: number, chain: Certificate[]) => boolean): boolean; interface oids { [key: string]: string; @@ -202,7 +204,7 @@ declare module "node-forge" { */ setSubject(attrs: CertificateField[], uniqueId?: string): void; /** - * Sets the subject of this certificate. + * Sets the issuer of this certificate. * * @param attrs the array of subject attributes to use. * @param uniqueId an optional a unique ID to use. @@ -244,6 +246,15 @@ declare module "node-forge" { } + interface CAStore { + addCertificate(cert: Certificate | string): void; + hasCertificate(cert: Certificate | string): boolean; + removeCertificate(cert: Certificate | string): Certificate | null; + listAllCertificates(): pki.Certificate[]; + getIssuer(subject: Certificate): Certificate | null; + getBySubject(subject: string): Certificate | null; + } + function certificateFromAsn1(obj: asn1.Asn1, computeHash?: boolean): Certificate; function decryptRsaPrivateKey(pem: PEM, passphrase?: string): PrivateKey; diff --git a/types/node-forge/node-forge-tests.ts b/types/node-forge/node-forge-tests.ts index a8d352ad1a..62f0718c21 100644 --- a/types/node-forge/node-forge-tests.ts +++ b/types/node-forge/node-forge-tests.ts @@ -203,3 +203,22 @@ if (forge.util.fillString('1', 5) !== '11111') throw Error('forge.util.fillStrin throw Error("rsa signature verification fail"); } } + +{ + const emptyStore = forge.pki.createCaStore(); + + const certificate = forge.pki.createCertificate(); + const pem = forge.pki.certificateToPem(certificate); + + const caStore = forge.pki.createCaStore(); + caStore.addCertificate(certificate); + caStore.removeCertificate(certificate); + + caStore.listAllCertificates(); + + caStore.removeCertificate(certificate); + + forge.pki.verifyCertificateChain(caStore, [certificate], (verified, depth, chain) => { + return true; + }); +} diff --git a/types/node/index.d.ts b/types/node/index.d.ts index f71cd9f6ec..f484e48703 100644 --- a/types/node/index.d.ts +++ b/types/node/index.d.ts @@ -1126,10 +1126,10 @@ declare module "http" { 'access-control-allow-headers'?: string; 'accept-patch'?: string; 'accept-ranges'?: string; - 'authorization'?: string; 'age'?: string; 'allow'?: string; 'alt-svc'?: string; + 'authorization'?: string; 'cache-control'?: string; 'connection'?: string; 'content-disposition'?: string; @@ -1139,14 +1139,24 @@ declare module "http" { 'content-location'?: string; 'content-range'?: string; 'content-type'?: string; + 'cookie'?: string; 'date'?: string; + 'expect'?: string; 'expires'?: string; + 'forwarded'?: string; + 'from'?: string; 'host'?: string; + 'if-match'?: string; + 'if-modified-since'?: string; + 'if-none-match'?: string; + 'if-unmodified-since'?: string; 'last-modified'?: string; 'location'?: string; 'pragma'?: string; 'proxy-authenticate'?: string; + 'proxy-authorization'?: string; 'public-key-pins'?: string; + 'range'?: string; 'referer'?: string; 'retry-after'?: string; 'set-cookie'?: string[]; @@ -1608,6 +1618,131 @@ declare module "cluster" { function eventNames(): string[]; } +declare module "worker_threads" { + import { EventEmitter } from "events"; + import { Readable, Writable } from "stream"; + + const isMainThread: boolean; + const parentPort: null | MessagePort; + const threadId: number; + const workerData: any; + + class MessageChannel { + readonly port1: MessagePort; + readonly port2: MessagePort; + } + + class MessagePort extends EventEmitter { + close(): void; + postMessage(value: any, transferList?: Array): void; + ref(): void; + unref(): void; + start(): void; + + addListener(event: "close", listener: () => void): this; + addListener(event: "message", listener: (value: any) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + + emit(event: "close"): boolean; + emit(event: "message", value: any): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + + on(event: "close", listener: () => void): this; + on(event: "message", listener: (value: any) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + + once(event: "close", listener: () => void): this; + once(event: "message", listener: (value: any) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + + prependListener(event: "close", listener: () => void): this; + prependListener(event: "message", listener: (value: any) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "message", listener: (value: any) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + + removeListener(event: "close", listener: () => void): this; + removeListener(event: "message", listener: (value: any) => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + + off(event: "close", listener: () => void): this; + off(event: "message", listener: (value: any) => void): this; + off(event: string | symbol, listener: (...args: any[]) => void): this; + } + + interface WorkerOptions { + eval?: boolean; + workerData?: any; + stdin?: boolean; + stdout?: boolean; + stderr?: boolean; + } + + class Worker extends EventEmitter { + readonly stdin: Writable | null; + readonly stdout: Readable; + readonly stderr: Readable; + readonly threadId: number; + + constructor(filename: string, options?: WorkerOptions); + + postMessage(value: any, transferList?: Array): void; + ref(): void; + unref(): void; + terminate(callback?: (err: any, exitCode: number) => void): void; + + addListener(event: "error", listener: (err: any) => void): this; + addListener(event: "exit", listener: (exitCode: number) => void): this; + addListener(event: "message", listener: (value: any) => void): this; + addListener(event: "online", listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + + emit(event: "error", err: any): boolean; + emit(event: "exit", exitCode: number): boolean; + emit(event: "message", value: any): boolean; + emit(event: "online"): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + + on(event: "error", listener: (err: any) => void): this; + on(event: "exit", listener: (exitCode: number) => void): this; + on(event: "message", listener: (value: any) => void): this; + on(event: "online", listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + + once(event: "error", listener: (err: any) => void): this; + once(event: "exit", listener: (exitCode: number) => void): this; + once(event: "message", listener: (value: any) => void): this; + once(event: "online", listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + + prependListener(event: "error", listener: (err: any) => void): this; + prependListener(event: "exit", listener: (exitCode: number) => void): this; + prependListener(event: "message", listener: (value: any) => void): this; + prependListener(event: "online", listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + + prependOnceListener(event: "error", listener: (err: any) => void): this; + prependOnceListener(event: "exit", listener: (exitCode: number) => void): this; + prependOnceListener(event: "message", listener: (value: any) => void): this; + prependOnceListener(event: "online", listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + + removeListener(event: "error", listener: (err: any) => void): this; + removeListener(event: "exit", listener: (exitCode: number) => void): this; + removeListener(event: "message", listener: (value: any) => void): this; + removeListener(event: "online", listener: () => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + + off(event: "error", listener: (err: any) => void): this; + off(event: "exit", listener: (exitCode: number) => void): this; + off(event: "message", listener: (value: any) => void): this; + off(event: "online", listener: () => void): this; + off(event: string | symbol, listener: (...args: any[]) => void): this; + } +} + declare module "zlib" { import * as stream from "stream"; @@ -8998,3 +9133,65 @@ declare module "perf_hooks" { const performance: Performance; } + +declare module "trace_events" { + /** + * The `Tracing` object is used to enable or disable tracing for sets of + * categories. Instances are created using the + * `trace_events.createTracing()` method. + * + * When created, the `Tracing` object is disabled. Calling the + * `tracing.enable()` method adds the categories to the set of enabled trace + * event categories. Calling `tracing.disable()` will remove the categories + * from the set of enabled trace event categories. + */ + export interface Tracing { + /** + * A comma-separated list of the trace event categories covered by this + * `Tracing` object. + */ + readonly categories: string; + + /** + * Disables this `Tracing` object. + * + * Only trace event categories _not_ covered by other enabled `Tracing` + * objects and _not_ specified by the `--trace-event-categories` flag + * will be disabled. + */ + disable(): void; + + /** + * Enables this `Tracing` object for the set of categories covered by + * the `Tracing` object. + */ + enable(): void; + + /** + * `true` only if the `Tracing` object has been enabled. + */ + readonly enabled: boolean; + } + + interface CreateTracingOptions { + /** + * An array of trace category names. Values included in the array are + * coerced to a string when possible. An error will be thrown if the + * value cannot be coerced. + */ + categories: string[]; + } + + /** + * Creates and returns a Tracing object for the given set of categories. + */ + export function createTracing(options: CreateTracingOptions): Tracing; + + /** + * Returns a comma-separated list of all currently-enabled trace event + * categories. The current set of enabled trace event categories is + * determined by the union of all currently-enabled `Tracing` objects and + * any categories enabled using the `--trace-event-categories` flag. + */ + export function getEnabledCategories(): string; +} diff --git a/types/node/inspector.d.ts b/types/node/inspector.d.ts index 3a2bb35afe..a9d0f1140a 100644 --- a/types/node/inspector.d.ts +++ b/types/node/inspector.d.ts @@ -1912,6 +1912,90 @@ declare module "inspector" { } } + namespace NodeTracing { + interface TraceConfig { + /** + * Controls how the trace buffer stores data. + */ + recordMode?: string; + /** + * Included category filters. + */ + includedCategories: string[]; + } + + interface StartParameterType { + traceConfig: TraceConfig; + } + + interface GetCategoriesReturnType { + /** + * A list of supported tracing categories. + */ + categories: string[]; + } + + interface DataCollectedEventDataType { + value: Array<{}>; + } + } + + namespace NodeWorker { + type WorkerID = string; + + /** + * Unique identifier of attached debugging session. + */ + type SessionID = string; + + interface WorkerInfo { + workerId: WorkerID; + type: string; + title: string; + url: string; + } + + interface SendMessageToWorkerParameterType { + message: string; + /** + * Identifier of the session. + */ + sessionId: SessionID; + } + + interface EnableParameterType { + /** + * Whether to new workers should be paused until the frontend sends `Runtime.runIfWaitingForDebugger` + * message to run them. + */ + waitForDebuggerOnStart: boolean; + } + + interface AttachedToWorkerEventDataType { + /** + * Identifier assigned to the session used to send/receive messages. + */ + sessionId: SessionID; + workerInfo: WorkerInfo; + waitingForDebugger: boolean; + } + + interface DetachedFromWorkerEventDataType { + /** + * Detached session identifier. + */ + sessionId: SessionID; + } + + interface ReceivedMessageFromWorkerEventDataType { + /** + * Identifier of a session which sends a message. + */ + sessionId: SessionID; + message: string; + } + } + /** * The inspector.Session is used for dispatching messages to the V8 inspector back-end and receiving message responses and notifications. */ @@ -1958,6 +2042,7 @@ declare module "inspector" { * `messageAdded` notification. */ post(method: "Console.enable", callback?: (err: Error | null) => void): void; + /** * Continues execution until specific location is reached. */ @@ -2155,6 +2240,7 @@ declare module "inspector" { * Steps over the statement. */ post(method: "Debugger.stepOver", callback?: (err: Error | null) => void): void; + /** * Enables console to refer to the node with given id via $x (see Command Line API for more details * $x functions). @@ -2193,6 +2279,7 @@ declare module "inspector" { post(method: "HeapProfiler.takeHeapSnapshot", params?: HeapProfiler.TakeHeapSnapshotParameterType, callback?: (err: Error | null) => void): void; post(method: "HeapProfiler.takeHeapSnapshot", callback?: (err: Error | null) => void): void; + post(method: "Profiler.disable", callback?: (err: Error | null) => void): void; post(method: "Profiler.enable", callback?: (err: Error | null) => void): void; @@ -2250,6 +2337,7 @@ declare module "inspector" { * @experimental */ post(method: "Profiler.takeTypeProfile", callback?: (err: Error | null, params: Profiler.TakeTypeProfileReturnType) => void): void; + /** * Add handler to promise with given promise object id. */ @@ -2360,11 +2448,47 @@ declare module "inspector" { * @experimental */ post(method: "Runtime.terminateExecution", callback?: (err: Error | null) => void): void; + /** * Returns supported domains. */ post(method: "Schema.getDomains", callback?: (err: Error | null, params: Schema.GetDomainsReturnType) => void): void; + /** + * Gets supported tracing categories. + */ + post(method: "NodeTracing.getCategories", callback?: (err: Error | null, params: NodeTracing.GetCategoriesReturnType) => void): void; + + /** + * Start trace events collection. + */ + post(method: "NodeTracing.start", params?: NodeTracing.StartParameterType, callback?: (err: Error | null) => void): void; + post(method: "NodeTracing.start", callback?: (err: Error | null) => void): void; + + /** + * Stop trace events collection. Remaining collected events will be sent as a sequence of + * dataCollected events followed by tracingComplete event. + */ + post(method: "NodeTracing.stop", callback?: (err: Error | null) => void): void; + + /** + * Sends protocol message over session with given id. + */ + post(method: "NodeWorker.sendMessageToWorker", params?: NodeWorker.SendMessageToWorkerParameterType, callback?: (err: Error | null) => void): void; + post(method: "NodeWorker.sendMessageToWorker", callback?: (err: Error | null) => void): void; + + /** + * Instructs the inspector to attach to running workers. Will also attach to new workers + * as they start + */ + post(method: "NodeWorker.enable", params?: NodeWorker.EnableParameterType, callback?: (err: Error | null) => void): void; + post(method: "NodeWorker.enable", callback?: (err: Error | null) => void): void; + + /** + * Detaches from all running workers and disables attaching to new workers as they are started. + */ + post(method: "NodeWorker.disable", callback?: (err: Error | null) => void): void; + // Events addListener(event: string, listener: (...args: any[]) => void): this; @@ -2464,6 +2588,33 @@ declare module "inspector" { */ addListener(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + addListener(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; + + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + addListener(event: "NodeTracing.tracingComplete", listener: () => void): this; + + /** + * Issued when attached to a worker. + */ + addListener(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when detached from the worker. + */ + addListener(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; + + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + addListener(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; emit(event: "inspectorNotification", message: InspectorNotification<{}>): boolean; emit(event: "Console.messageAdded", message: InspectorNotification): boolean; @@ -2486,6 +2637,11 @@ declare module "inspector" { emit(event: "Runtime.executionContextDestroyed", message: InspectorNotification): boolean; emit(event: "Runtime.executionContextsCleared"): boolean; emit(event: "Runtime.inspectRequested", message: InspectorNotification): boolean; + emit(event: "NodeTracing.dataCollected", message: InspectorNotification): boolean; + emit(event: "NodeTracing.tracingComplete"): boolean; + emit(event: "NodeWorker.attachedToWorker", message: InspectorNotification): boolean; + emit(event: "NodeWorker.detachedFromWorker", message: InspectorNotification): boolean; + emit(event: "NodeWorker.receivedMessageFromWorker", message: InspectorNotification): boolean; on(event: string, listener: (...args: any[]) => void): this; @@ -2584,6 +2740,33 @@ declare module "inspector" { */ on(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + on(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; + + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + on(event: "NodeTracing.tracingComplete", listener: () => void): this; + + /** + * Issued when attached to a worker. + */ + on(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when detached from the worker. + */ + on(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; + + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + on(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; + once(event: string, listener: (...args: any[]) => void): this; /** @@ -2681,6 +2864,33 @@ declare module "inspector" { */ once(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + once(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; + + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + once(event: "NodeTracing.tracingComplete", listener: () => void): this; + + /** + * Issued when attached to a worker. + */ + once(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when detached from the worker. + */ + once(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; + + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + once(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; /** @@ -2778,6 +2988,33 @@ declare module "inspector" { */ prependListener(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + prependListener(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; + + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + prependListener(event: "NodeTracing.tracingComplete", listener: () => void): this; + + /** + * Issued when attached to a worker. + */ + prependListener(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when detached from the worker. + */ + prependListener(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; + + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + prependListener(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; /** @@ -2874,6 +3111,33 @@ declare module "inspector" { * call). */ prependOnceListener(event: "Runtime.inspectRequested", listener: (message: InspectorNotification) => void): this; + + /** + * Contains an bucket of collected trace events. + */ + prependOnceListener(event: "NodeTracing.dataCollected", listener: (message: InspectorNotification) => void): this; + + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + prependOnceListener(event: "NodeTracing.tracingComplete", listener: () => void): this; + + /** + * Issued when attached to a worker. + */ + prependOnceListener(event: "NodeWorker.attachedToWorker", listener: (message: InspectorNotification) => void): this; + + /** + * Issued when detached from the worker. + */ + prependOnceListener(event: "NodeWorker.detachedFromWorker", listener: (message: InspectorNotification) => void): this; + + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + prependOnceListener(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; } // Top Level API diff --git a/types/node/node-tests.ts b/types/node/node-tests.ts index c0f80728fc..e2e24dad68 100644 --- a/types/node/node-tests.ts +++ b/types/node/node-tests.ts @@ -17,6 +17,7 @@ import * as path from "path"; import * as readline from "readline"; import * as childProcess from "child_process"; import * as cluster from "cluster"; +import * as workerThreads from "worker_threads"; import * as os from "os"; import * as vm from "vm"; import * as console2 from "console"; @@ -30,6 +31,7 @@ import * as async_hooks from "async_hooks"; import * as http2 from "http2"; import * as inspector from "inspector"; import * as perf_hooks from "perf_hooks"; +import * as trace_events from "trace_events"; import Module = require("module"); // Specifically test buffer module regression. @@ -2932,6 +2934,56 @@ async function asyncStreamPipelineFinished() { } } +////////////////////////////////////////////////////////////////////// +/// worker_threads tests: https://nodejs.org/api/worker_threads.html /// +////////////////////////////////////////////////////////////////////// + +{ + { + if (workerThreads.isMainThread) { + module.exports = async function parseJSAsync(script: string) { + return new Promise((resolve, reject) => { + const worker = new workerThreads.Worker(__filename, { + workerData: script + }); + worker.on('message', resolve); + worker.on('error', reject); + worker.on('exit', (code) => { + if (code !== 0) + reject(new Error(`Worker stopped with exit code ${code}`)); + }); + }); + }; + } else { + const script = workerThreads.workerData; + workerThreads.parentPort.postMessage(script); + } + } + + { + const { port1, port2 } = new workerThreads.MessageChannel(); + port1.on('message', (message) => console.log('received', message)); + port2.postMessage({ foo: 'bar' }); + } + + { + if (workerThreads.isMainThread) { + const worker = new workerThreads.Worker(__filename); + const subChannel = new workerThreads.MessageChannel(); + worker.postMessage({ hereIsYourPort: subChannel.port1 }, [subChannel.port1]); + subChannel.port2.on('message', (value) => { + console.log('received:', value); + }); + } else { + workerThreads.parentPort.once('message', (value) => { + assert(value.hereIsYourPort instanceof MessagePort); + value.hereIsYourPort.postMessage('the worker is sending this'); + value.hereIsYourPort.close(); + }); + } + } +} + //////////////////////////////////////////////////// /// os tests : https://nodejs.org/api/os.html //////////////////////////////////////////////////// @@ -4673,9 +4725,26 @@ import * as constants from 'constants'; const pauseReason: string = message.params.reason; }); session.on('Debugger.resumed', () => {}); + // Node Inspector events + session.on('NodeTracing.dataCollected', (message: inspector.InspectorNotification) => { + const value: Array<{}> = message.params.value; + }); } } +/////////////////////////////////////////////////////////// +/// Trace Events Tests /// +/////////////////////////////////////////////////////////// + +{ + const enabledCategories: string = trace_events.getEnabledCategories(); + const tracing: trace_events.Tracing = trace_events.createTracing({ categories: ['node', 'v8'] }); + const categories: string = tracing.categories; + const enabled: boolean = tracing.enabled; + tracing.enable(); + tracing.disable(); +} + //////////////////////////////////////////////////// /// module tests : http://nodejs.org/api/modules.html //////////////////////////////////////////////////// diff --git a/types/node/scripts/generate-inspector/event-emitter.ts b/types/node/scripts/generate-inspector/event-emitter.ts index 658109d6b2..3d3410633f 100644 --- a/types/node/scripts/generate-inspector/event-emitter.ts +++ b/types/node/scripts/generate-inspector/event-emitter.ts @@ -66,10 +66,11 @@ export const createListeners = (events: Event[]): string[] => { "", ...createListenerBlockFn("prependOnceListener")(events), ].reduce((acc, next, index, arr) => { - // removes trailing and consecutive empty lines + // removes leading, trailing and consecutive empty lines + const isFirst = index === 0; const isLast = index === arr.length - 1; const followsEmptyLine = acc.length > 0 && acc[acc.length - 1] === ""; - if ((isLast || followsEmptyLine) && next === "") { + if ((isFirst || isLast || followsEmptyLine) && next === "") { return acc; } else { acc.push(next); diff --git a/types/node/scripts/generate-inspector/generate-substitute-args.ts b/types/node/scripts/generate-inspector/generate-substitute-args.ts index 0054e9a85c..cd12eff1a8 100644 --- a/types/node/scripts/generate-inspector/generate-substitute-args.ts +++ b/types/node/scripts/generate-inspector/generate-substitute-args.ts @@ -4,17 +4,21 @@ import { capitalize, createDocs, flattenArgs, hasElements, isObjectReference } f const INDENT = " "; +// Turns a type into a type representing an array of that type +const arrify = (typeString: string) => { + return typeString === '{}' ? `Array<${typeString}>` : `${typeString}[]`; +} + // Converts DevTools type to TS type const createTypeString = (type: schema.Field, domain?: string): string => { return isObjectReference(type) ? type.$ref : - type.type === "any" ? "any" : + type.type === "any" ? "any" : type.type === "integer" ? "number" : type.type === "number" ? "number" : type.type === "boolean" ? "boolean" : type.type === "string" ? "string" : - type.type === "array" ? `${createTypeString(type.items, domain)}[]` : - type.type === "object" ? "{}" // this code path is likely never exercised - : "never"; + type.type === "array" ? arrify(createTypeString(type.items, domain)) : + type.type === "object" ? "{}" : "never"; // "never" has yet to be observed }; // Helper for createInterface -- constructs a list of interface fields @@ -138,7 +142,7 @@ export const generateSubstituteArgs = (protocol: schema.Schema): { [propName: st .map(item => item.commands .map(command => createPostFunctions(command, item.domain)) .reduce(flattenArgs(""), [])) - .reduce(flattenArgs(), []); + .reduce(flattenArgs(""), []); const eventOverloads: string[] = createListeners(protocol.domains .map(item => { diff --git a/types/node/scripts/generate-inspector/index.ts b/types/node/scripts/generate-inspector/index.ts index eb5da5ef2e..f555105e37 100644 --- a/types/node/scripts/generate-inspector/index.ts +++ b/types/node/scripts/generate-inspector/index.ts @@ -2,25 +2,55 @@ // [tag] corresponds to a tag name in the node-core repository. import { execSync } from "child_process"; -import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs"; +import { existsSync, readFileSync, writeFileSync } from "fs"; import * as https from "https"; import * as schema from "./devtools-protocol-schema"; import { generateSubstituteArgs } from "./generate-substitute-args"; -import { flattenArgs, substitute, trimRight } from "./utils"; +import { substitute, trimRight } from "./utils"; +import { string } from "parsimmon"; + +const httpsGet = (url: string) => new Promise((resolve, reject) => { + https.get(url, res => { + const frames: Buffer[] = []; + res.on("data", (data: Buffer) => { + frames.push(data); + }); + res.on("end", () => { + resolve(Buffer.concat(frames).toString("utf8")); + }); + res.on("error", (err: Error) => { + reject(err); + }); + }); +}); // Input arguments const tag = process.argv[2] || process.version; -const PROTOCOL_URL = `https://raw.githubusercontent.com/nodejs/node/${tag}/deps/v8/src/inspector/js_protocol.json`; - -const devToolsPath = `${__dirname}/../../node_modules/devtools-protocol`; - -function writeProtocolToFile(json: string) { - const protocol: schema.Schema = JSON.parse(json); +const V8_PROTOCOL_URL = `https://raw.githubusercontent.com/nodejs/node/${tag}/deps/v8/src/inspector/js_protocol.json`; +const NODE_PROTOCOL_URL = `https://raw.githubusercontent.com/nodejs/node/${tag}/src/inspector/node_protocol.pdl`; +const INSPECTOR_PROTOCOL_REMOTE = `https://chromium.googlesource.com/deps/inspector_protocol`; +const INSPECTOR_PROTOCOL_LOCAL_DIR = "/tmp/inspector_protocol"; +/** + * Given a list of Inspector protocol definitions, write an inspector.d.ts + * containing all of those definitions merged together. + * @param jsonProtocols A list of Inspector protocol definitions. + */ +function writeProtocolsToFile(jsonProtocols: string[]) { + const combinedProtocol: schema.Schema = { + version: { major: '', minor: '' }, // doesn't matter + domains: [] + }; + for (const json of jsonProtocols) { + if (json) { + const protocol: schema.Schema = JSON.parse(json); + combinedProtocol.domains.push(...protocol.domains); + } + } + const substituteArgs = generateSubstituteArgs(combinedProtocol); const template = readFileSync(`${__dirname}/inspector.d.ts.template`, "utf8"); - - const substituteArgs = generateSubstituteArgs(protocol); + const inspectorDts = substitute(template, substituteArgs).split("\n") .map(line => trimRight(line)) .join("\n"); @@ -28,12 +58,24 @@ function writeProtocolToFile(json: string) { writeFileSync("./inspector.d.ts", inspectorDts, "utf8"); } -https.get(PROTOCOL_URL, res => { - const frames: Buffer[] = []; - res.on("data", (data: Buffer) => { - frames.push(data); - }); - res.on("end", () => { - writeProtocolToFile(Buffer.concat(frames).toString("utf8")); - }); -}); +/** + * Given a PDL-formatted string, return a JSON-formatted string. + * Note that this function run blocking shell commands, as it depends on an + * external script to do the conversion. + * @param pdl A PDL-formatted string. + */ +function convertPdlToJson(pdl: string): string { + if (!existsSync(INSPECTOR_PROTOCOL_LOCAL_DIR)) { + execSync(`git clone ${INSPECTOR_PROTOCOL_REMOTE} ${INSPECTOR_PROTOCOL_LOCAL_DIR}`); + } + writeFileSync("/tmp/inspector_protocol.pdl", pdl); + execSync(`${INSPECTOR_PROTOCOL_LOCAL_DIR}/convert_protocol_to_json.py /tmp/inspector_protocol.pdl /tmp/inspector_protocol.json`); + return readFileSync("/tmp/inspector_protocol.json", 'utf8'); +} + +// "Main" -- get the V8 built-in inspector protocol definition, as well as the +// Node extensions, and then write this to inspector.d.ts. +Promise.all([ + httpsGet(V8_PROTOCOL_URL), + httpsGet(NODE_PROTOCOL_URL).then(convertPdlToJson).catch(() => '') +]).then(writeProtocolsToFile).catch(console.error); diff --git a/types/oauth2orize/index.d.ts b/types/oauth2orize/index.d.ts index 798030c7d2..b3a62d01e4 100644 --- a/types/oauth2orize/index.d.ts +++ b/types/oauth2orize/index.d.ts @@ -99,6 +99,7 @@ export class OAuth2Server { decision(options: DecisionOptions, parse: DecisionParseFunction): MiddlewareFunction; decision(parse: DecisionParseFunction): MiddlewareFunction; + decision(): MiddlewareFunction; token(options?: any): MiddlewareFunction; diff --git a/types/office-js/index.d.ts b/types/office-js/index.d.ts index 3e7f64375f..b8b06bd1f2 100644 --- a/types/office-js/index.d.ts +++ b/types/office-js/index.d.ts @@ -9421,7 +9421,7 @@ declare namespace Office { } /** - * The InternetHeaders object represents properties that are preserved after the item leaves Exchange and converted to a MIME message. + * The InternetHeaders object represents properties that are preserved after the message item leaves Exchange and is converted to a MIME message. * These properties are stored as x-headers in the MIME message. * * InternetHeaders are stored as key/value pairs on a per-item basis. @@ -15225,7 +15225,7 @@ declare namespace Office { * {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Compose or read * * Item IDs retrieved via EWS or via the itemId property use a different format than the format used by REST APIs (such as the - * {@link https://docs.microsoft.com/previous-versions/office/office-365-api/api/version-2.0/mail-rest-operations | Outlook Mail API} or the {@link http://graph.microsoft.io/ | Microsoft Graph}. + * {@link https://docs.microsoft.com/previous-versions/office/office-365-api/api/version-2.0/mail-rest-operations | Outlook Mail API} or the {@link https://graph.microsoft.io/ | Microsoft Graph}. * The convertToRestId method converts an EWS-formatted ID into the proper format for REST. * * @param itemId An item ID formatted for Exchange Web Services (EWS) diff --git a/types/openapi-factory/index.d.ts b/types/openapi-factory/index.d.ts new file mode 100644 index 0000000000..e41958e6df --- /dev/null +++ b/types/openapi-factory/index.d.ts @@ -0,0 +1,59 @@ +// Type definitions for openapi-factory 4.2 +// Project: https://github.com/wparad/openapi-factory.js +// Definitions by: Daan Boerlage +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +declare namespace OpenApi { + interface ApiOptions { + requestMiddleware?: () => any; + responseMiddleware?: () => any; + errorMiddleware?: () => any; + } + + interface HttpMethodOptions { + rawBody?: boolean; + } + + interface HttpResponse { + statusCode?: number; + headers?: object; + body?: (object | string); + } +} + +declare class OpenApi { + constructor(options: OpenApi.ApiOptions, overrideLogger?: () => void); + + setAuthorizer(authorizerFunc: (req?: any) => Promise): void; + onEvent(onEventFunc: (req?: any) => Promise): void; + onSchedule(onScheduleFunc: (req?: any) => Promise): void; + + head(route: string, handler: (req?: object) => (OpenApi.HttpResponse | Promise)): void; + head(route: string, options: OpenApi.HttpMethodOptions, handler: (req?: any) => any): void; + + get(route: string, handler: (req?: object) => (OpenApi.HttpResponse | Promise)): void; + get(route: string, options: OpenApi.HttpMethodOptions, handler: (req?: object) => (OpenApi.HttpResponse | Promise)): void; + + post(route: string, handler: (req?: object) => (OpenApi.HttpResponse | Promise)): void; + post(route: string, options: OpenApi.HttpMethodOptions, handler: (req?: object) => (OpenApi.HttpResponse | Promise)): void; + + put(route: string, handler: (req?: object) => (OpenApi.HttpResponse | Promise)): void; + put(route: string, options: OpenApi.HttpMethodOptions, handler: (req?: object) => (OpenApi.HttpResponse | Promise)): void; + + patch(route: string, handler: (req?: object) => (OpenApi.HttpResponse | Promise)): void; + patch(route: string, options: OpenApi.HttpMethodOptions, handler: (req?: object) => (OpenApi.HttpResponse | Promise)): void; + + delete(route: string, handler: (req?: object) => (OpenApi.HttpResponse | Promise)): void; + delete(route: string, options: OpenApi.HttpMethodOptions, handler: (req?: object) => (OpenApi.HttpResponse | Promise)): void; + + options(route: string, handler: (req?: object) => (OpenApi.HttpResponse | Promise)): void; + options(route: string, options: OpenApi.HttpMethodOptions, handler: (req?: object) => (OpenApi.HttpResponse | Promise)): void; + + any(route: string, handler: (req?: object) => (OpenApi.HttpResponse | Promise)): void; + any(route: string, options: OpenApi.HttpMethodOptions, handler: (req?: object) => (OpenApi.HttpResponse | Promise)): void; + + handler(event: object, context: object): Promise; +} + +export = OpenApi; diff --git a/types/openapi-factory/openapi-factory-tests.ts b/types/openapi-factory/openapi-factory-tests.ts new file mode 100644 index 0000000000..8213104a44 --- /dev/null +++ b/types/openapi-factory/openapi-factory-tests.ts @@ -0,0 +1,29 @@ +import OpenApiFactory = require('openapi-factory'); + +const api = new OpenApiFactory({}); + +api.setAuthorizer((req: any) => req); +api.onEvent((req: any) => req); +api.onSchedule((req: any) => req); + +const testReponse = { + statusCode: 200 +}; + +api.head('/v1/test', () => testReponse); +api.get('/v1/test', () => testReponse); +api.post('/v1/test', () => testReponse); +api.put('/v1/test', () => testReponse); +api.patch('/v1/test', () => testReponse); +api.delete('/v1/test', () => testReponse); +api.options('/v1/test', () => testReponse); +api.any('/v1/test2', () => testReponse); + +api.head('/v2/test', { rawBody: true }, () => testReponse); +api.get('/v2/test', { rawBody: true }, () => testReponse); +api.post('/v2/test', { rawBody: true }, () => testReponse); +api.put('/v2/test', { rawBody: true }, () => testReponse); +api.patch('/v2/test', { rawBody: true }, () => testReponse); +api.delete('/v2/test', { rawBody: true }, () => testReponse); +api.options('/v2/test', { rawBody: true }, () => testReponse); +api.any('/v2/test2', { rawBody: true }, () => testReponse); diff --git a/types/openapi-factory/tsconfig.json b/types/openapi-factory/tsconfig.json new file mode 100644 index 0000000000..e9035817a2 --- /dev/null +++ b/types/openapi-factory/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "openapi-factory-tests.ts" + ] +} diff --git a/types/openapi-factory/tslint.json b/types/openapi-factory/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/openapi-factory/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/openfin/index.d.ts b/types/openfin/index.d.ts index 55ee5b6741..78b1801b0b 100644 --- a/types/openfin/index.d.ts +++ b/types/openfin/index.d.ts @@ -420,7 +420,7 @@ declare namespace fin { /** * The timeout for displaying a notification.Can be in milliseconds or "never". */ - duration?: number | "never"; + timeout?: number | "never"; /** * The url of the notification */ @@ -804,9 +804,9 @@ declare namespace fin { */ getSnapshot(callback?: (base64Snapshot: string) => void, errorCallback?: (reason: string) => void): void; /** - * Gets the current state ("minimized", "maximized", or "restored") of the window. + * Gets the current state ("minimized", "maximized", or "normal") of the window. */ - getState(callback?: (state: "minimized" | "maximized" | "restored") => void, errorCallback?: (reason: string) => void): void; + getState(callback?: (state: "minimized" | "maximized" | "normal") => void, errorCallback?: (reason: string) => void): void; /** * Returns the zoom level of the window. */ diff --git a/types/openfin/openfin-tests.ts b/types/openfin/openfin-tests.ts index 167a6c86be..e4430ff9c2 100644 --- a/types/openfin/openfin-tests.ts +++ b/types/openfin/openfin-tests.ts @@ -207,7 +207,7 @@ function test_notification() { notification.close(); // sendMessage notification = new fin.desktop.Notification({ - duration: 10, + timeout: 10, url: "http://localhost:5000/Account/Register", message: "Hello", onShow: () => { }, diff --git a/types/openui5/tslint.json b/types/openui5/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/openui5/tslint.json +++ b/types/openui5/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/p-defer/index.d.ts b/types/p-defer/index.d.ts index 7eff607e7d..8386706d89 100644 --- a/types/p-defer/index.d.ts +++ b/types/p-defer/index.d.ts @@ -1,16 +1,17 @@ // Type definitions for p-defer 1.0 // Project: https://github.com/sindresorhus/p-defer // Definitions by: Sam Verschueren +// BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare namespace pDefer { - interface DeferredPromise { - resolve(value?: U | PromiseLike): Promise; - reject(reason: any): Promise; - promise: Promise; - } -} +export = pDefer; declare function pDefer(): pDefer.DeferredPromise; -export = pDefer; +declare namespace pDefer { + interface DeferredPromise { + resolve(value?: T | PromiseLike): void; + reject(reason: any): void; + promise: Promise; + } +} diff --git a/types/p-defer/p-defer-tests.ts b/types/p-defer/p-defer-tests.ts index 9ea4647620..f61bce624b 100644 --- a/types/p-defer/p-defer-tests.ts +++ b/types/p-defer/p-defer-tests.ts @@ -1,13 +1,13 @@ import pDefer = require('p-defer'); -function delay(deferred: pDefer.DeferredPromise, ms: number) { +function delay(deferred: pDefer.DeferredPromise, ms: number) { setTimeout(deferred.resolve, ms, '🦄'); return deferred.promise; } -let s: string; -async function f() { s = await delay(pDefer(), 100); } +const s: Promise = delay(pDefer(), 100); -async function u() { - const u: Promise = pDefer().resolve(); -} +// $ExpectType void +pDefer().resolve(); +// $ExpectType void +pDefer().reject('oh no'); diff --git a/types/paper/index.d.ts b/types/paper/index.d.ts index d3c818b112..5709826f6a 100644 --- a/types/paper/index.d.ts +++ b/types/paper/index.d.ts @@ -4865,7 +4865,7 @@ declare module paper { /** * The current scale factor of the view, as described by its matrix. */ - scaling: number; + scaling: Point; /** * The view’s transformation matrix, defining the view onto the project’s contents (position, zoom level, rotation, etc). diff --git a/types/paper/paper-tests.ts b/types/paper/paper-tests.ts index 165c64b2d8..1d1bc32abe 100644 --- a/types/paper/paper-tests.ts +++ b/types/paper/paper-tests.ts @@ -79,6 +79,8 @@ hitTestResults = paper.project.hitTestAll(hitTestPoint, hitOptionsInterfaceEmpty hitTestResults = paper.project.hitTestAll(hitTestPoint, hitOptionsInterfacePartial); hitTestResults = paper.project.hitTestAll(hitTestPoint, hitOptionsInterfaceFull); +paper.view.scaling = new paper.Point(1, 1); + function Examples() { function BooleanOperations(){ let text = new paper.PointText({ diff --git a/types/passport-bnet/index.d.ts b/types/passport-bnet/index.d.ts new file mode 100644 index 0000000000..e7ffaaedce --- /dev/null +++ b/types/passport-bnet/index.d.ts @@ -0,0 +1,37 @@ +// Type definitions for passport-bnet 2.0 +// Project: https://github.com/Blizzard/passport-bnet#readme +// Definitions by: Ivan Fernandes +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import { Strategy as OAuth2Strategy, VerifyFunction, VerifyFunctionWithRequest, _StrategyOptionsBase } from 'passport-oauth2'; + +declare class BnetStrategy extends OAuth2Strategy { + constructor(options: BnetStrategy.StrategyOptions, verify: VerifyFunction); + constructor(options: BnetStrategy.StrategyOptionsWithRequest, verify: VerifyFunctionWithRequest); +} + +declare namespace BnetStrategy { + // passport--bnet accepts any options that passport-oauth2 accepts, but add the option region and makes authorizationURL and tokenURL optional + interface _BaseBnetOptions extends Partial<_StrategyOptionsBase> { + clientID: string; + clientSecret: string; + + region?: string; + } + + interface StrategyOptions extends _BaseBnetOptions { + passReqToCallback?: false; + } + + interface StrategyOptionsWithRequest extends _BaseBnetOptions { + passReqToCallback: true; + } + + function getHost(region: string): string; + + type Strategy = BnetStrategy; + const Strategy: typeof BnetStrategy; +} + +export = BnetStrategy; diff --git a/types/passport-bnet/passport-bnet-tests.ts b/types/passport-bnet/passport-bnet-tests.ts new file mode 100644 index 0000000000..b02cf40519 --- /dev/null +++ b/types/passport-bnet/passport-bnet-tests.ts @@ -0,0 +1,62 @@ +// Based on passport-oauth2/passport-oauth2-tests.ts + +import BnetStrategy = require("passport-bnet"); +import { Strategy, StrategyOptions, StrategyOptionsWithRequest } from "passport-bnet"; +import { Strategy as OAuth2Strategy, VerifyCallback } from "passport-oauth2"; +import { Request } from "express"; + +const strategyOptions1: StrategyOptions = { + callbackURL: 'http://www.example.com/callback', + clientID: 'dummy', + clientSecret: 'secret', + region: 'us', + scope: "email", + scopeSeparator: ' ', + customHeaders: {} +}; + +function verifyFunction1(_accessToken: string, _refreshToken: string, _profile: any, verifyCallback: VerifyCallback) { + verifyCallback(new Error('unimplemented')); +} + +function verifyFunction2(_accessToken: string, _refreshToken: string, _results: any, _profile: any, verifyCallback: VerifyCallback) { + verifyCallback(new Error('unimplemented')); +} + +const strategy1: BnetStrategy = new BnetStrategy(strategyOptions1, verifyFunction1); + +const strategy2: Strategy = new BnetStrategy(strategyOptions1, verifyFunction2); + +function verifyFunction3(_req: Request, _accessToken: string, _refreshToken: string, _profile: any, verifyCallback: VerifyCallback) { + verifyCallback(undefined, { userid: '1' }); +} + +function verifyFunction4(_req: Request, _accessToken: string, _refreshToken: string, _results: any, _profile: any, verifyCallback: VerifyCallback) { + verifyCallback(undefined, { userid: '1' }); +} + +const strategyOptions2: StrategyOptionsWithRequest = { + authorizationURL: 'http://www.example.com/auth', + callbackURL: 'http://www.example.com/callback', + clientID: 'dummy', + clientSecret: 'secret', + tokenURL: 'http://www.example.com/token', + region: 'us', + scope: "email", + scopeSeparator: ' ', + customHeaders: {}, + passReqToCallback: true +}; + +const strategy3: OAuth2Strategy = new BnetStrategy +(strategyOptions2, verifyFunction3); + +const strategy4: Strategy = new Strategy(strategyOptions2, verifyFunction4); + +class MyStrategy extends BnetStrategy { + useProtectedProperty() { + this._oauth2.get('http://www.example.com/profile', 'token', err => err.statusCode); + this._oauth2.get('http://www.example.com/profile', 'token', (err, result) => result); + this._oauth2.get('http://www.example.com/profile', 'token', (err, result, response) => response); + } +} diff --git a/types/passport-bnet/tsconfig.json b/types/passport-bnet/tsconfig.json new file mode 100644 index 0000000000..28da7a7a65 --- /dev/null +++ b/types/passport-bnet/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "passport-bnet-tests.ts" + ] +} \ No newline at end of file diff --git a/types/passport-bnet/tslint.json b/types/passport-bnet/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/passport-bnet/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/passport-github2/index.d.ts b/types/passport-github2/index.d.ts index 0b2c1f6a5d..4ca8e93124 100644 --- a/types/passport-github2/index.d.ts +++ b/types/passport-github2/index.d.ts @@ -3,12 +3,14 @@ // Definitions by: Yasunori Ohoka // Maarten Mulders // Christoph Werner +// Ivan Fernandes // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 import passport = require('passport'); import oauth2 = require('passport-oauth2'); import express = require('express'); +import { OutgoingHttpHeaders } from 'http'; export interface Profile extends passport.Profile { profileUrl: string; @@ -25,7 +27,7 @@ export interface StrategyOption extends passport.AuthenticateOptions { authorizationURL?: string; tokenURL?: string; scopeSeparator?: string; - customHeaders?: string; + customHeaders?: OutgoingHttpHeaders; userProfileURL?: string; } @@ -46,7 +48,7 @@ export interface _StrategyOptionsBase extends OAuth2StrategyOptionsWithoutRequir authorizationURL?: string; tokenURL?: string; scopeSeparator?: string; - customHeaders?: string; + customHeaders?: OutgoingHttpHeaders; userProfileURL?: string; } diff --git a/types/passport-oauth2/index.d.ts b/types/passport-oauth2/index.d.ts index d985852bd6..28a1a06348 100644 --- a/types/passport-oauth2/index.d.ts +++ b/types/passport-oauth2/index.d.ts @@ -3,12 +3,14 @@ // Definitions by: Pasi Eronen // Wang Zishi // Eduardo AC +// Ivan Fernandes // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 import { Request } from 'express'; import { Strategy } from 'passport'; import { OAuth2 } from 'oauth'; +import { OutgoingHttpHeaders } from 'http'; declare class OAuth2Strategy extends Strategy { name: string; @@ -32,6 +34,23 @@ declare class OAuth2Strategy extends Strategy { } declare namespace OAuth2Strategy { + interface Metadata { + authorizationURL: string; + tokenURL: string; + clientID: string; + } + + type StateStoreStoreCallback = (err: Error | null, state: any) => void; + type StateStoreVerifyCallback = (err: Error, ok: boolean, state: any) => void; + + interface StateStore { + store(req: Request, callback: StateStoreStoreCallback): void; + store(req: Request, meta: Metadata, callback: StateStoreStoreCallback): void; + + verify(req: Request, state: string, callback: StateStoreVerifyCallback): void; + verify(req: Request, state: string, meta: Metadata, callback: StateStoreVerifyCallback): void; + } + type VerifyCallback = (err?: Error | null, user?: object, info?: object) => void; type VerifyFunction = @@ -47,6 +66,12 @@ declare namespace OAuth2Strategy { clientID: string; clientSecret: string; callbackURL?: string; + customHeaders?: OutgoingHttpHeaders; + scope?: string | string[]; + scopeSeparator?: string; + sessionKey?: string; + store?: StateStore; + state?: any; } interface StrategyOptions extends _StrategyOptionsBase { passReqToCallback?: false; diff --git a/types/passport-oauth2/passport-oauth2-tests.ts b/types/passport-oauth2/passport-oauth2-tests.ts index 864b2cb9d6..30faeebda0 100644 --- a/types/passport-oauth2/passport-oauth2-tests.ts +++ b/types/passport-oauth2/passport-oauth2-tests.ts @@ -1,5 +1,6 @@ import OAuth2Strategy = require('passport-oauth2'); -import { Strategy, StrategyOptions, StrategyOptionsWithRequest, VerifyCallback, AuthorizationError, TokenError, InternalOAuthError } from 'passport-oauth2'; +import { Strategy, StrategyOptions, StrategyOptionsWithRequest, VerifyCallback, AuthorizationError, TokenError, + InternalOAuthError, Metadata, StateStore, StateStoreStoreCallback, StateStoreVerifyCallback } from 'passport-oauth2'; import { Strategy as PassportStrategy } from 'passport'; import { Request } from 'express'; @@ -56,3 +57,34 @@ class MyStrategy extends OAuth2Strategy { this._oauth2.get('http://www.example.com/profile', 'token', (err, result, response) => response); } } + +const metadata: Metadata = { + authorizationURL: 'http://www.example.com/auth', + clientID: 'dummy', + tokenURL: 'http://www.example.com/token' +}; + +class MyStore implements StateStore { + store(req: Request, meta: StateStoreStoreCallback | Metadata, callback?: StateStoreStoreCallback): void {} + verify(req: Request, state: string, meta: StateStoreVerifyCallback | Metadata, callback?: StateStoreVerifyCallback): void {} +} + +const myStore = new MyStore(); + +const strategyOptions3: StrategyOptions = { + authorizationURL: 'http://www.example.com/auth', + clientID: 'dummy', + clientSecret: 'secret', + tokenURL: 'http://www.example.com/token', + callbackURL: 'http://www.example.com/callback', + customHeaders: { + 'content-type': 'text/html' + }, + scope: ['scope1', 'scope2'], + scopeSeparator: ' ', + sessionKey: 'oauth', + state: {id: 1}, + store: myStore +}; + +const strategy5: Strategy = new Strategy(strategyOptions3, verifyFunction2); diff --git a/types/passport-saml/index.d.ts b/types/passport-saml/index.d.ts index cc2faafe5c..9338b88deb 100644 --- a/types/passport-saml/index.d.ts +++ b/types/passport-saml/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/bergie/passport-saml // Definitions by: Chris Barth // Damian Assennato +// Karol Samborski // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 diff --git a/types/passport-saml/multiSamlStrategy.d.ts b/types/passport-saml/multiSamlStrategy.d.ts new file mode 100644 index 0000000000..405c7264dc --- /dev/null +++ b/types/passport-saml/multiSamlStrategy.d.ts @@ -0,0 +1,10 @@ +import express = require('express'); +import { Strategy, SamlConfig, VerifyWithRequest, VerifyWithoutRequest } from './index'; + +export interface MultiSamlConfig extends SamlConfig { + getSamlOptions(req: express.Request, callback: (err: Error | null, samlOptions: SamlConfig) => void): void; +} + +export class MultiSamlStrategy extends Strategy { + constructor(config: MultiSamlConfig, verify: VerifyWithRequest | VerifyWithoutRequest); +} diff --git a/types/passport-saml/passport-saml-tests.ts b/types/passport-saml/passport-saml-tests.ts index 615c1b7320..b22421fe81 100644 --- a/types/passport-saml/passport-saml-tests.ts +++ b/types/passport-saml/passport-saml-tests.ts @@ -1,6 +1,7 @@ import express = require('express'); import passport = require('passport'); import SamlStrategy = require('passport-saml'); +import MultiSamlStrategy = require('passport-saml/multiSamlStrategy'); import fs = require('fs'); const samlStrategy = new SamlStrategy.Strategy( @@ -33,3 +34,27 @@ passport.use(samlStrategy); passport.authenticate('samlCustomName', {failureRedirect: '/', failureFlash: true}); const metadata = samlStrategy.generateServiceProviderMetadata("decryptionCert"); + +const multiSamlStrategy = new MultiSamlStrategy.MultiSamlStrategy( + { + name: 'samlCustomName', + path: '/login/callback', + entryPoint: 'https://openidp.feide.no/simplesaml/saml2/idp/SSOService.php', + issuer: 'passport-saml', + getSamlOptions(req: express.Request, callback: (err: Error | null, samlOptions: SamlStrategy.SamlConfig) => void) { + callback(null, { + name: 'samlCustomName', + path: '/login/callback2', + entryPoint: 'https://openidp.feide.no/simplesaml/saml2/idp/SSOService.php', + issuer: 'passport-saml', + }); + } + }, + (profile: {}, done: (err: Error | null, user: {}, info?: {}) => void) => { + const user = {}; + done(null, user); + } +); + +passport.use(multiSamlStrategy); +passport.authenticate('samlCustomName', {failureRedirect: '/', failureFlash: true}); diff --git a/types/passport-saml/tsconfig.json b/types/passport-saml/tsconfig.json index 0809dbbaf7..39283fa663 100644 --- a/types/passport-saml/tsconfig.json +++ b/types/passport-saml/tsconfig.json @@ -18,6 +18,7 @@ }, "files": [ "index.d.ts", + "multiSamlStrategy.d.ts", "passport-saml-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/peerjs/index.d.ts b/types/peerjs/index.d.ts index 4ca88fd50b..f3ec14c796 100644 --- a/types/peerjs/index.d.ts +++ b/types/peerjs/index.d.ts @@ -2,7 +2,7 @@ // Project: http://peerjs.com/ // Definitions by: Toshiya Nakakura // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 3.0 /// diff --git a/types/peerjs/package.json b/types/peerjs/package.json new file mode 100644 index 0000000000..d27d838dc6 --- /dev/null +++ b/types/peerjs/package.json @@ -0,0 +1,7 @@ +{ + "private": true, + "types": "index", + "typesVersions": { + ">=3.2.0-0": { "*": ["ts3.2/*"] } + } +} diff --git a/types/peerjs/peerjs-tests.ts b/types/peerjs/peerjs-tests.ts index 2246e6a8fd..eef24bf001 100644 --- a/types/peerjs/peerjs-tests.ts +++ b/types/peerjs/peerjs-tests.ts @@ -40,7 +40,7 @@ var connection = peerById.connect("id", { metadata: {message: 'hi i want to chat with you!'} }); -var call = peerById.call('callto-id', (window).localStream); +var call = peerById.call('callto-id', (window as any).localStream); var openHandler=()=> console.log("open"); peerById.on("open", openHandler); diff --git a/types/peerjs/ts3.2/index.d.ts b/types/peerjs/ts3.2/index.d.ts new file mode 100644 index 0000000000..71a6cc3c26 --- /dev/null +++ b/types/peerjs/ts3.2/index.d.ts @@ -0,0 +1,194 @@ +// Type definitions for PeerJS +// Project: http://peerjs.com/ +// Definitions by: Toshiya Nakakura +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace PeerJs{ + interface PeerJSOption{ + key?: string; + host?: string; + port?: number; + path?: string; + secure?: boolean; + config?: RTCConfiguration; + debug?: number; + } + + interface PeerConnectOption{ + label?: string; + metadata?: any; + serialization?: string; + reliable?: boolean; + + } + + interface DataConnection{ + send(data: any): void; + close(): void; + on(event: string, cb: ()=>void): void; + on(event: 'data', cb: (data: any)=>void): void; + on(event: 'open', cb: ()=>void): void; + on(event: 'close', cb: ()=>void): void; + on(event: 'error', cb: (err: any)=>void): void; + off(event: string, fn: Function, once?: boolean): void; + dataChannel: RTCDataChannel; + label: string; + metadata: any; + open: boolean; + peerConnection: any; + peer: string; + reliable: boolean; + serialization: string; + type: string; + buffSize: number; + } + + interface MediaConnection{ + answer(stream?: any): void; + close(): void; + on(event: string, cb: ()=>void): void; + on(event: 'stream', cb: (stream: any)=>void): void; + on(event: 'close', cb: ()=>void): void; + on(event: 'error', cb: (err: any)=>void): void; + off(event: string, fn: Function, once?: boolean): void; + open: boolean; + metadata: any; + peer: string; + type: string; + } + + interface utilSupportsObj { + audioVideo: boolean; + data: boolean; + binary: boolean; + reliable: boolean; + } + + interface util{ + browser: string; + supports: utilSupportsObj; + } + + export interface Peer{ + /** + * + * @param id The brokering ID of the remote peer (their peer.id). + * @param options for specifying details about Peer Connection + */ + connect(id: string, options?: PeerJs.PeerConnectOption): PeerJs.DataConnection; + /** + * Connects to the remote peer specified by id and returns a data connection. + * @param id The brokering ID of the remote peer (their peer.id). + * @param stream The caller's media stream + * @param options Metadata associated with the connection, passed in by whoever initiated the connection. + */ + call(id: string, stream: any, options?: any): PeerJs.MediaConnection; + /** + * Calls the remote peer specified by id and returns a media connection. + * @param event Event name + * @param cb Callback Function + */ + on(event: string, cb: ()=>void): void; + /** + * Emitted when a connection to the PeerServer is established. + * @param event Event name + * @param cb id is the brokering ID of the peer + */ + on(event: 'open', cb: (id: string)=>void): void; + /** + * Emitted when a new data connection is established from a remote peer. + * @param event Event name + * @param cb Callback Function + */ + on(event: 'connection', cb: (dataConnection: PeerJs.DataConnection)=>void): void; + /** + * Emitted when a remote peer attempts to call you. + * @param event Event name + * @param cb Callback Function + */ + on(event: 'call', cb: (mediaConnection: PeerJs.MediaConnection)=>void): void; + /** + * Emitted when the peer is destroyed and can no longer accept or create any new connections. + * @param event Event name + * @param cb Callback Function + */ + on(event: 'close', cb: ()=>void): void; + /** + * Emitted when the peer is disconnected from the signalling server + * @param event Event name + * @param cb Callback Function + */ + on(event: 'disconnected', cb: ()=>void): void; + /** + * Errors on the peer are almost always fatal and will destroy the peer. + * @param event Event name + * @param cb Callback Function + */ + on(event: 'error', cb: (err: any)=>void): void; + /** + * Remove event listeners.(EventEmitter3) + * @param {String} event The event we want to remove. + * @param {Function} fn The listener that we need to find. + * @param {Boolean} once Only remove once listeners. + */ + off(event: string, fn: Function, once?: boolean): void; + /** + * Close the connection to the server, leaving all existing data and media connections intact. + */ + disconnect(): void; + /** + * Attempt to reconnect to the server with the peer's old ID + */ + reconnect(): void; + /** + * Close the connection to the server and terminate all existing connections. + */ + destroy(): void; + + /** + * Retrieve a data/media connection for this peer. + * @param peer + * @param id + */ + getConnection(peer: Peer, id: string): any; + + /** + * Get a list of available peer IDs + * @param callback + */ + listAllPeers(callback: (peerIds: Array)=>void): void; + /** + * The brokering ID of this peer + */ + id: string; + /** + * A hash of all connections associated with this peer, keyed by the remote peer's ID. + */ + connections: any; + /** + * false if there is an active connection to the PeerServer. + */ + disconnected: boolean; + /** + * true if this peer and all of its connections can no longer be used. + */ + destroyed: boolean; + } +} + +declare var Peer: { + prototype: RTCIceServer; + /** + * A peer can connect to other peers and listen for connections. + * @param id Other peers can connect to this peer using the provided ID. + * If no ID is given, one will be generated by the brokering server. + * @param options for specifying details about PeerServer + */ + new (id: string, options?: PeerJs.PeerJSOption): PeerJs.Peer; + + /** + * A peer can connect to other peers and listen for connections. + * @param options for specifying details about PeerServer + */ + new (options: PeerJs.PeerJSOption): PeerJs.Peer; +}; diff --git a/types/peerjs/ts3.2/peerjs-tests.ts b/types/peerjs/ts3.2/peerjs-tests.ts new file mode 100644 index 0000000000..eef24bf001 --- /dev/null +++ b/types/peerjs/ts3.2/peerjs-tests.ts @@ -0,0 +1,54 @@ +var peerByOption: PeerJs.Peer = new Peer({ + key: 'peerKey', + debug: 3, +}); + +peerByOption.on("connection", dataConnection => { + var type: string = dataConnection.type; +}); + +peerByOption.listAllPeers(function(items){ + for(var i in items){ + console.log(decodeURI(items[i])); + } +}); + +var peerById: PeerJs.Peer = new Peer("peerid"); + +var peerByIdAndOption: PeerJs.Peer = new Peer( + "peerId", + { + key: 'peerKey', + debug: 3, + }); +peerByIdAndOption.on("call", mediaConnection => { + var isOpen: boolean = mediaConnection.open; +}); + +var id = peerByOption.id; +var connections = peerByOption.connections; +var flag = peerByOption.disconnected; +flag = peerByOption.destroyed; + +peerByOption.disconnect(); +peerByOption.reconnect(); +peerByOption.destroy(); + +var connection = peerById.connect("id", { + label: 'chat', + serialization: 'none', + metadata: {message: 'hi i want to chat with you!'} +}); + +var call = peerById.call('callto-id', (window as any).localStream); + +var openHandler=()=> console.log("open"); +peerById.on("open", openHandler); +peerById.on("connection", (c)=> console.log("connection")); +peerById.on("call", (media)=> console.log("call")); +peerById.on("close", ()=> console.log("close")); +peerById.on("disconnected", ()=> console.log("disconnected")); +peerById.on("error", (err)=> console.log(err)); +peerById.off("open", openHandler); + +var connection2 = peerById.getConnection(peerByOption, "callto-id"); diff --git a/types/peerjs/ts3.2/tsconfig.json b/types/peerjs/ts3.2/tsconfig.json new file mode 100644 index 0000000000..eaa819fc0c --- /dev/null +++ b/types/peerjs/ts3.2/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "peerjs-tests.ts" + ] +} diff --git a/types/peerjs/ts3.2/tslint.json b/types/peerjs/ts3.2/tslint.json new file mode 100644 index 0000000000..a41bf5d19a --- /dev/null +++ b/types/peerjs/ts3.2/tslint.json @@ -0,0 +1,79 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "adjacent-overload-signatures": false, + "array-type": false, + "arrow-return-shorthand": false, + "ban-types": false, + "callable-types": false, + "comment-format": false, + "dt-header": false, + "eofline": false, + "export-just-namespace": false, + "import-spacing": false, + "interface-name": false, + "interface-over-type-literal": false, + "jsdoc-format": false, + "max-line-length": false, + "member-access": false, + "new-parens": false, + "no-any-union": false, + "no-boolean-literal-compare": false, + "no-conditional-assignment": false, + "no-consecutive-blank-lines": false, + "no-construct": false, + "no-declare-current-package": false, + "no-duplicate-imports": false, + "no-duplicate-variable": false, + "no-empty-interface": false, + "no-for-in-array": false, + "no-inferrable-types": false, + "no-internal-module": false, + "no-irregular-whitespace": false, + "no-mergeable-namespace": false, + "no-misused-new": false, + "no-namespace": false, + "no-object-literal-type-assertion": false, + "no-padding": false, + "no-redundant-jsdoc": false, + "no-redundant-jsdoc-2": false, + "no-redundant-undefined": false, + "no-reference-import": false, + "no-relative-import-in-test": false, + "no-self-import": false, + "no-single-declare-module": false, + "no-string-throw": false, + "no-unnecessary-callback-wrapper": false, + "no-unnecessary-class": false, + "no-unnecessary-generics": false, + "no-unnecessary-qualifier": false, + "no-unnecessary-type-assertion": false, + "no-useless-files": false, + "no-var-keyword": false, + "no-var-requires": false, + "no-void-expression": false, + "no-trailing-whitespace": false, + "object-literal-key-quotes": false, + "object-literal-shorthand": false, + "one-line": false, + "one-variable-per-declaration": false, + "only-arrow-functions": false, + "prefer-conditional-expression": false, + "prefer-const": false, + "prefer-declare-function": false, + "prefer-for-of": false, + "prefer-method-signature": false, + "prefer-template": false, + "radix": false, + "semicolon": false, + "space-before-function-paren": false, + "space-within-parens": false, + "strict-export-declare-modifiers": false, + "trim-file": false, + "triple-equals": false, + "typedef-whitespace": false, + "unified-signatures": false, + "void-return": false, + "whitespace": false + } +} diff --git a/types/pollyjs__adapter-fetch/index.d.ts b/types/pollyjs__adapter-fetch/index.d.ts index 3d93435d51..d38313db9d 100644 --- a/types/pollyjs__adapter-fetch/index.d.ts +++ b/types/pollyjs__adapter-fetch/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for @pollyjs/adapter-fetch 1.2 +// Type definitions for @pollyjs/adapter-fetch 1.3 // Project: https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter-fetch // Definitions by: feinoujc // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/types/pollyjs__adapter/index.d.ts b/types/pollyjs__adapter/index.d.ts index b3810a67bb..0bc49fd73b 100644 --- a/types/pollyjs__adapter/index.d.ts +++ b/types/pollyjs__adapter/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for @pollyjs/adapter 1.2 +// Type definitions for @pollyjs/adapter 1.3 // Project: https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/adapter // Definitions by: feinoujc // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/types/pollyjs__core/index.d.ts b/types/pollyjs__core/index.d.ts index 83b6b933b9..4f6d308d0d 100644 --- a/types/pollyjs__core/index.d.ts +++ b/types/pollyjs__core/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for @pollyjs/core 1.2 +// Type definitions for @pollyjs/core 1.3 // Project: https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/core // Definitions by: feinoujc // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -12,8 +12,10 @@ export const Timing: { fixed(ms: number): () => Promise; relative(ratio: number): (ms: number) => Promise; }; + +export type MatchBy = (input: T) => R; export interface PollyConfig { - mode?: MODES; + mode?: MODES | string; adapters?: Array; adapterOptions?: any; @@ -34,20 +36,20 @@ export interface PollyConfig { timing?: ((ms: number) => Promise) | (() => Promise); matchRequestsBy?: { - method?: boolean; - headers?: any; - body?: boolean; + method?: boolean | MatchBy; + headers?: boolean | { exclude: string[] } | MatchBy>; + body?: boolean | MatchBy; order?: boolean; url?: { - protocol?: boolean; - username?: boolean; - password?: boolean; - hostname?: boolean; - port?: boolean; - pathname?: boolean; - query?: boolean; - hash?: boolean; + protocol?: boolean | MatchBy; + username?: boolean | MatchBy; + password?: boolean | MatchBy; + hostname?: boolean | MatchBy; + port?: boolean | MatchBy; + pathname?: boolean | MatchBy; + query?: boolean | MatchBy; + hash?: boolean | MatchBy; }; }; } diff --git a/types/pollyjs__core/pollyjs__core-tests.ts b/types/pollyjs__core/pollyjs__core-tests.ts index 22f5516646..0644eff7f4 100644 --- a/types/pollyjs__core/pollyjs__core-tests.ts +++ b/types/pollyjs__core/pollyjs__core-tests.ts @@ -6,7 +6,74 @@ const polly = new Polly('test recording', { recordFailedRequests: true, adapters: ['xhr', 'fetch'], persister: 'rest', - timing: Timing.relative(3) + timing: Timing.relative(3), + matchRequestsBy: { + method: true, + headers: true, + body: true, + order: true, + + url: { + protocol: true, + username: true, + password: true, + hostname: true, + port: true, + pathname: true, + query: true, + hash: false + } + } +}); + +new Polly('test recording', { + mode: 'replay', + recordFailedRequests: true, + adapters: ['xhr', 'fetch'], + persister: 'rest', + timing: Timing.relative(3), + matchRequestsBy: { + method(method) { + return method.toLowerCase(); + }, + headers: 1 === 1 ? { exclude: ['X-Auth'] } : (headers) => { + delete headers['X-Auth']; + return headers; + }, + body(body) { + const json = JSON.parse(body); + + delete json.email; + return JSON.stringify(json); + }, + + url: { + protocol(protocol) { + return protocol === 'http' ? 'https:' : protocol; + }, + username(username) { + return username === 'johndoe' ? 'username' : username; + }, + password(password) { + return password || 'password'; + }, + hostname(hostname) { + return hostname.replace('.com', '.net'); + }, + port(port) { + return port > 80 ? 3000 : 433; + }, + pathname(pathname) { + return pathname.replace('/api/v1', '/api'); + }, + query(query) { + return { ...query, token: '' }; + }, + hash(hash) { + return hash.replace(/token=[0-9]+/, ''); + } + } + } }); function log(_: string) { diff --git a/types/pollyjs__persister-fs/index.d.ts b/types/pollyjs__persister-fs/index.d.ts index 3d97b382f7..fc7f9ad656 100644 --- a/types/pollyjs__persister-fs/index.d.ts +++ b/types/pollyjs__persister-fs/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for @pollyjs/persister-fs 1.2 +// Type definitions for @pollyjs/persister-fs 1.3 // Project: https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister-fs // Definitions by: feinoujc // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/types/pollyjs__persister/index.d.ts b/types/pollyjs__persister/index.d.ts index 45fc1fc250..87e1c27f5b 100644 --- a/types/pollyjs__persister/index.d.ts +++ b/types/pollyjs__persister/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for @pollyjs/persister 1.2 +// Type definitions for @pollyjs/persister 1.3 // Project: https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/persister // Definitions by: feinoujc // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/types/pollyjs__utils/index.d.ts b/types/pollyjs__utils/index.d.ts index e87392fcee..ca3e7735ef 100644 --- a/types/pollyjs__utils/index.d.ts +++ b/types/pollyjs__utils/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for @pollyjs/utils 1.2 +// Type definitions for @pollyjs/utils 1.3 // Project: https://github.com/netflix/pollyjs/tree/master/packages/@pollyjs/utils // Definitions by: feinoujc // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/types/pretty-ms/index.d.ts b/types/pretty-ms/index.d.ts index b1e151cd65..ca9bf663e2 100644 --- a/types/pretty-ms/index.d.ts +++ b/types/pretty-ms/index.d.ts @@ -1,7 +1,8 @@ -// Type definitions for pretty-ms 3.2 +// Type definitions for pretty-ms 4.0 // Project: https://github.com/sindresorhus/pretty-ms#readme // Definitions by: BendingBender // ocboogie +// silh // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export = prettyMs; @@ -14,6 +15,9 @@ declare namespace prettyMs { msDecimalDigits?: number; keepDecimalsOnWholeSeconds?: boolean; compact?: boolean; + unitCount?: number; verbose?: boolean; + separateMs?: boolean; + formatSubMs?: boolean; } } diff --git a/types/pretty-ms/pretty-ms-tests.ts b/types/pretty-ms/pretty-ms-tests.ts index ae5e8120b2..bb5e8a69ec 100644 --- a/types/pretty-ms/pretty-ms-tests.ts +++ b/types/pretty-ms/pretty-ms-tests.ts @@ -7,4 +7,7 @@ str = prettyMs(1335669000, {verbose: true}); str = prettyMs(1335669000, {keepDecimalsOnWholeSeconds: true}); str = prettyMs(1335669000, {secDecimalDigits: 1}); str = prettyMs(1335669000, {msDecimalDigits: 2}); +str = prettyMs(1335669000, {unitCount: 2}); +str = prettyMs(1335669000, {separateMs: true}); +str = prettyMs(1335669000, {formatSubMs: true}); str = prettyMs(new Date(2014, 0, 1, 10, 40).getTime() - new Date(2014, 0, 1, 10, 5).getTime()); diff --git a/types/pretty-ms/v3/index.d.ts b/types/pretty-ms/v3/index.d.ts new file mode 100644 index 0000000000..b1e151cd65 --- /dev/null +++ b/types/pretty-ms/v3/index.d.ts @@ -0,0 +1,19 @@ +// Type definitions for pretty-ms 3.2 +// Project: https://github.com/sindresorhus/pretty-ms#readme +// Definitions by: BendingBender +// ocboogie +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = prettyMs; + +declare function prettyMs(input: number, options?: prettyMs.PrettyMsOptions): string; + +declare namespace prettyMs { + interface PrettyMsOptions { + secDecimalDigits?: number; + msDecimalDigits?: number; + keepDecimalsOnWholeSeconds?: boolean; + compact?: boolean; + verbose?: boolean; + } +} diff --git a/types/pretty-ms/v3/pretty-ms-tests.ts b/types/pretty-ms/v3/pretty-ms-tests.ts new file mode 100644 index 0000000000..ae5e8120b2 --- /dev/null +++ b/types/pretty-ms/v3/pretty-ms-tests.ts @@ -0,0 +1,10 @@ +import prettyMs = require('pretty-ms'); + +let str: string; +str = prettyMs(133); +str = prettyMs(1337, {compact: true}); +str = prettyMs(1335669000, {verbose: true}); +str = prettyMs(1335669000, {keepDecimalsOnWholeSeconds: true}); +str = prettyMs(1335669000, {secDecimalDigits: 1}); +str = prettyMs(1335669000, {msDecimalDigits: 2}); +str = prettyMs(new Date(2014, 0, 1, 10, 40).getTime() - new Date(2014, 0, 1, 10, 5).getTime()); diff --git a/types/pretty-ms/v3/tsconfig.json b/types/pretty-ms/v3/tsconfig.json new file mode 100644 index 0000000000..5d4f2d4c31 --- /dev/null +++ b/types/pretty-ms/v3/tsconfig.json @@ -0,0 +1,28 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "paths": { + "pretty-ms": [ + "pretty-ms/v3" + ] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "pretty-ms-tests.ts" + ] +} diff --git a/types/pretty-ms/v3/tslint.json b/types/pretty-ms/v3/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/pretty-ms/v3/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/progress/index.d.ts b/types/progress/index.d.ts index 74596c4c13..c1e199ec6c 100644 --- a/types/progress/index.d.ts +++ b/types/progress/index.d.ts @@ -1,67 +1,13 @@ -// Type definitions for node-progress v2.0.0 -// Project: https://github.com/tj/node-progress +// Type definitions for node-progress 2.0 +// Project: https://github.com/visionmedia/node-progress // Definitions by: Sebastian Lenz // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// +export as namespace ProgressBar; - -/** - * These are keys in the options object you can pass to the progress bar along with total as seen in the example above. - */ -interface ProgressBarOptions { - /** - * Total number of ticks to complete. - */ - total: number; - - /** - * current completed index - */ - curr?: number; - - /** - * head character defaulting to complete character - */ - head?: string; - - /** - * The displayed width of the progress bar defaulting to total. - */ - width?: number; - - /** - * minimum time between updates in milliseconds defaulting to 16 - */ - renderThrottle?: number; - - /** - * The output stream defaulting to stderr. - */ - stream?: NodeJS.WritableStream; - - /** - * Completion character defaulting to "=". - */ - complete?: string; - - /** - * Incomplete character defaulting to "-". - */ - incomplete?: string; - - /** - * Option to clear the bar on completion defaulting to false. - */ - clear?: boolean; - - /** - * Optional function to call when the progress bar completes. - */ - callback?: Function; -} - +export = ProgressBar; /** * Flexible ascii progress bar. @@ -90,7 +36,7 @@ declare class ProgressBar { * - `:eta` eta in seconds */ constructor(format: string, total: number); - constructor(format: string, options: ProgressBarOptions); + constructor(format: string, options: ProgressBar.ProgressBarOptions); /** @@ -120,7 +66,7 @@ declare class ProgressBar { * overall completion to. */ update(ratio: number, tokens?: any): void; - + /** * "interrupt" the progress bar and write a message above it. */ @@ -128,14 +74,78 @@ declare class ProgressBar { /** * Terminates a progress bar. - */ + */ terminate(): void; /** * Completed status of progress (Boolean) */ complete: boolean; -} -declare namespace ProgressBar { } -export = ProgressBar; + /** + * Current tick number. + */ + curr: number; + + /** + * Total number of ticks to complete. + */ + total: number; +} + +declare namespace ProgressBar { + /** + * These are keys in the options object you can pass to the progress bar along with total as seen in the example above. + */ + interface ProgressBarOptions { + /** + * Total number of ticks to complete. + */ + total: number; + + /** + * current completed index + */ + curr?: number; + + /** + * head character defaulting to complete character + */ + head?: string; + + /** + * The displayed width of the progress bar defaulting to total. + */ + width?: number; + + /** + * minimum time between updates in milliseconds defaulting to 16 + */ + renderThrottle?: number; + + /** + * The output stream defaulting to stderr. + */ + stream?: NodeJS.WritableStream; + + /** + * Completion character defaulting to "=". + */ + complete?: string; + + /** + * Incomplete character defaulting to "-". + */ + incomplete?: string; + + /** + * Option to clear the bar on completion defaulting to false. + */ + clear?: boolean; + + /** + * Optional function to call when the progress bar completes. + */ + callback?: Function; + } +} diff --git a/types/progress/progress-tests.ts b/types/progress/progress-tests.ts index 561f226b64..d93eb9bc3f 100644 --- a/types/progress/progress-tests.ts +++ b/types/progress/progress-tests.ts @@ -1,42 +1,48 @@ -var ProgressBar = require('progress'); +import * as ProgressBar from 'progress'; /** - * Usage example from https://github.com/tj/node-progress + * Usage example from https://github.com/visionmedia/node-progress + * (in Typescript) */ -var bar = new ProgressBar(':bar', { total: 10 }); -var timer = setInterval(function () { - bar.tick(); - if (bar.complete) { +const usageBar = new ProgressBar(':bar', { total: 10 }); +const timer = setInterval(function () { + usageBar.tick(); + if (usageBar.complete) { console.log('\ncomplete\n'); clearInterval(timer); } }, 100); - /** - * Custom token example from https://github.com/tj/node-progress + * Custom token example from https://github.com/visionmedia/node-progress + * (in Typescript) */ -var bar = new ProgressBar(':current: :token1 :token2', { total: 3 }); - -bar.tick({ - 'token1': "Hello", - 'token2': "World!\n" -}); - -bar.tick(2, { - 'token1': "Goodbye", - 'token2': "World!" -}); + const list = [ + 'image01.jpg', 'image02.jpg', 'image03.jpg', 'image04.jpg', 'image05.jpg', + 'image06.jpg', 'image07.jpg', 'image08.jpg', 'image09.jpg', 'image10.jpg' + ]; + const customTokenBar = new ProgressBar(':percent eta: :eta downloading :current/:total :file', { + total: list.length + }); + const customInterval = setInterval(function (){ + customTokenBar.tick({ + 'file': list[customTokenBar.curr] + }) + if (customTokenBar.complete) { + clearInterval(customInterval) + } + }, 500) /** * Interrupt example from https://github.com/visionmedia/node-progress + * (in Typescript) */ -var bar = new ProgressBar(':bar :current/:total', { total: 10 }); -var timer = setInterval(function () { - bar.tick(); - if (bar.complete) { - clearInterval(timer); - } else if (bar.curr === 5) { - bar.interrupt('this message appears above the progress bar\ncurrent progress is ' + bar.curr + '/' + bar.total); +const interruptBar = new ProgressBar(':bar :current/:total', { total: 10 }); +const interruptTimer = setInterval(function () { + interruptBar.tick(); + if (interruptBar.complete) { + clearInterval(interruptTimer); + } else if (interruptBar.curr === 5 || interruptBar.curr === 8) { + interruptBar.interrupt('interrupt: current progress is ' + interruptBar.curr + '/' + interruptBar.total); } -}, 1000); \ No newline at end of file +}, 1000); diff --git a/types/proj4/index.d.ts b/types/proj4/index.d.ts index afba494556..d7d4cf1ae5 100644 --- a/types/proj4/index.d.ts +++ b/types/proj4/index.d.ts @@ -1,6 +1,7 @@ -// Type definitions for proj4 2.3 +// Type definitions for proj4 2.5 // Project: https://github.com/proj4js/proj4js // Definitions by: Denis Carriere +// BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace proj4 { @@ -21,9 +22,9 @@ declare namespace proj4 { ep2: number; } - interface Static { - forward(coordinates: TemplateCoordinates): number[]; - inverse(coordinates: TemplateCoordinates): number[]; + interface Converter { + forward(coordinates: T): T; + inverse(coordinates: T): T; } interface InterfaceProjection { @@ -38,6 +39,39 @@ declare namespace proj4 { inverse(coordinates: TemplateCoordinates): number[]; } + interface ProjectionDefinition { + title: string; + projName?: string; + ellps?: string; + datum?: string; + datumName?: string; + rf?: number; + lat0?: number; + lat1?: number; + lat2?: number; + lat_ts?: number; + long0?: number; + long1?: number; + long2?: number; + alpha?: number; + longc?: number; + x0?: number; + y0?: number; + k0?: number; + a?: number; + b?: number; + R_A?: true; + zone?: number; + utmSouth?: true; + datum_params?: string | number[]; + to_meter?: number; + units?: string; + from_greenwich?: number; + datumCode?: string; + natGrids?: string; + axis?: string; + } + const defaultDatum: string; function Proj(srsCode: any, callback?: any): InterfaceProjection; @@ -45,23 +79,38 @@ declare namespace proj4 { const WGS84: any; /** - * Depecrated v3 + * @deprecated v3 */ function Point(x: number, y: number, z?: number): InterfaceCoordinates; function Point(coordinates: TemplateCoordinates | string): InterfaceCoordinates; function toPoint(array: number[]): InterfaceCoordinates; - function defs(name: string, projection?: string): any; - function defs(name: string[][]): any; + function defs(name: string, projection: string | ProjectionDefinition): void; + function defs(name: string[][]): undefined[]; + function defs(name: string): ProjectionDefinition; - function transform(source: InterfaceProjection, dest: InterfaceProjection, point: TemplateCoordinates): any; + function transform( + source: InterfaceProjection, + dest: InterfaceProjection, + point: TemplateCoordinates + ): any; function mgrs(coordinates: number[], accuracy: number): string; const version: string; } -declare function proj4(fromProjection: string, toProjection?: string, coordinates?: proj4.TemplateCoordinates): proj4.Static; -declare function proj4(fromProjection: string, coordinates: proj4.TemplateCoordinates): number[]; +declare function proj4(fromProjection: string, toProjection?: string): proj4.Converter; +declare function proj4( + toProjection: string, + coordinates: T +): T; +declare function proj4( + fromProjection: string, + toProjection: string, + coordinates: T +): T; + export = proj4; +export as namespace proj4; diff --git a/types/proj4/proj4-tests.ts b/types/proj4/proj4-tests.ts index 3d1ab1ab9b..7df09014db 100644 --- a/types/proj4/proj4-tests.ts +++ b/types/proj4/proj4-tests.ts @@ -3,31 +3,55 @@ import proj4 = require('proj4'); /////////////////////////////////////////// // Tests data initialisation /////////////////////////////////////////// -const name = 'WGS84'; const epsg = { 4269: '+title=NAD83 (long/lat) +proj=longlat +a=6378137.0 +b=6356752.31414036 +ellps=GRS80 +datum=NAD83 +units=degrees', 4326: '+title=WGS 84 (long/lat) +proj=longlat +ellps=WGS84 +datum=WGS84 +units=degrees', }; -const point1 = [-71, 41]; -const point2 = {x: 2, y: 5}; -const mgrs = "24XWT783908"; +const firstProjection = epsg[4269]; +const secondProjection = epsg[4326]; + +const pointArr = [-71, 41]; +const pointObj = { x: 2, y: 5 }; /////////////////////////////////////////// // Tests Measurement /////////////////////////////////////////// -proj4(epsg['4269'], epsg['4326'], point1); -proj4(epsg['4269'], point1); -proj4(epsg['4269'], epsg['4326']).forward(point2); -proj4(epsg['4269'], epsg['4326']).inverse(point2); +proj4(firstProjection, secondProjection, pointArr); +proj4(firstProjection, pointArr); + +// $ExpectType number[] +proj4(firstProjection, secondProjection, pointArr); +// $ExpectType { x: number; y: number; } +proj4(firstProjection, secondProjection, pointObj); + +// $ExpectType number[] +proj4(firstProjection, pointArr); +// $ExpectType { x: number; y: number; } +proj4(firstProjection, pointObj); + +// $ExpectType Converter +proj4(firstProjection, secondProjection); +// $ExpectType Converter +proj4(firstProjection); + +// $ExpectType number[] +proj4(firstProjection, secondProjection).forward(pointArr); +// $ExpectType { x: number; y: number; } +proj4(firstProjection, secondProjection).forward(pointObj); +// $ExpectType number[] +proj4(firstProjection, secondProjection).inverse(pointArr); +// $ExpectType { x: number; y: number; } +proj4(firstProjection, secondProjection).inverse(pointObj); /////////////////////////////////// // Named Projections /////////////////////////////////// -proj4.defs('WGS84', epsg['4326']); -proj4.defs([ - ['EPSG:4326', epsg['4326']], - ['EPSG:4269', epsg['4269']] -]); + +// $ExpectType ProjectionDefinition +proj4.defs('WGS84'); +proj4.defs('WGS84', secondProjection); +// $ExpectType undefined[] +proj4.defs([['EPSG:4326', secondProjection], ['EPSG:4269', firstProjection]]); proj4.defs('urn:x-ogc:def:crs:EPSG:4326', proj4.defs('EPSG:4326')); /////////////////////////////////// diff --git a/types/proj4/tsconfig.json b/types/proj4/tsconfig.json index a55659d52c..02713475d5 100644 --- a/types/proj4/tsconfig.json +++ b/types/proj4/tsconfig.json @@ -6,7 +6,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ @@ -20,4 +20,4 @@ "index.d.ts", "proj4-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/promised-ldap/index.d.ts b/types/promised-ldap/index.d.ts new file mode 100644 index 0000000000..8b0182bea6 --- /dev/null +++ b/types/promised-ldap/index.d.ts @@ -0,0 +1,95 @@ +// Type definitions for promised-ldap 0.3 +// Project: https://github.com/stewartml/promised-ldap +// Definitions by: Alan Plum +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +import { EventEmitter } from "events"; +import * as ldap from "ldapjs"; + +declare class Client extends EventEmitter { + constructor({ url }: { url: string }); + + search( + base: string, + options: ldap.SearchOptions, + controls?: ldap.Control | ldap.Control[] + ): Promise<{ + entries: any[]; + references: any[]; + }>; + + authenticate(base: string, dn: string, password: string): Promise; + authenticateUser( + base: string, + dn: string, + password: string + ): Promise<{ name: string; email: string; groups: string[] } | null>; + + bind( + dn: string, + password: string, + controls?: ldap.Control | ldap.Control[] + ): Promise; + + add( + name: string, + entry: object, + controls?: ldap.Control | ldap.Control[] + ): Promise; + + compare( + name: string, + attr: string, + value: string, + controls?: ldap.Control | ldap.Control[] + ): Promise; + + del(name: string, controls?: ldap.Control | ldap.Control[]): Promise; + + exop( + name: string, + value: string, + controls?: ldap.Control | ldap.Control[] + ): Promise; + + modify( + name: string, + change: ldap.Change | ldap.Change[], + controls?: ldap.Control | ldap.Control[] + ): Promise; + + modifyDN( + name: string, + newName: string, + controls?: ldap.Control | ldap.Control[] + ): Promise; + + _search( + base: string, + options: ldap.SearchOptions, + controls?: ldap.Control | ldap.Control[], + _bypass?: boolean + ): Promise; + _search( + base: string, + options: ldap.SearchOptions, + _bypass: boolean + ): Promise; + + starttls( + options: object, + controls: ldap.Control | ldap.Control[], + _bypass?: boolean + ): Promise; + + unbind(): Promise; + + destroy(err?: any): void; +} + +declare namespace Client { + type SearchOptions = ldap.SearchOptions; +} + +export = Client; diff --git a/types/promised-ldap/promised-ldap-tests.ts b/types/promised-ldap/promised-ldap-tests.ts new file mode 100644 index 0000000000..b61f7ef6fc --- /dev/null +++ b/types/promised-ldap/promised-ldap-tests.ts @@ -0,0 +1,39 @@ +import ldap = require("promised-ldap"); +import ldapjs = require("ldapjs"); + +const client = new ldap({ + url: "ldap://127.0.0.1:1389" +}); + +client.authenticate("test", "cn=root", "secret").then((res: any) => { + console.log(res); +}); + +client.authenticateUser("test", "cn=root", "secret").then((res: any) => { + console.log(res); +}); + +client.bind("cn=root", "secret").catch((err: Error) => { + console.error(err); +}); + +const opts: ldap.SearchOptions = { + filter: "(&(l=Seattle)(email=*@foo.com))", + scope: "sub", + attributes: ["dn", "sn", "cn"] +}; + +client._search("o=example", opts).then((res: NodeJS.EventEmitter) => { + console.log(res); +}); + +const change = new ldapjs.Change({ + operation: "add", + modification: { + pets: ["cat", "dog"] + } +}); + +client.modify("cn=foo, o=example", change).catch((err: Error) => { + console.error(err); +}); diff --git a/types/promised-ldap/tsconfig.json b/types/promised-ldap/tsconfig.json new file mode 100644 index 0000000000..89b60715eb --- /dev/null +++ b/types/promised-ldap/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "promised-ldap-tests.ts"] +} diff --git a/types/promised-ldap/tslint.json b/types/promised-ldap/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/promised-ldap/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/prompts/index.d.ts b/types/prompts/index.d.ts index 7aa3f2ea63..7dc3a928a7 100644 --- a/types/prompts/index.d.ts +++ b/types/prompts/index.d.ts @@ -1,7 +1,8 @@ -// Type definitions for prompts 1.1 +// Type definitions for prompts 1.2 // Project: https://github.com/terkelg/prompts // Definitions by: Berkay GURSOY // Daniel Perez Alvarez +// Kamontat Chantrachirathumrong // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -47,18 +48,19 @@ declare namespace prompts { interface Choice { title: string; value: string; + disable?: boolean; } interface Options { - onSubmit: (prompt: PromptObject, answer: any, answers: any[]) => void; - onCancel: (prompt: PromptObject, answers: any) => void; + onSubmit?: (prompt: PromptObject, answer: any, answers: any[]) => void; + onCancel?: (prompt: PromptObject, answers: any) => void; } interface PromptObject { - type: ValueOrFunc; + type: ValueOrFunc | Falsy; name: ValueOrFunc; message?: ValueOrFunc; - initial?: string; + initial?: string | number | boolean; style?: string; format?: PrevCaller; validate?: PrevCaller; @@ -85,5 +87,9 @@ declare namespace prompts { prompt: PromptObject ) => R; + type Falsy = false | null | undefined; + + type PromptType = "text" | "password" | "invisible" | "number" | "confirm" | "list" | "toggle" | "select" | "multiselect" | "autocomplete"; + type ValueOrFunc = T | PrevCaller; } diff --git a/types/prop-types/index.d.ts b/types/prop-types/index.d.ts index 3b0a1164d6..5f95d354dd 100644 --- a/types/prop-types/index.d.ts +++ b/types/prop-types/index.d.ts @@ -5,11 +5,15 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 +export type ReactComponentLike = + | string + | ((props: any, context?: any) => any) + | (new (props: any, context?: any) => any); + export interface ReactElementLike { - type: string | ((...args: any[]) => ReactElementLike); + type: ReactComponentLike; props: any; key: string | number | null; - children?: ReactNodeLike; } export interface ReactNodeArray extends Array {} @@ -28,9 +32,9 @@ export const nominalTypeHack: unique symbol; export type IsOptional = undefined | null extends T ? true : undefined extends T ? true : null extends T ? true : false; -export type RequiredKeys = { [K in keyof V]: V[K] extends Validator ? IsOptional extends true ? never : K : never }[keyof V]; +export type RequiredKeys = { [K in keyof V]-?: Exclude extends Validator ? IsOptional extends true ? never : K : never }[keyof V]; export type OptionalKeys = Exclude>; -export type InferPropsInner = { [K in keyof V]: InferType; }; +export type InferPropsInner = { [K in keyof V]-?: InferType; }; export interface Validator { (props: object, propName: string, componentName: string, location: string, propFullName: string): Error | null; @@ -41,7 +45,7 @@ export interface Requireable extends Validator { isRequired: Validator>; } -export type ValidationMap = { [K in keyof T]-?: Validator }; +export type ValidationMap = { [K in keyof T]?: Validator }; export type InferType = V extends Validator ? T : any; export type InferProps = diff --git a/types/prop-types/prop-types-tests.ts b/types/prop-types/prop-types-tests.ts index a9bde3af00..baf210fdeb 100644 --- a/types/prop-types/prop-types-tests.ts +++ b/types/prop-types/prop-types-tests.ts @@ -129,35 +129,26 @@ type ExtractedPartialProps = PropTypes.InferProps; type ExtractedPropsWithoutAnnotation = PropTypes.InferProps; type ExtractedPropsFromOuterPropsWithoutAnnotation = PropTypes.InferProps['props']; -// $ExpectType: true +// $ExpectType true type ExtractPropsMatch = ExtractedProps extends ExtractedPropsWithoutAnnotation ? true : false; -// $ExpectType: true +// $ExpectType true type ExtractPropsMatch2 = ExtractedPropsWithoutAnnotation extends ExtractedProps ? true : false; -// $ExpectType: true +// $ExpectType true type ExtractPropsMatch3 = ExtractedProps extends Props ? true : false; -// $ExpectType: true +// $ExpectType true type ExtractPropsMatch4 = Props extends ExtractedPropsWithoutAnnotation ? true : false; -// $ExpectType: true +// $ExpectType true type ExtractFromOuterPropsMatch = ExtractedPropsFromOuterProps extends ExtractedPropsFromOuterPropsWithoutAnnotation ? true : false; -// $ExpectType: true +// $ExpectType true type ExtractFromOuterPropsMatch2 = ExtractedPropsFromOuterPropsWithoutAnnotation extends ExtractedPropsFromOuterProps ? true : false; -// $ExpectType: true +// $ExpectType true type ExtractFromOuterPropsMatch3 = ExtractedPropsFromOuterProps extends Props ? true : false; -// $ExpectType: true +// $ExpectType true type ExtractFromOuterPropsMatch4 = Props extends ExtractedPropsFromOuterPropsWithoutAnnotation ? true : false; -// $ExpectType: false +// $ExpectType false type ExtractPropsMismatch = ExtractedPartialProps extends Props ? true : false; -// $ExpectType: {} -type UnmatchedPropKeys = Pick>; -// $ExpectType: {} -type UnmatchedPropKeys2 = Pick>; - PropTypes.checkPropTypes({ xs: PropTypes.array }, { xs: [] }, 'location', 'componentName'); // This would be the type that JSX sees @@ -189,7 +180,7 @@ const componentDefaultProps = { type DefaultizedProps = Defaultize, typeof componentDefaultProps>; type UndefaultizedProps = Undefaultize, typeof componentDefaultProps>; -// $ExpectType: true +// $ExpectType true type DefaultizedPropsTest = { fi?: (...args: any[]) => any; foo?: string | null; @@ -197,7 +188,7 @@ type DefaultizedPropsTest = { baz?: boolean | null; bat?: ReactNode; } extends DefaultizedProps ? true : false; -// $ExpectType: true +// $ExpectType true type UndefaultizedPropsTest = { fi: (...args: any[]) => any; foo?: string | null; diff --git a/types/public-ip/index.d.ts b/types/public-ip/index.d.ts index 463a1a2d18..58fb81aa93 100644 --- a/types/public-ip/index.d.ts +++ b/types/public-ip/index.d.ts @@ -1,12 +1,16 @@ -// Type definitions for public-ip 2.3 +// Type definitions for public-ip 2.4 // Project: https://github.com/sindresorhus/public-ip#readme // Definitions by: BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -export function v4(options?: Options): Promise; -export function v6(options?: Options): Promise; +export function v4(options?: Options): CancelablePromise; +export function v6(options?: Options): CancelablePromise; export interface Options { https?: boolean; timeout?: number; } + +export type CancelablePromise = Promise & { + cancel(): void; +}; diff --git a/types/public-ip/public-ip-tests.ts b/types/public-ip/public-ip-tests.ts index e7e0540bbe..6e5983bc99 100644 --- a/types/public-ip/public-ip-tests.ts +++ b/types/public-ip/public-ip-tests.ts @@ -1,16 +1,17 @@ import * as publicIp from 'public-ip'; -let str: string; publicIp.v4().then(ip => { - str = ip; + ip; // $ExpectType string }); -publicIp.v4({https: false, timeout: 10}).then(ip => { - str = ip; +publicIp.v4({ https: false, timeout: 10 }).then(ip => { + ip; // $ExpectType string }); +publicIp.v4().cancel(); publicIp.v6().then(ip => { - str = ip; + ip; // $ExpectType string }); -publicIp.v6({https: false, timeout: 10}).then(ip => { - str = ip; +publicIp.v6({ https: false, timeout: 10 }).then(ip => { + ip; // $ExpectType string }); +publicIp.v6().cancel(); diff --git a/types/pubnub/index.d.ts b/types/pubnub/index.d.ts index 8337acfbe4..257ca3cd44 100644 --- a/types/pubnub/index.d.ts +++ b/types/pubnub/index.d.ts @@ -1,8 +1,9 @@ // Type definitions for pubnub 4.0 // Project: https://github.com/pubnub/javascript -// Definitions by: bitbankinc , rollymaduk , vitosamson +// Definitions by: bitbankinc , rollymaduk , vitosamson , FlorianDr // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // @see https://www.pubnub.com/docs/web-javascript/api-reference-configuration +// TypeScript Version: 2.2 declare class Pubnub { constructor(config: Pubnub.PubnubConfig); @@ -88,6 +89,18 @@ declare class Pubnub { setState( params: Pubnub.SetStateParameters ): Promise; + + encrypt( + data: string, + customCipherKey?: string, + options?: Pubnub.CryptoParameters, + ): any; + + decrypt( + data: object, + customCipherKey?: string, + options?: Pubnub.CryptoParameters + ): any; } declare namespace Pubnub { @@ -296,6 +309,14 @@ declare namespace Pubnub { }; } + // encrypt & decrypt + interface CryptoParameters { + encryptKey?: boolean; + keyEncoding?: string; + keyLength?: number; + mode?: string; + } + interface Categories { PNNetworkUpCategory: string; PNNetworkDownCategory: string; diff --git a/types/pubnub/pubnub-tests.ts b/types/pubnub/pubnub-tests.ts index 1d8b2bb1ca..50660bd942 100644 --- a/types/pubnub/pubnub-tests.ts +++ b/types/pubnub/pubnub-tests.ts @@ -86,3 +86,15 @@ pubnub.setState({ channels: [] }, (status, res) => { pubnub.setState({ channels: [] }).then(res => { console.log(res.state); }); + +const cryptoOptions = { + encryptKey: true, + keyEncoding: 'utf8', + keyLength: 256, + mode: 'cbc' +}; +const mySecret = { + message: 'Hi!', +}; +pubnub.decrypt(mySecret, undefined, cryptoOptions); +pubnub.encrypt('egrah5rwgrehwqh5eh3hwfwef', undefined, cryptoOptions); diff --git a/types/punycode/index.d.ts b/types/punycode/index.d.ts new file mode 100644 index 0000000000..a3048a5e28 --- /dev/null +++ b/types/punycode/index.d.ts @@ -0,0 +1,16 @@ +// Type definitions for punycode 2.1 +// Project: https://mths.be/punycode +// Definitions by: Dmitry Guketlev +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export function decode(input: string): string; +export function encode(input: string): string; +export function toUnicode(input: string): string; +export function toASCII(input: string): string; + +export namespace ucs2 { + function decode(string: string): number[]; + function encode(array: ReadonlyArray): string; +} + +export const version: string; diff --git a/types/punycode/punycode-tests.ts b/types/punycode/punycode-tests.ts new file mode 100644 index 0000000000..4de954fbc7 --- /dev/null +++ b/types/punycode/punycode-tests.ts @@ -0,0 +1,11 @@ +import punycode = require('punycode'); + +const result1: string = punycode.decode('x'); +const result2: string = punycode.encode('x'); +const result3: string = punycode.toASCII('x'); +const result4: string = punycode.toUnicode('x'); + +const ucs2result1: number[] = punycode.ucs2.decode('x'); +const ucs2result2: string = punycode.ucs2.encode([1, 2, 3]); + +const version: string = punycode.version; diff --git a/types/punycode/tsconfig.json b/types/punycode/tsconfig.json new file mode 100644 index 0000000000..0474c0a874 --- /dev/null +++ b/types/punycode/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "punycode-tests.ts" + ] +} diff --git a/types/punycode/tslint.json b/types/punycode/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/punycode/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/puppeteer/DeviceDescriptors.d.ts b/types/puppeteer/DeviceDescriptors.d.ts new file mode 100644 index 0000000000..e457748fda --- /dev/null +++ b/types/puppeteer/DeviceDescriptors.d.ts @@ -0,0 +1,22 @@ +declare namespace devices { + interface Viewport { + width: number; + height: number; + deviceScaleFactor: number; + isMobile: boolean; + hasTouch: boolean; + isLandscape: boolean; + } + + interface Device { + name: string; + userAgent: string; + viewport: Viewport; + } +} + +declare const devices: { + [key: string]: devices.Device; +}; + +export = devices; diff --git a/types/puppeteer/index.d.ts b/types/puppeteer/index.d.ts index cbb31f2fd0..2051603f69 100644 --- a/types/puppeteer/index.d.ts +++ b/types/puppeteer/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for puppeteer 1.10 +// Type definitions for puppeteer 1.11 // Project: https://github.com/GoogleChrome/puppeteer#readme // Definitions by: Marvin Hagemeister // Christopher Deutsch @@ -398,6 +398,8 @@ export interface Cookie { path: string; /** The cookie Unix expiration time in seconds. */ expires: number; + /** The cookie size */ + size: number; /** The cookie http only flag. */ httpOnly: boolean; /** The session cookie flag. */ @@ -414,7 +416,6 @@ export interface DeleteCookie { url?: string; domain?: string; path?: string; - secure?: boolean; } export interface SetCookie { @@ -512,6 +513,9 @@ export interface DirectNavigationOptions extends NavigationOptions { referer?: string; } +/** Accepts values labeled with units. If number, treat as pixels. */ +export type LayoutDimension = string | number; + export type PDFFormat = | "Letter" | "Legal" @@ -579,22 +583,21 @@ export interface PDFOptions { * @default 'Letter' */ format?: PDFFormat; - /** Paper width, accepts values labeled with units. */ - width?: string; - /** Paper height, accepts values labeled with units. */ - height?: string; - /** Paper margins, defaults to none. */ + /** Paper width. */ + width?: LayoutDimension; + /** Paper height. */ + height?: LayoutDimension; + /** Paper margins, defaults to none. */ margin?: { - /** Top margin, accepts values labeled with units. */ - top?: string; - /** Right margin, accepts values labeled with units. */ - right?: string; - /** Bottom margin, accepts values labeled with units. */ - bottom?: string; - /** Left margin, accepts values labeled with units. */ - left?: string; + /** Top margin. */ + top?: LayoutDimension; + /** Right margin. */ + right?: LayoutDimension; + /** Bottom margin. */ + bottom?: LayoutDimension; + /** Left margin. */ + left?: LayoutDimension; }; - /** * Give any CSS @page size declared in the page priority over what is declared in width and * height or format options. @@ -968,7 +971,7 @@ export interface Request { /** * @returns The `Frame` object that initiated the request, or `null` if navigating to error pages */ - frame(): Promise; + frame(): Frame | null; /** * An object with HTTP headers associated with the request. @@ -1177,8 +1180,9 @@ export interface FrameBase extends Evalable { /** * Sets the page content. * @param html HTML markup to assign to the page. + * @param options The navigation parameters. */ - setContent(html: string): Promise; + setContent(html: string, options?: NavigationOptions): Promise; /** * This method fetches an element with `selector`, scrolls it into view if needed, @@ -1395,11 +1399,11 @@ export interface AXNode { /** * Whether the checkbox is checked, or "mixed". */ - checked: boolean | string; + checked: boolean | "mixed"; /** * Whether the toggle button is checked, or "mixed". */ - pressed: boolean | string; + pressed: boolean | "mixed"; /** * The level of a heading. */ @@ -1620,9 +1624,9 @@ export interface Page extends EventEmitter, FrameBase { /** * Determines whether cache is enabled on the page. - * @param enabled Whether or not to enable cache on the page. + * @param [enabled=true] Whether or not to enable cache on the page. */ - setCacheEnabled(enabled: boolean): Promise; + setCacheEnabled(enabled?: boolean): Promise; /** * Sets the cookies on the page. @@ -1933,27 +1937,7 @@ export interface Target { url(): string; } -export interface LaunchOptions extends Timeoutable { - /** - * Whether to open chrome in appMode. - * @default false - */ - appMode?: boolean; - /** - * Whether to ignore HTTPS errors during navigation. - * @default false - */ - ignoreHTTPSErrors?: boolean; - /** - * Do not use `puppeteer.defaultArgs()` for launching Chromium. - * @default false - */ - ignoreDefaultArgs?: boolean | string[]; - /** - * Whether to run Chromium in headless mode. - * @default true - */ - headless?: boolean; +export interface LaunchOptions extends ChromeArgOptions, BrowserOptions, Timeoutable { /** * Path to a Chromium executable to run instead of bundled Chromium. If * executablePath is a relative path, then it is resolved relative to current @@ -1961,10 +1945,73 @@ export interface LaunchOptions extends Timeoutable { */ executablePath?: string; /** - * Slows down Puppeteer operations by the specified amount of milliseconds. - * Useful so that you can see what is going on. + * Do not use `puppeteer.defaultArgs()` for launching Chromium. + * @default false */ - slowMo?: number; + ignoreDefaultArgs?: boolean | string[]; + /** + * Close chrome process on Ctrl-C. + * @default true + */ + handleSIGINT?: boolean; + /** + * Close chrome process on SIGTERM. + * @default true + */ + handleSIGTERM?: boolean; + /** + * Close chrome process on SIGHUP. + * @default true + */ + handleSIGHUP?: boolean; + /** + * Whether to pipe browser process stdout and stderr into process.stdout and + * process.stderr. + * @default false + */ + dumpio?: boolean; + /** + * Specify environment variables that will be visible to Chromium. + * @default `process.env`. + */ + env?: { + [key: string]: string | boolean | number; + }; + /** + * Connects to the browser over a pipe instead of a WebSocket. + * @default false + */ + pipe?: boolean; +} + +export interface ChromeArgOptions { + /** + * Whether to run browser in headless mode. + * @default true unless the devtools option is true. + */ + headless?: boolean; + /** + * Additional arguments to pass to the browser instance. + * The list of Chromium flags can be found here. + */ + args?: string[]; + /** + * Path to a User Data Directory. + */ + userDataDir?: string; + /** + * Whether to auto-open a DevTools panel for each tab. + * If this option is true, the headless option will be set false. + */ + devtools?: boolean; +} + +export interface BrowserOptions { + /** + * Whether to ignore HTTPS errors during navigation. + * @default false + */ + ignoreHTTPSErrors?: boolean; /** * Sets a consistent viewport for each page. Defaults to an 800x600 viewport. null disables the default viewport. */ @@ -1988,7 +2035,6 @@ export interface LaunchOptions extends Timeoutable { */ isMobile?: boolean; /** - * * Specifies if viewport supports touch events. * @default false */ @@ -1998,83 +2044,28 @@ export interface LaunchOptions extends Timeoutable { * @default false */ isLandscape?: boolean; - }; + } | null; /** - * Additional arguments to pass to the Chromium instance. List of Chromium - * flags can be found here. + * Slows down Puppeteer operations by the specified amount of milliseconds. + * Useful so that you can see what is going on. */ - args?: string[]; - /** - * Close chrome process on Ctrl-C. - * @default true - */ - handleSIGINT?: boolean; - /** - * Close chrome process on SIGTERM. - * @default true - */ - handleSIGTERM?: boolean; - /** - * Close chrome process on SIGHUP. - * @default true - */ - handleSIGHUP?: boolean; - /** - * Whether to pipe browser process stdout and stderr into process.stdout and - * process.stderr. - * @default false - */ - dumpio?: boolean; - /** Path to a User Data Directory. */ - userDataDir?: string; - /** - * Specify environment variables that will be visible to Chromium. - * @default `process.env`. - */ - env?: { - [key: string]: string | boolean | number; - }; - /** - * Whether to auto-open DevTools panel for each tab. If this option is true, the headless option will be set false. - */ - devtools?: boolean; - /** - * Connects to the browser over a pipe instead of a WebSocket. - * @default false - */ - pipe?: boolean; + slowMo?: number; } -export interface DefaultArgsOptions { - /** - * Whether to run browser in headless mode. - * @default true unless the devtools option is true. - */ - headless?: boolean; - /** - * Additional arguments to pass to the browser instance. - * The list of Chromium flags can be found here. - */ - args?: string[]; - /** - * Path to a User Data Directory. - */ - userDataDir?: string; - /** - * Whether to auto-open a DevTools panel for each tab. - * If this option is true, the headless option will be set false. - */ - devtools?: boolean; -} - -export interface ConnectOptions { +export interface ConnectOptions extends BrowserOptions { /** A browser websocket endpoint to connect to. */ browserWSEndpoint?: string; /** - * Whether to ignore HTTPS errors during navigation. - * @default false + * **Experimental** Specify a custom transport object for Puppeteer to use. */ - ignoreHTTPSErrors?: boolean; + transport?: ConnectionTransport; +} + +export interface ConnectionTransport { + send(message: string): void; + close(): void; + onmessage?(message: string): void; + onclose?(): void; } export interface CDPSession extends EventEmitter { @@ -2119,7 +2110,7 @@ export interface CoverageEntry { /** Attaches Puppeteer to an existing Chromium instance */ export function connect(options?: ConnectOptions): Promise; /** The default flags that Chromium will be launched with */ -export function defaultArgs(options?: DefaultArgsOptions): string[]; +export function defaultArgs(options?: ChromeArgOptions): string[]; /** Path where Puppeteer expects to find bundled Chromium */ export function executablePath(): string; /** The method launches a browser instance with given arguments. The browser will be closed when the parent node.js process is closed. */ diff --git a/types/puppeteer/puppeteer-tests.ts b/types/puppeteer/puppeteer-tests.ts index b708f1bc0c..e2a559d8e6 100644 --- a/types/puppeteer/puppeteer-tests.ts +++ b/types/puppeteer/puppeteer-tests.ts @@ -1,5 +1,6 @@ import * as puppeteer from "puppeteer"; import { TimeoutError } from "puppeteer/Errors"; +import * as Devices from "puppeteer/DeviceDescriptors"; // Accessibility @@ -118,6 +119,7 @@ puppeteer.launch().then(async browser => { }); await page.emulateMedia("screen"); + await page.emulate(Devices['test']); await page.pdf({ path: "page.pdf" }); await page.setRequestInterception(true); @@ -200,6 +202,13 @@ puppeteer.launch().then(async browser => { browser.close(); })(); +// Launching with default viewport disabled +(async () => { + await puppeteer.launch({ + defaultViewport: null + }); +})(); + // Test v0.12 features (async () => { const browser = await puppeteer.launch({ diff --git a/types/puppeteer/tsconfig.json b/types/puppeteer/tsconfig.json index f253604e14..57b57e65aa 100644 --- a/types/puppeteer/tsconfig.json +++ b/types/puppeteer/tsconfig.json @@ -21,6 +21,7 @@ }, "files": [ "Errors.d.ts", + "DeviceDescriptors.d.ts", "index.d.ts", "puppeteer-tests.ts" ] diff --git a/types/q/tslint.json b/types/q/tslint.json index 0bded8e292..4af8abbc8d 100644 --- a/types/q/tslint.json +++ b/types/q/tslint.json @@ -7,6 +7,7 @@ "no-unnecessary-type-assertion": false, "prefer-declare-function": false, "strict-export-declare-modifiers": false, - "unified-signatures": false + "unified-signatures": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/q/v0/tslint.json b/types/q/v0/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/q/v0/tslint.json +++ b/types/q/v0/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/qtip2/tslint.json b/types/qtip2/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/qtip2/tslint.json +++ b/types/qtip2/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/rabbitmq-schema/index.d.ts b/types/rabbitmq-schema/index.d.ts new file mode 100644 index 0000000000..3c607115ab --- /dev/null +++ b/types/rabbitmq-schema/index.d.ts @@ -0,0 +1,71 @@ +// Type definitions for rabbitmq-schema 2.0 +// Project: https://github.com/tjmehta/rabbitmq-schema +// Definitions by: Alex Duka +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +interface Binding { + destination: Exchange | Queue; + source: Exchange; + args?: object; + routingPattern?: string; +} + +interface TopicBinding extends Binding { + routingPattern: string; +} + +interface DirectBinding extends Binding { + routingPattern: string; +} + +interface Topology { + options?: object; +} + +interface Exchange extends Topology { + exchange: string; + type: string; + bindings: Binding[]; +} + +interface FanoutExchange extends Exchange { + type: 'fanout'; +} + +interface TopicExchange extends Exchange { + type: 'topic'; + bindings: TopicBinding[]; +} + +interface DirectExchange extends Exchange { + type: 'direct'; + bindings: DirectBinding[]; +} + +interface Queue extends Topology { + queue: string; + messageSchema: object; +} + +declare class RabbitMQSchema { + constructor(schema: Topology | Topology[], parentPath?: string); + + getExchanges(): Exchange[]; + + getBindings(): Binding[]; + + getQueues(): Queue[]; + + getDirectBindings(): DirectBinding[]; + + validate(schema: Topology | Topology[], parentPath?: string): void; + + validateMessage(exchangeName: string, routingPattern: string, message: T): T; + + getQueueByName(name: string): Queue | void; + + getExchangeByName(name: string): Exchange | void; +} + +export = RabbitMQSchema; diff --git a/types/rabbitmq-schema/rabbitmq-schema-tests.ts b/types/rabbitmq-schema/rabbitmq-schema-tests.ts new file mode 100644 index 0000000000..067c9c3c5a --- /dev/null +++ b/types/rabbitmq-schema/rabbitmq-schema-tests.ts @@ -0,0 +1,16 @@ +import RabbitMqSchema = require('rabbitmq-schema'); + +const topology = {}; + +const rabbitSchema = new RabbitMqSchema({}, ''); + +rabbitSchema.getExchanges(); +rabbitSchema.getBindings(); +rabbitSchema.getQueues(); +rabbitSchema.getDirectBindings(); + +rabbitSchema.getQueueByName('images.jpeg.get'); +rabbitSchema.getExchangeByName('images'); + +rabbitSchema.validate(topology); +rabbitSchema.validateMessage('images', 'images.jpeg.get', {testMsg: 'ok'}); diff --git a/types/rabbitmq-schema/tsconfig.json b/types/rabbitmq-schema/tsconfig.json new file mode 100644 index 0000000000..81e519bb47 --- /dev/null +++ b/types/rabbitmq-schema/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "strictFunctionTypes": true, + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "rabbitmq-schema-tests.ts" + ] +} diff --git a/types/rabbitmq-schema/tslint.json b/types/rabbitmq-schema/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/rabbitmq-schema/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/radix64/index.d.ts b/types/radix64/index.d.ts new file mode 100644 index 0000000000..f376184fce --- /dev/null +++ b/types/radix64/index.d.ts @@ -0,0 +1,23 @@ +// Type definitions for radix64 1.1 +// Project: https://github.com/maxired/radix64 +// Definitions by: Jeow Li Huan +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +type MethodsString = 'base64' | 'base64URL' | 'base64URLNaturalSort' | 'base64URLASCIISort'; + +interface MethodsEnum { + BASE64: MethodsString; + BASE64URL: MethodsString; + BASE64NATURAL: MethodsString; + BASE64ASCII: MethodsString; + DEFAULT: MethodsString; +} + +interface Radix { + radix64: (number: number, method?: MethodsString) => string; + ascii64: (number: number, pad?: number) => string; + methods: MethodsEnum; +} + +declare const radix: Radix; +export = radix; diff --git a/types/radix64/radix64-tests.ts b/types/radix64/radix64-tests.ts new file mode 100644 index 0000000000..a77554c238 --- /dev/null +++ b/types/radix64/radix64-tests.ts @@ -0,0 +1,11 @@ +import radix64 = require("radix64"); + +const num: string = radix64.radix64(42); + +const numAndEnum: string = radix64.radix64(1337, radix64.methods.BASE64NATURAL); + +const numAndString: string = radix64.radix64(1337, 'base64URL'); + +const asciiNum: string = radix64.ascii64(42); + +const asciiNumAndPad: string = radix64.ascii64(42, 25); diff --git a/types/radix64/tsconfig.json b/types/radix64/tsconfig.json new file mode 100644 index 0000000000..362ad6d26e --- /dev/null +++ b/types/radix64/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "radix64-tests.ts" + ] +} diff --git a/types/radix64/tslint.json b/types/radix64/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/radix64/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/ramda/index.d.ts b/types/ramda/index.d.ts index a3bc51c8ca..026da15ec9 100644 --- a/types/ramda/index.d.ts +++ b/types/ramda/index.d.ts @@ -777,6 +777,7 @@ declare namespace R { * matches, fn returns undefined. */ cond(fns: ReadonlyArray<[Pred, (...a: any[]) => any]>): (...a: any[]) => any; + cond(fns: ReadonlyArray<[SafePred, (...a: A[]) => B]>): (...a: A[]) => B; /** * Wraps a constructor function inside a curried function that can be called with the same arguments and returns the same type. @@ -1122,6 +1123,7 @@ declare namespace R { * of the condition predicate. */ ifElse(fn: Pred, onTrue: Arity1Fn, onFalse: Arity1Fn): Arity1Fn; + ifElse(fn: Pred, onTrue: Arity2Fn, onFalse: Arity2Fn): Arity2Fn; /** * Increments its argument. diff --git a/types/ramda/ramda-tests.ts b/types/ramda/ramda-tests.ts index 2f68808d17..2e292ffd59 100644 --- a/types/ramda/ramda-tests.ts +++ b/types/ramda/ramda-tests.ts @@ -1306,14 +1306,21 @@ type Pair = KeyValuePair; }; () => { - const fn = R.cond([ - [R.equals(0), R.always("water freezes at 0°C")], - [R.equals(100), R.always("water boils at 100°C")], - [R.T, (temp: number) => `nothing special happens at ${temp}°C`] + const f = R.cond([ + [x => x === 0, () => "a"], + [() => true, () => "b"], ]); - const a: string = fn(0); // => 'water freezes at 0°C' - const b: string = fn(50); // => 'nothing special happens at 50°C' - const c: string = fn(100); // => 'water boils at 100°C' + f(0); // $ExpectType string + f(""); // $ExpectError + f(1, 2); // $ExpectType string + + const g = R.cond([ + [(a, b) => a === b, () => "a"], + [() => true, () => "b"], + ]); + g(0); + g(""); + g(1, ""); }; () => { @@ -2650,6 +2657,17 @@ class Rectangle { flattenArrays([[[10], 123], [8, [10]], "hello"]); // => [[10, 123], [8, 10], "hello"] }; +() => { + const incCount = R.ifElse( + R.has('count'), + R.over(R.lensProp('count'), R.inc), + R.assoc('count', 1) + ); + incCount({}); // => { count: 1 } + incCount({ count: 1 }); // => { count: 2 } + R.ifElse(R.identical, R.add as (a: number, b: number) => number, R.always(""))(2, 2); // https://goo.gl/CVUSs9 +}; + () => { R.isEmpty([1, 2, 3]); // => false R.isEmpty([]); // => true diff --git a/types/random-boolean/index.d.ts b/types/random-boolean/index.d.ts new file mode 100644 index 0000000000..3390da9317 --- /dev/null +++ b/types/random-boolean/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for random-boolean 1.0 +// Project: https://github.com/arthurvr/random-boolean#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = randomBoolean; + +declare function randomBoolean(): boolean; diff --git a/types/random-boolean/random-boolean-tests.ts b/types/random-boolean/random-boolean-tests.ts new file mode 100644 index 0000000000..8ac983e111 --- /dev/null +++ b/types/random-boolean/random-boolean-tests.ts @@ -0,0 +1,4 @@ +import randomBoolean = require('random-boolean'); + +// $ExpectType boolean +randomBoolean(); diff --git a/types/random-boolean/tsconfig.json b/types/random-boolean/tsconfig.json new file mode 100644 index 0000000000..7392190732 --- /dev/null +++ b/types/random-boolean/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "random-boolean-tests.ts" + ] +} diff --git a/types/random-boolean/tslint.json b/types/random-boolean/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/random-boolean/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/random-float/index.d.ts b/types/random-float/index.d.ts new file mode 100644 index 0000000000..646d263128 --- /dev/null +++ b/types/random-float/index.d.ts @@ -0,0 +1,9 @@ +// Type definitions for random-float 1.0 +// Project: https://github.com/sindresorhus/random-float +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = randomFloat; + +declare function randomFloat(max: number): number; +declare function randomFloat(min: number, max: number): number; // tslint:disable-line unified-signatures diff --git a/types/random-float/random-float-tests.ts b/types/random-float/random-float-tests.ts new file mode 100644 index 0000000000..663190ce81 --- /dev/null +++ b/types/random-float/random-float-tests.ts @@ -0,0 +1,6 @@ +import randomFloat = require('random-float'); + +// $ExpectType number +randomFloat(5); +// $ExpectType number +randomFloat(10, 100); diff --git a/types/random-float/tsconfig.json b/types/random-float/tsconfig.json new file mode 100644 index 0000000000..faefa13645 --- /dev/null +++ b/types/random-float/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "random-float-tests.ts" + ] +} diff --git a/types/random-float/tslint.json b/types/random-float/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/random-float/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/random-int/index.d.ts b/types/random-int/index.d.ts new file mode 100644 index 0000000000..6f7f421976 --- /dev/null +++ b/types/random-int/index.d.ts @@ -0,0 +1,9 @@ +// Type definitions for random-int 1.0 +// Project: https://github.com/sindresorhus/random-int +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = randomInt; + +declare function randomInt(max: number): number; +declare function randomInt(min: number, max: number): number; // tslint:disable-line unified-signatures diff --git a/types/random-int/random-int-tests.ts b/types/random-int/random-int-tests.ts new file mode 100644 index 0000000000..68165e9c5d --- /dev/null +++ b/types/random-int/random-int-tests.ts @@ -0,0 +1,6 @@ +import randomInt = require('random-int'); + +// $ExpectType number +randomInt(5); +// $ExpectType number +randomInt(10, 100); diff --git a/types/random-int/tsconfig.json b/types/random-int/tsconfig.json new file mode 100644 index 0000000000..e1a576d337 --- /dev/null +++ b/types/random-int/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "random-int-tests.ts" + ] +} diff --git a/types/random-int/tslint.json b/types/random-int/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/random-int/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/random-item/index.d.ts b/types/random-item/index.d.ts new file mode 100644 index 0000000000..3fbbaca074 --- /dev/null +++ b/types/random-item/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for random-item 1.0 +// Project: https://github.com/sindresorhus/random-item +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = randomItem; + +declare function randomItem(input: T[]): T; diff --git a/types/random-item/random-item-tests.ts b/types/random-item/random-item-tests.ts new file mode 100644 index 0000000000..12185a0ad2 --- /dev/null +++ b/types/random-item/random-item-tests.ts @@ -0,0 +1,6 @@ +import randomItem = require('random-item'); + +// $ExpectType string +randomItem(['pony', 'unicorn', 'rainbow']); +// $ExpectType string | number +randomItem(['pony', 'unicorn', 'rainbow', 1]); diff --git a/types/random-item/tsconfig.json b/types/random-item/tsconfig.json new file mode 100644 index 0000000000..279aba16b5 --- /dev/null +++ b/types/random-item/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "random-item-tests.ts" + ] +} diff --git a/types/random-item/tslint.json b/types/random-item/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/random-item/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/random-obj-prop/index.d.ts b/types/random-obj-prop/index.d.ts new file mode 100644 index 0000000000..f9aca5624f --- /dev/null +++ b/types/random-obj-prop/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for random-obj-prop 1.0 +// Project: https://github.com/sindresorhus/random-obj-prop +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = randomObjProp; + +declare function randomObjProp(input: { [key: string]: T }): T; diff --git a/types/random-obj-prop/random-obj-prop-tests.ts b/types/random-obj-prop/random-obj-prop-tests.ts new file mode 100644 index 0000000000..7dd2fcd67d --- /dev/null +++ b/types/random-obj-prop/random-obj-prop-tests.ts @@ -0,0 +1,4 @@ +import randomObjProp = require('random-obj-prop'); + +// $ExpectType string | number +randomObjProp({ foo: 'pony', bar: 1 }); diff --git a/types/random-obj-prop/tsconfig.json b/types/random-obj-prop/tsconfig.json new file mode 100644 index 0000000000..f155cfc211 --- /dev/null +++ b/types/random-obj-prop/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "random-obj-prop-tests.ts" + ] +} diff --git a/types/random-obj-prop/tslint.json b/types/random-obj-prop/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/random-obj-prop/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/randombytes/index.d.ts b/types/randombytes/index.d.ts new file mode 100644 index 0000000000..049f893870 --- /dev/null +++ b/types/randombytes/index.d.ts @@ -0,0 +1,12 @@ +// Type definitions for randombytes 2.0 +// Project: https://github.com/crypto-browserify/randombytes +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import { randomBytes as _randomBytes } from 'crypto'; + +export = randomBytes; + +declare const randomBytes: typeof _randomBytes; diff --git a/types/randombytes/randombytes-tests.ts b/types/randombytes/randombytes-tests.ts new file mode 100644 index 0000000000..583fa685ec --- /dev/null +++ b/types/randombytes/randombytes-tests.ts @@ -0,0 +1,11 @@ +import randomBytes = require('randombytes'); + +// $ExpectType Buffer +randomBytes(16); +// $ExpectType void +randomBytes(16, (err, resp) => { + // $ExpectType Error | null + err; + // $ExpectType Buffer + resp; +}); diff --git a/types/randombytes/tsconfig.json b/types/randombytes/tsconfig.json new file mode 100644 index 0000000000..31ecde389d --- /dev/null +++ b/types/randombytes/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "randombytes-tests.ts" + ] +} diff --git a/types/randombytes/tslint.json b/types/randombytes/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/randombytes/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/range-parser/index.d.ts b/types/range-parser/index.d.ts index a1bcf4c9dc..e8e6ae4451 100644 --- a/types/range-parser/index.d.ts +++ b/types/range-parser/index.d.ts @@ -4,11 +4,11 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /** - * Returns `-1` when unsatisfiable and `-2` when syntactically invalid. - * * When ranges are returned, the array has a "type" property which is the type of * range that is required (most commonly, "bytes"). Each array element is an object * with a "start" and "end" property for the portion of the range. + * + * @returns `-1` when unsatisfiable and `-2` when syntactically invalid, ranges otherwise. */ declare function RangeParser(size: number, str: string, options?: RangeParser.Options): RangeParser.Result | RangeParser.Ranges; @@ -27,10 +27,9 @@ declare namespace RangeParser { */ combine?: boolean; } - const enum Result { - invaild = -2, - unsatisifiable = -1, - } + type ResultUnsatisfiable = -1; + type ResultInvalid = -2; + type Result = ResultUnsatisfiable | ResultInvalid; } export = RangeParser; diff --git a/types/range-parser/range-parser-tests.ts b/types/range-parser/range-parser-tests.ts index ec1ffa6e4e..2c18e3f9dc 100644 --- a/types/range-parser/range-parser-tests.ts +++ b/types/range-parser/range-parser-tests.ts @@ -2,8 +2,8 @@ import RangeParser = require('range-parser'); declare var console: { assert(b: boolean): void }; -console.assert(RangeParser(200, `malformed`) === RangeParser.Result.invaild); -console.assert(RangeParser(200, `bytes=500-20`) === RangeParser.Result.unsatisifiable); +console.assert(RangeParser(200, `malformed`) === -2); +console.assert(RangeParser(200, `bytes=500-20`) === -1); const range = RangeParser(1000, `bytes=0-499`); diff --git a/types/range-parser/tsconfig.json b/types/range-parser/tsconfig.json index 15585886a9..dc6de494bf 100644 --- a/types/range-parser/tsconfig.json +++ b/types/range-parser/tsconfig.json @@ -20,4 +20,4 @@ "index.d.ts", "range-parser-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/react-albus/index.d.ts b/types/react-albus/index.d.ts index be546011d4..ccc0ac8582 100644 --- a/types/react-albus/index.d.ts +++ b/types/react-albus/index.d.ts @@ -9,13 +9,13 @@ import * as React from "react"; import { History } from "history"; -export interface WizardStepObject { +export interface StepObject { id: string; } export interface WizardContext { - step: WizardStepObject; - steps: WizardStepObject[]; + step: StepObject; + steps: StepObject[]; history: History; next: () => void; previous: () => void; @@ -42,13 +42,24 @@ export interface WizardProps { export const Wizard: React.ComponentType; export interface StepsProps { - step?: WizardStepObject; + step?: StepObject; } export const Steps: React.ComponentType; -export type StepProps = { id: string } & ( +export type StepProps = StepObject & ( | { render?: (wizard: WizardContext) => React.ReactNode } | { children: (wizard: WizardContext) => React.ReactNode }); +/** + * In addition to id, any additional props added to will be available on each step object. + * This can be used to add names, descriptions, or other metadata to each step. + * To use this feature globally in your project you need to augment the StepObject + * @example + * declare module "react-albus" { + * interface StepObject { + * propName: string; + * } + * } + */ export const Step: React.ComponentType; diff --git a/types/react-albus/react-albus-tests.tsx b/types/react-albus/react-albus-tests.tsx index 2f31733b1d..57fe8147d1 100644 --- a/types/react-albus/react-albus-tests.tsx +++ b/types/react-albus/react-albus-tests.tsx @@ -1,6 +1,12 @@ import * as React from "react"; import { Wizard, Step, Steps, withWizard } from "react-albus"; +declare module "react-albus" { + interface StepObject { + quote?: string; + } +} + const Example = () => ( ( (

Merlin

@@ -28,6 +35,7 @@ const Example = () => ( /> (

Gandalf

diff --git a/types/react-big-calendar/index.d.ts b/types/react-big-calendar/index.d.ts index 790a5887cb..89e6f0eead 100644 --- a/types/react-big-calendar/index.d.ts +++ b/types/react-big-calendar/index.d.ts @@ -216,19 +216,19 @@ export class DateLocalizer { format(value: FormatInput, format: string, culture: Culture): string; } -export interface BigCalendarProps extends React.Props> { +export interface BigCalendarProps extends React.Props> { localizer: DateLocalizer; date?: stringOrDate; now?: Date; view?: View; - events?: T[]; - onNavigate?: (newDate: Date, action: Navigate) => void; + events?: TEvent[]; + onNavigate?: (newDate: Date, view: View, action: Navigate) => void; onView?: (view: View) => void; onDrillDown?: (date: Date, view: View) => void; onSelectSlot?: (slotInfo: { start: stringOrDate, end: stringOrDate, slots: Date[] | string[], action: 'select' | 'click' | 'doubleClick' }) => void; - onDoubleClickEvent?: (event: T, e: React.SyntheticEvent) => void; - onSelectEvent?: (event: T, e: React.SyntheticEvent) => void; + onDoubleClickEvent?: (event: TEvent, e: React.SyntheticEvent) => void; + onSelectEvent?: (event: TEvent, e: React.SyntheticEvent) => void; onSelecting?: (range: { start: stringOrDate, end: stringOrDate }) => boolean | undefined | null; selected?: any; views?: Views; @@ -243,7 +243,7 @@ export interface BigCalendarProps extends React.Props; + eventPropGetter?: EventPropGetter; slotPropGetter?: SlotPropGetter; dayPropGetter?: DayPropGetter; showMultiDayTimes?: boolean; @@ -254,14 +254,14 @@ export interface BigCalendarProps extends React.Props string); - allDayAccessor?: keyof T | ((event: T) => boolean); - startAccessor?: keyof T | ((event: T) => Date); - endAccessor?: keyof T | ((event: T) => Date); - resourceAccessor?: keyof T | ((event: T) => any); - resources?: any[]; - resourceIdAccessor?: keyof T | ((event: T) => any); - resourceTitleAccessor?: keyof T | ((event: T) => string); + titleAccessor?: keyof TEvent | ((event: TEvent) => string); + allDayAccessor?: keyof TEvent | ((event: TEvent) => boolean); + startAccessor?: keyof TEvent | ((event: TEvent) => Date); + endAccessor?: keyof TEvent | ((event: TEvent) => Date); + resourceAccessor?: keyof TEvent | ((event: TEvent) => any); + resources?: TResource[]; + resourceIdAccessor?: keyof TResource | ((resource: TResource) => any); + resourceTitleAccessor?: keyof TResource | ((resource: TResource) => string); defaultView?: View; defaultDate?: Date; className?: string; @@ -278,7 +278,7 @@ export interface MoveOptions { today: Date; } -export default class BigCalendar extends React.Component> { +export default class BigCalendar extends React.Component> { components: { dateCellWrapper: React.ComponentType, dayWrapper: React.ComponentType, diff --git a/types/react-big-calendar/react-big-calendar-tests.tsx b/types/react-big-calendar/react-big-calendar-tests.tsx index 321327e8e7..fd1e70f929 100644 --- a/types/react-big-calendar/react-big-calendar-tests.tsx +++ b/types/react-big-calendar/react-big-calendar-tests.tsx @@ -17,13 +17,25 @@ class CalendarEvent { start: Date; end: Date; desc: string; + resourceId?: string; - constructor(_title: string, _start: Date, _end: Date, _allDay?: boolean, _desc?: string) { + constructor(_title: string, _start: Date, _end: Date, _allDay?: boolean, _desc?: string, _resourceId?: string) { this.title = _title; this.allDay = _allDay || false; this.start = _start; this.end = _end; this.desc = _desc || ''; + this.resourceId = _resourceId; + } +} + +class CalendarResource { + title: string; + id: string; + + constructor(id: string, title: string) { + this.id = id; + this.title = title; } } @@ -49,66 +61,70 @@ class CalendarEvent { } { + class MyCalendar extends BigCalendar {} + // Full API Example Test - based on API Documentation // http://intljusticemission.github.io/react-big-calendar/examples/index.html#api - class FullAPIExample extends React.Component> { + class FullAPIExample extends React.Component> { render() { return ( - { }} - onView={(view: View) => { }} - onSelectSlot={(slotInfo) => { - const start = slotInfo.start; - const end = slotInfo.end; - const slots = slotInfo.slots; - }} - onSelectEvent={(event) => { }} - onSelecting={(slotInfo) => { - const start = slotInfo.start; - const end = slotInfo.end; - return true; - }} - views={['day']} - toolbar={true} - popup={true} - popupOffset={20} - selectable={true} - step={20} - rtl={true} - eventPropGetter={(event, start, end, isSelected) => ({ className: 'some-class' })} - titleAccessor={'title'} - allDayAccessor={(event: any) => !!event.allDay} - startAccessor={'start'} - endAccessor={(event: any) => event.end || event.start} - min={new Date()} - max={new Date()} - scrollToTime={new Date()} - formats={{ - dateFormat: "h a", - agendaDateFormat: (date: Date, culture?: string, localizer?: object) => "some-format", - dayRangeHeaderFormat: (range: DateRange, culture?: string, localizer?: object) => "some-format" - }} - messages={{}} - timeslots={24} - defaultView={'month'} - className={'my-calendar'} - elementProps={{ id: 'myCalendar' }} - components={{ - event: Event, - agenda: { - event: EventAgenda - }, - toolbar: Toolbar, - eventWrapper: EventWrapper, - }} - dayPropGetter={customDayPropGetter} - slotPropGetter={customSlotPropGetter} - defaultDate={new Date()} - /> + { }} + onView={(view: View) => { }} + onSelectSlot={(slotInfo) => { + const start = slotInfo.start; + const end = slotInfo.end; + const slots = slotInfo.slots; + }} + onSelectEvent={(event) => { }} + onSelecting={(slotInfo) => { + const start = slotInfo.start; + const end = slotInfo.end; + return true; + }} + views={['day']} + toolbar={true} + popup={true} + popupOffset={20} + selectable={true} + step={20} + rtl={true} + eventPropGetter={(event, start, end, isSelected) => ({ className: 'some-class' })} + titleAccessor={'title'} + allDayAccessor={(event: CalendarEvent) => !!event.allDay} + startAccessor={'start'} + endAccessor={(event: CalendarEvent) => event.end || event.start} + min={new Date()} + max={new Date()} + scrollToTime={new Date()} + formats={{ + dateFormat: "h a", + agendaDateFormat: (date: Date, culture?: string, localizer?: object) => "some-format", + dayRangeHeaderFormat: (range: DateRange, culture?: string, localizer?: object) => "some-format" + }} + messages={{}} + timeslots={24} + defaultView={'month'} + className={'my-calendar'} + elementProps={{ id: 'myCalendar' }} + components={{ + event: Event, + agenda: { + event: EventAgenda + }, + toolbar: Toolbar, + eventWrapper: EventWrapper, + }} + dayPropGetter={customDayPropGetter} + slotPropGetter={customSlotPropGetter} + defaultDate={new Date()} + resources={getResources()} + resourceAccessor={event => event.resourceId} + resourceIdAccessor={resource => resource.id} + resourceTitleAccessor={resource => resource.title} /> ); } } @@ -132,10 +148,19 @@ function getEvents(): CalendarEvent[] { new CalendarEvent('Happy Hour', new Date(2015, 3, 12, 17, 0, 0, 0), new Date(2015, 3, 12, 17, 30, 0, 0), undefined, 'Most important meal of the day'), new CalendarEvent('Dinner', new Date(2015, 3, 12, 20, 0, 0, 0), new Date(2015, 3, 12, 21, 0, 0, 0)), new CalendarEvent('Birthday Party', new Date(2015, 3, 13, 7, 0, 0), new Date(2015, 3, 13, 10, 30, 0)), + new CalendarEvent('Alice\'s break', new Date(2015, 3, 14, 20, 0, 0, 0), new Date(2015, 3, 14, 21, 0, 0, 0), undefined, undefined, "alice"), + new CalendarEvent('Bob\'s break', new Date(2015, 3, 15, 7, 0, 0), new Date(2015, 3, 15, 10, 30, 0), undefined, undefined, "bob"), ]; return events; } +function getResources(): CalendarResource[] { + return [ + new CalendarResource('alice', 'Alice'), + new CalendarResource('bob', 'Bob') + ]; +} + class EventAgenda extends React.Component { render() { // const { label } = this.props; diff --git a/types/react-bootstrap-typeahead/index.d.ts b/types/react-bootstrap-typeahead/index.d.ts index 52f99825d5..6e5fc2cbf0 100644 --- a/types/react-bootstrap-typeahead/index.d.ts +++ b/types/react-bootstrap-typeahead/index.d.ts @@ -1,29 +1,13 @@ -// Type definitions for react-bootstrap-typeahead 3.4 +// Type definitions for react-bootstrap-typeahead 3.2 // Project: https://github.com/ericgio/react-bootstrap-typeahead // Definitions by: Guymestef // Rajab Shakirov // Paito Anderson -// Andreas Richter // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 -// TODO: components +// TODO: , , , components import * as React from 'react'; -import * as CSS from 'csstype'; - -export interface TypeaheadFilterbyProps { - filterBy: string[]; - labelKey: (string | (() => void)); - multiple: boolean; - selected: any[]; - caseSensitive: boolean; - ignoreDiacritics: boolean; - text: string; -} - -export interface TypeaheadMenuProps { - text: string; -} export interface TypeaheadProps { /* For localized accessibility: Should return a string indicating the number of results for screen readers. Receives the current results. */ @@ -74,7 +58,7 @@ export interface TypeaheadProps { emptyLabel?: string; /* Either an array of fields in option to search, or a custom filtering callback. */ - filterBy?: (string[] | ((option: T | string, props: TypeaheadFilterbyProps) => boolean)); + filterBy?: (string[] | ((option: T | string, text: string) => boolean)); /* Highlights the menu item if there is only one result and allows selecting that item by hitting enter. Does not work with allowNew. */ @@ -154,7 +138,7 @@ export interface TypeaheadProps { renderMenu?: (results: Array, menuProps: any) => any; /* Provides a hook for customized rendering of menu item contents. */ - renderMenuItemChildren?: (option: T, props: TypeaheadMenuProps, index: number) => any; + renderMenuItemChildren?: (option: T, props: TypeaheadProps, index: number) => any; /* Provides a hook for customized rendering of tokens when multiple selections are enabled. */ renderToken?: (selectedItem: T | string, onRemove: () => void) => any; diff --git a/types/react-bootstrap-typeahead/react-bootstrap-typeahead-tests.tsx b/types/react-bootstrap-typeahead/react-bootstrap-typeahead-tests.tsx index c77052a3c6..6f302b4a55 100644 --- a/types/react-bootstrap-typeahead/react-bootstrap-typeahead-tests.tsx +++ b/types/react-bootstrap-typeahead/react-bootstrap-typeahead-tests.tsx @@ -1,5 +1,5 @@ import * as React from 'react'; -import { Typeahead, Highlighter, Menu, MenuItem } from 'react-bootstrap-typeahead'; +import { Typeahead } from 'react-bootstrap-typeahead'; const options = [ { name: 'Alabama', population: 4780127, capital: 'Montgomery', region: 'South' }, diff --git a/types/react-burger-menu/index.d.ts b/types/react-burger-menu/index.d.ts index 85d49494c2..544dd84aec 100644 --- a/types/react-burger-menu/index.d.ts +++ b/types/react-burger-menu/index.d.ts @@ -16,6 +16,7 @@ export interface Styles { bmCross: Partial; bmCrossButton: Partial; bmItemList: Partial; + bmMenuWrap: Partial; bmMenu: Partial; bmMorphShape: Partial; bmOverlay: Partial; diff --git a/types/react-css-collapse/index.d.ts b/types/react-css-collapse/index.d.ts new file mode 100644 index 0000000000..e454d5946b --- /dev/null +++ b/types/react-css-collapse/index.d.ts @@ -0,0 +1,18 @@ +// Type definitions for react-css-collapse 3.6 +// Project: https://github.com/SparebankenVest/react-css-collapse +// Definitions by: Daniel Ford +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +declare module 'react-css-collapse' { + interface Props { + isOpen: boolean; + className?: string | null; + onRest?: () => void; + transition?: string | null; + } + class Collapse extends React.Component { + render(): React.ReactElement; + } + export default Collapse; +} diff --git a/types/react-css-collapse/react-css-collapse-tests.tsx b/types/react-css-collapse/react-css-collapse-tests.tsx new file mode 100644 index 0000000000..3b699b530d --- /dev/null +++ b/types/react-css-collapse/react-css-collapse-tests.tsx @@ -0,0 +1,14 @@ +import * as React from "react"; +import { SFC } from "react"; +import { render } from "react-dom"; +import Collapse from "react-css-collapse"; + +const TestOpen: SFC = () => ( + +
+ i am open +
+
+); + +render(, document.getElementById("main")); diff --git a/types/react-css-collapse/tsconfig.json b/types/react-css-collapse/tsconfig.json new file mode 100644 index 0000000000..efb2921718 --- /dev/null +++ b/types/react-css-collapse/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "jsx": "react" + }, + "files": [ + "index.d.ts", + "react-css-collapse-tests.tsx" + ] +} diff --git a/types/react-css-collapse/tslint.json b/types/react-css-collapse/tslint.json new file mode 100644 index 0000000000..9e934cc4fe --- /dev/null +++ b/types/react-css-collapse/tslint.json @@ -0,0 +1,8 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "no-single-declare-module": false, + "no-declare-current-package": false, + "no-duplicate-imports": false + } +} diff --git a/types/react-data-grid/index.d.ts b/types/react-data-grid/index.d.ts index b41c2c2501..94d8af72d9 100644 --- a/types/react-data-grid/index.d.ts +++ b/types/react-data-grid/index.d.ts @@ -583,7 +583,7 @@ declare namespace AdazzleReactDataGrid { declare namespace AdazzleReactDataGridPlugins { interface AutoCompleteEditorProps { onCommit?: () => void; - options?: Array<{ id: number; title: string }>; + options?: Array<{ id: any; title: string }>; label?: any; value?: any; height?: number; diff --git a/types/react-datepicker/index.d.ts b/types/react-datepicker/index.d.ts index 4af6cae9b2..5f07b253f3 100644 --- a/types/react-datepicker/index.d.ts +++ b/types/react-datepicker/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for react-datepicker 1.8 +// Type definitions for react-datepicker 2.0 // Project: https://github.com/Hacker0x01/react-datepicker // Definitions by: Rajab Shakirov , // Andrey Balokha , @@ -8,72 +8,96 @@ // Koala Human // Sean Kelley // Justin Grant +// Jake Boone // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 import * as React from "react"; -import * as moment from "moment"; import * as Popper from "popper.js"; +export function registerLocale(localeName: string, localeData: {}): void; +export function setDefaultLocale(localeName: string): void; +export function getDefaultLocale(): string; + export interface ReactDatePickerProps { adjustDateOnChange?: boolean; allowSameDay?: boolean; autoComplete?: string; autoFocus?: boolean; calendarClassName?: string; + calendarContainer?(props: { children: React.ReactNode[] }): React.ReactNode; children?: React.ReactNode; className?: string; + clearButtonTitle?: string; customInput?: React.ReactNode; customInputRef?: string; dateFormat?: string | string[]; dateFormatCalendar?: string; - dayClassName?(date: moment.Moment): string | null; + dayClassName?(date: Date): string | null; disabled?: boolean; disabledKeyboardNavigation?: boolean; dropdownMode?: 'scroll' | 'select'; - endDate?: moment.Moment; - excludeDates?: moment.Moment[]; - excludeTimes?: moment.Moment[]; - filterDate?(date: moment.Moment): boolean; + endDate?: Date; + excludeDates?: Date[]; + excludeTimes?: Date[]; + filterDate?(date: Date): boolean; fixedHeight?: boolean; forceShowMonthNavigation?: boolean; - formatWeekNumber?(date: moment.Moment): string | number; - highlightDates?: moment.Moment[]; + formatWeekDay?(date: Date): string; + formatWeekNumber?(date: Date): string | number; + highlightDates?: Date[]; id?: string; - includeDates?: moment.Moment[]; - includeTimes?: moment.Moment[]; + includeDates?: Date[]; + includeTimes?: Date[]; + injectTimes?: Date[]; inline?: boolean; isClearable?: boolean; locale?: string; - maxDate?: moment.Moment; - maxTime?: moment.Moment; - minDate?: moment.Moment; - minTime?: moment.Moment; + maxDate?: Date; + maxTime?: Date; + minDate?: Date; + minTime?: Date; monthsShown?: number; name?: string; + nextMonthButtonLabel?: string; onBlur?(event: React.FocusEvent): void; - onChange(date: moment.Moment | null, event: React.SyntheticEvent | undefined): void; + onChange(date: Date | null, event: React.SyntheticEvent | undefined): void; onChangeRaw?(event: React.FocusEvent): void; onClickOutside?(event: React.MouseEvent): void; onFocus?(event: React.FocusEvent): void; + onInputClick?(): void; + onInputError?(err: {code: number; msg: string}): void; onKeyDown?(event: React.KeyboardEvent): void; - onMonthChange?(date: moment.Moment): void; - onSelect?(date: moment.Moment, event: React.SyntheticEvent | undefined): void; - onWeekSelect?(firstDayOfWeek: moment.Moment, weekNumber: string | number, event: React.SyntheticEvent | undefined): void; - onYearChange?(date: moment.Moment): void; - openToDate?: moment.Moment; + onMonthChange?(date: Date): void; + onSelect?(date: Date, event: React.SyntheticEvent | undefined): void; + onWeekSelect?(firstDayOfWeek: Date, weekNumber: string | number, event: React.SyntheticEvent | undefined): void; + onYearChange?(date: Date): void; + open?: boolean; + openToDate?: Date; peekNextMonth?: boolean; placeholderText?: string; popperClassName?: string; popperContainer?(props: { children: React.ReactNode[] }): React.ReactNode; popperModifiers?: Popper.Modifiers; popperPlacement?: string; + popperProps?: {}; preventOpenOnFocus?: boolean; + previousMonthButtonLabel?: string; readOnly?: boolean; + renderCustomHeader?(params: { + date: Date; + changeYear(year: number): void; + changeMonth(month: number): void; + decreaseMonth(): void; + increaseMonth(): void; + prevMonthButtonDisabled: boolean; + nextMonthButtonDisabled: boolean; + }): React.ReactNode; + renderDayContents?(dayOfMonth: number): React.ReactNode; required?: boolean; scrollableMonthYearDropdown?: boolean; scrollableYearDropdown?: boolean; - selected?: moment.Moment | null; + selected?: Date | null; selectsEnd?: boolean; selectsStart?: boolean; shouldCloseOnSelect?: boolean; @@ -84,17 +108,16 @@ export interface ReactDatePickerProps { showTimeSelectOnly?: boolean; showWeekNumbers?: boolean; showYearDropdown?: boolean; - startDate?: moment.Moment; + startDate?: Date; startOpen?: boolean; tabIndex?: number; timeCaption?: string; timeFormat?: string; timeIntervals?: number; title?: string; - todayButton?: string; + todayButton?: React.ReactNode; useShortMonthInDropdown?: boolean; useWeekdaysShort?: boolean; - utcOffset?: number; value?: string; weekLabel?: string; withPortal?: boolean; diff --git a/types/react-datepicker/package.json b/types/react-datepicker/package.json index fc763e4d4b..245f69cd2c 100644 --- a/types/react-datepicker/package.json +++ b/types/react-datepicker/package.json @@ -1,7 +1,6 @@ { "private": true, "dependencies": { - "moment": ">=2.14.0", "popper.js": "^1.14.1" } } diff --git a/types/react-datepicker/react-datepicker-tests.tsx b/types/react-datepicker/react-datepicker-tests.tsx index 1414672684..b47c08ed73 100644 --- a/types/react-datepicker/react-datepicker-tests.tsx +++ b/types/react-datepicker/react-datepicker-tests.tsx @@ -1,18 +1,121 @@ import * as React from 'react'; -import * as moment from 'moment'; -import DatePicker from 'react-datepicker'; +import DatePicker, { + registerLocale, + setDefaultLocale, + getDefaultLocale, +} from 'react-datepicker'; + +registerLocale('en-GB', { options: { weekStartsOn: 1 } }); +setDefaultLocale('en-GB'); +const defaultLocale = getDefaultLocale(); {}} - onYearChange={(date: moment.Moment) => {}} + adjustDateOnChange + allowSameDay + autoComplete="" + autoFocus + calendarClassName="" + calendarContainer={props =>
} + className="" + clearButtonTitle="" + customInput={} + customInputRef="" + dateFormat="" + dateFormatCalendar="" + dayClassName={date => ''} + disabled + disabledKeyboardNavigation + dropdownMode="scroll" + endDate={new Date()} + excludeDates={[new Date()]} + excludeTimes={[new Date()]} + filterDate={date => true} + fixedHeight + forceShowMonthNavigation + formatWeekDay={date => ''} + formatWeekNumber={date => 0} + highlightDates={[new Date()]} + id="" + includeDates={[new Date()]} + includeTimes={[new Date()]} + injectTimes={[new Date()]} + inline + isClearable + locale="" + maxDate={new Date()} + maxTime={new Date()} + minDate={new Date()} + minTime={new Date()} + monthsShown={1} + name="" + nextMonthButtonLabel="" + onBlur={event => null} + onChange={(date: Date | null) => {}} + onChangeRaw={event => null} + onClickOutside={event => null} + onFocus={event => null} + onInputClick={() => null} + onInputError={err => err.code + err.msg} + onKeyDown={event => null} + onMonthChange={date => null} + onSelect={(date, event) => null} + onWeekSelect={(firstDayOfWeek, weekNumber, event) => null} + onYearChange={(date: Date) => {}} + open + openToDate={new Date()} + peekNextMonth + placeholderText="" + popperClassName="" + popperContainer={props =>
} popperModifiers={{ flip: { - enabled: false - } + enabled: false, + }, }} - includeTimes={[moment()]} + popperPlacement="" + popperProps={{}} + preventOpenOnFocus + previousMonthButtonLabel="" + readOnly + renderCustomHeader={({ + date, + changeYear, + changeMonth, + decreaseMonth, + increaseMonth, + prevMonthButtonDisabled, + nextMonthButtonDisabled, + }) =>
} + renderDayContents={dayOfMonth =>
} + required + scrollableMonthYearDropdown + scrollableYearDropdown + selected={new Date()} + selectsEnd + selectsStart + shouldCloseOnSelect + showDisabledMonthNavigation + showMonthDropdown + showMonthYearDropdown + showTimeSelect + showTimeSelectOnly + showWeekNumbers + showYearDropdown + startDate={new Date()} + startOpen + tabIndex={1} + timeCaption="" + timeFormat="" + timeIntervals={1} + title="" + todayButton={
} + useShortMonthInDropdown + useWeekdaysShort + value="" + weekLabel="" + withPortal + yearDropdownItemNumber={1} > -
- +
+ ; diff --git a/types/react-dates/index.d.ts b/types/react-dates/index.d.ts index 9e96538f7d..17ea9788f6 100644 --- a/types/react-dates/index.d.ts +++ b/types/react-dates/index.d.ts @@ -1,12 +1,11 @@ // Type definitions for react-dates v17.1.0 // Project: https://github.com/airbnb/react-dates -// Definitions by: Artur Ampilogov +// Definitions by: Artur Ampilogov // Nathan Holland // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 - // Required fields are made according to 'minimum REQUIRED setup' in https://github.com/airbnb/react-dates/blob/master/README.md - + import * as React from 'react'; import * as moment from 'moment'; @@ -18,9 +17,8 @@ declare namespace momentPropTypes { type momentDurationObj = any; } - declare namespace ReactDates { - // SHAPES + // SHAPES // // shapes/AnchorDirectionShape.js type AnchorDirectionShape = 'left' | 'right'; @@ -28,96 +26,100 @@ declare namespace ReactDates { // shapes/CalendarInfoPositionShape.js type CalendarInfoPositionShape = 'top' | 'bottom' | 'before' | 'after'; - // shapes/DateRangePickerShape.js interface DateRangePickerShape { // required props for a functional interactive DateRangePicker - startDate: momentPropTypes.momentObj | null, - startDateId: string, - endDate: momentPropTypes.momentObj | null, - endDateId: string, - focusedInput: FocusedInputShape | null, + startDate: momentPropTypes.momentObj | null; + startDateId: string; + endDate: momentPropTypes.momentObj | null; + endDateId: string; + focusedInput: FocusedInputShape | null; - onDatesChange: (arg: { - startDate: momentPropTypes.momentObj | null, - endDate: momentPropTypes.momentObj | null - }) => void, - onFocusChange: (arg: FocusedInputShape | null) => void, - - onClose?: (final: { startDate: momentPropTypes.momentObj, endDate: momentPropTypes.momentObj }) => void, + onDatesChange: ( + arg: { + startDate: momentPropTypes.momentObj | null; + endDate: momentPropTypes.momentObj | null; + } + ) => void; + onFocusChange: (arg: FocusedInputShape | null) => void; + + onClose?: ( + final: { + startDate: momentPropTypes.momentObj; + endDate: momentPropTypes.momentObj; + } + ) => void; // input related props - startDatePlaceholderText?: string, - endDatePlaceholderText?: string, - disabled?: DisabledShape, - required?: boolean, - readOnly?: boolean, - screenReaderInputMessage?: string, - showClearDates?: boolean, - showDefaultInputIcon?: boolean, - inputIconPosition?: IconPositionShape, - customInputIcon?: string | JSX.Element, - customArrowIcon?: string | JSX.Element, - customCloseIcon?: string | JSX.Element, - noBorder?: boolean, - block?: boolean, - small?: boolean, - regular?: boolean, - keepFocusOnInput?: boolean, - + startDatePlaceholderText?: string; + endDatePlaceholderText?: string; + disabled?: DisabledShape; + required?: boolean; + readOnly?: boolean; + screenReaderInputMessage?: string; + showClearDates?: boolean; + showDefaultInputIcon?: boolean; + inputIconPosition?: IconPositionShape; + customInputIcon?: string | JSX.Element; + customArrowIcon?: string | JSX.Element; + customCloseIcon?: string | JSX.Element; + noBorder?: boolean; + block?: boolean; + small?: boolean; + regular?: boolean; + keepFocusOnInput?: boolean; // calendar presentation and interaction related props - renderMonthText?: (day: momentPropTypes.momentObj) => (string | JSX.Element), + renderMonthText?: (day: momentPropTypes.momentObj) => string | JSX.Element; renderMonthElement?: ( props: { - month: momentPropTypes.momentObj; - onMonthSelect: (currentMonth: momentPropTypes.momentObj, newMonthVal: string) => void; - onYearSelect: (currentMonth: momentPropTypes.momentObj, newYearVal: string) => void; + month: momentPropTypes.momentObj; + onMonthSelect: (currentMonth: momentPropTypes.momentObj, newMonthVal: string) => void; + onYearSelect: (currentMonth: momentPropTypes.momentObj, newYearVal: string) => void; } - ) => string | JSX.Element, - orientation?: OrientationShape, - anchorDirection?: AnchorDirectionShape, - openDirection?: OpenDirectionShape, - horizontalMargin?: number, - withPortal?: boolean, - withFullScreenPortal?: boolean, - appendToBody?: boolean, - disableScroll?: boolean, - daySize?: number, - isRTL?: boolean, - firstDayOfWeek?: DayOfWeekShape, - initialVisibleMonth?: () => momentPropTypes.momentObj, - numberOfMonths?: number, - keepOpenOnDateSelect?: boolean, - reopenPickerOnClearDates?: boolean, - renderCalendarInfo?: () => (string | JSX.Element), - calendarInfoPosition?: CalendarInfoPositionShape, - hideKeyboardShortcutsPanel?: boolean, - verticalHeight?: number, - transitionDuration?: number, - verticalSpacing?: number, + ) => string | JSX.Element; + orientation?: OrientationShape; + anchorDirection?: AnchorDirectionShape; + openDirection?: OpenDirectionShape; + horizontalMargin?: number; + withPortal?: boolean; + withFullScreenPortal?: boolean; + appendToBody?: boolean; + disableScroll?: boolean; + daySize?: number; + isRTL?: boolean; + firstDayOfWeek?: DayOfWeekShape; + initialVisibleMonth?: () => momentPropTypes.momentObj; + numberOfMonths?: number; + keepOpenOnDateSelect?: boolean; + reopenPickerOnClearDates?: boolean; + renderCalendarInfo?: () => string | JSX.Element; + calendarInfoPosition?: CalendarInfoPositionShape; + hideKeyboardShortcutsPanel?: boolean; + verticalHeight?: number; + transitionDuration?: number; + verticalSpacing?: number; // navigation related props - navPrev?: string | JSX.Element, - navNext?: string | JSX.Element, - onPrevMonthClick?: (newCurrentMonth: momentPropTypes.momentObj) => void, - onNextMonthClick?: (newCurrentMonth: momentPropTypes.momentObj) => void, + navPrev?: string | JSX.Element; + navNext?: string | JSX.Element; + onPrevMonthClick?: (newCurrentMonth: momentPropTypes.momentObj) => void; + onNextMonthClick?: (newCurrentMonth: momentPropTypes.momentObj) => void; // day presentation and interaction related props - renderCalendarDay?: (day: momentPropTypes.momentObj) => (string | JSX.Element), - renderDayContents?: (day: momentPropTypes.momentObj) => (string | JSX.Element), - minimumNights?: number, - enableOutsideDays?: boolean, - isDayBlocked?: (day: any) => boolean, - isOutsideRange?: (day: any) => boolean, - isDayHighlighted?: (day: any) => boolean, - + renderCalendarDay?: (day: momentPropTypes.momentObj) => string | JSX.Element; + renderDayContents?: (day: momentPropTypes.momentObj) => string | JSX.Element; + minimumNights?: number; + enableOutsideDays?: boolean; + isDayBlocked?: (day: any) => boolean; + isOutsideRange?: (day: any) => boolean; + isDayHighlighted?: (day: any) => boolean; // internationalization props - displayFormat?: (string | (() => string)), - monthFormat?: string, - weekDayFormat?: string, - phrases?: DateRangePickerPhrases, - dayAriaLabelFormat?: string + displayFormat?: string | (() => string); + monthFormat?: string; + weekDayFormat?: string; + phrases?: DateRangePickerPhrases; + dayAriaLabelFormat?: string; } // shapes/DayOfWeekShape.js @@ -141,260 +143,270 @@ declare namespace ReactDates { // shape/ScrollableOrientationShape.js type ScrollableOrientationShape = 'horizontal' | 'vertical' | 'verticalScrollable'; - // shapes/SingleDatePickerShape.js interface SingleDatePickerShape { - id: string, + id: string; // required props for a functional interactive SingleDatePicker - date: momentPropTypes.momentObj | null, - focused: boolean, - - onDateChange: (date: momentPropTypes.momentObj | null) => void, - onFocusChange: (arg: { focused: boolean | null }) => void, - + date: momentPropTypes.momentObj | null; + focused: boolean; + + onDateChange: (date: momentPropTypes.momentObj | null) => void; + onFocusChange: (arg: { focused: boolean | null }) => void; + // input related props - placeholder?: string, - disabled?: boolean, - required?: boolean, - readOnly?: boolean, - screenReaderInputMessage?: string, - showClearDate?: boolean, - customCloseIcon?: string | JSX.Element, - showDefaultInputIcon?: boolean, - inputIconPosition?: IconPositionShape, - customInputIcon?: string | JSX.Element, - noBorder?: boolean, - block?: boolean, - small?: boolean, - regular?: boolean, - verticalSpacing?: number, - keepFocusOnInput?: boolean, + placeholder?: string; + disabled?: boolean; + required?: boolean; + readOnly?: boolean; + screenReaderInputMessage?: string; + showClearDate?: boolean; + customCloseIcon?: string | JSX.Element; + showDefaultInputIcon?: boolean; + inputIconPosition?: IconPositionShape; + customInputIcon?: string | JSX.Element; + noBorder?: boolean; + block?: boolean; + small?: boolean; + regular?: boolean; + verticalSpacing?: number; + keepFocusOnInput?: boolean; // calendar presentation and interaction related props - renderMonthText?: (day: momentPropTypes.momentObj) => (string | JSX.Element), + renderMonthText?: (day: momentPropTypes.momentObj) => string | JSX.Element; renderMonthElement?: ( props: { - month: momentPropTypes.momentObj; - onMonthSelect: (currentMonth: momentPropTypes.momentObj, newMonthVal: string) => void; - onYearSelect: (currentMonth: momentPropTypes.momentObj, newYearVal: string) => void; + month: momentPropTypes.momentObj; + onMonthSelect: (currentMonth: momentPropTypes.momentObj, newMonthVal: string) => void; + onYearSelect: (currentMonth: momentPropTypes.momentObj, newYearVal: string) => void; } - ) => string | JSX.Element, - orientation?: OrientationShape, - anchorDirection?: AnchorDirectionShape, - openDirection?: OpenDirectionShape, - horizontalMargin?: number, - withPortal?: boolean, - withFullScreenPortal?: boolean, - appendToBody?: boolean, - disableScroll?: boolean, - initialVisibleMonth?: () => momentPropTypes.momentObj, - firstDayOfWeek?: DayOfWeekShape, - numberOfMonths?: number, - keepOpenOnDateSelect?: boolean, - reopenPickerOnClearDates?: boolean, - renderCalendarInfo?: () => (string | JSX.Element), - calendarInfoPosition?: CalendarInfoPositionShape, - hideKeyboardShortcutsPanel?: boolean, - daySize?: number, - isRTL?: boolean, - verticalHeight?: number | null, - transitionDuration?: number, + ) => string | JSX.Element; + orientation?: OrientationShape; + anchorDirection?: AnchorDirectionShape; + openDirection?: OpenDirectionShape; + horizontalMargin?: number; + withPortal?: boolean; + withFullScreenPortal?: boolean; + appendToBody?: boolean; + disableScroll?: boolean; + initialVisibleMonth?: () => momentPropTypes.momentObj; + firstDayOfWeek?: DayOfWeekShape; + numberOfMonths?: number; + keepOpenOnDateSelect?: boolean; + reopenPickerOnClearDates?: boolean; + renderCalendarInfo?: () => string | JSX.Element; + calendarInfoPosition?: CalendarInfoPositionShape; + hideKeyboardShortcutsPanel?: boolean; + daySize?: number; + isRTL?: boolean; + verticalHeight?: number | null; + transitionDuration?: number; // navigation related props - navPrev?: string | JSX.Element, - navNext?: string | JSX.Element, - onPrevMonthClick?: (newCurrentMonth: momentPropTypes.momentObj) => void, - onNextMonthClick?: (newCurrentMonth: momentPropTypes.momentObj) => void, - onClose?: (final: { startDate: momentPropTypes.momentObj, endDate: momentPropTypes.momentObj }) => void, + navPrev?: string | JSX.Element; + navNext?: string | JSX.Element; + onPrevMonthClick?: (newCurrentMonth: momentPropTypes.momentObj) => void; + onNextMonthClick?: (newCurrentMonth: momentPropTypes.momentObj) => void; + onClose?: ( + final: { + startDate: momentPropTypes.momentObj; + endDate: momentPropTypes.momentObj; + } + ) => void; // day presentation and interaction related props - renderCalendarDay?: (day: momentPropTypes.momentObj) => (string | JSX.Element), - renderDayContents?: (day: momentPropTypes.momentObj) => (string | JSX.Element), - enableOutsideDays?: boolean, - isDayBlocked?: (day: any) => boolean, - isOutsideRange?: (day: any) => boolean, - isDayHighlighted?: (day: any) => boolean, + renderCalendarDay?: (day: momentPropTypes.momentObj) => string | JSX.Element; + renderDayContents?: (day: momentPropTypes.momentObj) => string | JSX.Element; + enableOutsideDays?: boolean; + isDayBlocked?: (day: any) => boolean; + isOutsideRange?: (day: any) => boolean; + isDayHighlighted?: (day: any) => boolean; // internationalization props - displayFormat?: (string | (() => string)), - monthFormat?: string, - weekDayFormat?: string, - phrases?: SingleDatePickerPhrases, - dayAriaLabelFormat?: string, + displayFormat?: string | (() => string); + monthFormat?: string; + weekDayFormat?: string; + phrases?: SingleDatePickerPhrases; + dayAriaLabelFormat?: string; } // PHRASES // // defaultPhrases.js type DateRangePickerPhrases = { - calendarLabel?: string, - closeDatePicker?: string, - clearDates?: string, - focusStartDate?: string, - jumpToPrevMonth?: string, - jumpToNextMonth?: string, - keyboardShortcuts?: string, - showKeyboardShortcutsPanel?: string, - hideKeyboardShortcutsPanel?: string, - openThisPanel?: string, - enterKey?: string, - leftArrowRightArrow?: string, - upArrowDownArrow?: string, - pageUpPageDown?: string, - homeEnd?: string, - escape?: string, - questionMark?: string, - selectFocusedDate?: string, - moveFocusByOneDay?: string, - moveFocusByOneWeek?: string, - moveFocusByOneMonth?: string, - moveFocustoStartAndEndOfWeek?: string, - returnFocusToInput?: string, - keyboardNavigationInstructions?: string, - chooseAvailableStartDate?: (date: string) => string, - chooseAvailableEndDate?: (date: string) => string, - dateIsUnavailable?: (date: string) => string, - dateIsSelected?: (date: string) => string + calendarLabel?: string; + closeDatePicker?: string; + clearDates?: string; + focusStartDate?: string; + jumpToPrevMonth?: string; + jumpToNextMonth?: string; + keyboardShortcuts?: string; + showKeyboardShortcutsPanel?: string; + hideKeyboardShortcutsPanel?: string; + openThisPanel?: string; + enterKey?: string; + leftArrowRightArrow?: string; + upArrowDownArrow?: string; + pageUpPageDown?: string; + homeEnd?: string; + escape?: string; + questionMark?: string; + selectFocusedDate?: string; + moveFocusByOneDay?: string; + moveFocusByOneWeek?: string; + moveFocusByOneMonth?: string; + moveFocustoStartAndEndOfWeek?: string; + returnFocusToInput?: string; + keyboardNavigationInstructions?: string; + chooseAvailableStartDate?: (date: string) => string; + chooseAvailableEndDate?: (date: string) => string; + dateIsUnavailable?: (date: string) => string; + dateIsSelected?: (date: string) => string; }; // defaultPhrases.js type DateRangePickerInputPhrases = { - focusStartDate?: string, - clearDates?: string, - keyboardNavigationInstructions?: string, - } + focusStartDate?: string; + clearDates?: string; + keyboardNavigationInstructions?: string; + }; // defaultPhrases.js - type SingleDatePickerPhrases = { - calendarLabel?: string, - closeDatePicker?: string, - clearDate?: string, - jumpToPrevMonth?: string, - jumpToNextMonth?: string, - keyboardShortcuts?: string, - showKeyboardShortcutsPanel?: string, - hideKeyboardShortcutsPanel?: string, - openThisPanel?: string, - enterKey?: string, - leftArrowRightArrow?: string, - upArrowDownArrow?: string, - pageUpPageDown?: string, - homeEnd?: string, - escape?: string, - questionMark?: string, - selectFocusedDate?: string, - moveFocusByOneDay?: string, - moveFocusByOneWeek?: string, - moveFocusByOneMonth?: string, - moveFocustoStartAndEndOfWeek?: string, - returnFocusToInput?: string, - keyboardNavigationInstructions?: string, - chooseAvailableDate?: (date: string) => string, - dateIsUnavailable?: (date: string) => string, - dateIsSelected?: (date: string) => string, + type SingleDatePickerPhrases = { + calendarLabel?: string; + closeDatePicker?: string; + clearDate?: string; + jumpToPrevMonth?: string; + jumpToNextMonth?: string; + keyboardShortcuts?: string; + showKeyboardShortcutsPanel?: string; + hideKeyboardShortcutsPanel?: string; + openThisPanel?: string; + enterKey?: string; + leftArrowRightArrow?: string; + upArrowDownArrow?: string; + pageUpPageDown?: string; + homeEnd?: string; + escape?: string; + questionMark?: string; + selectFocusedDate?: string; + moveFocusByOneDay?: string; + moveFocusByOneWeek?: string; + moveFocusByOneMonth?: string; + moveFocustoStartAndEndOfWeek?: string; + returnFocusToInput?: string; + keyboardNavigationInstructions?: string; + chooseAvailableDate?: (date: string) => string; + dateIsUnavailable?: (date: string) => string; + dateIsSelected?: (date: string) => string; }; // defaultPhrases.js type SingleDatePickerInputPhrases = { - clearDate?: string, - keyboardNavigationInstructions?: string, - } + clearDate?: string; + keyboardNavigationInstructions?: string; + }; // defaultPhrases.js type DayPickerPhrases = { - calendarLabel?: string, - jumpToPrevMonth?: string, - jumpToNextMonth?: string, - keyboardShortcuts?: string, - showKeyboardShortcutsPanel?: string, - hideKeyboardShortcutsPanel?: string, - openThisPanel?: string, - enterKey?: string, - leftArrowRightArrow?: string, - upArrowDownArrow?: string, - pageUpPageDown?: string, - homeEnd?: string, - escape?: string, - questionMark?: string, - selectFocusedDate?: string, - moveFocusByOneDay?: string, - moveFocusByOneWeek?: string, - moveFocusByOneMonth?: string, - moveFocustoStartAndEndOfWeek?: string, - returnFocusToInput?: string, - chooseAvailableStartDate?: (date: string) => string, - chooseAvailableEndDate?: (date: string) => string, - chooseAvailableDate?: (date: string) => string, - dateIsUnavailable?: (date: string) => string, - dateIsSelected?: (date: string) => string, + calendarLabel?: string; + jumpToPrevMonth?: string; + jumpToNextMonth?: string; + keyboardShortcuts?: string; + showKeyboardShortcutsPanel?: string; + hideKeyboardShortcutsPanel?: string; + openThisPanel?: string; + enterKey?: string; + leftArrowRightArrow?: string; + upArrowDownArrow?: string; + pageUpPageDown?: string; + homeEnd?: string; + escape?: string; + questionMark?: string; + selectFocusedDate?: string; + moveFocusByOneDay?: string; + moveFocusByOneWeek?: string; + moveFocusByOneMonth?: string; + moveFocustoStartAndEndOfWeek?: string; + returnFocusToInput?: string; + chooseAvailableStartDate?: (date: string) => string; + chooseAvailableEndDate?: (date: string) => string; + chooseAvailableDate?: (date: string) => string; + dateIsUnavailable?: (date: string) => string; + dateIsSelected?: (date: string) => string; }; // defaultPhrases.js type DayPickerKeyboardShortcutsPhrases = { - keyboardShortcuts?: string, - showKeyboardShortcutsPanel?: string, - hideKeyboardShortcutsPanel?: string, - openThisPanel?: string, - enterKey?: string, - leftArrowRightArrow?: string, - upArrowDownArrow?: string, - pageUpPageDown?: string, - homeEnd?: string, - escape?: string, - questionMark?: string, - selectFocusedDate?: string, - moveFocusByOneDay?: string, - moveFocusByOneWeek?: string, - moveFocusByOneMonth?: string, - moveFocustoStartAndEndOfWeek?: string, - returnFocusToInput?: string, + keyboardShortcuts?: string; + showKeyboardShortcutsPanel?: string; + hideKeyboardShortcutsPanel?: string; + openThisPanel?: string; + enterKey?: string; + leftArrowRightArrow?: string; + upArrowDownArrow?: string; + pageUpPageDown?: string; + homeEnd?: string; + escape?: string; + questionMark?: string; + selectFocusedDate?: string; + moveFocusByOneDay?: string; + moveFocusByOneWeek?: string; + moveFocusByOneMonth?: string; + moveFocustoStartAndEndOfWeek?: string; + returnFocusToInput?: string; }; // defaultPhrases.js type DayPickerNavigationPhrases = { - jumpToPrevMonth?: string, - jumpToNextMonth?: string, + jumpToPrevMonth?: string; + jumpToNextMonth?: string; }; - + // defaultPhrases.js type CalendarDayPhrases = { - chooseAvailableDate: (date: string) => string, - dateIsUnavailable: (date: string) => string, - dateIsSelected: (date: string) => string, + chooseAvailableDate: (date: string) => string; + dateIsUnavailable: (date: string) => string; + dateIsSelected: (date: string) => string; }; // COMPONENTS - // + // // components/DateRangePicker.js type DateRangePicker = React.ClassicComponentClass; var DateRangePicker: React.ClassicComponentClass; // components/DayPickerRangeController.jsx - interface DayPickerRangeControllerShape extends DayPickerShape{ + interface DayPickerRangeControllerShape extends DayPickerShape { // REQUIRED props - startDate: momentPropTypes.momentObj | null, - endDate: momentPropTypes.momentObj | null, - onDatesChange: (arg: { - startDate: momentPropTypes.momentObj | null, - endDate: momentPropTypes.momentObj | null - } - ) => void, - focusedInput: FocusedInputShape, - onFocusChange: (arg: FocusedInputShape | null) => void, + startDate: momentPropTypes.momentObj | null; + endDate: momentPropTypes.momentObj | null; + onDatesChange: ( + arg: { + startDate: momentPropTypes.momentObj | null; + endDate: momentPropTypes.momentObj | null; + } + ) => void; + focusedInput: FocusedInputShape; + onFocusChange: (arg: FocusedInputShape | null) => void; - startDateOffset?: (day: any) => any, - endDateOffset?: (day: any) => any, + startDateOffset?: (day: any) => any; + endDateOffset?: (day: any) => any; - onClose?: (final: { startDate: momentPropTypes.momentObj, endDate: momentPropTypes.momentObj }) => void, + onClose?: ( + final: { + startDate: momentPropTypes.momentObj; + endDate: momentPropTypes.momentObj; + } + ) => void; - keepOpenOnDateSelect?: boolean, - minimumNights?: number, - disabled?: DisabledShape, - isOutsideRange?: (day: any) => boolean, - isDayBlocked?: (day: any) => boolean, - isDayHighlighted?: (day: any) => boolean, + keepOpenOnDateSelect?: boolean; + minimumNights?: number; + disabled?: DisabledShape; + isOutsideRange?: (day: any) => boolean; + isDayBlocked?: (day: any) => boolean; + isDayHighlighted?: (day: any) => boolean; } type DayPickerRangeController = React.ClassicComponentClass; @@ -402,64 +414,64 @@ declare namespace ReactDates { // components/DayPickerShape.jsx interface DayPickerShape { - renderMonthText?: (day: momentPropTypes.momentObj) => (string | JSX.Element), + renderMonthText?: (day: momentPropTypes.momentObj) => string | JSX.Element; renderMonthElement?: ( props: { - month: momentPropTypes.momentObj; - onMonthSelect: (currentMonth: momentPropTypes.momentObj, newMonthVal: string) => void; - onYearSelect: (currentMonth: momentPropTypes.momentObj, newYearVal: string) => void; + month: momentPropTypes.momentObj; + onMonthSelect: (currentMonth: momentPropTypes.momentObj, newMonthVal: string) => void; + onYearSelect: (currentMonth: momentPropTypes.momentObj, newYearVal: string) => void; } - ) => string | JSX.Element, - enableOutsideDays?: boolean, - numberOfMonths?: number, - orientation?: ScrollableOrientationShape, - withPortal?: boolean, - initialVisibleMonth?: () => momentPropTypes.momentObj, - firstDayOfWeek?: 0 | 1 | 2 | 3 | 4 | 5 | 6, - hideKeyboardShortcutsPanel?: boolean, - daySize?: number, - verticalHeight?: number, - noBorder?: boolean, - transitionDuration?: number, + ) => string | JSX.Element; + enableOutsideDays?: boolean; + numberOfMonths?: number; + orientation?: ScrollableOrientationShape; + withPortal?: boolean; + initialVisibleMonth?: () => momentPropTypes.momentObj; + firstDayOfWeek?: 0 | 1 | 2 | 3 | 4 | 5 | 6; + hideKeyboardShortcutsPanel?: boolean; + daySize?: number; + verticalHeight?: number; + noBorder?: boolean; + transitionDuration?: number; - navPrev?: string | JSX.Element, - navNext?: string | JSX.Element, + navPrev?: string | JSX.Element; + navNext?: string | JSX.Element; - onPrevMonthClick?: (newCurrentMonth: momentPropTypes.momentObj) => void, - onNextMonthClick?: (newCurrentMonth: momentPropTypes.momentObj) => void, - onOutsideClick?: (e: any) => void, - renderCalendarDay?: (day: momentPropTypes.momentObj) => (string | JSX.Element), - renderDayContents?: (day: momentPropTypes.momentObj) => (string | JSX.Element), - renderCalendarInfo?: () => (string | JSX.Element), - calendarInfoPosition?: CalendarInfoPositionShape, + onPrevMonthClick?: (newCurrentMonth: momentPropTypes.momentObj) => void; + onNextMonthClick?: (newCurrentMonth: momentPropTypes.momentObj) => void; + onOutsideClick?: (e: any) => void; + renderCalendarDay?: (day: momentPropTypes.momentObj) => string | JSX.Element; + renderDayContents?: (day: momentPropTypes.momentObj) => string | JSX.Element; + renderCalendarInfo?: () => string | JSX.Element; + calendarInfoPosition?: CalendarInfoPositionShape; // accessibility - onBlur?: () => void, - isFocused?: boolean, - showKeyboardShortcuts?: boolean, + onBlur?: () => void; + isFocused?: boolean; + showKeyboardShortcuts?: boolean; // i18n - monthFormat?: string, - weekDayFormat?: string, - phrases?: SingleDatePickerPhrases, - dayAriaLabelFormat?: string, + monthFormat?: string; + weekDayFormat?: string; + phrases?: SingleDatePickerPhrases; + dayAriaLabelFormat?: string; - isRTL?: boolean + isRTL?: boolean; } // components/DayPickerSingleDateController.jsx interface DayPickerSingleDateControllerShape extends DayPickerShape { - date: momentPropTypes.momentObj | null, - onDateChange: (date: momentPropTypes.momentObj | null) => void, - focused: boolean, - onFocusChange: (arg: { focused: boolean | null }) => void, + date: momentPropTypes.momentObj | null; + onDateChange: (date: momentPropTypes.momentObj | null) => void; + focused: boolean; + onFocusChange: (arg: { focused: boolean | null }) => void; - onClose?: (final: { date: momentPropTypes.momentObj }) => void, + onClose?: (final: { date: momentPropTypes.momentObj }) => void; - keepOpenOnDateSelect?: boolean, - isOutsideRange?: (day: any) => boolean, - isDayBlocked?: (day: any) => boolean, - isDayHighlighted?: (day: any) => boolean, + keepOpenOnDateSelect?: boolean; + isOutsideRange?: (day: any) => boolean; + isDayBlocked?: (day: any) => boolean; + isDayHighlighted?: (day: any) => boolean; } type DayPickerSingleDateController = React.ClassicComponentClass; @@ -482,7 +494,13 @@ declare namespace ReactDates { // utils/toISODateString.js var toISODateString: (date: moment.MomentInput, currentFormat: moment.MomentFormatSpecification) => string | null; // utils/toLocalizedDateString.js - var toLocalizedDateString: (date: moment.MomentInput, currentFormat: moment.MomentFormatSpecification) => string | null; + var toLocalizedDateString: ( + date: moment.MomentInput, + currentFormat: moment.MomentFormatSpecification + ) => string | null; // utils/toMomentObject.js - var toMomentObject: (dateString: moment.MomentInput, customFormat: moment.MomentFormatSpecification) => moment.Moment | null; + var toMomentObject: ( + dateString: moment.MomentInput, + customFormat: moment.MomentFormatSpecification + ) => moment.Moment | null; } diff --git a/types/react-facebook-login/index.d.ts b/types/react-facebook-login/index.d.ts index 82672660a8..419761974e 100644 --- a/types/react-facebook-login/index.d.ts +++ b/types/react-facebook-login/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for react-facebook-login 3.6 +// Type definitions for react-facebook-login 4.1 // Project: https://github.com/keppelen/react-facebook-login // Definitions by: Alexandre Paré , Jan Karres // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -6,7 +6,7 @@ import * as React from "react"; -interface ReactFacebookLoginProps { +export interface ReactFacebookLoginProps { appId: string; callback(userInfo: ReactFacebookLoginInfo): void; onFailure?(response: ReactFacebookFailureResponse): void; @@ -18,7 +18,7 @@ interface ReactFacebookLoginProps { cssClass?: string; disableMobileRedirect?: boolean; fields?: string; - icon?: string | React.ReactNode; + icon?: React.ReactNode; isDisabled?: boolean; language?: string; onClick?(event: React.MouseEvent): void; @@ -32,6 +32,10 @@ interface ReactFacebookLoginProps { xfbml?: boolean; isMobile?: boolean; tag?: Node | React.Component; + returnScopes?: boolean; + state?: string; + authType?: string; + responseType?: string; } export interface ReactFacebookFailureResponse { @@ -45,14 +49,12 @@ export interface ReactFacebookLoginInfo { email?: string; } -interface ReactFacebookLoginState { +export interface ReactFacebookLoginState { isSdkLoaded?: boolean; isProcessing?: boolean; } -declare class ReactFacebookLogin extends React.Component< +export default class ReactFacebookLogin extends React.Component< ReactFacebookLoginProps, ReactFacebookLoginState > {} - -export default ReactFacebookLogin; diff --git a/types/react-facebook-login/react-facebook-login-tests.tsx b/types/react-facebook-login/react-facebook-login-tests.tsx index d7b2ebcde8..a52c955596 100644 --- a/types/react-facebook-login/react-facebook-login-tests.tsx +++ b/types/react-facebook-login/react-facebook-login-tests.tsx @@ -1,7 +1,6 @@ import * as React from 'react'; import * as ReactDOM from 'react-dom'; - -import FacebookLogin, { ReactFacebookLoginInfo, ReactFacebookFailureResponse } from 'react-facebook-login'; +import FacebookLogin, { ReactFacebookFailureResponse, ReactFacebookLoginInfo, ReactFacebookLoginProps } from 'react-facebook-login'; const responseFacebook = (response: ReactFacebookLoginInfo) => { console.log(response); @@ -106,3 +105,9 @@ class MyComponent2 extends React.Component { ); } } + +type FacebookLoginWrapperProps = ReactFacebookLoginProps & { className?: string }; + +export const FacebookLoginWrapper = ({ className, ...props }: FacebookLoginWrapperProps) => ( + +); diff --git a/types/react-flatpickr/index.d.ts b/types/react-flatpickr/index.d.ts index a0a9725ccd..c867527b06 100644 --- a/types/react-flatpickr/index.d.ts +++ b/types/react-flatpickr/index.d.ts @@ -1,18 +1,25 @@ -// Type definitions for react-flatpickr 3.2 +// Type definitions for react-flatpickr 3.6 // Project: https://github.com/coderhaoxin/react-flatpickr // Definitions by: begincalendar +// snaveevans // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 -import { Component } from 'react'; -import flatpickr from 'flatpickr'; +import { Component } from "react"; +import flatpickr from "flatpickr"; export interface DateTimePickerProps { defaultValue?: string; options?: flatpickr.Options.Options; onChange?: flatpickr.Options.Hook; - value?: string; - className?: string; + onOpen?: flatpickr.Options.Hook; + onClose?: flatpickr.Options.Hook; + onMonthChange?: flatpickr.Options.Hook; + onYearChange?: flatpickr.Options.Hook; + onReady?: flatpickr.Options.Hook; + onValueUpdate?: flatpickr.Options.Hook; + onDayCreate?: flatpickr.Options.Hook; + value?: string | Date | number | ReadonlyArray; } export default class DatePicker extends Component {} diff --git a/types/react-flatpickr/react-flatpickr-tests.tsx b/types/react-flatpickr/react-flatpickr-tests.tsx index 452d8529b4..7a1c64c266 100644 --- a/types/react-flatpickr/react-flatpickr-tests.tsx +++ b/types/react-flatpickr/react-flatpickr-tests.tsx @@ -1,22 +1,42 @@ -import flatpickr from 'flatpickr'; -import * as React from 'react'; -import DatePicker from 'react-flatpickr'; +import flatpickr from "flatpickr"; +import * as React from "react"; +import DatePicker from "react-flatpickr"; -const noParamsElement = ; +const noParamsElement = ; -const defaultValueElement = ; +const defaultValueElement = ; const options = { - dateFormat: 'YYYY-MM-DD' + dateFormat: "YYYY-MM-DD" }; -const optionsElement = ; +const optionsElement = ; -const onChange = ( - selectedDates: Date[], dateStr: string, instance: flatpickr.Instance, +const hook = ( + selectedDates: Date[], + dateStr: string, + instance: flatpickr.Instance, elem: HTMLElement ) => null; -const onChangeElement = ; +const onChangeElement = ; +const onOpenElement = ; +const onCloseElement = ; +const onMonthChangeElement = ; +const onYearChangeElement = ; +const onReadyElement = ; +const onValueUpdateElement = ; +const onDayCreateElement = ; -const valueElement = ; - -const classNameElement = ; +const valueStringElement = ; +const valueDateElement = ; +const valueNumberElement = ; +const valueStringArrayElement = ( + +); +const valueDateArrayElement = ( + +); +const valueNumberArrayElement = ( + +); diff --git a/types/react-instantsearch-core/index.d.ts b/types/react-instantsearch-core/index.d.ts index e76be4ee08..bceb91ca85 100644 --- a/types/react-instantsearch-core/index.d.ts +++ b/types/react-instantsearch-core/index.d.ts @@ -128,7 +128,52 @@ export class Configure extends React.Component {} export function connectAutoComplete(Composed: React.ComponentType): React.ComponentClass; export function connectBreadcrumb(Composed: React.ComponentType): React.ComponentClass; export function connectConfigure(Composed: React.ComponentType): React.ComponentClass; -export function connectCurrentRefinements(Composed: React.ComponentType): React.ComponentClass; + +export type Refinement = { + label: string; + attribute: string; + index: string; + id: string; + value: RefinementValue; +} & ({ + currentRefinement: string; +} | { + items: Array<{ label: string, value: RefinementValue }>; + currentRefinement: string[]; +}); + +export type RefinementValue = (searchState: SearchState) => SearchState; + +export interface CurrentRefinementsExposed { + /** + * Function to modify the items being displayed, e.g. for filtering or sorting them. + * Takes an items as parameter and expects it back in return. + */ + transformItems?: (...args: any[]) => any; + /** Pass true to also clear the search query */ + clearsQuery?: boolean; +} + +export interface CurrentRefinementsProvided { + /** a function to remove a single filter */ + refine: (refinement: RefinementValue | RefinementValue[]) => void; + /** + * all the filters, the value is to pass to the refine function for removing all currentrefinements, + * label is for the display. When existing several refinements for the same atribute name, then you + * get a nested items object that contains a label and a value function to use to remove a single filter. + * attribute and currentRefinement are metadata containing row values. + */ + items: Refinement[]; + /** the search query */ + query: string; +} + +export function connectCurrentRefinements( + stateless: React.StatelessComponent, +): React.ComponentClass; +export function connectCurrentRefinements>( + Composed: React.ComponentType, +): ConnectedComponentClass; export interface NESW { northEast: { lat: number, lng: number }; @@ -263,13 +308,16 @@ export function connectRange(Composed: React.ComponentType): React.Componen export interface RefinementListProvided { /** a function to toggle a refinement */ - refine: (...args: any[]) => any; + refine: (value: string[]) => any; /** a function to generate a URL for the corresponding search state */ createURL: (...args: any[]) => any; /** the refinement currently applied */ currentRefinement: string[]; - /** the list of items the RefinementList can display. */ - items: Array>; + /** + * The list of items the RefinementList can display. + * If isFromSearch is false, the hit properties like _highlightResult are undefined + */ + items: Array>; /** a function to toggle a search inside items values */ searchForItems: (...args: any[]) => any; /** a boolean that says if the items props contains facet values from the global search or from the search inside items. */ @@ -455,12 +503,18 @@ export interface SearchResults { */ export type Hit = TDoc & { objectID: string; + /** + * Contains the searchable attributes within the document and shows which part of the + * attribute was matched by the search terms. Note that if the index has defined + * any searchable attributes, this object will only contain those keys and others + * will not exist. + */ '_highlightResult': HighlightResult; }; export type HighlightResult = TDoc extends { [k: string]: any } ? - { [K in keyof TDoc]: HighlightResultField } : + { [K in keyof TDoc]?: HighlightResultField } : never; type HighlightResultField = diff --git a/types/react-instantsearch-core/react-instantsearch-core-tests.tsx b/types/react-instantsearch-core/react-instantsearch-core-tests.tsx index 62bf99e3d4..e39a9f53e6 100644 --- a/types/react-instantsearch-core/react-instantsearch-core-tests.tsx +++ b/types/react-instantsearch-core/react-instantsearch-core-tests.tsx @@ -7,7 +7,11 @@ import { connectStateResults, SearchBoxProvided, connectSearchBox, - connectRefinementList + connectRefinementList, + CurrentRefinementsProvided, + connectCurrentRefinements, + RefinementListProvided, + Refinement } from 'react-instantsearch-core'; () => { @@ -100,9 +104,7 @@ import {

{additionalProp}

{searchResults.hits.map((h) => { // $ExpectType string - const compound = h._highlightResult.field3.compound.value; - // $ExpectType never - const field2 = h._highlightResult.field2; + const compound = h._highlightResult.field3!.compound!.value; return {compound}; })}
; @@ -119,7 +121,7 @@ import {

{additionalProp}

{searchResults.hits.map((h) => { // $ExpectType string[] - const words = h._highlightResult.field3.compound.matchedWords; + const words = h._highlightResult.field3!.compound!.matchedWords; return {h.field2}: {words.join(',')}; })}
; @@ -153,3 +155,67 @@ import { // reading and manipulating the current query of the search. const ConnectedSearchBox = connectSearchBox(MySearchBox); }; + +() => { + const MyCurrentRefinements = ({refine, items, query}: CurrentRefinementsProvided) => + <> + {items.map((refinement) => ( +
refine(refinement.value) }> + +
+ ))} + ; + + const ConnectedCurrentRefinements = connectCurrentRefinements(MyCurrentRefinements); + + item} />; +}; + +() => { + function renderRefinement( + label: string, + value: Refinement['value'], + refine: CurrentRefinementsProvided['refine'], + ) { + return ; + } + + const MyCurrentRefinements = connectCurrentRefinements(({refine, items, query}: CurrentRefinementsProvided) => { + return <> + {items.map((refinement) => { + let str: string = refinement.currentRefinement; // $ExpectError + /* + * When existing several refinements for the same atribute name, then you get a + * nested items object that contains a label and a value function to use to remove a single filter. + * https://community.algolia.com/react-instantsearch/connectors/connectCurrentRefinements.html + */ + if ('items' in refinement) { + str = refinement.currentRefinement; // $ExpectError + return <> + {refinement.items.map((i) => renderRefinement(i.label, i.value, refine))} + ; + } + + console.log(refinement.items); // $ExpectError + return renderRefinement(refinement.currentRefinement, refinement.value, refine); + })} + ; + }); +}; + +() => { + const MyRefinementList = ({items, refine}: RefinementListProvided) => + <> + {items.map((item) => ( + + ))} + ; + const ConnectedRefinementList = connectRefinementList(MyRefinementList); + + ; +}; diff --git a/types/react-instantsearch-dom/index.d.ts b/types/react-instantsearch-dom/index.d.ts index f1dec59118..6ecb03c981 100644 --- a/types/react-instantsearch-dom/index.d.ts +++ b/types/react-instantsearch-dom/index.d.ts @@ -118,8 +118,9 @@ export interface SearchBoxProps extends CommonWidgetProps { reset?: JSX.Element; loadingIndicator?: JSX.Element; - onSubmit?: (...args: any[]) => any; - onReset?: (...args: any[]) => any; + onSubmit?: (event: React.SyntheticEvent) => any; + onReset?: (event: React.SyntheticEvent) => any; + onChange?: (event: React.SyntheticEvent) => any; } /** * The SearchBox component displays a search box that lets the user search for a specific query. diff --git a/types/react-instantsearch-dom/react-instantsearch-dom-tests.tsx b/types/react-instantsearch-dom/react-instantsearch-dom-tests.tsx index 6d9b7b55f8..e10d3fde08 100644 --- a/types/react-instantsearch-dom/react-instantsearch-dom-tests.tsx +++ b/types/react-instantsearch-dom/react-instantsearch-dom-tests.tsx @@ -216,6 +216,21 @@ import { Hit, connectRefinementList, connectMenu } from 'react-instantsearch-cor ; }; +(() => { + function onSearchBoxChange(event: React.SyntheticEvent) { + } + + function onSearchBoxReset(event: React.SyntheticEvent) { + } + + function onSearchBoxSubmit(event: React.SyntheticEvent) { + } + + } />; +}); + import { createInstantSearch } from 'react-instantsearch-dom/server'; // import { createServer } from 'http'; declare function createServer(handler: (req: any, res: any) => any): any; diff --git a/types/react-instantsearch/react-instantsearch-tests.tsx b/types/react-instantsearch/react-instantsearch-tests.tsx index 82672b7a60..9abf91c0ef 100644 --- a/types/react-instantsearch/react-instantsearch-tests.tsx +++ b/types/react-instantsearch/react-instantsearch-tests.tsx @@ -348,7 +348,7 @@ import { createInstantSearch } from "react-instantsearch-core"; : item.label; return ( -
  • +
  • props.refine(item.value)}> {label} {item.isRefined ? '- selected' : ''} diff --git a/types/react-intl-redux/index.d.ts b/types/react-intl-redux/index.d.ts index 9d9e805df9..4410e7c019 100644 --- a/types/react-intl-redux/index.d.ts +++ b/types/react-intl-redux/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/ratson/react-intl-redux // Definitions by: Karol Janyst // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.8 +// TypeScript Version: 3.0 import { Action, AnyAction } from "redux" import { Provider as ReduxProvider } from "react-redux" diff --git a/types/react-lifecycle-component/index.d.ts b/types/react-lifecycle-component/index.d.ts index 315d04f7fb..bb6dc65dd8 100644 --- a/types/react-lifecycle-component/index.d.ts +++ b/types/react-lifecycle-component/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/JamieDixon/react-lifecycle-component // Definitions by: Alexander Fisher // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.8 +// TypeScript Version: 3.0 import { ComponentLifecycle, Component, ComponentClass } from 'react'; import { Connect } from 'react-redux'; diff --git a/types/react-lottie/index.d.ts b/types/react-lottie/index.d.ts index 8e4f3b717b..a57da91307 100644 --- a/types/react-lottie/index.d.ts +++ b/types/react-lottie/index.d.ts @@ -7,7 +7,7 @@ import * as React from 'react'; -interface Options { +export interface Options { /** * Defines if the animation should play only once or repeatedly in an endless loop */ @@ -41,7 +41,7 @@ interface Options { }; } -interface EventListener { +export interface EventListener { /** * The event sent by Lottie */ @@ -61,7 +61,7 @@ interface EventListener { callback: () => void; } -interface LottieProps { +export interface LottieProps { /** * Object representing animation settings */ diff --git a/types/react-native-dialog/index.d.ts b/types/react-native-dialog/index.d.ts index 10e977f420..14d7458140 100644 --- a/types/react-native-dialog/index.d.ts +++ b/types/react-native-dialog/index.d.ts @@ -1,6 +1,8 @@ // Type definitions for react-native-dialog 4.0 // Project: https://github.com/mmazzarolo/react-native-dialog // Definitions by: MrLuje +// Stack Builders +// Esteban Ibarra // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -32,7 +34,7 @@ interface ButtonProps { interface ContainerProps { blurComponentIOS?: ReactNode; - children: JSX.Element[]; + children: React.ReactNode[]; /** * default: false */ diff --git a/types/react-native-dialog/react-native-dialog-tests.tsx b/types/react-native-dialog/react-native-dialog-tests.tsx index 151ee14af5..544025051c 100644 --- a/types/react-native-dialog/react-native-dialog-tests.tsx +++ b/types/react-native-dialog/react-native-dialog-tests.tsx @@ -2,6 +2,24 @@ import Dialog from "react-native-dialog"; import { createRef, Component } from "react"; class Example extends Component { + dynamicButtons() { + const buttonFunc = () => console.log('click'); + const buttons = [ + { label: 'Button 1', action: buttonFunc }, + { label: 'Button 2', action: buttonFunc }, + ]; + return buttons.map(({ label , action }) => + + ); + } + + singleButton() { + return ( null} />); + } + render() { const ref = createRef(); @@ -23,6 +41,8 @@ class Example extends Component { label="Validate" onPress={() => console.log("test")} /> + {this.dynamicButtons()} + {this.singleButton()} ); } diff --git a/types/react-native-draggable-flatlist/index.d.ts b/types/react-native-draggable-flatlist/index.d.ts new file mode 100644 index 0000000000..0b96f0b3cd --- /dev/null +++ b/types/react-native-draggable-flatlist/index.d.ts @@ -0,0 +1,59 @@ +// Type definitions for react-native-draggable-flatlist 1.1 +// Project: https://github.com/computerjazz/react-native-draggable-flatlist#readme +// Definitions by: Stack Builders +// Esteban Ibarra +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import { VirtualizedListWithoutRenderItemProps } from "react-native"; +import { Component } from "react"; + +export interface RenderItemInfo { + item: ItemR; + index: number; + move: () => void; + moveEnd: () => void; + isActive: boolean; +} + +export interface OnMoveEndInfo { + data: ReadonlyArray | null; + to: number; + from: number; + row: ItemM; +} + +interface DraggableFlatListProps extends VirtualizedListWithoutRenderItemProps { + /** + * Items to be rendered. + */ + data: ReadonlyArray | null; + + /** + * Function that returns updated ordering of data + */ + onMoveEnd?: (info: OnMoveEndInfo) => void; + + /** + * Function that is called when row becomes active. + */ + onMoveBegin?: (index: number) => void; + + /** + * Sets where scrolling begins. + * + * Default is 5 + */ + scrollPercent?: number; + + /** + * Function that calls move when the row should become active (in an onPress, onLongPress, etc). Calls moveEnd when the gesture is complete (in onPressOut). + */ + renderItem: (info: RenderItemInfo) => React.ReactElement | null; +} + +declare class DraggableFlatList extends Component> { + constructor(props: DraggableFlatListProps); +} + +export default DraggableFlatList; diff --git a/types/react-native-draggable-flatlist/react-native-draggable-flatlist-tests.tsx b/types/react-native-draggable-flatlist/react-native-draggable-flatlist-tests.tsx new file mode 100644 index 0000000000..40d613e4ea --- /dev/null +++ b/types/react-native-draggable-flatlist/react-native-draggable-flatlist-tests.tsx @@ -0,0 +1,44 @@ +import * as React from 'react'; +import { TouchableOpacity, Text } from 'react-native'; +import DraggableFlatList, { RenderItemInfo } from 'react-native-draggable-flatlist'; + +interface Item { + name: string; + mail: string; +} + +class Example extends React.Component { + state = { + data: [ + { name: 'Esteban', mail: 'foo@foo.com' }, + { name: 'Xavier', mail: 'foo2@foo.com' }, + ] + }; + + renderItem({ item, index, move, moveEnd, isActive }: RenderItemInfo) { + return ( + + {index} + {item.name} + {item.mail} + + ); + } + + render() { + const { data } = this.state; + return ( + `draggable-item-${index}`} + scrollPercent={10} + onMoveEnd={({ data }) => this.setState({ data })} + ListFooterComponent={{'Hello'}} + /> + ); + } +} diff --git a/types/react-native-draggable-flatlist/tsconfig.json b/types/react-native-draggable-flatlist/tsconfig.json new file mode 100644 index 0000000000..b3c009feac --- /dev/null +++ b/types/react-native-draggable-flatlist/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "jsx": "react-native" + }, + "files": [ + "index.d.ts", + "react-native-draggable-flatlist-tests.tsx" + ] +} diff --git a/types/react-native-draggable-flatlist/tslint.json b/types/react-native-draggable-flatlist/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-native-draggable-flatlist/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-native/index.d.ts b/types/react-native/index.d.ts index ae1aa35f00..ae3127bc1d 100644 --- a/types/react-native/index.d.ts +++ b/types/react-native/index.d.ts @@ -3629,6 +3629,18 @@ interface ImagePropsAndroid { * Duration of fade in animation. */ fadeDuration?: number; + + /** + * Required if loading images via 'uri' from drawable folder on Android. + * Explanation: https://medium.com/@adamjacobb/react-native-performance-images-adf5843e120 + */ + width?: number; + + /** + * Required if loading images via 'uri' from drawable folder on Android + * Explanation: https://medium.com/@adamjacobb/react-native-performance-images-adf5843e120 + */ + height?: number; } /** @@ -6325,6 +6337,12 @@ export interface ScrollViewProps */ horizontal?: boolean; + /** + * If sticky headers should stick at the bottom instead of the top of the + * ScrollView. This is usually used with inverted ScrollViews. + */ + invertStickyHeaders?: boolean; + /** * Determines whether the keyboard gets dismissed in response to a drag. * - 'none' (the default) drags do not dismiss the keyboard. diff --git a/types/react-native/test/index.tsx b/types/react-native/test/index.tsx index b5d7a5faeb..79c5a111ca 100644 --- a/types/react-native/test/index.tsx +++ b/types/react-native/test/index.tsx @@ -430,6 +430,7 @@ class ScrollerListComponentTest extends React.Component< ; export interface DrawerItemsProps { - navigation: NavigationScreenProp; + navigation: NavigationScreenProp; items: NavigationRoute[]; activeItemKey?: string; activeTintColor?: string; diff --git a/types/react-places-autocomplete/index.d.ts b/types/react-places-autocomplete/index.d.ts index 62e3d93a1d..e24e479be8 100644 --- a/types/react-places-autocomplete/index.d.ts +++ b/types/react-places-autocomplete/index.d.ts @@ -1,7 +1,8 @@ -// Type definitions for react-places-autocomplete 6.1 +// Type definitions for react-places-autocomplete 7.2 // Project: https://github.com/kenny-hibino/react-places-autocomplete/ // Definitions by: Guilherme Hübner // Andrew Makarov +// Nokky Goren // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 // @@ -15,13 +16,10 @@ export interface formattedSuggestionType { } export interface PropTypes { - inputProps: { - value: string; - onChange: (value: string) => void; + inputProps?: { type?: string; name?: string; placeholder?: string; - onBlur?: (event: React.FocusEvent) => void; disabled?: boolean; }; onError?: (status: string, clearSuggestion: () => void) => void; @@ -41,7 +39,7 @@ export interface PropTypes { autocompleteItem?: React.CSSProperties; autocompleteItemActive?: React.CSSProperties; }; - options?: { + searchOptions?: { bounds?: google.maps.LatLngBounds | google.maps.LatLngBoundsLiteral; componentRestrictions?: google.maps.GeocoderComponentRestrictions; location?: google.maps.LatLng | google.maps.LatLngLiteral; @@ -49,6 +47,9 @@ export interface PropTypes { radius?: number | string; types?: string[]; }; + value?: string; + onChange?: (value: string) => void; + onBlur?: (event: React.FocusEvent) => void; debounce?: number; highlightFirstSuggestion?: boolean; diff --git a/types/react-places-autocomplete/react-places-autocomplete-tests.tsx b/types/react-places-autocomplete/react-places-autocomplete-tests.tsx index 41e6ff37b4..a7a7816d99 100644 --- a/types/react-places-autocomplete/react-places-autocomplete-tests.tsx +++ b/types/react-places-autocomplete/react-places-autocomplete-tests.tsx @@ -45,7 +45,7 @@ class Test extends React.Component { return (
    - + ); } diff --git a/types/react-qr-reader/index.d.ts b/types/react-qr-reader/index.d.ts index de426667c0..908960f25c 100644 --- a/types/react-qr-reader/index.d.ts +++ b/types/react-qr-reader/index.d.ts @@ -6,11 +6,7 @@ import * as React from "react"; -export as namespace QrReader; - -export default QrReader; - -export namespace QrReader { +declare namespace QrReader { interface props { onScan: (data: string | null) => void; onError: (err: any) => void; @@ -26,5 +22,8 @@ export namespace QrReader { } } -declare class QrReader extends React.Component { -} +export as namespace QrReader; + +declare class QrReader extends React.Component {} + +export = QrReader; diff --git a/types/react-qr-reader/react-qr-reader-tests.tsx b/types/react-qr-reader/react-qr-reader-tests.tsx index 20632f8029..0a6796bfd9 100644 --- a/types/react-qr-reader/react-qr-reader-tests.tsx +++ b/types/react-qr-reader/react-qr-reader-tests.tsx @@ -1,5 +1,5 @@ import * as React from "react"; -import QrReader from "react-qr-reader"; +import * as QrReader from "react-qr-reader"; export class Test extends React.Component { render() { diff --git a/types/react-redux-toastr/index.d.ts b/types/react-redux-toastr/index.d.ts index fc11da9c43..9a7a115725 100644 --- a/types/react-redux-toastr/index.d.ts +++ b/types/react-redux-toastr/index.d.ts @@ -4,7 +4,7 @@ // Artyom Stukans // Mika Kuitunen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.8 +// TypeScript Version: 3.0 import { Component } from 'react'; import { Action, Reducer } from 'redux'; diff --git a/types/react-redux/index.d.ts b/types/react-redux/index.d.ts index 2f919581f4..bcbcced0bd 100644 --- a/types/react-redux/index.d.ts +++ b/types/react-redux/index.d.ts @@ -13,7 +13,7 @@ // Anatoli Papirovski // Boris Sergeyev // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.8 +// TypeScript Version: 3.0 // Known Issue: // There is a known issue in TypeScript, which doesn't allow decorators to change the signature of the classes @@ -65,11 +65,11 @@ export type AdvancedComponentDecorator = * DecorationTargetProps[P] definition, its definition will be that of InjectedProps[P] */ export type Matching = { - [P in keyof DecorationTargetProps]: P extends keyof InjectedProps - ? InjectedProps[P] extends DecorationTargetProps[P] - ? DecorationTargetProps[P] - : InjectedProps[P] - : DecorationTargetProps[P]; + [P in keyof DecorationTargetProps]: P extends keyof InjectedProps + ? InjectedProps[P] extends DecorationTargetProps[P] + ? DecorationTargetProps[P] + : InjectedProps[P] + : DecorationTargetProps[P]; }; /** @@ -95,16 +95,16 @@ export type GetProps = C extends ComponentType ? P : never; // Applies LibraryManagedAttributes (proper handling of defaultProps // and propTypes), as well as defines WrappedComponent. export type ConnectedComponentClass = ComponentClass> & { - WrappedComponent: C; + WrappedComponent: C; }; // Injects props and removes them from the prop requirements. // Will not pass through the injected props if they are passed in during // render. Also adds new prop requirements from TNeedsProps. export type InferableComponentEnhancerWithProps = - >>>( - component: C - ) => ConnectedComponentClass, keyof Shared>> & TNeedsProps>; + >>>( + component: C + ) => ConnectedComponentClass, keyof Shared>> & TNeedsProps>; // Injects props and removes them from the prop requirements. // Will not pass through the injected props if they are passed in during @@ -112,14 +112,19 @@ export type InferableComponentEnhancerWithProps = export type InferableComponentEnhancer = InferableComponentEnhancerWithProps; +export type InferThunkActionCreatorType any> = + TActionCreator extends (...args: infer TParams) => (...args: any[]) => infer TReturn + ? (...args: TParams) => TReturn + : TActionCreator; + export type HandleThunkActionCreator = - TActionCreator extends (...args: any[]) => (...args: any[]) => any - ? ReturnType + TActionCreator extends (...args: any[]) => any + ? InferThunkActionCreatorType : TActionCreator; // redux-thunk middleware returns thunk's return value from dispatch call // https://github.com/reduxjs/redux-thunk#composition -export type WithThunkActionCreators = +export type ResolveThunks = TDispatchProps extends { [key: string]: any } ? { [C in keyof TDispatchProps]: HandleThunkActionCreator @@ -155,17 +160,27 @@ export interface Connect { ( mapStateToProps: null | undefined, - mapDispatchToProps: MapDispatchToPropsParam + mapDispatchToProps: MapDispatchToPropsNonObject + ): InferableComponentEnhancerWithProps; + + ( + mapStateToProps: null | undefined, + mapDispatchToProps: TDispatchProps, ): InferableComponentEnhancerWithProps< - WithThunkActionCreators, + ResolveThunks, TOwnProps >; ( mapStateToProps: MapStateToPropsParam, - mapDispatchToProps: MapDispatchToPropsParam + mapDispatchToProps: MapDispatchToPropsNonObject + ): InferableComponentEnhancerWithProps; + + ( + mapStateToProps: MapStateToPropsParam, + mapDispatchToProps: TDispatchProps, ): InferableComponentEnhancerWithProps< - TStateProps & WithThunkActionCreators, + TStateProps & ResolveThunks, TOwnProps >; @@ -203,21 +218,35 @@ export interface Connect { ( mapStateToProps: null | undefined, - mapDispatchToProps: MapDispatchToPropsParam, + mapDispatchToProps: MapDispatchToPropsNonObject, + mergeProps: null | undefined, + options: Options<{}, TStateProps, TOwnProps> + ): InferableComponentEnhancerWithProps; + + ( + mapStateToProps: null | undefined, + mapDispatchToProps: TDispatchProps, mergeProps: null | undefined, options: Options<{}, TStateProps, TOwnProps> ): InferableComponentEnhancerWithProps< - WithThunkActionCreators, + ResolveThunks, TOwnProps >; ( mapStateToProps: MapStateToPropsParam, - mapDispatchToProps: MapDispatchToPropsParam, + mapDispatchToProps: MapDispatchToPropsNonObject, + mergeProps: null | undefined, + options: Options + ): InferableComponentEnhancerWithProps; + + ( + mapStateToProps: MapStateToPropsParam, + mapDispatchToProps: TDispatchProps, mergeProps: null | undefined, options: Options ): InferableComponentEnhancerWithProps< - TStateProps & WithThunkActionCreators, + TStateProps & ResolveThunks, TOwnProps >; // tslint:enable:no-unnecessary-generics @@ -243,10 +272,12 @@ export type MapDispatchToProps = MapDispatchToPropsFunction | TDispatchProps; export type MapDispatchToPropsFactory = - (dispatch: Dispatch, ownProps: TOwnProps) => MapDispatchToProps; + (dispatch: Dispatch, ownProps: TOwnProps) => MapDispatchToPropsFunction; export type MapDispatchToPropsParam = MapDispatchToPropsFactory | MapDispatchToProps; +export type MapDispatchToPropsNonObject = MapDispatchToPropsFactory | MapDispatchToPropsFunction; + export type MergeProps = (stateProps: TStateProps, dispatchProps: TDispatchProps, ownProps: TOwnProps) => TMergedProps; diff --git a/types/react-redux/react-redux-tests.tsx b/types/react-redux/react-redux-tests.tsx index aff8515e87..554ace09ff 100644 --- a/types/react-redux/react-redux-tests.tsx +++ b/types/react-redux/react-redux-tests.tsx @@ -102,23 +102,79 @@ function MapDispatch() { } function MapDispatchWithThunkActionCreators() { - class TestComponent extends React.Component<{ - foo: string, - onClick(): void, - thunkAction(): Promise - }> {} - - const mapDispatchToProps = () => ({ - onClick: () => {}, - thunkAction: () => async () => {} + const simpleAction = (payload: boolean) => ({ + type: 'SIMPLE_ACTION', + payload, }); + const thunkAction = (param1: number, param2: string) => ( + async (dispatch: Dispatch, { foo }: OwnProps) => { + return foo; + } + ); + interface OwnProps { + foo: string; + } + interface TestComponentProps extends OwnProps { + simpleAction: typeof simpleAction; + thunkAction(param1: number, param2: string): Promise; + } + class TestComponent extends React.Component {} - const Test = connect( - null, - mapDispatchToProps, + const mapStateToProps = ({ foo }: { foo: string }) => ({ foo }); + const mapDispatchToProps = { simpleAction, thunkAction }; + + const Test1 = connect(null, mapDispatchToProps)(TestComponent); + const Test2 = connect(mapStateToProps, mapDispatchToProps)(TestComponent); + const Test3 = connect( + null, mapDispatchToProps, null, { storeKey: 'somekey' } )(TestComponent); + const Test4 = connect( + mapStateToProps, mapDispatchToProps, null, { storeKey: 'somekey' } + )(TestComponent); + const verify =
    + ; + + ; + +
    ; +} - const verify = ; +function MapManualDispatchThatLooksLikeThunk() { + interface OwnProps { + foo: string; + } + interface TestComponentProps extends OwnProps { + remove: (item: string) => () => object; + } + class TestComponent extends React.Component { + render() { + return
    ; + } + } + + const mapStateToProps = ({ foo }: { foo: string }) => ({ foo }); + function mapDispatchToProps(dispatch: Dispatch) { + return { + remove(item: string) { + return () => dispatch({ type: 'REMOVE_ITEM', item }); + } + }; + } + + const Test1 = connect(null, mapDispatchToProps)(TestComponent); + const Test2 = connect(mapStateToProps, mapDispatchToProps)(TestComponent); + const Test3 = connect( + null, mapDispatchToProps, null, { storeKey: 'somekey' } + )(TestComponent); + const Test4 = connect( + mapStateToProps, mapDispatchToProps, null, { storeKey: 'somekey' } + )(TestComponent); + const verify =
    + ; + + ; + +
    ; } function MapStateAndDispatchObject() { diff --git a/types/react-router-dom/react-router-dom-tests.tsx b/types/react-router-dom/react-router-dom-tests.tsx index a550a579fa..a7715e9ea1 100644 --- a/types/react-router-dom/react-router-dom-tests.tsx +++ b/types/react-router-dom/react-router-dom-tests.tsx @@ -27,6 +27,10 @@ type OtherProps = RouteComponentProps<{ }>; const Component: React.SFC = props => { + if (!props.match) { + return null; + } + const { id } = props.match.params; return (
    {id}
    diff --git a/types/react-router-redux/index.d.ts b/types/react-router-redux/index.d.ts index 9dfbd58c11..7abdc88505 100644 --- a/types/react-router-redux/index.d.ts +++ b/types/react-router-redux/index.d.ts @@ -4,7 +4,7 @@ // Shoya Tanaka // Mykolas // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.8 +// TypeScript Version: 3.0 import { Store, diff --git a/types/react-router/index.d.ts b/types/react-router/index.d.ts index f62fc44b18..eee1b15972 100644 --- a/types/react-router/index.d.ts +++ b/types/react-router/index.d.ts @@ -72,11 +72,20 @@ export interface RouteComponentProps { + history: H.History; + location: H.Location; + match: match | null; +} + export interface RouteProps { location?: H.Location; component?: React.ComponentType> | React.ComponentType; render?: ((props: RouteComponentProps) => React.ReactNode); - children?: ((props: RouteComponentProps) => React.ReactNode) | React.ReactNode; + children?: ((props: RouteChildrenProps) => React.ReactNode) | React.ReactNode; path?: string | string[]; exact?: boolean; sensitive?: boolean; diff --git a/types/react-router/test/Children.tsx b/types/react-router/test/Children.tsx index c3dea4f482..7f33629f3c 100644 --- a/types/react-router/test/Children.tsx +++ b/types/react-router/test/Children.tsx @@ -20,3 +20,9 @@ function RouteWithElementJsxChildren() { {
    Hello!
    } ; } + +function RouteWithFunctionChildrenUsingNullableMatch() { + return + {({ match }) => match !== null ?
    Matched path: {match.path}
    :
    No match!
    } +
    ; +} diff --git a/types/react-sortable-tree/index.d.ts b/types/react-sortable-tree/index.d.ts index bcc6596ee6..0c0cc075e2 100644 --- a/types/react-sortable-tree/index.d.ts +++ b/types/react-sortable-tree/index.d.ts @@ -46,6 +46,11 @@ export interface FullTree { export interface NodeData extends TreeNode, TreePath, TreeIndex { } +export interface FlatDataItem extends TreeNode, TreePath { + lowerSiblingsCounts: number[]; + parentNode: TreeItem; +} + export interface SearchData extends NodeData { searchQuery: any; } @@ -61,6 +66,11 @@ export interface OnVisibilityToggleData extends FullTree, TreeNode { expanded: boolean; } +export interface OnDragStateChangedData { + isDragging: boolean; + draggedNode: TreeItem; +} + interface PreviousAndNextLocation { prevTreeIndex: number; prevPath: NumberOrStringArray; @@ -96,7 +106,7 @@ export interface NodeRendererProps { toggleChildrenVisibility?(data: NodeData): void; buttons?: JSX.Element[]; className?: string; - style?: { [index: string]: any }; + style?: React.CSSProperties; title?: (data: NodeData) => JSX.Element | JSX.Element; subtitle?: (data: NodeData) => JSX.Element | JSX.Element; icons?: JSX.Element[]; @@ -109,12 +119,12 @@ export interface NodeRendererProps { connectDragPreview: ConnectDragPreview; connectDragSource: ConnectDragSource; - parentNode?: { [index: string]: any }; + parentNode?: TreeItem; startDrag: any; endDrag: any; isDragging: boolean; didDrop: boolean; - draggedNode?: { [index: string]: any }; + draggedNode?: TreeItem; isOver: boolean; canDrop?: boolean; } @@ -124,7 +134,7 @@ export type PlaceholderRenderer = React.ComponentClass export interface PlaceholderRendererProps { isOver: boolean; canDrop: boolean; - draggedNode: { [index: string]: any }; + draggedNode: TreeItem; } type NumberOrStringArray = Array; @@ -147,54 +157,52 @@ export interface TreeRendererProps { connectDropTarget: ConnectDropTarget; isOver: boolean; canDrop?: boolean; - draggedNode?: { [index: string]: any }; + draggedNode?: TreeItem; // used in dndManager - getPrevRow: any; // @TODO what is this method? + getPrevRow: () => FlatDataItem | null; node: TreeItem; path: NumberOrStringArray; } -export interface ThemeProps { - style?: { [index: string]: any }; - innerStyle?: { [index: string]: any }; +interface ThemeTreeProps { + style?: React.CSSProperties; + innerStyle?: React.CSSProperties; reactVirtualizedListProps?: Partial; scaffoldBlockPxWidth?: number; slideRegionSize?: number; rowHeight?: ((info: Index) => number) | number; - treeNodeRenderer?: TreeRenderer; nodeContentRenderer?: NodeRenderer; placeholderRenderer?: PlaceholderRenderer; } -export interface ReactSortableTreeProps { +export interface ThemeProps extends ThemeTreeProps { + treeNodeRenderer?: TreeRenderer; +} + +export interface ReactSortableTreeProps extends ThemeTreeProps { treeData: TreeItem[]; onChange(treeData: TreeItem[]): void; - style?: { [index: string]: any }; - className?: string; - innerStyle?: { [index: string]: any }; + getNodeKey?(data: TreeNode & TreeIndex): string | number; + generateNodeProps?(data: ExtendedNodeData): { [index: string]: any }; + onMoveNode?(data: NodeData & FullTree & OnMovePreviousAndNextLocation): void; + onVisibilityToggle?(data: OnVisibilityToggleData): void; + onDragStateChanged?(data: OnDragStateChangedData): void; maxDepth?: number; + rowDirection?: 'ltr' | 'rtl'; + canDrag?: ((data: ExtendedNodeData) => boolean) | boolean; + canDrop?(data: OnDragPreviousAndNextLocation & NodeData): boolean; + canNodeHaveChildren?(node: TreeItem): boolean; + theme?: ThemeProps; searchMethod?(data: SearchData): boolean; searchQuery?: string | any; searchFocusOffset?: number; - searchFinishCallback?(matches: NodeData[]): void; - generateNodeProps?(data: ExtendedNodeData): { [index: string]: any }; - getNodeKey?(data: TreeNode & TreeIndex): string | number; - onMoveNode?(data: NodeData & FullTree & OnMovePreviousAndNextLocation): void; - onVisibilityToggle?(data: OnVisibilityToggleData): void; - canDrag?: ((data: ExtendedNodeData) => boolean) | boolean; - canDrop?(data: OnDragPreviousAndNextLocation & NodeData): boolean; - reactVirtualizedListProps?: Partial; - rowHeight?: ((info: Index) => number) | number; - slideRegionSize?: number; - scaffoldBlockPxWidth?: number; - isVirtualized?: boolean; - nodeContentRenderer?: NodeRenderer; - dndType?: string; - placeholderRenderer?: PlaceholderRenderer; - theme?: ThemeProps; - shouldCopyOnOutsideDrop?: boolean | ((data: ShouldCopyData) => boolean); onlyExpandSearchedNodes?: boolean; + searchFinishCallback?(matches: NodeData[]): void; + dndType?: string; + shouldCopyOnOutsideDrop?: boolean | ((data: ShouldCopyData) => boolean); + className?: string; + isVirtualized?: boolean; } declare const SortableTree: React.ComponentClass; diff --git a/types/react-sortable-tree/utils/tree-data-utils.d.ts b/types/react-sortable-tree/utils/tree-data-utils.d.ts index b9c7bb94a0..b80e82dd81 100644 --- a/types/react-sortable-tree/utils/tree-data-utils.d.ts +++ b/types/react-sortable-tree/utils/tree-data-utils.d.ts @@ -1,4 +1,4 @@ -import { FullTree, TreePath, TreeItem, TreeIndex, SearchData, NodeData, TreeNode } from '..'; +import { FullTree, TreePath, TreeItem, TreeIndex, SearchData, NodeData, TreeNode, FlatDataItem } from '..'; export type GetNodeKeyFunction = (data: TreeIndex & TreeNode) => string | number; export type WalkAndMapFunctionParameters = FullTree & {getNodeKey: GetNodeKeyFunction, callback: Function, ignoreCollapsed?: boolean}; @@ -13,6 +13,11 @@ export function getVisibleNodeInfoAtIndex( }): TreeNode & TreePath & {lowerSiblingsCounts: number[]} | null; export function walk(data: WalkAndMapFunctionParameters): void; export function map(data: WalkAndMapFunctionParameters): TreeItem[]; +export function toggleExpandedForAll( + data: FullTree & { + expanded?: boolean, + }, +): TreeItem[]; export function changeNodeAtPath( data: FullTree & TreePath & { newNode: Function | any, @@ -26,12 +31,18 @@ export function removeNodeAtPath( ignoreCollapsed?: boolean, }, ): TreeItem[]; +export function removeNode( + data: FullTree & TreePath & { + getNodeKey: GetNodeKeyFunction, + ignoreCollapsed?: boolean, + }, +): (FullTree & TreeNode & TreeIndex) | null; export function getNodeAtPath( data: FullTree & TreePath & { getNodeKey: GetNodeKeyFunction, ignoreCollapsed?: boolean, }, -): TreeNode & TreeIndex | null; +): (TreeNode & TreeIndex) | null; export function addNodeUnderParent( data: FullTree & { newNode: TreeItem, @@ -39,6 +50,7 @@ export function addNodeUnderParent( getNodeKey: GetNodeKeyFunction, ignoreCollapsed?: boolean, expandParent?: boolean, + addAsFirstChild?: boolean, }, ): FullTree & TreeIndex; export function insertNode( @@ -56,7 +68,7 @@ export function getFlatDataFromTree( getNodeKey: GetNodeKeyFunction, ignoreCollapsed?: boolean, }, -): Array; +): FlatDataItem[]; export function getTreeFromFlatData( data: { flatData: FlattenedData, diff --git a/types/react-splitter-layout/index.d.ts b/types/react-splitter-layout/index.d.ts new file mode 100644 index 0000000000..29273e87ef --- /dev/null +++ b/types/react-splitter-layout/index.d.ts @@ -0,0 +1,97 @@ +// Type definitions for react-splitter-layout 3.0 +// Project: https://github.com/zesik/react-splitter-layout +// Definitions by: Markus Lasermann +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import * as React from "react"; + +export default class SplitterLayout extends React.PureComponent { +} + +export type TPrimaryIndex = 0|1; + +export interface SplitterLayoutProps { + /** + * Custom CSS class name applied to the layout div. + * You can use this to customize layout style. + * Refers to the original stylesheet to see what you can customize. + */ + customClassName?: string; + + /** + * Determine whether the layout should be a horizontal split or a vertical split. + * + * @default false + */ + vertical?: boolean; + + /** + * Determine whether the width of each pane should be calculated in percentage or by pixels. + * The default value is false, which means width is calculated in pixels. + * + * @default false + */ + percentage?: boolean; + + /** + * Index of the primary pane. + * Since SplitterLayout supports at most 2 children, only 0 or 1 is allowed. + * + * A primary pane is used to show users primary content, while a secondary pane is the other pane. + * When window size changes and percentage is set to false, primary pane's size is flexible + * and secondary pane's size is kept unchanged. However, when the window size is not enough + * for showing both minimal primary pane and minimal secondary pane, + * the primary pane's size is served first. + * + * @default 0 + */ + primaryIndex?: TPrimaryIndex; + + /** + * Minimal size of primary pane. + * When percentage is set to false, this value is pixel size (25 means 25px). + * When percentage is set to true, this value is percentage (25 means 25%). + * + * @default 0 + */ + primaryMinSize?: number; + + /** + * Minimal size of secondary pane. + */ + secondaryMinSize?: number; + + /** + * Initial size of secondary pane when page loads. + * If this prop is not defined, SplitterLayout tries to split the layout with equal sizes. + * (Note: equal size may not apply when there are nested layouts.) + * + * @default undefined + */ + secondaryInitialSize?: number; + + /** + * Called when dragging is started. + * + * No parameter will be passed to event handlers. + */ + onDragStart?: () => void; + + /** + * Called when dragging finishes. + * + * No parameter will be passed to event handlers. + */ + onDragEnd?: () => void; + + /** + * Called when the size of secondary pane is changed. + * + * Event handlers will be passed with a single parameter of number type representing + * new size of secondary pane. + * When percentage is set to false, the value is in pixel size. + * When percentage is set to true, the value is in percentage. + */ + onSecondaryPaneSizeChange?: (value: number) => void; +} diff --git a/types/react-splitter-layout/react-splitter-layout-tests.tsx b/types/react-splitter-layout/react-splitter-layout-tests.tsx new file mode 100644 index 0000000000..fa9860a2b7 --- /dev/null +++ b/types/react-splitter-layout/react-splitter-layout-tests.tsx @@ -0,0 +1,17 @@ +import * as React from "react"; +import SplitterLayout, { SplitterLayoutProps } from "react-splitter-layout"; + +export class SplitterLayoutTest extends React.PureComponent { + render(): JSX.Element { + const props: SplitterLayoutProps = { + percentage: true, + secondaryInitialSize: 40, + }; + return ( + +
    1st
    +
    2nd
    +
    + ); + } +} diff --git a/types/react-splitter-layout/tsconfig.json b/types/react-splitter-layout/tsconfig.json new file mode 100644 index 0000000000..e268261ea1 --- /dev/null +++ b/types/react-splitter-layout/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "jsx": "react", + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "react-splitter-layout-tests.tsx" + ] +} diff --git a/types/react-splitter-layout/tslint.json b/types/react-splitter-layout/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-splitter-layout/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-syntax-highlighter/index.d.ts b/types/react-syntax-highlighter/index.d.ts index c631dea9f7..c1ad8f0242 100644 --- a/types/react-syntax-highlighter/index.d.ts +++ b/types/react-syntax-highlighter/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for react-syntax-highlighter +// Type definitions for react-syntax-highlighter 10.1 // Project: https://github.com/conorhastings/react-syntax-highlighter // Definitions by: Ivo Stratev // Aimee Gamble-Milner @@ -42,626 +42,626 @@ declare module 'react-syntax-highlighter/prism-light' { export default class SyntaxHighlighter extends React.Component {} } -declare module 'react-syntax-highlighter/styles/hljs' { - export { default as agate } from 'react-syntax-highlighter/styles/hljs/agate'; - export { default as androidstudio } from 'react-syntax-highlighter/styles/hljs/androidstudio'; - export { default as arduinoLight } from 'react-syntax-highlighter/styles/hljs/arduino-light'; - export { default as arta } from 'react-syntax-highlighter/styles/hljs/arta'; - export { default as ascetic } from 'react-syntax-highlighter/styles/hljs/ascetic'; - export { default as atelierCaveDark } from 'react-syntax-highlighter/styles/hljs/atelier-cave-dark'; - export { default as atelierCaveLight } from 'react-syntax-highlighter/styles/hljs/atelier-cave-light'; - export { default as atelierDuneDark } from 'react-syntax-highlighter/styles/hljs/atelier-dune-dark'; - export { default as atelierDuneLight } from 'react-syntax-highlighter/styles/hljs/atelier-dune-light'; - export { default as atelierEstuaryDark } from 'react-syntax-highlighter/styles/hljs/atelier-estuary-dark'; - export { default as atelierEstuaryLight } from 'react-syntax-highlighter/styles/hljs/atelier-estuary-light'; - export { default as atelierForestDark } from 'react-syntax-highlighter/styles/hljs/atelier-forest-dark'; - export { default as atelierForestLight } from 'react-syntax-highlighter/styles/hljs/atelier-forest-light'; - export { default as atelierHeathDark } from 'react-syntax-highlighter/styles/hljs/atelier-heath-dark'; - export { default as atelierHeathLight } from 'react-syntax-highlighter/styles/hljs/atelier-heath-light'; - export { default as atelierLakesideDark } from 'react-syntax-highlighter/styles/hljs/atelier-lakeside-dark'; - export { default as atelierLakesideLight } from 'react-syntax-highlighter/styles/hljs/atelier-lakeside-light'; - export { default as atelierPlateauDark } from 'react-syntax-highlighter/styles/hljs/atelier-plateau-dark'; - export { default as atelierPlateauLight } from 'react-syntax-highlighter/styles/hljs/atelier-plateau-light'; - export { default as atelierSavannaDark } from 'react-syntax-highlighter/styles/hljs/atelier-savanna-dark'; - export { default as atelierSavannaLight } from 'react-syntax-highlighter/styles/hljs/atelier-savanna-light'; - export { default as atelierSeasideDark } from 'react-syntax-highlighter/styles/hljs/atelier-seaside-dark'; - export { default as atelierSeasideLight } from 'react-syntax-highlighter/styles/hljs/atelier-seaside-light'; - export { default as atelierSulphurpoolDark } from 'react-syntax-highlighter/styles/hljs/atelier-sulphurpool-dark'; - export { default as atelierSulphurpoolLight } from 'react-syntax-highlighter/styles/hljs/atelier-sulphurpool-light'; - export { default as atomOneDark } from 'react-syntax-highlighter/styles/hljs/atom-one-dark'; - export { default as atomOneLight } from 'react-syntax-highlighter/styles/hljs/atom-one-light'; - export { default as brownPaper } from 'react-syntax-highlighter/styles/hljs/brown-paper'; - export { default as codepenEmbed } from 'react-syntax-highlighter/styles/hljs/codepen-embed'; - export { default as colorBrewer } from 'react-syntax-highlighter/styles/hljs/color-brewer'; - export { default as darcula } from 'react-syntax-highlighter/styles/hljs/darcula'; - export { default as dark } from 'react-syntax-highlighter/styles/hljs/dark'; - export { default as darkula } from 'react-syntax-highlighter/styles/hljs/darkula'; - export { default as defaultStyle } from 'react-syntax-highlighter/styles/hljs/default-style'; - export { default as docco } from 'react-syntax-highlighter/styles/hljs/docco'; - export { default as dracula } from 'react-syntax-highlighter/styles/hljs/dracula'; - export { default as far } from 'react-syntax-highlighter/styles/hljs/far'; - export { default as foundation } from 'react-syntax-highlighter/styles/hljs/foundation'; - export { default as githubGist } from 'react-syntax-highlighter/styles/hljs/github-gist'; - export { default as github } from 'react-syntax-highlighter/styles/hljs/github'; - export { default as googlecode } from 'react-syntax-highlighter/styles/hljs/googlecode'; - export { default as grayscale } from 'react-syntax-highlighter/styles/hljs/grayscale'; - export { default as gruvboxDark } from 'react-syntax-highlighter/styles/hljs/gruvbox-dark'; - export { default as gruvboxLight } from 'react-syntax-highlighter/styles/hljs/gruvbox-light'; - export { default as hopscotch } from 'react-syntax-highlighter/styles/hljs/hopscotch'; - export { default as hybrid } from 'react-syntax-highlighter/styles/hljs/hybrid'; - export { default as idea } from 'react-syntax-highlighter/styles/hljs/idea'; - export { default as irBlack } from 'react-syntax-highlighter/styles/hljs/ir-black'; - export { default as kimbieDark } from 'react-syntax-highlighter/styles/hljs/kimbie.dark'; - export { default as kimbieLight } from 'react-syntax-highlighter/styles/hljs/kimbie.light'; - export { default as magula } from 'react-syntax-highlighter/styles/hljs/magula'; - export { default as monoBlue } from 'react-syntax-highlighter/styles/hljs/mono-blue'; - export { default as monokaiSublime } from 'react-syntax-highlighter/styles/hljs/monokai-sublime'; - export { default as monokai } from 'react-syntax-highlighter/styles/hljs/monokai'; - export { default as obsidian } from 'react-syntax-highlighter/styles/hljs/obsidian'; - export { default as ocean } from 'react-syntax-highlighter/styles/hljs/ocean'; - export { default as paraisoDark } from 'react-syntax-highlighter/styles/hljs/paraiso-dark'; - export { default as paraisoLight } from 'react-syntax-highlighter/styles/hljs/paraiso-light'; - export { default as pojoaque } from 'react-syntax-highlighter/styles/hljs/pojoaque'; - export { default as purebasic } from 'react-syntax-highlighter/styles/hljs/purebasic'; - export { default as qtcreatorDark } from 'react-syntax-highlighter/styles/hljs/qtcreator_dark'; - export { default as qtcreatorLight } from 'react-syntax-highlighter/styles/hljs/qtcreator_light'; - export { default as railscasts } from 'react-syntax-highlighter/styles/hljs/railscasts'; - export { default as rainbow } from 'react-syntax-highlighter/styles/hljs/rainbow'; - export { default as routeros } from 'react-syntax-highlighter/styles/hljs/routeros'; - export { default as schoolBook } from 'react-syntax-highlighter/styles/hljs/school-book'; - export { default as solarizedDark } from 'react-syntax-highlighter/styles/hljs/solarized-dark'; - export { default as solarizedLight } from 'react-syntax-highlighter/styles/hljs/solarized-light'; - export { default as sunburst } from 'react-syntax-highlighter/styles/hljs/sunburst'; - export { default as tomorrowNightBlue } from 'react-syntax-highlighter/styles/hljs/tomorrow-night-blue'; - export { default as tomorrowNightBright } from 'react-syntax-highlighter/styles/hljs/tomorrow-night-bright'; - export { default as tomorrowNightEighties } from 'react-syntax-highlighter/styles/hljs/tomorrow-night-eighties'; - export { default as tomorrowNight } from 'react-syntax-highlighter/styles/hljs/tomorrow-night'; - export { default as tomorrow } from 'react-syntax-highlighter/styles/hljs/tomorrow'; - export { default as vs } from 'react-syntax-highlighter/styles/hljs/vs'; - export { default as vs2015 } from 'react-syntax-highlighter/styles/hljs/vs2015'; - export { default as xcode } from 'react-syntax-highlighter/styles/hljs/xcode'; - export { default as xt256 } from 'react-syntax-highlighter/styles/hljs/xt256'; - export { default as zenburn } from 'react-syntax-highlighter/styles/hljs/zenburn'; +declare module 'react-syntax-highlighter/dist/styles/hljs' { + export { default as agate } from 'react-syntax-highlighter/dist/styles/hljs/agate'; + export { default as androidstudio } from 'react-syntax-highlighter/dist/styles/hljs/androidstudio'; + export { default as arduinoLight } from 'react-syntax-highlighter/dist/styles/hljs/arduino-light'; + export { default as arta } from 'react-syntax-highlighter/dist/styles/hljs/arta'; + export { default as ascetic } from 'react-syntax-highlighter/dist/styles/hljs/ascetic'; + export { default as atelierCaveDark } from 'react-syntax-highlighter/dist/styles/hljs/atelier-cave-dark'; + export { default as atelierCaveLight } from 'react-syntax-highlighter/dist/styles/hljs/atelier-cave-light'; + export { default as atelierDuneDark } from 'react-syntax-highlighter/dist/styles/hljs/atelier-dune-dark'; + export { default as atelierDuneLight } from 'react-syntax-highlighter/dist/styles/hljs/atelier-dune-light'; + export { default as atelierEstuaryDark } from 'react-syntax-highlighter/dist/styles/hljs/atelier-estuary-dark'; + export { default as atelierEstuaryLight } from 'react-syntax-highlighter/dist/styles/hljs/atelier-estuary-light'; + export { default as atelierForestDark } from 'react-syntax-highlighter/dist/styles/hljs/atelier-forest-dark'; + export { default as atelierForestLight } from 'react-syntax-highlighter/dist/styles/hljs/atelier-forest-light'; + export { default as atelierHeathDark } from 'react-syntax-highlighter/dist/styles/hljs/atelier-heath-dark'; + export { default as atelierHeathLight } from 'react-syntax-highlighter/dist/styles/hljs/atelier-heath-light'; + export { default as atelierLakesideDark } from 'react-syntax-highlighter/dist/styles/hljs/atelier-lakeside-dark'; + export { default as atelierLakesideLight } from 'react-syntax-highlighter/dist/styles/hljs/atelier-lakeside-light'; + export { default as atelierPlateauDark } from 'react-syntax-highlighter/dist/styles/hljs/atelier-plateau-dark'; + export { default as atelierPlateauLight } from 'react-syntax-highlighter/dist/styles/hljs/atelier-plateau-light'; + export { default as atelierSavannaDark } from 'react-syntax-highlighter/dist/styles/hljs/atelier-savanna-dark'; + export { default as atelierSavannaLight } from 'react-syntax-highlighter/dist/styles/hljs/atelier-savanna-light'; + export { default as atelierSeasideDark } from 'react-syntax-highlighter/dist/styles/hljs/atelier-seaside-dark'; + export { default as atelierSeasideLight } from 'react-syntax-highlighter/dist/styles/hljs/atelier-seaside-light'; + export { default as atelierSulphurpoolDark } from 'react-syntax-highlighter/dist/styles/hljs/atelier-sulphurpool-dark'; + export { default as atelierSulphurpoolLight } from 'react-syntax-highlighter/dist/styles/hljs/atelier-sulphurpool-light'; + export { default as atomOneDark } from 'react-syntax-highlighter/dist/styles/hljs/atom-one-dark'; + export { default as atomOneLight } from 'react-syntax-highlighter/dist/styles/hljs/atom-one-light'; + export { default as brownPaper } from 'react-syntax-highlighter/dist/styles/hljs/brown-paper'; + export { default as codepenEmbed } from 'react-syntax-highlighter/dist/styles/hljs/codepen-embed'; + export { default as colorBrewer } from 'react-syntax-highlighter/dist/styles/hljs/color-brewer'; + export { default as darcula } from 'react-syntax-highlighter/dist/styles/hljs/darcula'; + export { default as dark } from 'react-syntax-highlighter/dist/styles/hljs/dark'; + export { default as darkula } from 'react-syntax-highlighter/dist/styles/hljs/darkula'; + export { default as defaultStyle } from 'react-syntax-highlighter/dist/styles/hljs/default-style'; + export { default as docco } from 'react-syntax-highlighter/dist/styles/hljs/docco'; + export { default as dracula } from 'react-syntax-highlighter/dist/styles/hljs/dracula'; + export { default as far } from 'react-syntax-highlighter/dist/styles/hljs/far'; + export { default as foundation } from 'react-syntax-highlighter/dist/styles/hljs/foundation'; + export { default as githubGist } from 'react-syntax-highlighter/dist/styles/hljs/github-gist'; + export { default as github } from 'react-syntax-highlighter/dist/styles/hljs/github'; + export { default as googlecode } from 'react-syntax-highlighter/dist/styles/hljs/googlecode'; + export { default as grayscale } from 'react-syntax-highlighter/dist/styles/hljs/grayscale'; + export { default as gruvboxDark } from 'react-syntax-highlighter/dist/styles/hljs/gruvbox-dark'; + export { default as gruvboxLight } from 'react-syntax-highlighter/dist/styles/hljs/gruvbox-light'; + export { default as hopscotch } from 'react-syntax-highlighter/dist/styles/hljs/hopscotch'; + export { default as hybrid } from 'react-syntax-highlighter/dist/styles/hljs/hybrid'; + export { default as idea } from 'react-syntax-highlighter/dist/styles/hljs/idea'; + export { default as irBlack } from 'react-syntax-highlighter/dist/styles/hljs/ir-black'; + export { default as kimbieDark } from 'react-syntax-highlighter/dist/styles/hljs/kimbie.dark'; + export { default as kimbieLight } from 'react-syntax-highlighter/dist/styles/hljs/kimbie.light'; + export { default as magula } from 'react-syntax-highlighter/dist/styles/hljs/magula'; + export { default as monoBlue } from 'react-syntax-highlighter/dist/styles/hljs/mono-blue'; + export { default as monokaiSublime } from 'react-syntax-highlighter/dist/styles/hljs/monokai-sublime'; + export { default as monokai } from 'react-syntax-highlighter/dist/styles/hljs/monokai'; + export { default as obsidian } from 'react-syntax-highlighter/dist/styles/hljs/obsidian'; + export { default as ocean } from 'react-syntax-highlighter/dist/styles/hljs/ocean'; + export { default as paraisoDark } from 'react-syntax-highlighter/dist/styles/hljs/paraiso-dark'; + export { default as paraisoLight } from 'react-syntax-highlighter/dist/styles/hljs/paraiso-light'; + export { default as pojoaque } from 'react-syntax-highlighter/dist/styles/hljs/pojoaque'; + export { default as purebasic } from 'react-syntax-highlighter/dist/styles/hljs/purebasic'; + export { default as qtcreatorDark } from 'react-syntax-highlighter/dist/styles/hljs/qtcreator_dark'; + export { default as qtcreatorLight } from 'react-syntax-highlighter/dist/styles/hljs/qtcreator_light'; + export { default as railscasts } from 'react-syntax-highlighter/dist/styles/hljs/railscasts'; + export { default as rainbow } from 'react-syntax-highlighter/dist/styles/hljs/rainbow'; + export { default as routeros } from 'react-syntax-highlighter/dist/styles/hljs/routeros'; + export { default as schoolBook } from 'react-syntax-highlighter/dist/styles/hljs/school-book'; + export { default as solarizedDark } from 'react-syntax-highlighter/dist/styles/hljs/solarized-dark'; + export { default as solarizedLight } from 'react-syntax-highlighter/dist/styles/hljs/solarized-light'; + export { default as sunburst } from 'react-syntax-highlighter/dist/styles/hljs/sunburst'; + export { default as tomorrowNightBlue } from 'react-syntax-highlighter/dist/styles/hljs/tomorrow-night-blue'; + export { default as tomorrowNightBright } from 'react-syntax-highlighter/dist/styles/hljs/tomorrow-night-bright'; + export { default as tomorrowNightEighties } from 'react-syntax-highlighter/dist/styles/hljs/tomorrow-night-eighties'; + export { default as tomorrowNight } from 'react-syntax-highlighter/dist/styles/hljs/tomorrow-night'; + export { default as tomorrow } from 'react-syntax-highlighter/dist/styles/hljs/tomorrow'; + export { default as vs } from 'react-syntax-highlighter/dist/styles/hljs/vs'; + export { default as vs2015 } from 'react-syntax-highlighter/dist/styles/hljs/vs2015'; + export { default as xcode } from 'react-syntax-highlighter/dist/styles/hljs/xcode'; + export { default as xt256 } from 'react-syntax-highlighter/dist/styles/hljs/xt256'; + export { default as zenburn } from 'react-syntax-highlighter/dist/styles/hljs/zenburn'; } -declare module 'react-syntax-highlighter/styles/hljs/agate' { +declare module 'react-syntax-highlighter/dist/styles/hljs/agate' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/hljs/androidstudio' { +declare module 'react-syntax-highlighter/dist/styles/hljs/androidstudio' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/hljs/arduino-light' { +declare module 'react-syntax-highlighter/dist/styles/hljs/arduino-light' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/hljs/arta' { +declare module 'react-syntax-highlighter/dist/styles/hljs/arta' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/hljs/ascetic' { +declare module 'react-syntax-highlighter/dist/styles/hljs/ascetic' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/hljs/atelier-cave-dark' { +declare module 'react-syntax-highlighter/dist/styles/hljs/atelier-cave-dark' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/hljs/atelier-cave-light' { +declare module 'react-syntax-highlighter/dist/styles/hljs/atelier-cave-light' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/hljs/atelier-dune-dark' { +declare module 'react-syntax-highlighter/dist/styles/hljs/atelier-dune-dark' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/hljs/atelier-dune-light' { +declare module 'react-syntax-highlighter/dist/styles/hljs/atelier-dune-light' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/hljs/atelier-estuary-dark' { +declare module 'react-syntax-highlighter/dist/styles/hljs/atelier-estuary-dark' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/hljs/atelier-estuary-light' { +declare module 'react-syntax-highlighter/dist/styles/hljs/atelier-estuary-light' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/hljs/atelier-forest-dark' { +declare module 'react-syntax-highlighter/dist/styles/hljs/atelier-forest-dark' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/hljs/atelier-forest-light' { +declare module 'react-syntax-highlighter/dist/styles/hljs/atelier-forest-light' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/hljs/atelier-heath-dark' { +declare module 'react-syntax-highlighter/dist/styles/hljs/atelier-heath-dark' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/hljs/atelier-heath-light' { +declare module 'react-syntax-highlighter/dist/styles/hljs/atelier-heath-light' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/hljs/atelier-lakeside-dark' { +declare module 'react-syntax-highlighter/dist/styles/hljs/atelier-lakeside-dark' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/hljs/atelier-lakeside-light' { +declare module 'react-syntax-highlighter/dist/styles/hljs/atelier-lakeside-light' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/hljs/atelier-plateau-dark' { +declare module 'react-syntax-highlighter/dist/styles/hljs/atelier-plateau-dark' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/hljs/atelier-plateau-light' { +declare module 'react-syntax-highlighter/dist/styles/hljs/atelier-plateau-light' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/hljs/atelier-savanna-dark' { +declare module 'react-syntax-highlighter/dist/styles/hljs/atelier-savanna-dark' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/hljs/atelier-savanna-light' { +declare module 'react-syntax-highlighter/dist/styles/hljs/atelier-savanna-light' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/hljs/atelier-seaside-dark' { +declare module 'react-syntax-highlighter/dist/styles/hljs/atelier-seaside-dark' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/hljs/atelier-seaside-light' { +declare module 'react-syntax-highlighter/dist/styles/hljs/atelier-seaside-light' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/hljs/atelier-sulphurpool-dark' { +declare module 'react-syntax-highlighter/dist/styles/hljs/atelier-sulphurpool-dark' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/hljs/atelier-sulphurpool-light' { +declare module 'react-syntax-highlighter/dist/styles/hljs/atelier-sulphurpool-light' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/hljs/atom-one-dark' { +declare module 'react-syntax-highlighter/dist/styles/hljs/atom-one-dark' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/hljs/atom-one-light' { +declare module 'react-syntax-highlighter/dist/styles/hljs/atom-one-light' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/hljs/brown-paper' { +declare module 'react-syntax-highlighter/dist/styles/hljs/brown-paper' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/hljs/codepen-embed' { +declare module 'react-syntax-highlighter/dist/styles/hljs/codepen-embed' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/hljs/color-brewer' { +declare module 'react-syntax-highlighter/dist/styles/hljs/color-brewer' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/hljs/darcula' { +declare module 'react-syntax-highlighter/dist/styles/hljs/darcula' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/hljs/dark' { +declare module 'react-syntax-highlighter/dist/styles/hljs/dark' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/hljs/darkula' { +declare module 'react-syntax-highlighter/dist/styles/hljs/darkula' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/hljs/default-style' { +declare module 'react-syntax-highlighter/dist/styles/hljs/default-style' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/hljs/docco' { +declare module 'react-syntax-highlighter/dist/styles/hljs/docco' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/hljs/dracula' { +declare module 'react-syntax-highlighter/dist/styles/hljs/dracula' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/hljs/far' { +declare module 'react-syntax-highlighter/dist/styles/hljs/far' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/hljs/foundation' { +declare module 'react-syntax-highlighter/dist/styles/hljs/foundation' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/hljs/github-gist' { +declare module 'react-syntax-highlighter/dist/styles/hljs/github-gist' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/hljs/github' { +declare module 'react-syntax-highlighter/dist/styles/hljs/github' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/hljs/googlecode' { +declare module 'react-syntax-highlighter/dist/styles/hljs/googlecode' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/hljs/grayscale' { +declare module 'react-syntax-highlighter/dist/styles/hljs/grayscale' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/hljs/gruvbox-dark' { +declare module 'react-syntax-highlighter/dist/styles/hljs/gruvbox-dark' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/hljs/gruvbox-light' { +declare module 'react-syntax-highlighter/dist/styles/hljs/gruvbox-light' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/hljs/hopscotch' { +declare module 'react-syntax-highlighter/dist/styles/hljs/hopscotch' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/hljs/hybrid' { +declare module 'react-syntax-highlighter/dist/styles/hljs/hybrid' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/hljs/idea' { +declare module 'react-syntax-highlighter/dist/styles/hljs/idea' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/hljs/ir-black' { +declare module 'react-syntax-highlighter/dist/styles/hljs/ir-black' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/hljs/kimbie.dark' { +declare module 'react-syntax-highlighter/dist/styles/hljs/kimbie.dark' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/hljs/kimbie.light' { +declare module 'react-syntax-highlighter/dist/styles/hljs/kimbie.light' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/hljs/magula' { +declare module 'react-syntax-highlighter/dist/styles/hljs/magula' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/hljs/mono-blue' { +declare module 'react-syntax-highlighter/dist/styles/hljs/mono-blue' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/hljs/monokai-sublime' { +declare module 'react-syntax-highlighter/dist/styles/hljs/monokai-sublime' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/hljs/monokai' { +declare module 'react-syntax-highlighter/dist/styles/hljs/monokai' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/hljs/obsidian' { +declare module 'react-syntax-highlighter/dist/styles/hljs/obsidian' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/hljs/ocean' { +declare module 'react-syntax-highlighter/dist/styles/hljs/ocean' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/hljs/paraiso-dark' { +declare module 'react-syntax-highlighter/dist/styles/hljs/paraiso-dark' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/hljs/paraiso-light' { +declare module 'react-syntax-highlighter/dist/styles/hljs/paraiso-light' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/hljs/pojoaque' { +declare module 'react-syntax-highlighter/dist/styles/hljs/pojoaque' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/hljs/purebasic' { +declare module 'react-syntax-highlighter/dist/styles/hljs/purebasic' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/hljs/qtcreator_dark' { +declare module 'react-syntax-highlighter/dist/styles/hljs/qtcreator_dark' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/hljs/qtcreator_light' { +declare module 'react-syntax-highlighter/dist/styles/hljs/qtcreator_light' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/hljs/railscasts' { +declare module 'react-syntax-highlighter/dist/styles/hljs/railscasts' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/hljs/rainbow' { +declare module 'react-syntax-highlighter/dist/styles/hljs/rainbow' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/hljs/routeros' { +declare module 'react-syntax-highlighter/dist/styles/hljs/routeros' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/hljs/school-book' { +declare module 'react-syntax-highlighter/dist/styles/hljs/school-book' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/hljs/solarized-dark' { +declare module 'react-syntax-highlighter/dist/styles/hljs/solarized-dark' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/hljs/solarized-light' { +declare module 'react-syntax-highlighter/dist/styles/hljs/solarized-light' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/hljs/sunburst' { +declare module 'react-syntax-highlighter/dist/styles/hljs/sunburst' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/hljs/tomorrow-night-blue' { +declare module 'react-syntax-highlighter/dist/styles/hljs/tomorrow-night-blue' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/hljs/tomorrow-night-bright' { +declare module 'react-syntax-highlighter/dist/styles/hljs/tomorrow-night-bright' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/hljs/tomorrow-night-eighties' { +declare module 'react-syntax-highlighter/dist/styles/hljs/tomorrow-night-eighties' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/hljs/tomorrow-night' { +declare module 'react-syntax-highlighter/dist/styles/hljs/tomorrow-night' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/hljs/tomorrow' { +declare module 'react-syntax-highlighter/dist/styles/hljs/tomorrow' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/hljs/vs' { +declare module 'react-syntax-highlighter/dist/styles/hljs/vs' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/hljs/vs2015' { +declare module 'react-syntax-highlighter/dist/styles/hljs/vs2015' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/hljs/xcode' { +declare module 'react-syntax-highlighter/dist/styles/hljs/xcode' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/hljs/xt256' { +declare module 'react-syntax-highlighter/dist/styles/hljs/xt256' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/hljs/zenburn' { +declare module 'react-syntax-highlighter/dist/styles/hljs/zenburn' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/prism' { - export { default as atomDark } from 'react-syntax-highlighter/styles/prism/atom-dark'; - export { default as base16AteliersulphurpoolLight } from 'react-syntax-highlighter/styles/prism/base16-ateliersulphurpool.light'; - export { default as cb } from 'react-syntax-highlighter/styles/prism/cb'; - export { default as coy } from 'react-syntax-highlighter/styles/prism/coy'; - export { default as darcula } from 'react-syntax-highlighter/styles/prism/darcula'; - export { default as dark } from 'react-syntax-highlighter/styles/prism/dark'; - export { default as duotoneDark } from 'react-syntax-highlighter/styles/prism/duotone-dark'; - export { default as duotoneEarth } from 'react-syntax-highlighter/styles/prism/duotone-earth'; - export { default as duotoneForest } from 'react-syntax-highlighter/styles/prism/duotone-forest'; - export { default as duotoneLight } from 'react-syntax-highlighter/styles/prism/duotone-light'; - export { default as duotoneSea } from 'react-syntax-highlighter/styles/prism/duotone-sea'; - export { default as duotoneSpace } from 'react-syntax-highlighter/styles/prism/duotone-space'; - export { default as funky } from 'react-syntax-highlighter/styles/prism/funky'; - export { default as ghcolors } from 'react-syntax-highlighter/styles/prism/ghcolors'; - export { default as hopscotch } from 'react-syntax-highlighter/styles/prism/hopscotch'; - export { default as okaidia } from 'react-syntax-highlighter/styles/prism/okaidia'; - export { default as pojoaque } from 'react-syntax-highlighter/styles/prism/pojoaque'; - export { default as prism } from 'react-syntax-highlighter/styles/prism/prism'; - export { default as solarizedlight } from 'react-syntax-highlighter/styles/prism/solarizedlight'; - export { default as tomorrow } from 'react-syntax-highlighter/styles/prism/tomorrow'; - export { default as twilight } from 'react-syntax-highlighter/styles/prism/twilight'; - export { default as vs } from 'react-syntax-highlighter/styles/prism/vs'; - export { default as xonokai } from 'react-syntax-highlighter/styles/prism/xonokai'; +declare module 'react-syntax-highlighter/dist/styles/prism' { + export { default as atomDark } from 'react-syntax-highlighter/dist/styles/prism/atom-dark'; + export { default as base16AteliersulphurpoolLight } from 'react-syntax-highlighter/dist/styles/prism/base16-ateliersulphurpool.light'; + export { default as cb } from 'react-syntax-highlighter/dist/styles/prism/cb'; + export { default as coy } from 'react-syntax-highlighter/dist/styles/prism/coy'; + export { default as darcula } from 'react-syntax-highlighter/dist/styles/prism/darcula'; + export { default as dark } from 'react-syntax-highlighter/dist/styles/prism/dark'; + export { default as duotoneDark } from 'react-syntax-highlighter/dist/styles/prism/duotone-dark'; + export { default as duotoneEarth } from 'react-syntax-highlighter/dist/styles/prism/duotone-earth'; + export { default as duotoneForest } from 'react-syntax-highlighter/dist/styles/prism/duotone-forest'; + export { default as duotoneLight } from 'react-syntax-highlighter/dist/styles/prism/duotone-light'; + export { default as duotoneSea } from 'react-syntax-highlighter/dist/styles/prism/duotone-sea'; + export { default as duotoneSpace } from 'react-syntax-highlighter/dist/styles/prism/duotone-space'; + export { default as funky } from 'react-syntax-highlighter/dist/styles/prism/funky'; + export { default as ghcolors } from 'react-syntax-highlighter/dist/styles/prism/ghcolors'; + export { default as hopscotch } from 'react-syntax-highlighter/dist/styles/prism/hopscotch'; + export { default as okaidia } from 'react-syntax-highlighter/dist/styles/prism/okaidia'; + export { default as pojoaque } from 'react-syntax-highlighter/dist/styles/prism/pojoaque'; + export { default as prism } from 'react-syntax-highlighter/dist/styles/prism/prism'; + export { default as solarizedlight } from 'react-syntax-highlighter/dist/styles/prism/solarizedlight'; + export { default as tomorrow } from 'react-syntax-highlighter/dist/styles/prism/tomorrow'; + export { default as twilight } from 'react-syntax-highlighter/dist/styles/prism/twilight'; + export { default as vs } from 'react-syntax-highlighter/dist/styles/prism/vs'; + export { default as xonokai } from 'react-syntax-highlighter/dist/styles/prism/xonokai'; } -declare module 'react-syntax-highlighter/styles/prism/atom-dark' { +declare module 'react-syntax-highlighter/dist/styles/prism/atom-dark' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/prism/base16-ateliersulphurpool.light' { +declare module 'react-syntax-highlighter/dist/styles/prism/base16-ateliersulphurpool.light' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/prism/cb' { +declare module 'react-syntax-highlighter/dist/styles/prism/cb' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/prism/coy' { +declare module 'react-syntax-highlighter/dist/styles/prism/coy' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/prism/darcula' { +declare module 'react-syntax-highlighter/dist/styles/prism/darcula' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/prism/dark' { +declare module 'react-syntax-highlighter/dist/styles/prism/dark' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/prism/duotone-dark' { +declare module 'react-syntax-highlighter/dist/styles/prism/duotone-dark' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/prism/duotone-earth' { +declare module 'react-syntax-highlighter/dist/styles/prism/duotone-earth' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/prism/duotone-forest' { +declare module 'react-syntax-highlighter/dist/styles/prism/duotone-forest' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/prism/duotone-light' { +declare module 'react-syntax-highlighter/dist/styles/prism/duotone-light' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/prism/duotone-sea' { +declare module 'react-syntax-highlighter/dist/styles/prism/duotone-sea' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/prism/duotone-space' { +declare module 'react-syntax-highlighter/dist/styles/prism/duotone-space' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/prism/funky' { +declare module 'react-syntax-highlighter/dist/styles/prism/funky' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/prism/ghcolors' { +declare module 'react-syntax-highlighter/dist/styles/prism/ghcolors' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/prism/hopscotch' { +declare module 'react-syntax-highlighter/dist/styles/prism/hopscotch' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/prism/okaidia' { +declare module 'react-syntax-highlighter/dist/styles/prism/okaidia' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/prism/pojoaque' { +declare module 'react-syntax-highlighter/dist/styles/prism/pojoaque' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/prism/prism' { +declare module 'react-syntax-highlighter/dist/styles/prism/prism' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/prism/solarizedlight' { +declare module 'react-syntax-highlighter/dist/styles/prism/solarizedlight' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/prism/tomorrow' { +declare module 'react-syntax-highlighter/dist/styles/prism/tomorrow' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/prism/twilight' { +declare module 'react-syntax-highlighter/dist/styles/prism/twilight' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/prism/vs' { +declare module 'react-syntax-highlighter/dist/styles/prism/vs' { const style: any; export default style; } -declare module 'react-syntax-highlighter/styles/prism/xonokai' { +declare module 'react-syntax-highlighter/dist/styles/prism/xonokai' { const style: any; export default style; } diff --git a/types/react-syntax-highlighter/react-syntax-highlighter-tests.tsx b/types/react-syntax-highlighter/react-syntax-highlighter-tests.tsx index c516d9f610..36a55aedc1 100644 --- a/types/react-syntax-highlighter/react-syntax-highlighter-tests.tsx +++ b/types/react-syntax-highlighter/react-syntax-highlighter-tests.tsx @@ -3,8 +3,8 @@ import SyntaxHighlighter from "react-syntax-highlighter"; import PrismSyntaxHighlighter from "react-syntax-highlighter/prism"; import PrismLightHighlighter, { registerLanguage } from "react-syntax-highlighter/prism-light"; import jsx from 'react-syntax-highlighter/languages/prism/jsx'; -import { docco } from "react-syntax-highlighter/styles/hljs"; -import { atomDark } from "react-syntax-highlighter/styles/prism"; +import { docco } from "react-syntax-highlighter/dist/styles/hljs"; +import { atomDark } from "react-syntax-highlighter/dist/styles/prism"; function hljsHighlighter(): JSX.Element { const codeString: string = `class CPP { diff --git a/types/react-syntax-highlighter/tslint.json b/types/react-syntax-highlighter/tslint.json index a41bf5d19a..4cfa77fc40 100644 --- a/types/react-syntax-highlighter/tslint.json +++ b/types/react-syntax-highlighter/tslint.json @@ -7,7 +7,7 @@ "ban-types": false, "callable-types": false, "comment-format": false, - "dt-header": false, + "dt-header": true, "eofline": false, "export-just-namespace": false, "import-spacing": false, diff --git a/types/react-table/index.d.ts b/types/react-table/index.d.ts index d6b1679edd..42d09c4338 100644 --- a/types/react-table/index.d.ts +++ b/types/react-table/index.d.ts @@ -1,6 +1,10 @@ // Type definitions for react-table 6.7 // Project: https://github.com/react-tools/react-table -// Definitions by: Roy Xue , Pavel Sakalo , Krzysztof Porębski , Andy S +// Definitions by: Roy Xue , +// Pavel Sakalo , +// Krzysztof Porębski , +// Andy S , +// Grzegorz Rozdzialik // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 import * as React from 'react'; @@ -19,7 +23,7 @@ export type ComponentPropsGetterC = (finalState: any, rowInfo?: undefined, colum export type ComponentPropsGetterRC = (finalState: any, rowInfo?: RowInfo, column?: Column, instance?: any) => object | undefined; export type DefaultFilterFunction = (filter: Filter, row: any, column: any) => boolean; -export type FilterFunction = (filter: Filter, rows: any[], column: any) => boolean; +export type FilterFunction = (filter: Filter, rows: any[], column: any) => any[]; export type SubComponentFunction = (rowInfo: RowInfo) => React.ReactNode; export type PageChangeFunction = (page: number) => void; export type PageSizeChangeFunction = (newPageSize: number, newPage: number) => void; @@ -46,7 +50,7 @@ export interface SortingRule { desc?: true; } -export interface TableProps extends +export interface TableProps extends Partial, Partial, Partial, @@ -56,6 +60,8 @@ export interface TableProps extends /** Default: [] */ data: D[]; + resolveData?: (data: D[]) => ResolvedData[]; + /** Default: false */ loading: boolean; @@ -164,7 +170,7 @@ export interface TableProps extends column: Partial; /** Array of all Available Columns */ - columns?: Array>; + columns?: Array>; /** Expander defaults. */ expanderDefaults: Partial; @@ -180,9 +186,9 @@ export interface TableProps extends /** Control callback for functional rendering */ children: ( - state: FinalState, + state: FinalState, makeTable: () => React.ReactElement, - instance: Instance + instance: Instance ) => React.ReactNode; } diff --git a/types/react-table/lib/hoc/selectTable.d.ts b/types/react-table/lib/hoc/selectTable.d.ts index d70d84eb78..d1fc5d8392 100644 --- a/types/react-table/lib/hoc/selectTable.d.ts +++ b/types/react-table/lib/hoc/selectTable.d.ts @@ -1,4 +1,4 @@ -import { ComponentType } from 'react'; +import { ComponentType, ComponentClass } from 'react'; import { TableProps } from '../../index'; @@ -12,7 +12,7 @@ export interface SelectInputComponentProps { row: any; } -export interface SelectAllInputComponent { +export interface SelectAllInputComponentProps { selectType: SelectType; checked: boolean; onClick: () => any; @@ -28,7 +28,7 @@ export interface SelectTableAdditionalProps { selectAll?: boolean; - toggleAll?: SelectAllInputComponent['onClick']; + toggleAll?: SelectAllInputComponentProps['onClick']; toggleSelection?: SelectInputComponentProps['onClick']; @@ -38,7 +38,7 @@ export interface SelectTableAdditionalProps { selectType?: SelectType; SelectInputComponent?: ComponentType; - SelectAllInputComponent?: ComponentType; + SelectAllInputComponent?: ComponentType; } export interface SelectTableHOCOptions { @@ -49,8 +49,8 @@ export interface SelectTableHOCOptions { } declare function selectTableHOC>( - Component: ComponentType, + WrappedComponent: ComponentType, options?: SelectTableHOCOptions -): ComponentType; +): ComponentClass; export default selectTableHOC; diff --git a/types/react-table/lib/hoc/treeTable.d.ts b/types/react-table/lib/hoc/treeTable.d.ts index 35d1522119..e696ceda02 100644 --- a/types/react-table/lib/hoc/treeTable.d.ts +++ b/types/react-table/lib/hoc/treeTable.d.ts @@ -1,9 +1,9 @@ -import { ComponentType } from 'react'; +import { ComponentType, ComponentClass } from 'react'; import { TableProps } from '../../index'; declare function treeTableHOC>( - Component: ComponentType -): ComponentType; + WrappedComponent: ComponentType +): ComponentClass; export default treeTableHOC; diff --git a/types/react-table/test/select-table-tests.tsx b/types/react-table/test/select-table-tests.tsx index 1a1b231292..fe4ee5c694 100644 --- a/types/react-table/test/select-table-tests.tsx +++ b/types/react-table/test/select-table-tests.tsx @@ -3,18 +3,41 @@ import * as ReactDOM from 'react-dom'; import ReactTable, { Column } from 'react-table'; import selectTableHOC, { - SelectTableAdditionalProps + SelectTableAdditionalProps, + SelectInputComponentProps, + SelectAllInputComponentProps } from 'react-table/lib/hoc/selectTable'; const SelectTable = selectTableHOC(ReactTable); +const SelectInput: React.StatelessComponent = ({ + onClick, + id, + checked, + row +}) => ( + onClick(id, e.shiftKey, row)} + checked={checked} + /> +); + +const SelectAllInput: React.StatelessComponent< + SelectAllInputComponentProps +> = ({ onClick, checked }) => ( + +); + const selectTableAdditionalProps: SelectTableAdditionalProps = { isSelected: () => true, keyField: 'id', selectAll: true, selectType: 'checkbox', toggleAll: () => null, - toggleSelection: () => null + toggleSelection: () => null, + SelectInputComponent: SelectInput, + SelectAllInputComponent: SelectAllInput }; const data = [{ id: 1, name: 'Foo' }, { id: 2, name: 'Bar' }]; @@ -29,6 +52,7 @@ ReactDOM.render( {...selectTableAdditionalProps} data={data} columns={columns} + ref={React.createRef()} />, document.getElementById('root') ); diff --git a/types/react-table/test/tree-table-tests.tsx b/types/react-table/test/tree-table-tests.tsx index a099124c61..6bb9461f78 100644 --- a/types/react-table/test/tree-table-tests.tsx +++ b/types/react-table/test/tree-table-tests.tsx @@ -4,7 +4,7 @@ import * as ReactDOM from 'react-dom'; import ReactTable, { Column } from 'react-table'; import treeTableHOC from 'react-table/lib/hoc/treeTable'; -const SelectTable = treeTableHOC(ReactTable); +const TreeTable = treeTableHOC(ReactTable); const data = [{ id: 1, name: 'Foo' }, { id: 2, name: 'Bar' }]; @@ -14,6 +14,6 @@ const columns: Column[] = [ ]; ReactDOM.render( - , + , document.getElementById('root') ); diff --git a/types/react/global.d.ts b/types/react/global.d.ts index 0c7a24070a..2ea2b7ca91 100644 --- a/types/react/global.d.ts +++ b/types/react/global.d.ts @@ -34,6 +34,7 @@ interface HTMLBodyElement extends HTMLElement { } interface HTMLBRElement extends HTMLElement { } interface HTMLButtonElement extends HTMLElement { } interface HTMLCanvasElement extends HTMLElement { } +interface HTMLDataListElement extends HTMLElement { } interface HTMLDialogElement extends HTMLElement { } interface HTMLDivElement extends HTMLElement { } interface HTMLDListElement extends HTMLElement { } @@ -43,8 +44,6 @@ interface HTMLFormElement extends HTMLElement { } interface HTMLHeadingElement extends HTMLElement { } interface HTMLHeadElement extends HTMLElement { } interface HTMLHRElement extends HTMLElement { } -interface HTMLTableColElement extends HTMLElement { } -interface HTMLDataListElement extends HTMLElement { } interface HTMLHtmlElement extends HTMLElement { } interface HTMLIFrameElement extends HTMLElement { } interface HTMLImageElement extends HTMLElement { } @@ -71,53 +70,13 @@ interface HTMLSourceElement extends HTMLElement { } interface HTMLSpanElement extends HTMLElement { } interface HTMLStyleElement extends HTMLElement { } interface HTMLTableElement extends HTMLElement { } -interface HTMLTableSectionElement extends HTMLElement { } -interface HTMLTableDataCellElement extends HTMLElement { } -interface HTMLTextAreaElement extends HTMLElement { } -interface HTMLTableSectionElement extends HTMLElement { } -interface HTMLTableHeaderCellElement extends HTMLElement { } -interface HTMLTableSectionElement extends HTMLElement { } -interface HTMLTitleElement extends HTMLElement { } -interface HTMLTableRowElement extends HTMLElement { } -interface HTMLTrackElement extends HTMLElement { } -interface HTMLUListElement extends HTMLElement { } -interface HTMLVideoElement extends HTMLElement { } interface HTMLTableColElement extends HTMLElement { } -interface HTMLDataListElement extends HTMLElement { } -interface HTMLHtmlElement extends HTMLElement { } -interface HTMLIFrameElement extends HTMLElement { } -interface HTMLImageElement extends HTMLElement { } -interface HTMLInputElement extends HTMLElement { } -interface HTMLModElement extends HTMLElement { } -interface HTMLLabelElement extends HTMLElement { } -interface HTMLLegendElement extends HTMLElement { } -interface HTMLLIElement extends HTMLElement { } -interface HTMLLinkElement extends HTMLElement { } -interface HTMLMapElement extends HTMLElement { } -interface HTMLMetaElement extends HTMLElement { } -interface HTMLObjectElement extends HTMLElement { } -interface HTMLOListElement extends HTMLElement { } -interface HTMLOptGroupElement extends HTMLElement { } -interface HTMLOptionElement extends HTMLElement { } -interface HTMLParagraphElement extends HTMLElement { } -interface HTMLParamElement extends HTMLElement { } -interface HTMLPreElement extends HTMLElement { } -interface HTMLProgressElement extends HTMLElement { } -interface HTMLQuoteElement extends HTMLElement { } -interface HTMLScriptElement extends HTMLElement { } -interface HTMLSelectElement extends HTMLElement { } -interface HTMLSourceElement extends HTMLElement { } -interface HTMLSpanElement extends HTMLElement { } -interface HTMLStyleElement extends HTMLElement { } -interface HTMLTableElement extends HTMLElement { } -interface HTMLTableSectionElement extends HTMLElement { } interface HTMLTableDataCellElement extends HTMLElement { } -interface HTMLTextAreaElement extends HTMLElement { } -interface HTMLTableSectionElement extends HTMLElement { } interface HTMLTableHeaderCellElement extends HTMLElement { } -interface HTMLTableSectionElement extends HTMLElement { } -interface HTMLTitleElement extends HTMLElement { } interface HTMLTableRowElement extends HTMLElement { } +interface HTMLTableSectionElement extends HTMLElement { } +interface HTMLTextAreaElement extends HTMLElement { } +interface HTMLTitleElement extends HTMLElement { } interface HTMLTrackElement extends HTMLElement { } interface HTMLUListElement extends HTMLElement { } interface HTMLVideoElement extends HTMLElement { } diff --git a/types/react/index.d.ts b/types/react/index.d.ts index f525d7838c..730268f974 100644 --- a/types/react/index.d.ts +++ b/types/react/index.d.ts @@ -298,7 +298,7 @@ declare namespace React { } interface ProviderExoticComponent

    extends ExoticComponent

    { - propTypes?: ValidationMap

    ; + propTypes?: WeakValidationMap

    ; } type ContextType> = C extends Context ? T : never; @@ -322,23 +322,25 @@ declare namespace React { const Children: ReactChildren; const Fragment: ExoticComponent<{ children?: ReactNode }>; const StrictMode: ExoticComponent<{ children?: ReactNode }>; - /** - * This feature is not yet available for server-side rendering. - * Suspense support will be added in a later release. - */ - const Suspense: ExoticComponent<{ - children?: ReactNode + + interface SuspenseProps { + children?: ReactNode; /** A fallback react tree to show when a Suspense child (like React.lazy) suspends */ - fallback: NonNullable|null + fallback: NonNullable|null; // I tried looking at the code but I have no idea what it does. // https://github.com/facebook/react/issues/13206#issuecomment-432489986 /** * Not implemented yet, requires unstable_ConcurrentMode */ - // maxDuration?: number - }>; + // maxDuration?: number; + } + /** + * This feature is not yet available for server-side rendering. + * Suspense support will be added in a later release. + */ + const Suspense: ExoticComponent; const version: string; // @@ -459,7 +461,7 @@ declare namespace React { interface FunctionComponent

    { (props: P & { children?: ReactNode }, context?: any): ReactElement | null; - propTypes?: ValidationMap

    ; + propTypes?: WeakValidationMap

    ; contextTypes?: ValidationMap; defaultProps?: Partial

    ; displayName?: string; @@ -467,7 +469,7 @@ declare namespace React { interface RefForwardingComponent { (props: P & { children?: ReactNode }, ref: Ref | null): ReactElement | null; - propTypes?: ValidationMap

    ; + propTypes?: WeakValidationMap

    ; contextTypes?: ValidationMap; defaultProps?: Partial

    ; displayName?: string; @@ -475,7 +477,7 @@ declare namespace React { interface ComponentClass

    extends StaticLifecycle { new (props: P, context?: any): Component; - propTypes?: ValidationMap

    ; + propTypes?: WeakValidationMap

    ; contextType?: Context; contextTypes?: ValidationMap; childContextTypes?: ValidationMap; @@ -834,17 +836,6 @@ declare namespace React { */ // TODO (TypeScript 3.0): function useRef(initialValue: T|null): RefObject; - /** - * The signature is identical to `useEffect`, but it fires synchronously during the same phase that - * React performs its DOM mutations, before sibling components have been updated. Use this to perform - * custom DOM mutations. - * - * Prefer the standard `useEffect` when possible to avoid blocking visual updates. - * - * @version experimental - * @see https://reactjs.org/docs/hooks-reference.html#usemutationeffect - */ - function useMutationEffect(effect: EffectCallback, inputs?: InputIdentityList): void; /** * The signature is identical to `useEffect`, but it fires synchronously after all DOM mutations. * Use this to read layout from the DOM and synchronously re-render. Updates scheduled inside @@ -1022,6 +1013,8 @@ declare namespace React { */ getModifierState(key: string): boolean; metaKey: boolean; + movementX: number; + movementY: number; nativeEvent: NativeMouseEvent; pageX: number; pageY: number; @@ -1160,6 +1153,8 @@ declare namespace React { // Form Events onChange?: FormEventHandler; onChangeCapture?: FormEventHandler; + onBeforeInput?: FormEventHandler; + onBeforeInputCapture?: FormEventHandler; onInput?: FormEventHandler; onInputCapture?: FormEventHandler; onReset?: FormEventHandler; @@ -2567,6 +2562,14 @@ declare namespace React { type ValidationMap = PropTypes.ValidationMap; + type WeakValidationMap = { + [K in keyof T]?: null extends T[K] + ? Validator + : undefined extends T[K] + ? Validator + : Validator + }; + interface ReactPropTypes { any: typeof PropTypes.any; array: typeof PropTypes.array; diff --git a/types/react/test/hooks.tsx b/types/react/test/hooks.tsx index c3495dd717..5239d3b522 100644 --- a/types/react/test/hooks.tsx +++ b/types/react/test/hooks.tsx @@ -95,11 +95,9 @@ function useEveryHook(ref: React.Ref<{ id: number }>|undefined): () => boolean { // $ExpectError React.useImperativeMethods(ref, () => ({}), [id]); - React.useMutationEffect(() => { + React.useLayoutEffect(() => { setState(1); setState(prevState => prevState - 1); - }, []); - React.useLayoutEffect(() => { didLayout.current = true; }, []); React.useEffect(() => { diff --git a/types/react/test/tsx.tsx b/types/react/test/tsx.tsx index 60fcb6dccc..9309799de7 100644 --- a/types/react/test/tsx.tsx +++ b/types/react/test/tsx.tsx @@ -345,3 +345,28 @@ declare global { } const CustomElement2: React.ReactType = 'my-declared-element'; + +interface TestPropTypesProps { + foo: string; +} +interface TestPropTypesProps1 { + foo?: string; +} +interface TestPropTypesProps2 { + foo: string | null; +} +interface TestPropTypesProps3 { + foo?: string | null; +} +const testPropTypes = { + foo: PropTypes.string +}; +type DeclaredPropTypes

    = Required['propTypes'], undefined>>; +// $ExpectType false +type propTypesTest = typeof testPropTypes extends DeclaredPropTypes ? true : false; +// $ExpectType true +type propTypesTest1 = typeof testPropTypes extends DeclaredPropTypes ? true : false; +// $ExpectType true +type propTypesTest2 = typeof testPropTypes extends DeclaredPropTypes ? true : false; +// $ExpectType true +type propTypesTest3 = typeof testPropTypes extends DeclaredPropTypes ? true : false; diff --git a/types/recharts/index.d.ts b/types/recharts/index.d.ts index 34e3cbcb88..78da1ec8f5 100644 --- a/types/recharts/index.d.ts +++ b/types/recharts/index.d.ts @@ -11,6 +11,7 @@ // Paul Melnikow // Harry Cruse // Andrew Palugniok +// Robert Stigsson // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -45,6 +46,7 @@ export type StackOffsetType = 'sign' | 'expand' | 'none' | 'wiggle' | 'silhouett export type LineType = 'basis' | 'basisClosed' | 'basisOpen' | 'linear' | 'linearClosed' | 'natural' | 'monotoneX' | 'monotoneY' | 'monotone' | 'step' | 'stepBefore' | 'stepAfter' | CurveFactory; +export type IfOverflowType = 'hidden' | 'visible' | 'discard' | 'extendDomain'; export type AxisInterval = number | 'preserveStart' | 'preserveEnd' | 'preserveStartEnd'; export type PickedCSSStyleDeclarationKeys = @@ -363,6 +365,7 @@ export interface LegendPayload { value: any; id: any; type: LegendType; + color?: string; } export type BBoxUpdateCallback = (box: { width: number; height: number; }) => void; @@ -447,6 +450,7 @@ export interface PieProps extends EventAttributes, Partial | ContentRenderer | boolean; activeShape?: object | ContentRenderer | React.ReactElement; activeIndex?: number | number[]; + blendStroke?: boolean; } export class Pie extends React.Component { } @@ -634,6 +638,7 @@ export interface ReferenceAreaProps extends Partial { yAxis?: object; isFront?: boolean; alwaysShow?: boolean; + ifOverflow?: IfOverflowType; x1?: number | string; x2?: number | string; y1?: number | string; @@ -657,6 +662,7 @@ export interface ReferenceDotProps extends EventAttributes, Partial | React.ReactElement; diff --git a/types/rechoir/index.d.ts b/types/rechoir/index.d.ts new file mode 100644 index 0000000000..2cb3bbb7ab --- /dev/null +++ b/types/rechoir/index.d.ts @@ -0,0 +1,18 @@ +// Type definitions for rechoir 0.6 +// Project: https://github.com/tkellen/node-rechoir +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import { Extensions } from 'interpret'; + +export function prepare( + config: Extensions, + filepath: string, + requireFrom?: string +): true | Attempt[]; + +export interface Attempt { + moduleName: string; + module: any; + error: Error | null; +} diff --git a/types/rechoir/rechoir-tests.ts b/types/rechoir/rechoir-tests.ts new file mode 100644 index 0000000000..de4b18c74f --- /dev/null +++ b/types/rechoir/rechoir-tests.ts @@ -0,0 +1,6 @@ +import { extensions as config } from 'interpret'; +import { prepare } from 'rechoir'; + +// $ExpectType true | Attempt[] +prepare(config, './test/fixtures/test.coffee'); +prepare(config, './test/fixtures/test.coffee', './'); diff --git a/types/rechoir/tsconfig.json b/types/rechoir/tsconfig.json new file mode 100644 index 0000000000..03a006d997 --- /dev/null +++ b/types/rechoir/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "rechoir-tests.ts" + ] +} diff --git a/types/rechoir/tslint.json b/types/rechoir/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/rechoir/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/recompose/index.d.ts b/types/recompose/index.d.ts index e44ca48706..fc9ec4f15f 100644 --- a/types/recompose/index.d.ts +++ b/types/recompose/index.d.ts @@ -152,7 +152,7 @@ declare module 'recompose' { [updaterName: string]: StateHandler; }; type StateUpdaters = { - [updaterName in keyof TUpdaters]: (state: TState, props: TOutter) => StateHandler; + [updaterName in keyof TUpdaters]: (state: TState, props: TOutter) => TUpdaters[updaterName]; }; export function withStateHandlers, TOutter = {}>( createProps: TState | mapper, @@ -273,10 +273,10 @@ declare module 'recompose' { // fromRenderProps: https://github.com/acdlite/recompose/blob/master/docs/API.md#fromrenderprops export function fromRenderProps( - RenderPropsComponent: StatelessComponent, - propsMapper: (props: TRenderProps) => Partial, + RenderPropsComponent: Component, + propsMapper: (props: TRenderProps) => TInner, renderPropName?: string - ): ComponentEnhancer; + ): ComponentEnhancer; // Static property helpers: https://github.com/acdlite/recompose/blob/master/docs/API.md#static-property-helpers diff --git a/types/recompose/recompose-tests.tsx b/types/recompose/recompose-tests.tsx index a0ba38a87a..53cf796fd6 100644 --- a/types/recompose/recompose-tests.tsx +++ b/types/recompose/recompose-tests.tsx @@ -521,18 +521,30 @@ function testFromRenderProps() { interface InnerProps { renderValue: string; - outterValue: number; } interface OutterProps { outterValue: number; } - const RenderPropComponent: React.StatelessComponent<{ - render: (renderProps: RenderProps) => React.ReactElement; - }> = ({ render }) => render({ value: 'test' }); + interface ComponentProps { + renderValue: string; + outterValue: number; + } - const component: React.StatelessComponent = ({ renderValue }) =>

    {renderValue}
    ; + interface RenderComponentProps { + render: (renderProps: RenderProps) => React.ReactElement; + } + + class RenderPropComponent extends React.Component { + render () { + return this.props.render({ value: 'test' }); + } + } + + const component: React.StatelessComponent = ({ outterValue, renderValue }) => ( +
    {outterValue}{renderValue}
    + ); const Enhanced = fromRenderProps( RenderPropComponent, diff --git a/types/redux-action/index.d.ts b/types/redux-action/index.d.ts index dc5b9e5229..51c3cc3b61 100644 --- a/types/redux-action/index.d.ts +++ b/types/redux-action/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/coderhaoxin/redux-action // Definitions by: newraina // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /** * inspired by @types/redux-actions, thanks. diff --git a/types/redux-action/package.json b/types/redux-action/package.json index 0a14f5edc6..7cc600c266 100644 --- a/types/redux-action/package.json +++ b/types/redux-action/package.json @@ -1,7 +1,6 @@ { "private": true, "dependencies": { - "redux": "^3.6.0", - "redux-thunk": "^2.2.0" + "redux": "^4.0.1" } } diff --git a/types/redux-action/redux-action-tests.ts b/types/redux-action/redux-action-tests.ts index 2290ed9a3f..d1b065c08f 100644 --- a/types/redux-action/redux-action-tests.ts +++ b/types/redux-action/redux-action-tests.ts @@ -1,5 +1,4 @@ import * as ReduxAction from 'redux-action'; -import * as ReduxThunk from 'redux-thunk'; import * as Redux from 'redux'; interface Payload { @@ -11,7 +10,7 @@ const dispatch: Redux.Dispatch = (...args: any[]): any => { }; const actionCreator0 = ReduxAction.createAction('get items'); -dispatch(actionCreator0(1)) +actionCreator0(1)(dispatch, () => { }) .then(action => { const type: string = action.type; const payload: Payload = action.payload; @@ -19,7 +18,7 @@ dispatch(actionCreator0(1)) const actionCreator1 = ReduxAction.createAction(); -dispatch(actionCreator1(1)) +actionCreator1(1)(dispatch, () => { }) .then(action => { const type: string = action.type; const payload: Payload = action.payload; @@ -27,7 +26,7 @@ dispatch(actionCreator1(1)) const actionCreator2 = ReduxAction.createAction('get items', (name: string) => name); -dispatch(actionCreator2(1)) +actionCreator2(1)(dispatch, () => { }) .then(action => { const type: string = action.type; const payload: string = action.payload; @@ -35,7 +34,7 @@ dispatch(actionCreator2(1)) const actionCreator3 = ReduxAction.createAction('get items', (name: string) => Promise.resolve(name)); -dispatch(actionCreator3(1)) +actionCreator3(1)(dispatch, () => { }) .then(action => { const type: string = action.type; const payload: string = action.payload; @@ -43,7 +42,7 @@ dispatch(actionCreator3(1)) const actionCreator4 = ReduxAction.createAction((name: string) => name); -dispatch(actionCreator4(1)) +actionCreator4(1)(dispatch, () => { }) .then(action => { const type: string = action.type; const payload: string = action.payload; @@ -51,7 +50,7 @@ dispatch(actionCreator4(1)) const actionCreator5 = ReduxAction.createAction((name: string) => 1); -dispatch(actionCreator5('items')) +actionCreator5('items')(dispatch, () => { }) .then(action => { const type: string = action.type; const payload: number = action.payload; @@ -59,7 +58,7 @@ dispatch(actionCreator5('items')) const actionCreator6 = ReduxAction.createAction((name: string) => 1); -dispatch(actionCreator6('items', false)) +actionCreator6('items', false)(dispatch, () => { }) .then(action => { const type: string = action.type; const payload: number = action.payload; @@ -80,4 +79,4 @@ const reducer = ReduxAction.createReducer({ name: 'name' }, { } }); -const combinedReducer: Redux.Reducer = Redux.combineReducers({ reducer }); +const combinedReducer: Redux.Reducer<{ reducer: State }> = Redux.combineReducers<{ reducer: State }>({ reducer }); diff --git a/types/redux-auth-wrapper/index.d.ts b/types/redux-auth-wrapper/index.d.ts index 728be4a54b..3ec88b50dc 100644 --- a/types/redux-auth-wrapper/index.d.ts +++ b/types/redux-auth-wrapper/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/mjrussell/redux-auth-wrapper // Definitions by: Karol Janyst // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.8 +// TypeScript Version: 3.0 import { ComponentClass, StatelessComponent, ComponentType, ReactType } from "react"; diff --git a/types/redux-devtools/index.d.ts b/types/redux-devtools/index.d.ts index 234fb9a4bb..ddead025ff 100644 --- a/types/redux-devtools/index.d.ts +++ b/types/redux-devtools/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/gaearon/redux-devtools // Definitions by: Petryshyn Sergii // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.8 +// TypeScript Version: 3.0 import * as React from 'react'; import { GenericStoreEnhancer } from 'redux'; diff --git a/types/redux-form/index.d.ts b/types/redux-form/index.d.ts index e80c196c0a..5851728369 100644 --- a/types/redux-form/index.d.ts +++ b/types/redux-form/index.d.ts @@ -12,7 +12,7 @@ // Maddi Joyce // Kamil Wojcik // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.9 +// TypeScript Version: 3.0 import { ComponentClass, StatelessComponent, diff --git a/types/redux-form/v6/index.d.ts b/types/redux-form/v6/index.d.ts index a8209a7643..5127457884 100644 --- a/types/redux-form/v6/index.d.ts +++ b/types/redux-form/v6/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/erikras/redux-form // Definitions by: Carson Full , Daniel Lytkin , Karol Janyst , Luka Zakrajsek // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.8 +// TypeScript Version: 3.0 import { ComponentClass, diff --git a/types/redux-saga-tester/index.d.ts b/types/redux-saga-tester/index.d.ts index fda97e494b..d7772626ef 100644 --- a/types/redux-saga-tester/index.d.ts +++ b/types/redux-saga-tester/index.d.ts @@ -1,27 +1,19 @@ // Type definitions for redux-saga-tester 1.0 // Project: https://github.com/wix/redux-saga-tester#readme -// Definitions by: Ben Lorantfy +// Definitions by: Ben Lorantfy , Law Smith // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.4 + +import { Task } from 'redux-saga'; +import { AnyAction, Middleware, Reducer, ReducersMapObject } from 'redux'; -export interface AnyAction { - type: string; - [key: string]: any; -} -export type Reducer = (state: object, action: AnyAction) => object; -export interface ReducerMap { - [key: string]: Reducer; -} -export type ReduxMiddleware = (options: { dispatch: (action: AnyAction) => void, getState: () => object }) - => (next: (action: AnyAction) => any) - => any; export type SagaFunction = (...args: any[]) => any; -export interface SagaTesterOptions { +export interface SagaTesterOptions { initialState?: StateType; - reducers?: ReducerMap|Reducer; - middlewares?: ReduxMiddleware[]; - combineReducers?: (map: ReducerMap) => Reducer; + reducers?: ReducersMapObject | Reducer; + middlewares?: Middleware[]; + combineReducers?: (map: ReducersMapObject) => Reducer; ignoreReduxActions?: boolean; options?: object; } @@ -32,7 +24,7 @@ export default class SagaTester { /** * Starts execution of the provided saga. */ - start(saga: SagaFunction): void; + start(saga: SagaFunction, ...args: any[]): Task; /** * Dispatches an action to the redux store. diff --git a/types/redux-saga-tester/package.json b/types/redux-saga-tester/package.json new file mode 100644 index 0000000000..8d41143894 --- /dev/null +++ b/types/redux-saga-tester/package.json @@ -0,0 +1,7 @@ +{ + "private": true, + "dependencies": { + "redux": "^3.7.2", + "redux-saga": "^0.15.3" + } +} diff --git a/types/redux-saga-tester/redux-saga-tester-tests.ts b/types/redux-saga-tester/redux-saga-tester-tests.ts index 0dba716533..48eb490d0a 100644 --- a/types/redux-saga-tester/redux-saga-tester-tests.ts +++ b/types/redux-saga-tester/redux-saga-tester-tests.ts @@ -2,62 +2,79 @@ import SagaTester from 'redux-saga-tester'; // constructor with all options new SagaTester({ - initialState: { - orders: [], - }, - reducers: { - orders: (state, action) => state, - }, - middlewares: [ - ({ dispatch, getState }) => (next) => (action: { type: string }) => { - dispatch({ type: 'BLA' }); - getState(); + initialState: { + orders: [], + }, + reducers: { + orders: (state, action) => state, + }, + middlewares: [ + ({dispatch, getState}) => (next) => (action) => { + dispatch({type: 'BLA'}); + getState(); - return next(action); + return next(action); + }, + ], + ignoreReduxActions: false, + options: { + a: 23, }, - ], - ignoreReduxActions: false, - options: { - a: 23, - }, }); // constructor with function as reducers new SagaTester({ - reducers: (state, action) => state, + reducers: (state = {}, action) => state, +}); + +// constructor with reducer map +new SagaTester({ + reducers: { + a: (state, action) => state, + b: (state, action) => state, + c: (state, action) => state, + } }); // constructor with no options interface MockStateType { - orders: Array<{ name: string }>; + orders: Array<{ name: string }>; } -const sagaTester = new SagaTester({ initialState: { orders: [] }}); + +const sagaTester = new SagaTester({initialState: {orders: []}}); // start function* fakeSaga() { - return 23; + return 23; +} + +function* fakeSagaWithParams(param1: string, param2: number) { + return param1.length > param2; } sagaTester.start(fakeSaga); +sagaTester.start(fakeSagaWithParams, 'foo', 3); // dispatch -sagaTester.dispatch({ type: 'LOAD_ORDERS', orders: [] }); +sagaTester.dispatch({type: 'LOAD_ORDERS', orders: []}); // updateState -sagaTester.updateState({ orders: [] }); +sagaTester.updateState({orders: []}); // getState sagaTester.getState().orders; // waitFor -sagaTester.waitFor('LOAD_ORDERS').then(() => {}); -sagaTester.waitFor('LOAD_ORDERS', true).then(() => {}); +sagaTester.waitFor('LOAD_ORDERS').then(() => { +}); +sagaTester.waitFor('LOAD_ORDERS', true).then(() => { +}); // wasCalled -sagaTester.wasCalled("LOAD_ORDERS"); +sagaTester.wasCalled('LOAD_ORDERS'); // numCalled -sagaTester.numCalled("LOAD_ORDERS") === 1; +sagaTester.numCalled('LOAD_ORDERS') === 1; // getLatestCalledAction sagaTester.getLatestCalledAction().type; @@ -68,3 +85,8 @@ sagaTester.getCalledActions()[0].type; // getCalledActions sagaTester.reset(); sagaTester.reset(true); + +// getState +const state = sagaTester.getState(); +state.orders.length; +state.orders[0].name; diff --git a/types/resolve-pkg/index.d.ts b/types/resolve-pkg/index.d.ts new file mode 100644 index 0000000000..06a706acbe --- /dev/null +++ b/types/resolve-pkg/index.d.ts @@ -0,0 +1,14 @@ +// Type definitions for resolve-pkg 1.0 +// Project: https://github.com/sindresorhus/resolve-pkg +// Definitions by: Meno Abels +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.9 + +interface ResolvePkgOptions { + cwd?: boolean; +} + +type ResolveFunction = (moduleId: string, options?: ResolvePkgOptions) => string; +declare const resolveFunction: ResolveFunction; + +export = resolveFunction; diff --git a/types/resolve-pkg/resolve-pkg-tests.ts b/types/resolve-pkg/resolve-pkg-tests.ts new file mode 100644 index 0000000000..caa949a11e --- /dev/null +++ b/types/resolve-pkg/resolve-pkg-tests.ts @@ -0,0 +1,5 @@ +import rpkg = require('resolve-pkg'); + +const test1 = rpkg('hello'); +const test2 = rpkg('hello', {}); +const test3 = rpkg('hello', { cwd: true }); diff --git a/types/resolve-pkg/tsconfig.json b/types/resolve-pkg/tsconfig.json new file mode 100644 index 0000000000..04c11fa02f --- /dev/null +++ b/types/resolve-pkg/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "resolve-pkg-tests.ts" + ] +} diff --git a/types/resolve-pkg/tslint.json b/types/resolve-pkg/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/resolve-pkg/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/rethinkdb/index.d.ts b/types/rethinkdb/index.d.ts index 87293230a9..d54856f08c 100644 --- a/types/rethinkdb/index.d.ts +++ b/types/rethinkdb/index.d.ts @@ -377,7 +377,7 @@ declare module "rethinkdb" { /** * Turn a sequence into an array or object, necessary when merging a sequence. - * + * * See: https://www.rethinkdb.com/api/javascript/coerce_to/ */ coerceTo(key: 'array'): Expression; @@ -539,6 +539,7 @@ declare module "rethinkdb" { le(value: T): Expression; add(n: number): Expression; + add(n: Expression): Expression; /** * Subtract two numbers. diff --git a/types/ripemd160/index.d.ts b/types/ripemd160/index.d.ts new file mode 100644 index 0000000000..27de423a18 --- /dev/null +++ b/types/ripemd160/index.d.ts @@ -0,0 +1,16 @@ +// Type definitions for ripemd160 2.0 +// Project: https://github.com/crypto-browserify/ripemd160#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import { Hash } from 'crypto'; + +export = RIPEMD160; + +declare const RIPEMD160: RIPEMD160Static; + +interface RIPEMD160Static { + new (): Hash; +} diff --git a/types/ripemd160/ripemd160-tests.ts b/types/ripemd160/ripemd160-tests.ts new file mode 100644 index 0000000000..3a78efbac3 --- /dev/null +++ b/types/ripemd160/ripemd160-tests.ts @@ -0,0 +1,7 @@ +import RIPEMD160 = require('ripemd160'); + +new RIPEMD160().update('42').digest('hex'); + +const ripemd160stream = new RIPEMD160(); +ripemd160stream.end('42'); +(ripemd160stream.read() as Buffer).toString('hex'); diff --git a/types/ripemd160/tsconfig.json b/types/ripemd160/tsconfig.json new file mode 100644 index 0000000000..07abc9bd05 --- /dev/null +++ b/types/ripemd160/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "ripemd160-tests.ts" + ] +} diff --git a/types/ripemd160/tslint.json b/types/ripemd160/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/ripemd160/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/roman-numerals/index.d.ts b/types/roman-numerals/index.d.ts new file mode 100644 index 0000000000..0ab8e88047 --- /dev/null +++ b/types/roman-numerals/index.d.ts @@ -0,0 +1,7 @@ +// Type definitions for roman-numerals 0.3 +// Project: https://github.com/joshleaves/roman-numerals +// Definitions by: Alan Plum +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export function toRoman(arabic: number): string; +export function toArabic(roman: string): number; diff --git a/types/roman-numerals/roman-numerals-tests.ts b/types/roman-numerals/roman-numerals-tests.ts new file mode 100644 index 0000000000..a99972afae --- /dev/null +++ b/types/roman-numerals/roman-numerals-tests.ts @@ -0,0 +1,5 @@ +import { toArabic, toRoman } from "roman-numerals"; + +const XLII: string = toRoman(42); +const meaningOfLife: number = toArabic(XLII); +toRoman(meaningOfLife); diff --git a/types/roman-numerals/tsconfig.json b/types/roman-numerals/tsconfig.json new file mode 100644 index 0000000000..7edc311353 --- /dev/null +++ b/types/roman-numerals/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "roman-numerals-tests.ts"] +} diff --git a/types/roman-numerals/tslint.json b/types/roman-numerals/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/roman-numerals/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/rosie/index.d.ts b/types/rosie/index.d.ts index 1078b53573..01dc76c5af 100644 --- a/types/rosie/index.d.ts +++ b/types/rosie/index.d.ts @@ -3,11 +3,13 @@ // Definitions by: Abner Oliveira , // Chris Grigg , // Alex Bukurov +// Adam Misiorny // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 declare namespace rosie { interface IFactoryStatic { + new(): IFactory; /** * Defines a factory by name and constructor function. Call #attr and #option * on the result to define the properties of this factory. @@ -163,7 +165,8 @@ declare namespace rosie { * @param {function(number): *=} builder * @return {Factory} */ - sequence(name: keyof T, dependenciesOrBuilder?: () => any | keyof T[], builder?: Function) : IFactory; + sequence(name: K, builder?: (i: number) => any): IFactory; + sequence(name: K, dependencies: D[], builder: (i: number, ...args: any[]) => any): IFactory; /** * Sets a post-processor callback that will receive built objects and the diff --git a/types/rosie/rosie-tests.ts b/types/rosie/rosie-tests.ts index 6c2152a9e7..bb6b9defb8 100644 --- a/types/rosie/rosie-tests.ts +++ b/types/rosie/rosie-tests.ts @@ -19,6 +19,7 @@ resultObj = Factory.build('some'); Factory.define('coach') .option('buildPlayer', false) .sequence('id') + .sequence('name', (i: number) => `Coach${i}`) .attr('players', ['id', 'buildPlayer'], function(id: any, buildPlayer: boolean) { if (buildPlayer) { return [Factory.build('player', {coach_id: id})]; @@ -69,6 +70,21 @@ const person = Factory.build('Person'); let aString = ''; aString = person.firstName; +// Unregistered factories +const unregisteredPersonFactory = new Factory(); + +unregisteredPersonFactory.attr('firstName', 'John').sequence('id'); + +// Sequence with dependencies +unregisteredPersonFactory.sequence('lastName', ['age'], (i: number, age: number) => `Doe ${i} ${age}`) + +// Unregistered extended factories + +const unregisteredExtendedPersonFactory = new Factory().extend(unregisteredPersonFactory) + +unregisteredExtendedPersonFactory.attr('firstName', 'John2') +unregisteredExtendedPersonFactory.sequence('lastName', ['age'], (i: number) => `Doe2 ${i}`) + class CustomClass { type: string; diff --git a/types/sammy/tslint.json b/types/sammy/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/sammy/tslint.json +++ b/types/sammy/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/sasl-anonymous/index.d.ts b/types/sasl-anonymous/index.d.ts new file mode 100644 index 0000000000..b438a411d7 --- /dev/null +++ b/types/sasl-anonymous/index.d.ts @@ -0,0 +1,29 @@ +// Type definitions for sasl-anonymous 0.1 +// Project: https://github.com/jaredhanson/js-sasl-anonymous +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import { Mechanism } from 'saslmechanisms'; + +export = AnonymousMechanism; + +declare class AnonymousMechanism implements Mechanism { + static Mechanism: typeof AnonymousMechanism; + static prototype: { + name: 'ANONYMOUS'; + clientFirst: true; + }; + + name: 'ANONYMOUS'; + clientFirst: true; + + response(cred: AnonymousMechanism.Credentials): string; + + challenge(chal: string): void; +} + +declare namespace AnonymousMechanism { + interface Credentials { + trace?: string; + } +} diff --git a/types/sasl-anonymous/sasl-anonymous-tests.ts b/types/sasl-anonymous/sasl-anonymous-tests.ts new file mode 100644 index 0000000000..dd993fa49d --- /dev/null +++ b/types/sasl-anonymous/sasl-anonymous-tests.ts @@ -0,0 +1,22 @@ +import AnonymousMechanism = require('sasl-anonymous'); +import { Mechanism } from 'sasl-anonymous'; +import { Factory } from 'saslmechanisms'; + +new Factory().use(AnonymousMechanism); +new Factory().use(Mechanism); + +// $ExpectType "ANONYMOUS" +AnonymousMechanism.prototype.name; +// $ExpectType true +AnonymousMechanism.prototype.clientFirst; + +const m = new AnonymousMechanism(); + +// $ExpectType "ANONYMOUS" +m.name; +// $ExpectType true +m.clientFirst; +// $ExpectType string +m.response({ trace: 't' }); +// $ExpectType void +m.challenge('challenge'); diff --git a/types/sasl-anonymous/tsconfig.json b/types/sasl-anonymous/tsconfig.json new file mode 100644 index 0000000000..5a9ebd2f35 --- /dev/null +++ b/types/sasl-anonymous/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "sasl-anonymous-tests.ts" + ] +} diff --git a/types/sasl-anonymous/tslint.json b/types/sasl-anonymous/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/sasl-anonymous/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/sasl-digest-md5/index.d.ts b/types/sasl-digest-md5/index.d.ts new file mode 100644 index 0000000000..001875f330 --- /dev/null +++ b/types/sasl-digest-md5/index.d.ts @@ -0,0 +1,41 @@ +// Type definitions for sasl-digest-md5 0.1 +// Project: https://github.com/jaredhanson/js-sasl-digest-md5 +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import { Mechanism } from 'saslmechanisms'; + +export = DigestMd5Mechanism; + +declare class DigestMd5Mechanism implements Mechanism { + static Mechanism: typeof DigestMd5Mechanism; + static prototype: { + name: 'DIGEST-MD5'; + clientFirst: false; + }; + + name: 'DIGEST-MD5'; + clientFirst: false; + + constructor(options?: DigestMd5Mechanism.Options); + + response(cred: DigestMd5Mechanism.Credentials): string; + + challenge(chal: string): this; +} + +declare namespace DigestMd5Mechanism { + interface Options { + genNonce?: () => number; + } + + interface Credentials { + serviceType: string; + host: string; + username: string; + password: string; + serviceName?: string; + realm?: string; + authzid?: string; + } +} diff --git a/types/sasl-digest-md5/sasl-digest-md5-tests.ts b/types/sasl-digest-md5/sasl-digest-md5-tests.ts new file mode 100644 index 0000000000..f63c4b7359 --- /dev/null +++ b/types/sasl-digest-md5/sasl-digest-md5-tests.ts @@ -0,0 +1,30 @@ +import DigestMd5Mechanism = require('sasl-digest-md5'); +import { Mechanism } from 'sasl-digest-md5'; +import { Factory } from 'saslmechanisms'; + +new Factory().use(DigestMd5Mechanism); +new Factory().use(Mechanism); + +// $ExpectType "DIGEST-MD5" +DigestMd5Mechanism.prototype.name; +// $ExpectType false +DigestMd5Mechanism.prototype.clientFirst; + +const m = new DigestMd5Mechanism(); +new DigestMd5Mechanism({ + genNonce() { + return 1; + }, +}); + +// $ExpectType "DIGEST-MD5" +m.name; +// $ExpectType false +m.clientFirst; +// $ExpectType string +m.response({ serviceType: 's', host: 'h', username: 'u', password: 'p' }); +m.response({ serviceType: 's', host: 'h', username: 'u', password: 'p', serviceName: 'sn' }); +m.response({ serviceType: 's', host: 'h', username: 'u', password: 'p', realm: 'r' }); +m.response({ serviceType: 's', host: 'h', username: 'u', password: 'p', authzid: 'a' }); +// $ExpectType DigestMd5Mechanism +m.challenge('challenge'); diff --git a/types/sasl-digest-md5/tsconfig.json b/types/sasl-digest-md5/tsconfig.json new file mode 100644 index 0000000000..84059391b2 --- /dev/null +++ b/types/sasl-digest-md5/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "sasl-digest-md5-tests.ts" + ] +} diff --git a/types/sasl-digest-md5/tslint.json b/types/sasl-digest-md5/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/sasl-digest-md5/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/sasl-external/index.d.ts b/types/sasl-external/index.d.ts new file mode 100644 index 0000000000..06a90ce3a4 --- /dev/null +++ b/types/sasl-external/index.d.ts @@ -0,0 +1,29 @@ +// Type definitions for sasl-external 0.1 +// Project: https://github.com/jaredhanson/js-sasl-external +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import { Mechanism } from 'saslmechanisms'; + +export = ExternalMechanism; + +declare class ExternalMechanism implements Mechanism { + static Mechanism: typeof ExternalMechanism; + static prototype: { + name: 'EXTERNAL'; + clientFirst: true; + }; + + name: 'EXTERNAL'; + clientFirst: true; + + response(cred: ExternalMechanism.Credentials): string; + + challenge(chal: string): void; +} + +declare namespace ExternalMechanism { + interface Credentials { + authzid?: string; + } +} diff --git a/types/sasl-external/sasl-external-tests.ts b/types/sasl-external/sasl-external-tests.ts new file mode 100644 index 0000000000..919721aec5 --- /dev/null +++ b/types/sasl-external/sasl-external-tests.ts @@ -0,0 +1,22 @@ +import ExternalMechanism = require('sasl-external'); +import { Mechanism } from 'sasl-external'; +import { Factory } from 'saslmechanisms'; + +new Factory().use(ExternalMechanism); +new Factory().use(Mechanism); + +// $ExpectType "EXTERNAL" +ExternalMechanism.prototype.name; +// $ExpectType true +ExternalMechanism.prototype.clientFirst; + +const m = new ExternalMechanism(); + +// $ExpectType "EXTERNAL" +m.name; +// $ExpectType true +m.clientFirst; +// $ExpectType string +m.response({ authzid: 'a' }); +// $ExpectType void +m.challenge('challenge'); diff --git a/types/sasl-external/tsconfig.json b/types/sasl-external/tsconfig.json new file mode 100644 index 0000000000..b319008559 --- /dev/null +++ b/types/sasl-external/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "sasl-external-tests.ts" + ] +} diff --git a/types/sasl-external/tslint.json b/types/sasl-external/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/sasl-external/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/sasl-plain/index.d.ts b/types/sasl-plain/index.d.ts new file mode 100644 index 0000000000..a1c5f61467 --- /dev/null +++ b/types/sasl-plain/index.d.ts @@ -0,0 +1,31 @@ +// Type definitions for sasl-plain 0.1 +// Project: https://github.com/jaredhanson/js-sasl-plain +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import { Mechanism } from 'saslmechanisms'; + +export = PlainMechanism; + +declare class PlainMechanism implements Mechanism { + static Mechanism: typeof PlainMechanism; + static prototype: { + name: 'PLAIN'; + clientFirst: true; + }; + + name: 'PLAIN'; + clientFirst: true; + + response(cred: PlainMechanism.Credentials): string; + + challenge(chal: string): this; +} + +declare namespace PlainMechanism { + interface Credentials { + authzid?: string; + username: string; + password: string; + } +} diff --git a/types/sasl-plain/sasl-plain-tests.ts b/types/sasl-plain/sasl-plain-tests.ts new file mode 100644 index 0000000000..144d21451f --- /dev/null +++ b/types/sasl-plain/sasl-plain-tests.ts @@ -0,0 +1,23 @@ +import PlainMechanism = require('sasl-plain'); +import { Mechanism } from 'sasl-plain'; +import { Factory } from 'saslmechanisms'; + +new Factory().use(PlainMechanism); +new Factory().use(Mechanism); + +// $ExpectType "PLAIN" +PlainMechanism.prototype.name; +// $ExpectType true +PlainMechanism.prototype.clientFirst; + +const m = new PlainMechanism(); + +// $ExpectType "PLAIN" +m.name; +// $ExpectType true +m.clientFirst; +// $ExpectType string +m.response({ username: 'u', password: 'pw' }); +m.response({ username: 'u', password: 'pw', authzid: 'a' }); +// $ExpectType PlainMechanism +m.challenge('challenge'); diff --git a/types/sasl-plain/tsconfig.json b/types/sasl-plain/tsconfig.json new file mode 100644 index 0000000000..3e33152c74 --- /dev/null +++ b/types/sasl-plain/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "sasl-plain-tests.ts" + ] +} diff --git a/types/sasl-plain/tslint.json b/types/sasl-plain/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/sasl-plain/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/sasl-scram-sha-1/index.d.ts b/types/sasl-scram-sha-1/index.d.ts new file mode 100644 index 0000000000..d332b6126a --- /dev/null +++ b/types/sasl-scram-sha-1/index.d.ts @@ -0,0 +1,41 @@ +// Type definitions for sasl-scram-sha-1 1.2 +// Project: https://github.com/legastero/js-sasl-scram-sha-1 +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import { Mechanism } from 'saslmechanisms'; + +export = ScramSha1Mechanism; + +declare class ScramSha1Mechanism implements Mechanism { + static Mechanism: typeof ScramSha1Mechanism; + static prototype: { + name: 'SCRAM-SHA-1'; + clientFirst: true; + }; + + name: 'SCRAM-SHA-1'; + clientFirst: true; + + constructor(options?: ScramSha1Mechanism.Options); + + response(cred: ScramSha1Mechanism.Credentials): string; + + challenge(chal: string): this; +} + +declare namespace ScramSha1Mechanism { + interface Options { + genNonce?: () => number; + } + + interface Credentials { + authzid?: string; + username?: string; + password?: string; + salt?: string; + saltedPassword?: string; + clientKey?: string; + serverKey?: string; + } +} diff --git a/types/sasl-scram-sha-1/sasl-scram-sha-1-tests.ts b/types/sasl-scram-sha-1/sasl-scram-sha-1-tests.ts new file mode 100644 index 0000000000..85eb648193 --- /dev/null +++ b/types/sasl-scram-sha-1/sasl-scram-sha-1-tests.ts @@ -0,0 +1,33 @@ +import ScramSha1Mechanism = require('sasl-scram-sha-1'); +import { Mechanism } from 'sasl-scram-sha-1'; +import { Factory } from 'saslmechanisms'; + +new Factory().use(ScramSha1Mechanism); +new Factory().use(Mechanism); + +// $ExpectType "SCRAM-SHA-1" +ScramSha1Mechanism.prototype.name; +// $ExpectType true +ScramSha1Mechanism.prototype.clientFirst; + +const m = new ScramSha1Mechanism(); +new ScramSha1Mechanism({ + genNonce() { + return 1; + }, +}); + +// $ExpectType "SCRAM-SHA-1" +m.name; +// $ExpectType true +m.clientFirst; +// $ExpectType string +m.response({ authzid: 'a' }); +m.response({ username: 'u' }); +m.response({ password: 'pw' }); +m.response({ salt: 's' }); +m.response({ saltedPassword: 'sp' }); +m.response({ clientKey: 'ck' }); +m.response({ serverKey: 'sk' }); +// $ExpectType ScramSha1Mechanism +m.challenge('challenge'); diff --git a/types/sasl-scram-sha-1/tsconfig.json b/types/sasl-scram-sha-1/tsconfig.json new file mode 100644 index 0000000000..80181379ea --- /dev/null +++ b/types/sasl-scram-sha-1/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "sasl-scram-sha-1-tests.ts" + ] +} diff --git a/types/sasl-scram-sha-1/tslint.json b/types/sasl-scram-sha-1/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/sasl-scram-sha-1/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/saslmechanisms/index.d.ts b/types/saslmechanisms/index.d.ts new file mode 100644 index 0000000000..62f71e8a25 --- /dev/null +++ b/types/saslmechanisms/index.d.ts @@ -0,0 +1,31 @@ +// Type definitions for saslmechanisms 0.1 +// Project: https://github.com/jaredhanson/js-sasl +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = Factory; + +declare class Factory { + static Factory: typeof Factory; + + use(name: string, mechanism: Factory.MechanismStatic): this; + use(mechanism: Factory.MechanismStatic): this; + create(mechanisms: string[]): Factory.Mechanism | null; +} + +declare namespace Factory { + interface MechanismStatic { + new (): Mechanism; + prototype: { + [key: string]: any; + name: string; + }; + } + interface Mechanism { + name: string; + + response(cred: { [key: string]: any }): string; + + challenge(chal: string): void; + } +} diff --git a/types/saslmechanisms/saslmechanisms-tests.ts b/types/saslmechanisms/saslmechanisms-tests.ts new file mode 100644 index 0000000000..d7e6fe7620 --- /dev/null +++ b/types/saslmechanisms/saslmechanisms-tests.ts @@ -0,0 +1,22 @@ +import Fct = require('saslmechanisms'); +import { Factory, MechanismStatic, Mechanism } from 'saslmechanisms'; + +const Mech: MechanismStatic = null as any; + +const factory = new Fct(); +new Factory(); +new Factory.Factory(); + +// $ExpectType Factory +factory.use(Mech); +factory.use('Mech', Mech); + +const mech: Mechanism | null = factory.create(['Mech']); +if (mech) { + // $ExpectType string + mech.name; + // $ExpectType string + mech.response({ foo: 'bar' }); + // $ExpectType void + mech.challenge('challenge'); +} diff --git a/types/saslmechanisms/tsconfig.json b/types/saslmechanisms/tsconfig.json new file mode 100644 index 0000000000..64beedfc0f --- /dev/null +++ b/types/saslmechanisms/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "saslmechanisms-tests.ts" + ] +} diff --git a/types/saslmechanisms/tslint.json b/types/saslmechanisms/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/saslmechanisms/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/sass/index.d.ts b/types/sass/index.d.ts new file mode 100644 index 0000000000..bd416d9718 --- /dev/null +++ b/types/sass/index.d.ts @@ -0,0 +1,208 @@ +// Type definitions for sass 1.15 +// Project: https://github.com/sass/dart-sass +// Definitions by: Silas Rech +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +/// + +export type ImporterReturnType = { file: string } | { contents: string } | Error | null; + +export type Importer = (url: string, prev: string, done: (data: ImporterReturnType) => void) => ImporterReturnType | void; + +export interface Options { + /** + * Path to a file to compile. + * + * @default null + */ + file?: string; + + /** + * A string to pass to compile. + * + * It is recommended that you use `includePaths` in conjunction with this so that sass can find files when using the @import directive. + * + * @default null + */ + data?: string; + + /** + * Handles when the @import directive is encountered. + * + * A custom importer allows extension of the sass engine in both a synchronous and asynchronous manner. + * + * @default undefined + */ + importer?: Importer | Importer[]; + + /** + * Holds a collection of custom functions that may be invoked by the sass files being compiled. + * + * @default undefined + */ + functions?: { [key: string]: () => void }; + + /** + * An array of paths that should be looked in to attempt to resolve your @import declarations. + * When using `data`, it is recommended that you use this. + * + * @default [] + */ + includePaths?: string[]; + + /** + * Enable Sass Indented Syntax for parsing the data string or file. + * + * @default false + */ + indentedSyntax?: boolean; + + /** + * Used to determine whether to use space or tab character for indentation. + * + * @default 'space' + */ + indentType?: 'space' | 'tab'; + + /** + * Used to determine the number of spaces or tabs to be used for indentation. + * + * @default 2 + */ + indentWidth?: number; + + /** + * Used to determine which sequence to use for line breaks. + * + * @default 'lf' + */ + linefeed?: 'cr' | 'crlf' | 'lf' | 'lfcr'; + + /** + * Disable the inclusion of source map information in the output file. + * + * @default false + */ + omitSourceMapUrl?: boolean; + + /** + * Specify the intended location of the output file. + * Strongly recommended when outputting source maps so that they can properly refer back to their intended files. + * + * @default null + */ + outFile?: string; + + /** + * Determines the output format of the final CSS style. + * + * @default 'expanded' + */ + outputStyle?: 'compressed' | 'expanded'; + + /** + * Enables the outputting of a source map. + * + * @default undefined + */ + sourceMap?: boolean | string; + + /** + * Includes the contents in the source map information. + * + * @default false + */ + sourceMapContents?: boolean; + + /** + * Embeds the source map as a data URI. + * + * @default false + */ + sourceMapEmbed?: boolean; + + /** + * The value will be emitted as `sourceRoot` in the source map information. + * + * @default undefined + */ + sourceMapRoot?: string; +} + +export interface SassException extends Error { + /** + * The error message. + */ + message: string; + + /** + * The formatted error. + */ + formatted: string; + + /** + * The line number of error. + */ + line: number; + + /** + * The column number of error. + */ + column: number; + + /** + * The status code. + */ + status: number; + + /** + * The filename of error. + * + * In case file option was not set (in favour of `data`), this will reflect the value `stdin`. + */ + file: string; +} + +export interface Result { + /** + * The compiled CSS. + * + * Write this to a file, or serve it out as needed. + */ + css: Buffer; + + /** + * The source map. + */ + map?: Buffer; + stats: { + /** + * The path to the scss file, or `data` if the source was not a file. + */ + entry: string; + + /** + * `Date.now()` before the compilation. + */ + start: number; + + /** + * `Date.now()` after the compilation. + */ + end: number; + + /** + * `end - start` + */ + duration: number; + + /** + * Absolute paths to all related files in no particular order. + */ + includedFiles: string[]; + }; +} + +export function render(options: Options, callback: (exception: SassException, result: Result) => void): void; +export function renderSync(options: Options): Result; diff --git a/types/sass/sass-tests.ts b/types/sass/sass-tests.ts new file mode 100644 index 0000000000..ae656d0a98 --- /dev/null +++ b/types/sass/sass-tests.ts @@ -0,0 +1,7 @@ +import * as sass from 'sass'; + +sass.renderSync({ + file: 'index.scss', + sourceMap: true, + outFile: 'index.css', +}); diff --git a/types/sass/tsconfig.json b/types/sass/tsconfig.json new file mode 100644 index 0000000000..11599da1da --- /dev/null +++ b/types/sass/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "sass-tests.ts" + ] +} diff --git a/types/sass/tslint.json b/types/sass/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/sass/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/sc-auth/index.d.ts b/types/sc-auth/index.d.ts new file mode 100644 index 0000000000..84f92bf674 --- /dev/null +++ b/types/sc-auth/index.d.ts @@ -0,0 +1,19 @@ +// Type definitions for sc-auth 5.0 +// Project: https://github.com/SocketCluster/sc-auth +// Definitions by: Daniel Rose +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +import { VerifyOptions, VerifyCallback, Secret, SignCallback, SignOptions } from "jsonwebtoken"; + +export interface SCAuthEngine { + verifyToken(signedToken: string, key: string | Buffer, options?: VerifyOptions, callback?: VerifyCallback): void; + signToken(token: string | object | Buffer, key: Secret, options?: SignOptions, callback?: SignCallback): void; +} + +export class AuthEngine implements SCAuthEngine { + constructor(); + + verifyToken(signedToken: string, key: string | Buffer, options?: VerifyOptions, callback?: VerifyCallback): void; + signToken(token: string | object | Buffer, key: Secret, options?: SignOptions, callback?: SignCallback): void; +} diff --git a/types/sc-auth/sc-auth-tests.ts b/types/sc-auth/sc-auth-tests.ts new file mode 100644 index 0000000000..4fa57d3391 --- /dev/null +++ b/types/sc-auth/sc-auth-tests.ts @@ -0,0 +1,102 @@ +/** + * This mostly delegates to jwt, so using its tests as base + */ + +import scAuth = require("sc-auth"); +import fs = require("fs"); + +let signedToken = ""; +let cert: Buffer; + +interface TestObject { + foo: string; +} + +const testObject = { foo: "bar" }; + +const authEngine = new scAuth.AuthEngine(); + +// sign with default (HMAC SHA256) +authEngine.signToken(testObject, "shhhhh"); + +// sign with default (HMAC SHA256) and single audience +authEngine.signToken(testObject, "shhhhh", { audience: "theAudience" }); + +// sign with default (HMAC SHA256) and multiple audiences +authEngine.signToken(testObject, "shhhhh", { + audience: ["audience1", "audience2"] +}); + +// sign with default (HMAC SHA256) and a keyid +authEngine.signToken(testObject, "shhhhh", { keyid: "theKeyId" }); + +// sign with RSA SHA256 +cert = fs.readFileSync("private.key"); // get private key +authEngine.signToken(testObject, cert, { algorithm: "RS256" }); + +// sign with encrypted RSA SHA256 private key (only PEM encoding is supported) +const privKey: Buffer = fs.readFileSync("encrypted_private.key"); // get private key +const secret = { key: privKey.toString(), passphrase: "keypwd" }; +authEngine.signToken(testObject, secret, { algorithm: "RS256" }); // the algorithm option is mandatory in this case + +// sign asynchronously +authEngine.signToken(testObject, cert, { algorithm: "RS256" }, (err, token) => { + signedToken = token; +}); + +// verify a token symmetric +authEngine.verifyToken(signedToken, "shhhhh", {}, (err, decoded) => { + const result = decoded as TestObject; + + console.log(result.foo); // bar +}); + +// use external time for verifying +authEngine.verifyToken(signedToken, "shhhhh", { clockTimestamp: 1 }, (err, decoded) => { + const result = decoded as TestObject; + + console.log(result.foo); // bar +}); + +// invalid token +authEngine.verifyToken(signedToken, "wrong-secret", {}, (err, decoded) => { + console.log(err); + + // decoded undefined +}); + +// verify a token asymmetric +cert = fs.readFileSync("public.pem"); // get public key +authEngine.verifyToken(signedToken, cert, {}, (err, decoded) => { + const result = decoded as TestObject; + + console.log(result.foo); // bar +}); + +// verify audience +cert = fs.readFileSync("public.pem"); // get public key +authEngine.verifyToken(signedToken, cert, { audience: "urn:foo" }, (err, decoded) => { + // if audience mismatch, err == invalid audience + console.log(err); +}); + +// verify issuer +cert = fs.readFileSync("public.pem"); // get public key +authEngine.verifyToken(signedToken, cert, { audience: "urn:foo", issuer: "urn:issuer" }, (err, decoded) => { + // if issuer mismatch, err == invalid issuer + console.log(err); +}); + +// verify algorithm +cert = fs.readFileSync("public.pem"); // get public key +authEngine.verifyToken(signedToken, cert, { algorithms: ["RS256"] }, (err, decoded) => { + // if algorithm mismatch, err == invalid algorithm + console.log(err); +}); + +// verify without expiration check +cert = fs.readFileSync("public.pem"); // get public key +authEngine.verifyToken(signedToken, cert, { ignoreExpiration: true }, (err, decoded) => { + // if ignoreExpration == false and token is expired, err == expired token + console.log(err); +}); diff --git a/types/sc-auth/tsconfig.json b/types/sc-auth/tsconfig.json new file mode 100644 index 0000000000..5c8e3a1e19 --- /dev/null +++ b/types/sc-auth/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "sc-auth-tests.ts" + ] +} diff --git a/types/sc-auth/tslint.json b/types/sc-auth/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/sc-auth/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/sc-broker-cluster/clientcluster.d.ts b/types/sc-broker-cluster/clientcluster.d.ts new file mode 100644 index 0000000000..f2234df6ab --- /dev/null +++ b/types/sc-broker-cluster/clientcluster.d.ts @@ -0,0 +1,10 @@ +import { EventEmitter } from "events"; +import { SCBrokerClient } from "sc-broker"; +import { mapperFunction } from "."; + +export class ClientCluster extends EventEmitter { + constructor(clients: SCBrokerClient[]); + + setMapper(mapper: mapperFunction): void; + getMapper(): mapperFunction; +} diff --git a/types/sc-broker-cluster/index.d.ts b/types/sc-broker-cluster/index.d.ts new file mode 100644 index 0000000000..9314acda82 --- /dev/null +++ b/types/sc-broker-cluster/index.d.ts @@ -0,0 +1,160 @@ +// Type definitions for sc-broker-cluster 6.1 +// Project: https://github.com/SocketCluster/sc-broker-cluster +// Definitions by: Daniel Rose +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +import { SCServerSocket, SCServer } from "socketcluster-server"; +import { BrokerStartInfo, BrokerExitInfo } from "socketcluster"; +import { SpliceOptions, QueryOptions } from "sc-broker"; +import { SCChannel } from "sc-channel"; +import { EventEmitter } from "events"; +import { AsyncResultArrayCallback } from "async"; +import { KeyChain, FlexiMap } from "fleximap"; +import { Keys } from "expirymanager"; +import { ClientCluster } from "./clientcluster"; + +export class AbstractDataClient extends EventEmitter { + constructor(dataClient: ClientCluster); + + set(keyChain: KeyChain, value: any, getValue?: boolean, callback?: (err?: Error) => void): void; + set(keyChain: KeyChain, value: any, callback?: (err?: Error) => void): void; + + expire(keys: Keys, seconds: number, callback?: (err?: Error) => void): void; + unexpire(keys: Keys, callback?: (err?: Error) => void): void; + + add(keyChain: KeyChain, value: any, getValue?: boolean, callback?: (err?: Error) => void): void; + add(keyChain: KeyChain, value: any, callback?: (err?: Error) => void): void; + + get(keyChain: KeyChain, callback: (err: Error | null, value: any) => void): void; + + getRange(keyChain: KeyChain, fromIndex: number, toIndex: number, callback: (err: Error | null, value: any) => void): void; + getRange(keyChain: KeyChain, fromIndex: number, callback: (err: Error | null, value: any) => void): void; + + getAll(callback: (err: Error | null, value: any[] | object) => void): void; + + count(keyChain: KeyChain, callback: (err: Error | null, value: number) => void): void; + + remove(keyChain: KeyChain, getValue?: boolean, callback?: (err?: Error) => void): void; + remove(keyChain: KeyChain, callback?: (err?: Error) => void): void; + + removeRange(keyChain: KeyChain, fromIndex: number, toIndex?: number, getValue?: boolean, callback?: (err?: Error) => void): void; + removeRange(keyChain: KeyChain, fromIndex: number, toIndex?: number, callback?: (err?: Error) => void): void; + removeRange(keyChain: KeyChain, fromIndex: number, callback?: (err?: Error) => void): void; + + removeAll(callback?: (err: Error) => void): void; + + splice(keyChain: KeyChain, options?: SpliceOptions, callback?: (err?: Error) => void): void; + splice(keyChain: KeyChain, callback?: (err?: Error) => void): void; + + pop(keyChain: KeyChain, callback: (err: Error | null, data: any) => void): void; + + hasKey(keyChain: KeyChain, callback: (err: Error | null, data: boolean) => void): void; + + extractKeys(keyChain: KeyChain): string[]; + + extractValues(keyChain: KeyChain): any[]; + + exec(query: (datamap: FlexiMap) => void, options?: QueryOptions, callback?: (err: Error | null, data: any) => void): void; + exec(query: (datamap: FlexiMap) => void, callback: (err: Error | null, data: any) => void): void; +} + +export type handlerFunction = (data: any) => void; + +export type mapperFunction = (keyChain: KeyChain, method: string, clientIds: number[]) => number | number[]; + +/** + * The exchange object is a top-level SCBrokerClient which lets you publish events and manipulate data within your brokers - It represents a cluster of 1 or more brokers. + */ +export class SCExchange extends AbstractDataClient { + constructor(privateClientCluster: ClientCluster, publicClientCluster: ClientCluster, ioClusterClient: Client); + + send(data: any, mapIndex: number | string | string[] | null, callback?: (err?: Error) => void): void; + + publish(channelName: string, data: any, callback: (err?: Error) => void): void; + + subscribe(channelName: string): SCChannel; + unsubscribe(channelName: string): void; + + channel(channelName: string): SCChannel; + destroyChannel(channelName: string): void; + + subscriptions(includePending?: boolean): string[]; + isSubscribed(channelName: string, includePending?: boolean): boolean; + + watch(channelName: string, handler: handlerFunction): void; + unwatch(channelName: string, handler?: handlerFunction): void; + watchers(channelName: string): handlerFunction[]; + + setMapper(mapper: mapperFunction): void; + getMapper(): mapperFunction; + + map(keyChain: KeyChain, method: string): { type: string; targets: Client[] }; + + destroy(): void; +} + +export interface SCBrokerClusterServerOptions { + brokers: string[]; + debug?: boolean; + inspect?: boolean; + instanceId?: string; + secretKey?: string; + expiryAccuracy?: number; + downgradeToUser: number | string; + appBrokerControllerPath?: string; + processTermTimeout?: number; + ipcAckTimeout?: number; + brokerOptions?: SCServer.SCServerOptions; +} + +export class Server extends EventEmitter { + constructor(options: SCBrokerClusterServerOptions); + + on(event: "brokerStart", listener: (brokerInfo: BrokerStartInfo) => void): this; + on(event: "brokerExit", listener: (brokerInfo: BrokerExitInfo) => void): this; + on(event: "brokerMessage", listener: (brokerId: string, data: any, callback: (err: Error | null, data: any) => void) => void): this; + on(event: "ready", listener: () => void): this; + on(event: "error", listener: (err?: Error) => void): this; + + sendToBroker(brokerId: string, data: any, callback: (err: Error | null, data: any) => void): void; + killBrokers(): void; + destroy(): void; +} + +export interface SCBrokerClusterClientOptions { + brokers: string[]; + secretKey?: string; + pubSubBatchDuration?: number; + connectRetryErrorThreshold: number; +} + +export interface MessagePacket { + channel: string; + data: any; +} + +export class Client extends EventEmitter { + constructor(options: SCBrokerClusterClientOptions); + + exchange(): SCExchange; + + options: SCBrokerClusterClientOptions; + + on(event: "error", listener: (err?: Error) => void): this; + on(event: "warning", listener: (warning?: Error) => void): this; + on(event: "ready", listener: () => void): this; + on(event: "message", listener: (packet: MessagePacket) => void): this; + + destroy(callback: AsyncResultArrayCallback): void; + + subscribe(channel: string, callback: (err?: Error) => void): void; + unsubscribe(channel: string, callback: () => void): void; + unsubscribeAll(callback: () => void): void; + isSubscribed(channel: string, includePending: boolean): boolean; + + subscribeSocket(socket: SCServerSocket, channel: string, callback?: (err?: Error) => void): void; + unsubscribeSocket(socket: SCServerSocket, channel: string, callback?: () => void): void; + + setSCServer(scServer: SCServer): void; +} diff --git a/types/sc-broker-cluster/sc-broker-cluster-tests.ts b/types/sc-broker-cluster/sc-broker-cluster-tests.ts new file mode 100644 index 0000000000..0f5c274248 --- /dev/null +++ b/types/sc-broker-cluster/sc-broker-cluster-tests.ts @@ -0,0 +1,29 @@ +import { Client } from "sc-broker-cluster"; +import { SCServer, SCServerSocket } from "socketcluster-server"; +import WebSocket = require("ws"); + +const client = new Client({ + brokers: [], + secretKey: "secretKey", + pubSubBatchDuration: 100, + connectRetryErrorThreshold: 5 +}); + +client.on("error", err => {}); +client.on("warning", err => {}); + +const exchange = client.exchange(); + +const scServer = new SCServer(); +client.setSCServer(scServer); + +client.once("ready", () => {}); + +const wsSocket = new WebSocket("address"); +const socket = new SCServerSocket("id", scServer, wsSocket); +client.subscribeSocket(socket, "channelName", err => {}); + +client.unsubscribeSocket(socket, "channelName"); + +const data: any = {}; +exchange.publish("channelName", data, err => {}); diff --git a/types/sc-broker-cluster/scbroker.d.ts b/types/sc-broker-cluster/scbroker.d.ts new file mode 100644 index 0000000000..a7ddb7db87 --- /dev/null +++ b/types/sc-broker-cluster/scbroker.d.ts @@ -0,0 +1,3 @@ +import SCBroker = require("sc-broker/scbroker"); + +export = SCBroker; diff --git a/types/sc-broker-cluster/tsconfig.json b/types/sc-broker-cluster/tsconfig.json new file mode 100644 index 0000000000..8ace8fc9dc --- /dev/null +++ b/types/sc-broker-cluster/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "clientcluster.d.ts", + "scbroker.d.ts", + "sc-broker-cluster-tests.ts" + ] +} diff --git a/types/sc-broker-cluster/tslint.json b/types/sc-broker-cluster/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/sc-broker-cluster/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/sc-broker/index.d.ts b/types/sc-broker/index.d.ts new file mode 100644 index 0000000000..ccb83e880e --- /dev/null +++ b/types/sc-broker/index.d.ts @@ -0,0 +1,165 @@ +// Type definitions for sc-broker 5.1 +// Project: https://github.com/SocketCluster/sc-broker +// Definitions by: Daniel Rose +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +import { SCServer } from "socketcluster-server"; +import { WorkerExitInfo } from "socketcluster"; +import { EventEmitter } from "events"; +import { KeyChain, FlexiMap } from "fleximap"; +import { Keys, Key } from "expirymanager"; + +export interface SCBrokerServerOptions { + id?: string; + instanceId?: string; + debug?: boolean; + inspect?: boolean; + socketPath?: string; + port?: number; + expiryAccuracy?: number; + downgradeToUser: number | string; + brokerControllerPath?: string; + processTermTimeout?: number; + ipcAckTimeout?: number; + secretKey?: string; + brokerOptions?: SCServer.SCServerOptions; +} + +export interface SCBrokerServer extends EventEmitter { + options: SCBrokerServerOptions; + socketPath?: string; + port?: number; + ipcAckTimeout: number; + + on(event: "error", listener: (err?: Error) => void): this; + on(event: "brokerMessage", listener: (brokerId: string, data: any, callback: (err: Error | null, data: any) => void) => void): this; + on(event: "ready", listener: (data: any) => void): this; + on(event: "exit", listener: (data: WorkerExitInfo) => void): this; + + sendToBroker(data: any, callback?: (err: Error | null, data: any, brokerId: string) => void): void; +} + +export function createServer(options?: SCBrokerServerOptions): SCBrokerServer; + +export interface AutoReconnectOptions { + initialDelay?: number; + randomness?: number; + multiplier?: number; + maxDelay?: number; +} + +export interface SCBrokerClientOptions { + secretKey?: string; + timeout?: number; + socketPath?: string; + port?: number; + host?: string; + autoReconnect?: boolean; + autoReconnectOptions?: AutoReconnectOptions; + connectRetryErrorThreshold?: number; + pubSubBatchDuration?: number; +} + +export interface QueryOptions { + baseKey?: KeyChain; + noAck?: boolean; + data?: any; +} + +export interface SpliceOptions { + index?: number; + count?: number; + items?: any[]; + getValue?: boolean; + noAck?: boolean; +} + +export interface SCBrokerClient extends EventEmitter { + readonly CONNECTED: "connected"; + readonly CONNECTING: "connecting"; + readonly DISCONNECTED: "disconnected"; + + socketPath?: string; + port?: number; + host?: string; + autoReconnect: boolean; + autoReconnectOptions?: AutoReconnectOptions; + connectRetryErrorThreshold: number; + state: "connected" | "connecting" | "disconnected"; + connectAttempts: number; + pendingReconnect: boolean; + pendingReconnectTimeout: number | null; + + on(event: "error", listener: (err?: Error) => void): this; + on(event: "warning", listener: (warning?: Error) => void): this; + on(event: "ready", listener: (data: any) => void): this; + on(event: "message", listener: (channel: string, data: any) => void): this; + on(event: "subscribeFail", listener: (err: Error | null, channel: string) => void): this; + on(event: "subscribe", listener: (channel: string) => void): this; + on(event: "unsubscribe", listener: () => void): this; + + isConnected(): boolean; + + subscribe(channel: string, ackCallback: (err?: Error) => void, force?: boolean): void; + unsubscribe(channel: string, ackCallback: (err?: Error) => void): void; + + subscriptions(includePending?: boolean): string[]; + isSubscribed(channel: string, includePending?: boolean): boolean; + + publish(channel: string, data: any, callback: (err?: Error) => void): void; + + send(data: any, callback: (err?: Error) => void): void; + + set(keyChain: KeyChain, value: any, getValue?: boolean, callback?: (err?: Error) => void): void; + set(keyChain: KeyChain, value: any, callback?: (err?: Error) => void): void; + + expire(keys: Keys, seconds: number, callback?: (err?: Error) => void): void; + unexpire(keys: Keys, callback?: (err?: Error) => void): void; + getExpiry(key: Key, callback?: (err?: Error) => void): number; + + add(keyChain: KeyChain, value: any, getValue?: boolean, callback?: (err?: Error) => void): void; + add(keyChain: KeyChain, value: any, callback?: (err?: Error) => void): void; + + concat(keyChain: KeyChain, value: any, getValue?: boolean, callback?: (err?: Error) => void): void; + concat(keyChain: KeyChain, value: any, callback?: (err?: Error) => void): void; + + get(keyChain: KeyChain, callback: (err: Error | null, value: any) => void): void; + + getRange(keyChain: KeyChain, fromIndex: number, toIndex: number, callback: (err: Error | null, value: any) => void): void; + getRange(keyChain: KeyChain, fromIndex: number, callback: (err: Error | null, value: any) => void): void; + + getAll(callback: (err: Error | null, value: any[] | object) => void): void; + + count(keyChain: KeyChain, callback: (err: Error | null, value: number) => void): void; + + exec(query: (datamap: FlexiMap) => void, options?: QueryOptions, callback?: (err: Error | null, data: any) => void): void; + exec(query: (datamap: FlexiMap) => void, callback: (err: Error | null, data: any) => void): void; + + query(query: (datamap: FlexiMap) => void, data?: any, callback?: (err: Error | null, data: any) => void): void; + query(query: (datamap: FlexiMap) => void, callback: (err: Error | null, data: any) => void): void; + + remove(keyChain: KeyChain, getValue?: boolean, callback?: (err?: Error) => void): void; + remove(keyChain: KeyChain, callback?: (err?: Error) => void): void; + + removeRange(keyChain: KeyChain, fromIndex: number, toIndex?: number, getValue?: boolean, callback?: (err?: Error) => void): void; + removeRange(keyChain: KeyChain, fromIndex: number, toIndex?: number, callback?: (err?: Error) => void): void; + removeRange(keyChain: KeyChain, fromIndex: number, callback?: (err?: Error) => void): void; + + removeAll(callback?: (err: Error) => void): void; + + splice(keyChain: KeyChain, options?: SpliceOptions, callback?: (err?: Error) => void): void; + splice(keyChain: KeyChain, callback?: (err?: Error) => void): void; + + pop(keyChain: KeyChain, callback: (err: Error | null, data: any) => void): void; + + hasKey(keyChain: KeyChain, callback: (err: Error | null, data: boolean) => void): void; + + extractKeys(keyChain: KeyChain): string[]; + + extractValues(keyChain: KeyChain): any[]; + + end(callback: (err?: Error) => void): void; +} + +export function createClient(options?: SCBrokerClientOptions): SCBrokerClient; diff --git a/types/sc-broker/sc-broker-tests.ts b/types/sc-broker/sc-broker-tests.ts new file mode 100644 index 0000000000..201ff10a27 --- /dev/null +++ b/types/sc-broker/sc-broker-tests.ts @@ -0,0 +1,58 @@ +import { SCServer, SCServerSocket } from "socketcluster-server"; +import SCBroker = require("sc-broker/scbroker"); +import { FlexiMap } from "fleximap"; +import { ExpiryManager } from "expirymanager"; + +//////////////////////////////////////////////////// +/// SCBroker tests +//////////////////////////////////////////////////// + +const options: SCServer.SCServerOptions = { port: 80 }; + +let scBroker = new SCBroker(); +scBroker = new SCBroker(options); +scBroker.options = { environment: "prod" }; + +const id: number = scBroker.id; +const instanceId: number = scBroker.instanceId; +const dataMap: FlexiMap = scBroker.dataMap; +const dataExpirer: ExpiryManager = scBroker.dataExpirer; +const subscriptions = scBroker.subscriptions; + +const socket: SCServerSocket = subscriptions[1]["test"]; + +scBroker.on("subscribe", channel => { + const subscribeChannel: string = channel; +}); +scBroker.on("unsubscribe", channel => { + const unsubscribeChannel: string = channel; +}); +scBroker.on("publish", (channel, data) => { + const publishChannel: string = channel; + const publishData: any = data; +}); +scBroker.on("masterMessage", (data, masterMessageResponse) => { + const masterMessageData: any = data; + masterMessageResponse(null, "test"); + masterMessageResponse(new Error(), null); +}); + +scBroker.publish("testChannel", 123); + +scBroker.exec(dataMap => { + dataMap.set(["main", "message"], "Message"); + return dataMap.get(["main"]); +}); + +scBroker.sendToMaster("data"); +scBroker.sendToMaster(123, (err, response) => { + if (!err) { + const answer = response; + } +}); + +class MyBroker extends SCBroker { + run() { + this.on("subscribe", channel => {}); + } +} diff --git a/types/sc-broker/scbroker.d.ts b/types/sc-broker/scbroker.d.ts new file mode 100644 index 0000000000..057b983adf --- /dev/null +++ b/types/sc-broker/scbroker.d.ts @@ -0,0 +1,32 @@ +import { EventEmitter } from "events"; +import { SCServer, SCServerSocket } from "socketcluster-server"; +import { FlexiMap, KeyChain } from "fleximap"; +import { ExpiryManager } from "expirymanager"; + +export = SCBroker; + +interface Subscriptions { + [socketId: number]: { + [channel: string]: SCServerSocket; + }; +} + +declare class SCBroker extends EventEmitter { + id: number; + options: SCServer.SCServerOptions; + instanceId: number; + dataMap: FlexiMap; + dataExpirer: ExpiryManager; + subscriptions: Subscriptions; + + constructor(options?: SCServer.SCServerOptions); + + on(event: "subscribe" | "unsubscribe", listener: (channel: string) => void): this; + on(event: "publish", listener: (channel: string, data: any) => void): this; + on(event: "masterMessage", listener: (data: any, respond: (err: Error | null, responseData: any) => void) => void): this; + + publish(channel: string, message: any): void; + run(): void; + exec(query: (dataMap: FlexiMap, dataExpirer: ExpiryManager, subscriptions: Subscriptions) => any, baseKey?: KeyChain): any; + sendToMaster(data: any, callback?: (err: Error | null, responseData: any) => void): void; +} diff --git a/types/sc-broker/tsconfig.json b/types/sc-broker/tsconfig.json new file mode 100644 index 0000000000..6adfe07a5b --- /dev/null +++ b/types/sc-broker/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "scbroker.d.ts", + "sc-broker-tests.ts" + ] +} diff --git a/types/sc-broker/tslint.json b/types/sc-broker/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/sc-broker/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/sc-channel/index.d.ts b/types/sc-channel/index.d.ts new file mode 100644 index 0000000000..034723c0ba --- /dev/null +++ b/types/sc-channel/index.d.ts @@ -0,0 +1,45 @@ +// Type definitions for sc-channel 1.2 +// Project: https://github.com/SocketCluster/sc-channel +// Definitions by: Daniel Rose +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +import Emitter = require("component-emitter"); +import { SCExchange, handlerFunction } from "sc-broker-cluster"; + +export interface SCChannelOptions { + waitForAuth?: boolean; + batch?: boolean; + data?: any; +} + +export class SCChannel extends Emitter { + readonly PENDING: "pending"; + readonly SUBSCRIBED: "subscribed"; + readonly UNSUBSCRIBED: "unsubscribed"; + + name: string; + state: ChannelState; + waitForAuth: boolean; + batch: boolean; + data: any; + + constructor(name: string, client: SCExchange, options?: SCChannelOptions); + + setOptions(options?: SCChannelOptions): void; + getState(): "pending" | "subscribed" | "unsubscribed"; + + subscribe(options?: any): void; + unsubscribe(): void; + isSubscribed(includePending?: boolean): boolean; + + publish(data: any, callback?: (err?: Error) => void): void; + + watch(handler: handlerFunction): void; + unwatch(handler?: handlerFunction): void; + watchers(): handlerFunction[]; + + destroy(): void; +} + +export type ChannelState = "pending" | "subscribed" | "unsubscribed"; diff --git a/types/sc-channel/sc-channel-tests.ts b/types/sc-channel/sc-channel-tests.ts new file mode 100644 index 0000000000..bfc90cee12 --- /dev/null +++ b/types/sc-channel/sc-channel-tests.ts @@ -0,0 +1,33 @@ +import { SCChannel, SCChannelOptions } from "sc-channel"; +import { handlerFunction, Client, SCBrokerClusterClientOptions } from "sc-broker-cluster"; + +const clientOptions: SCBrokerClusterClientOptions = { brokers: [], connectRetryErrorThreshold: 0 }; +const client = new Client(clientOptions); + +let channel = new SCChannel("channelName", client.exchange()); +const channelOptions: SCChannelOptions = {}; +channel = new SCChannel("channelName", client.exchange(), channelOptions); + +channel.state = channel.PENDING; +channel.state = channel.SUBSCRIBED; +channel.state = channel.UNSUBSCRIBED; + +const channelName: string = channel.name; + +const handler: handlerFunction = () => { }; + +channel.watch(handler); +channel.unwatch(); + +channel.subscribe(); +channel.subscribe(channelOptions); +channel.unsubscribe(); + +const data: any = channel.data; + +channel.emit("subscribe", channelName); +channel.emit("unsubscribe", channelName); + +channel.setOptions(channelOptions); + +channel.publish(data); diff --git a/types/sc-channel/tsconfig.json b/types/sc-channel/tsconfig.json new file mode 100644 index 0000000000..c5c5ce5f14 --- /dev/null +++ b/types/sc-channel/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "sc-channel-tests.ts" + ] +} diff --git a/types/sc-channel/tslint.json b/types/sc-channel/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/sc-channel/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/segment-analytics/tslint.json b/types/segment-analytics/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/segment-analytics/tslint.json +++ b/types/segment-analytics/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/selectize/tslint.json b/types/selectize/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/selectize/tslint.json +++ b/types/selectize/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/selenium-webdriver/index.d.ts b/types/selenium-webdriver/index.d.ts index aa8a696576..4fa0ccf7ac 100644 --- a/types/selenium-webdriver/index.d.ts +++ b/types/selenium-webdriver/index.d.ts @@ -4,7 +4,8 @@ // Yuki Kokubun , // Craig Nishina , // Simon Gellis , -// Ben Dixon +// Ben Dixon , +// Ziyu // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -540,7 +541,7 @@ export namespace logging { * @param {string} name the logger's name. * @return {!Logger} the requested logger. */ - getLogger(name: string): Logger; + getLogger(name?: string): Logger; /** * Creates a new logger. @@ -552,6 +553,34 @@ export namespace logging { */ createLogger_(name: string, parent: Logger): Logger; } + + /** + * Retrieves a named logger, creating it in the process. This function will + * implicitly create the requested logger, and any of its parents, if they + * do not yet exist. + * + * @param {string} name the logger's name. + * @return {!Logger} the requested logger. + */ + function getLogger(name?: string): Logger; + + /** + * Adds the console handler to the given logger. The console handler will log + * all messages using the JavaScript Console API. + * + * @param {Logger=} opt_logger The logger to add the handler to; defaults + * to the root logger. + */ + function addConsoleHandler(opt_logger?: Logger): void; + + /** + * Removes the console log handler from the given logger. + * + * @param {Logger=} opt_logger The logger to remove the handler from; defaults + * to the root logger. + * @see exports.addConsoleHandler + */ + function removeConsoleHandler(opt_logger?: Logger): void; } export namespace promise { diff --git a/types/selenium-webdriver/test/index.ts b/types/selenium-webdriver/test/index.ts index f8decdace1..84ffc6a8c2 100644 --- a/types/selenium-webdriver/test/index.ts +++ b/types/selenium-webdriver/test/index.ts @@ -758,6 +758,12 @@ function TestLogging() { type = webdriver.logging.Type.DRIVER; type = webdriver.logging.Type.PERFORMANCE; type = webdriver.logging.Type.SERVER; + + let logger: webdriver.logging.Logger = webdriver.logging.getLogger(); + webdriver.logging.addConsoleHandler(); + webdriver.logging.addConsoleHandler(logger); + webdriver.logging.removeConsoleHandler(); + webdriver.logging.removeConsoleHandler(logger); } function TestLoggingEntry() { diff --git a/types/semantic-ui-form/global.d.ts b/types/semantic-ui-form/global.d.ts index 8e5b2c20b8..1f3294c8d6 100644 --- a/types/semantic-ui-form/global.d.ts +++ b/types/semantic-ui-form/global.d.ts @@ -212,7 +212,7 @@ declare namespace SemanticUI { /** * Callback if a form is all valid */ - onSuccess(this: JQuery, event: JQuery.Event, fields: any): void; + onSuccess(this: JQuery, event: JQuery.TriggeredEvent, fields: any): void; /** * Callback if any form field is invalid */ diff --git a/types/semantic-ui-form/semantic-ui-form-tests.ts b/types/semantic-ui-form/semantic-ui-form-tests.ts index f17ca33112..d481cb00ad 100644 --- a/types/semantic-ui-form/semantic-ui-form-tests.ts +++ b/types/semantic-ui-form/semantic-ui-form-tests.ts @@ -144,7 +144,7 @@ function test_form() { }, onSuccess(event, fields) { this; // $ExpectType JQuery - event; // $ExpectType Event + event; // $ExpectType TriggeredEvent fields; // $ExpectType any }, onFailure(formErrors, fields) { diff --git a/types/sequelize/index.d.ts b/types/sequelize/index.d.ts index f25aacc3e4..6898a82ca4 100644 --- a/types/sequelize/index.d.ts +++ b/types/sequelize/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Sequelize 4.27.10 +// Type definitions for Sequelize 4.27.11 // Project: http://sequelizejs.com // Definitions by: samuelneff // Peter Harris @@ -15,6 +15,7 @@ // Nick Schultz // Thomas Breleur // Antoine Boisadam +// Dima Smirnov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -3290,6 +3291,11 @@ declare namespace sequelize { */ type FindOptionsAttributesArray = Array; + /** + * Shortcut for order type in FindOptions.attributes + */ + type FindOptionsOrderArray = Array | { model: Model, as?: string } | fn>; + /** * Options that are passed to any model creating a SELECT query * @@ -3330,7 +3336,7 @@ declare namespace sequelize { * first element is the column / function to order by, the second is the direction. For example: * `order: [['name', 'DESC']]`. In this way the column will be escaped, but the direction will not. */ - order?: string | col | literal | Array | { model: Model, as?: string }> | Array | { model: Model, as?: string }>>; + order?: string | col | literal | FindOptionsOrderArray | fn | Array; /** * Limit the results @@ -5240,13 +5246,13 @@ declare namespace sequelize { * `this.constructor.prototype.find.apply(this, arguments)` */ classMethods?: Object; - + /** * Change the database schema. PG only feature, but also works with other dialects. */ schema?: string; - - + + /** * Change the database schema delimiter. Defaults to "." on PG but for other dialects can be also changed to "_". */ diff --git a/types/sequelize/sequelize-tests.ts b/types/sequelize/sequelize-tests.ts index 6b7ea6ea0a..943fed79e3 100644 --- a/types/sequelize/sequelize-tests.ts +++ b/types/sequelize/sequelize-tests.ts @@ -946,6 +946,8 @@ User.findAll( { where : { user_id : 1 }, attributes : ['a', 'b'], include : [{ m User.findAll( { order : s.literal( 'email =' ) } ); User.findAll( { order : [s.literal( 'email = ' + s.escape( 'test@sequelizejs.com' ) )] } ); User.findAll( { order : [['id', ';DELETE YOLO INJECTIONS']] } ); +User.findAll( { order : s.random() } ); +User.findAll( { order : [s.random()] } ); User.findAll( { include : [User], order : [[User, 'id', ';DELETE YOLO INJECTIONS']] } ); User.findAll( { include : [User], order : [['id', 'ASC NULLS LAST'], [User, 'id', 'DESC NULLS FIRST']] } ); User.findAll( { include : [{ model : User, where : { title : 'DoDat' }, include : [{ model : User }] }] } ); diff --git a/types/serialport/index.d.ts b/types/serialport/index.d.ts index 14ded3b6e3..c1a81376fa 100644 --- a/types/serialport/index.d.ts +++ b/types/serialport/index.d.ts @@ -103,7 +103,7 @@ declare namespace SerialPort { constructor(options: {delimiter: string | Buffer | number[], encoding?: 'ascii'|'utf8'|'utf16le'|'ucs2'|'base64'|'binary'|'hex'}); } class Ready extends Stream.Transform { - constructor(options: {data: string | Buffer | number[]}); + constructor(options: {delimiter: string | Buffer | number[]}); } class Regex extends Stream.Transform { constructor(options: {regex: RegExp}); diff --git a/types/serialport/serialport-tests.ts b/types/serialport/serialport-tests.ts index 16cf2b6a70..d6541a63c2 100644 --- a/types/serialport/serialport-tests.ts +++ b/types/serialport/serialport-tests.ts @@ -107,7 +107,7 @@ function test_parsers() { const CCTalkParser = new SerialPort.parsers.CCTalk(); const DelimiterParser = new SerialPort.parsers.Delimiter({ delimiter: Buffer.from('EOL') }); const ReadlineParser = new SerialPort.parsers.Readline({ delimiter: '\r\n' }); - const ReadyParser = new SerialPort.parsers.Ready({ data: 'READY' }); + const ReadyParser = new SerialPort.parsers.Ready({ delimiter: 'READY' }); const RegexParser = new SerialPort.parsers.Regex({regex: /.*/}); port.pipe(ByteLengthParser); diff --git a/types/sha.js/index.d.ts b/types/sha.js/index.d.ts new file mode 100644 index 0000000000..d5dc4ba752 --- /dev/null +++ b/types/sha.js/index.d.ts @@ -0,0 +1,26 @@ +// Type definitions for sha.js 2.4 +// Project: https://github.com/crypto-browserify/sha.js +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import { Hash } from 'crypto'; + +export = SHA; + +declare function SHA(algorithm: string): Hash; + +declare namespace SHA { + type Algorithm = 'sha' | 'sha1' | 'sha224' | 'sha256' | 'sha384' | 'sha512'; + interface HashStatic { + new (): Hash; + } + + const sha: HashStatic; + const sha1: HashStatic; + const sha224: HashStatic; + const sha256: HashStatic; + const sha384: HashStatic; + const sha512: HashStatic; +} diff --git a/types/sha.js/sha.js-tests.ts b/types/sha.js/sha.js-tests.ts new file mode 100644 index 0000000000..fd3cde2e47 --- /dev/null +++ b/types/sha.js/sha.js-tests.ts @@ -0,0 +1,15 @@ +import shajs = require('sha.js'); + +shajs('sha256') + .update('42') + .digest('hex'); +new shajs.sha().update('42').digest('hex'); +new shajs.sha1().update('42').digest('hex'); +new shajs.sha224().update('42').digest('hex'); +new shajs.sha256().update('42').digest('hex'); +new shajs.sha384().update('42').digest('hex'); +new shajs.sha512().update('42').digest('hex'); + +const sha256stream = shajs('sha256'); +sha256stream.end('42'); +(sha256stream.read() as Buffer).toString('hex'); diff --git a/types/sha.js/tsconfig.json b/types/sha.js/tsconfig.json new file mode 100644 index 0000000000..9f10462f5a --- /dev/null +++ b/types/sha.js/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "sha.js-tests.ts" + ] +} diff --git a/types/sha.js/tslint.json b/types/sha.js/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/sha.js/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/sharepoint/sharepoint-tests.ts b/types/sharepoint/sharepoint-tests.ts index e76536cd18..d3bbe1f808 100644 --- a/types/sharepoint/sharepoint-tests.ts +++ b/types/sharepoint/sharepoint-tests.ts @@ -2038,7 +2038,7 @@ namespace _ { // do is retrieve a reference to the term set with the same ID as the div, and // then add the term that belong to that term set under the div that was clicked. - function showTerms(event: JQuery.Event, groupID: SP.Guid, termSetID: SP.Guid) { + function showTerms(event: JQuery.ClickEvent, groupID: SP.Guid, termSetID: SP.Guid) { // First, cancel the bubble so that the group div click handler does not also fire // because that removes all term set divs and we don't want that here. event.originalEvent.cancelBubble = true; diff --git a/types/shasum/index.d.ts b/types/shasum/index.d.ts new file mode 100644 index 0000000000..500c811d07 --- /dev/null +++ b/types/shasum/index.d.ts @@ -0,0 +1,14 @@ +// Type definitions for shasum 1.0 +// Project: https://github.com/dominictarr/shasum +// Definitions by: TeamworkGuy2 +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * Single function that return the sha1sum. Installing this is just a little bit quicker than reading the crypto documentation. + * var shasum = require('shasum') + * shasum(string || buffer || object) + * It also works in the browser with browserify. + */ +declare function shasum(str: any, alg?: string | null, format?: "hex" | "latin1" | "base64"): string; + +export = shasum; diff --git a/types/shasum/shasum-tests.ts b/types/shasum/shasum-tests.ts new file mode 100644 index 0000000000..01c0ba32fc --- /dev/null +++ b/types/shasum/shasum-tests.ts @@ -0,0 +1,7 @@ +import shasum = require("shasum"); + +function test(): string { + const res1 = shasum("source"); + const res2 = shasum({ prop: "source" }, null, "hex"); + return res1 || res2; +} diff --git a/types/shasum/tsconfig.json b/types/shasum/tsconfig.json new file mode 100644 index 0000000000..a0be2a9c4b --- /dev/null +++ b/types/shasum/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "shasum-tests.ts" + ] +} \ No newline at end of file diff --git a/types/shasum/tslint.json b/types/shasum/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/shasum/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/shelljs/make.d.ts b/types/shelljs/make.d.ts new file mode 100644 index 0000000000..ca4c2b6135 --- /dev/null +++ b/types/shelljs/make.d.ts @@ -0,0 +1,41 @@ +import * as shelljs from './'; +declare global { + interface Target { + (...args: any[]): void; + result?: any; + done?: boolean; + } + const target: { + all?: Target; + [s: string]: Target; + }; + const cd: typeof shelljs.cd; + const pwd: typeof shelljs.pwd; + const ls: typeof shelljs.ls; + const find: typeof shelljs.find; + const cp: typeof shelljs.cp; + const rm: typeof shelljs.rm; + const mv: typeof shelljs.mv; + const mkdir: typeof shelljs.mkdir; + const cat: typeof shelljs.cat; + const sed: typeof shelljs.sed; + const grep: typeof shelljs.grep; + const echo: typeof shelljs.echo; + const pushd: typeof shelljs.pushd; + const popd: typeof shelljs.popd; + const dirs: typeof shelljs.dirs; + const ln: typeof shelljs.ln; + const exit: typeof shelljs.exit; + const env: typeof shelljs.env; + const exec: typeof shelljs.exec; + const chmod: typeof shelljs.chmod; + const tempdir: typeof shelljs.tempdir; + const error: typeof shelljs.error; + const touch: typeof shelljs.touch; + const head: typeof shelljs.head; + const sort: typeof shelljs.sort; + const tail: typeof shelljs.tail; + const uniq: typeof shelljs.uniq; + const set: typeof shelljs.set; + const config: typeof shelljs.config; +} diff --git a/types/shelljs/tsconfig.json b/types/shelljs/tsconfig.json index 7343a42a7e..51937bc2c0 100644 --- a/types/shelljs/tsconfig.json +++ b/types/shelljs/tsconfig.json @@ -18,6 +18,7 @@ }, "files": [ "index.d.ts", + "make.d.ts", "shelljs-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/should-sinon/index.d.ts b/types/should-sinon/index.d.ts index 79b04d5092..6544a55253 100644 --- a/types/should-sinon/index.d.ts +++ b/types/should-sinon/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/shouldjs/sinon // Definitions by: AryloYeung // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 3.0 +// TypeScript Version: 2.8 import * as s from 'sinon'; import should = require('should'); diff --git a/types/simpl-schema/index.d.ts b/types/simpl-schema/index.d.ts new file mode 100644 index 0000000000..b09a8fde96 --- /dev/null +++ b/types/simpl-schema/index.d.ts @@ -0,0 +1,246 @@ +// Type definitions for simpl-schema 0.1 +// Project: https://github.com/aldeed/simple-schema-js +// Definitions by: Andreas Richter +// Qkramer +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export interface ValidationContext extends SimpleSchemaValidationContextStatic { + addValidationErrors(errors: any): void; + clean(...args: any[]): any; + getErrorForKey(key: any, ...args: any[]): any; + reset(): void; + setValidationErrors(errors: any): void; + validationErrors(): any; +} + +interface CustomValidationContext { + /** The name of the schema key (e.g., "addresses.0.street") */ + key: string; + + /** The generic name of the schema key (e.g., "addresses.$.street") */ + genericKey: string; + + /** The schema definition object. */ + definition: SchemaDefinition; + + /** Does the object being validated have this key set? */ + isSet: boolean; + + /** Value to validate */ + value: any; + + /** The Mongo operator for which we're doing validation. Might be null. */ + operator: any; + validationContext: ValidationContext; + + /** + * Use this method to get information about other fields. Pass a field name + * (non-generic schema key) as the only argument. The return object will + * have isSet, value, and operator properties for that field. + */ + field(): any; + /** + * Use this method to get information about other fields that have the same + * parent object. Works the same way as field(). This is helpful when you use + * sub-schemas or when you're dealing with arrays of objects. + */ + siblingField(): any; + + /** + * Call this to add validation errors for any key. In general, you should use + * this to add errors for other keys. To add an error for the current key, + * return the error type string. If you do use this to add an error for the + * current key, return false from your custom validation function. + */ + addValidationErrors(errors: SimpleSchemaValidationError): any; +} + +interface SchemaDefinition { + type: any; + label?: string | (() => string); + optional?: boolean | (() => boolean); + min?: number | boolean | Date | (() => number | boolean | Date); + max?: number | boolean | Date | (() => number | boolean | Date); + minCount?: number | (() => number); + maxCount?: number | (() => number); + allowedValues?: any[] | (() => any[]); + decimal?: boolean; + exclusiveMax?: boolean; + exclusiveMin?: boolean; + regEx?: RegExp | RegExp[]; + /** + * For custom validation function. If you use an arrow function the context + * for "this" will not be available. Use "custom: function() { return + * something(this.value); }" instead. + */ + custom?: (this: CustomValidationContext) => undefined | string | SimpleSchemaValidationError; + blackbox?: boolean; + autoValue?: () => any; + defaultValue?: any; + trim?: boolean; +} + +interface CleanOption { + filter?: boolean; + autoConvert?: boolean; + removeEmptyStrings?: boolean; + trimStrings?: boolean; + getAutoValues?: boolean; + isModifier?: boolean; + extendAutoValueContext?: boolean; + removeNullsFromArrays?: boolean; +} + +interface SimpleSchemaOptions { + check?: boolean; + clean?: CleanOption; + defaultLabel?: string; + humanizeAutoLabels?: boolean; + requiredByDefault?: boolean; + tracker?: any; +} + +interface SimpleSchemaValidationError { + type: string; + [key: string]: number | string; +} + +interface SimpleSchemaStatic { + new( + schema: { + [key: string]: SchemaDefinition + | BooleanConstructor | StringConstructor | NumberConstructor | DateConstructor + | ArrayConstructor + | string | RegExp + | SimpleSchema + } | any[], + options?: SimpleSchemaOptions + ): SimpleSchema; + namedContext(name?: string): SimpleSchemaValidationContextStatic; + addValidator(validator: () => boolean): any; + pick(...fields: string[]): SimpleSchemaStatic; + omit(...fields: string[]): SimpleSchemaStatic; + clean(doc: any, options?: CleanOption): any; + schema(key?: string): SchemaDefinition | SchemaDefinition[]; + getDefinition(key: string, propList?: any, functionContext?: any): any; + keyIsInBlackBox(key: string): boolean; + labels(labels: {[key: string]: string}): void; + label(key: any): any; + Integer: RegExp; + messages(messages: any): any; + messageForError(type: any, key: any, def: any, value: any): string; + allowsKey(key: any): string; + newContext(): ValidationContext; + objectKeys(keyPrefix: any): any[]; + validate(obj: any, options?: ValidationOption): void; + validator(options: ValidationOption): () => boolean; + RegEx: { + Email: RegExp; + EmailWithTLD: RegExp; + Domain: RegExp; + WeakDomain: RegExp; + IP: RegExp; + IPv4: RegExp; + IPv6: RegExp; + Url: RegExp; + Id: RegExp; + ZipCode: RegExp; + Phone: RegExp; + }; + ErrorTypes: { + REQUIRED: string, + MIN_STRING: string, + MAX_STRING: string, + MIN_NUMBER: string, + MAX_NUMBER: string, + MIN_NUMBER_EXCLUSIVE: string, + MAX_NUMBER_EXCLUSIVE: string, + MIN_DATE: string, + MAX_DATE: string, + BAD_DATE: string, + MIN_COUNT: string, + MAX_COUNT: string, + MUST_BE_INTEGER: string, + VALUE_NOT_ALLOWED: string, + EXPECTED_TYPE: string, + FAILED_REGULAR_EXPRESSION: string, + KEY_NOT_IN_SCHEMA: string + }; +} + +interface ValidationOption { + modifier?: boolean; + upsert?: boolean; + clean?: boolean; + filter?: boolean; + upsertextendedCustomContext?: boolean; + keys?: string[]; +} + +interface SimpleSchemaValidationContextStaticKeys { + name: string; + type: string; + value?: any; +} + +interface SimpleSchemaError { + name: string; + type: string; +} + +interface SimpleSchemaValidationContextStatic { + validate(obj: any, options?: ValidationOption): boolean; + validateOne(doc: any, keyName: string, options?: ValidationOption): boolean; + resetValidation(): void; + isValid(): boolean; + invalidKeys(): SimpleSchemaValidationContextStaticKeys[]; + addInvalidKeys(errors: SimpleSchemaError[]): void; + keyIsInvalid(name: any): boolean; + keyErrorMessage(name: any): string; + getErrorObject(): any; +} + +interface MongoObjectStatic { + forEachNode(func: (() => void), options?: {endPointsOnly: boolean}): void; + getValueForPosition(position: string): any; + setValueForPosition(position: string, value: any): void; + removeValueForPosition(position: string): void; + getKeyForPosition(position: string): any; + getGenericKeyForPosition(position: string): any; + getInfoForKey(key: string): any; + getPositionForKey(key: string): string; + getPositionsForGenericKey(key: string): string[]; + getValueForKey(key: string): any; + addKey(key: string, val: any, op: string): any; + removeGenericKeys(keys: string[]): void; + removeGenericKey(key: string): void; + removeKey(key: string): void; + removeKeys(keys: string[]): void; + filterGenericKeys(test: (() => boolean)): void; + setValueForKey(key: string, val: any): void; + setValueForGenericKey(key: string, val: any): void; + getObject(): any; + getFlatObject(options?: {keepArrays?: boolean}): any; + affectsKey(key: string): any; + affectsGenericKey(key: string): any; + affectsGenericKeyImplicit(key: string): any; +} + +export const SimpleSchema: SimpleSchemaStatic; +export const SimpleSchemaValidationContext: SimpleSchemaValidationContextStatic; +export const MongoObject: MongoObjectStatic; + +export interface SimpleSchema extends SimpleSchemaStatic { + debug: boolean; + /** Validate a data object. Options: {keys: []} to limit */ + validate(obj: any, options?: ValidationOption): void; + addValidator(validator: () => boolean): any; + extendOptions(options: {[key: string]: any}): void; + messages(messages: any): void; +} + +export interface MongoObject { + expandKey(val: any, key: string, obj: any): void; +} + +export default SimpleSchema; diff --git a/types/simpl-schema/simpl-schema-tests.ts b/types/simpl-schema/simpl-schema-tests.ts new file mode 100644 index 0000000000..a3555c4428 --- /dev/null +++ b/types/simpl-schema/simpl-schema-tests.ts @@ -0,0 +1,77 @@ +import SimpleSchema from 'simpl-schema'; + +const StringSchema = new SimpleSchema({ + basicString: { + type: String + }, + limitedString: { + type: String, + allowedValues: ['pro', 'con'] + }, + regExpString: { + type: String, + regEx: SimpleSchema.RegEx.Id + }, + createdAt: { + type: Date, + autoValue: () => new Date() + }, + title: { + type: String, + label: "Title", + /* Can't use arrow function here, else the context won't be available */ + custom: function() { + const text = this.value; + + if (text.length > 100) return { type: SimpleSchema.ErrorTypes.MAX_STRING, max: 100 }; + else if (text.length < 10) return SimpleSchema.ErrorTypes.MIN_STRING; + } + } +}); + +StringSchema.validate({ + basicString: "Test", + limitedString: "pro", + regExpString: "id" +}, {keys: ['basicString']}); + +const StringSchemaWithOptions = new SimpleSchema({ + basicString: { + type: String + }, + limitedString: { + type: String, + allowedValues: ['pro', 'con'] + }, + subschema: { + type: StringSchema + }, + userId: { + type: String, + regEx: SimpleSchema.RegEx.Id + }, + createdAt: { + type: Date, + autoValue: () => new Date(), + }, +}, +{ + clean: { + filter: true, + autoConvert: true, + removeEmptyStrings: true, + trimStrings: true, + getAutoValues: true, + removeNullsFromArrays: true, + } +}); + +new SimpleSchema({ + shortBoolean: Boolean, + shortString: String, + shortNumber: Number, + shortInteger: SimpleSchema.Integer, + shortDate: Date, + shortArray: Array, + subSchema: StringSchemaWithOptions +}); diff --git a/types/simpl-schema/tsconfig.json b/types/simpl-schema/tsconfig.json new file mode 100644 index 0000000000..d079496f4e --- /dev/null +++ b/types/simpl-schema/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "simpl-schema-tests.ts" + ] +} diff --git a/types/simpl-schema/tslint.json b/types/simpl-schema/tslint.json new file mode 100644 index 0000000000..3043773b06 --- /dev/null +++ b/types/simpl-schema/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "object-literal-shorthand": false + } +} diff --git a/types/sindresorhus__class-names/index.d.ts b/types/sindresorhus__class-names/index.d.ts new file mode 100644 index 0000000000..fbb81c48c6 --- /dev/null +++ b/types/sindresorhus__class-names/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for @sindresorhus/class-names 1.0 +// Project: https://github.com/sindresorhus/class-names +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = classNames; + +declare function classNames(...input: any[]): string; diff --git a/types/sindresorhus__class-names/sindresorhus__class-names-tests.ts b/types/sindresorhus__class-names/sindresorhus__class-names-tests.ts new file mode 100644 index 0000000000..d8627cb705 --- /dev/null +++ b/types/sindresorhus__class-names/sindresorhus__class-names-tests.ts @@ -0,0 +1,25 @@ +import classNames = require('@sindresorhus/class-names'); + +// $ExpectType string +classNames('unicorn', 'rainbow'); +// $ExpectType string +classNames({ awesome: true, foo: false }, 'unicorn', { rainbow: false }); +// $ExpectType string +classNames('unicorn', null, undefined, 0, 1, { foo: null }); + +const buttonType = 'main'; +// $ExpectType string +classNames({ [`button-${buttonType}`]: true }); + +const props = { + type: 'success', + small: true, + block: undefined, +}; + +// $ExpectType string +classNames('button', { + [`button-${props.type}`]: props.type, + 'button-block': props.block, + 'button-small': props.small, +}); diff --git a/types/sindresorhus__class-names/tsconfig.json b/types/sindresorhus__class-names/tsconfig.json new file mode 100644 index 0000000000..a0b866ebdf --- /dev/null +++ b/types/sindresorhus__class-names/tsconfig.json @@ -0,0 +1,28 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "paths": { + "@sindresorhus/class-names": [ + "sindresorhus__class-names" + ] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "sindresorhus__class-names-tests.ts" + ] +} diff --git a/types/sindresorhus__class-names/tslint.json b/types/sindresorhus__class-names/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/sindresorhus__class-names/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/sindresorhus__to-milliseconds/index.d.ts b/types/sindresorhus__to-milliseconds/index.d.ts new file mode 100644 index 0000000000..8eb44b2a7b --- /dev/null +++ b/types/sindresorhus__to-milliseconds/index.d.ts @@ -0,0 +1,20 @@ +// Type definitions for @sindresorhus/to-milliseconds 1.0 +// Project: https://github.com/sindresorhus/to-milliseconds +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = toMilliseconds; + +declare function toMilliseconds(input: toMilliseconds.TimeSpec): number; + +declare namespace toMilliseconds { + interface TimeSpec { + days?: number; + hours?: number; + minutes?: number; + seconds?: number; + milliseconds?: number; + microseconds?: number; + nanoseconds?: number; + } +} diff --git a/types/sindresorhus__to-milliseconds/sindresorhus__to-milliseconds-tests.ts b/types/sindresorhus__to-milliseconds/sindresorhus__to-milliseconds-tests.ts new file mode 100644 index 0000000000..aff7ba6fe0 --- /dev/null +++ b/types/sindresorhus__to-milliseconds/sindresorhus__to-milliseconds-tests.ts @@ -0,0 +1,24 @@ +import toMilliseconds = require('@sindresorhus/to-milliseconds'); + +// $ExpectType number +toMilliseconds({ + days: 15, +}); +toMilliseconds({ + hours: 11, +}); +toMilliseconds({ + minutes: 23, +}); +toMilliseconds({ + seconds: 20, +}); +toMilliseconds({ + milliseconds: 1, +}); +toMilliseconds({ + microseconds: 1, +}); +toMilliseconds({ + nanoseconds: 1, +}); diff --git a/types/sindresorhus__to-milliseconds/tsconfig.json b/types/sindresorhus__to-milliseconds/tsconfig.json new file mode 100644 index 0000000000..be9b1a9bec --- /dev/null +++ b/types/sindresorhus__to-milliseconds/tsconfig.json @@ -0,0 +1,28 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "paths": { + "@sindresorhus/to-milliseconds": [ + "sindresorhus__to-milliseconds" + ] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "sindresorhus__to-milliseconds-tests.ts" + ] +} diff --git a/types/sindresorhus__to-milliseconds/tslint.json b/types/sindresorhus__to-milliseconds/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/sindresorhus__to-milliseconds/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/sinon-as-promised/index.d.ts b/types/sinon-as-promised/index.d.ts index 5e2e06ed83..5187168d61 100644 --- a/types/sinon-as-promised/index.d.ts +++ b/types/sinon-as-promised/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/bendrucker/sinon-as-promised // Definitions by: igrayson // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 3.0 +// TypeScript Version: 2.8 import * as s from "sinon"; diff --git a/types/sinon-chai/index.d.ts b/types/sinon-chai/index.d.ts index 6a0901eb8c..ad7c8cb857 100644 --- a/types/sinon-chai/index.d.ts +++ b/types/sinon-chai/index.d.ts @@ -4,7 +4,7 @@ // Jed Mao // Eyal Lapid // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 3.0 +// TypeScript Version: 2.8 /// /// diff --git a/types/sinon-chai/v2/index.d.ts b/types/sinon-chai/v2/index.d.ts index 8a03ea671c..cff6d0b3a2 100644 --- a/types/sinon-chai/v2/index.d.ts +++ b/types/sinon-chai/v2/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/domenic/sinon-chai // Definitions by: Kazi Manzur Rashid , Jed Mao // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 3.0 +// TypeScript Version: 2.8 /// /// diff --git a/types/sinon-chrome/index.d.ts b/types/sinon-chrome/index.d.ts index eec9604dec..c25273d757 100644 --- a/types/sinon-chrome/index.d.ts +++ b/types/sinon-chrome/index.d.ts @@ -4,7 +4,7 @@ // CRIMX // kobanyan // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 3.0 +// TypeScript Version: 2.8 /// /// diff --git a/types/sinon-express-mock/index.d.ts b/types/sinon-express-mock/index.d.ts index 84454048cd..f3974fc005 100644 --- a/types/sinon-express-mock/index.d.ts +++ b/types/sinon-express-mock/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Jared Chapiewsky // Tomek Łaziuk // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 3.0 +// TypeScript Version: 2.8 import { SinonStub, diff --git a/types/sinon-mongoose/index.d.ts b/types/sinon-mongoose/index.d.ts index f725965349..86109b4917 100644 --- a/types/sinon-mongoose/index.d.ts +++ b/types/sinon-mongoose/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/underscopeio/sinon-mongoose // Definitions by: stevehipwell // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 3.0 +// TypeScript Version: 2.8 import * as s from "sinon"; diff --git a/types/sinon-stub-promise/index.d.ts b/types/sinon-stub-promise/index.d.ts index 298eed87c0..d817113cf7 100644 --- a/types/sinon-stub-promise/index.d.ts +++ b/types/sinon-stub-promise/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Thiago Temple // Tim Stackhouse // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 3.0 +// TypeScript Version: 2.8 /// diff --git a/types/sinon-test/index.d.ts b/types/sinon-test/index.d.ts index 63318554ae..902064a7cb 100644 --- a/types/sinon-test/index.d.ts +++ b/types/sinon-test/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/sinonjs/sinon-test // Definitions by: Francis Saul // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 3.0 +// TypeScript Version: 2.8 import * as Sinon from 'sinon'; diff --git a/types/sinon/index.d.ts b/types/sinon/index.d.ts index b5c3952e7a..bc265d6718 100644 --- a/types/sinon/index.d.ts +++ b/types/sinon/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Sinon 5.0 +// Type definitions for Sinon 7.0 // Project: http://sinonjs.org/ // Definitions by: William Sears // Jonathan Little @@ -9,21 +9,21 @@ // Greg Jednaszewski // John Wood // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 3.0 +// TypeScript Version: 2.8 // sinon uses DOM dependencies which are absent in browser-less environment like node.js // to avoid compiler errors this monkey patch is used // see more details in https://github.com/DefinitelyTyped/DefinitelyTyped/issues/11351 -interface Event {} // tslint:disable-line no-empty-interface -interface Document {} // tslint:disable-line no-empty-interface +interface Event { } // tslint:disable-line no-empty-interface +interface Document { } // tslint:disable-line no-empty-interface declare namespace Sinon { - interface SinonSpyCallApi { + interface SinonSpyCallApi { // Properties /** * Array of received arguments. */ - args: TArgs; + args: any[]; // Methods /** @@ -38,11 +38,11 @@ declare namespace Sinon { * so a call that received the provided arguments (in the same spots) and possibly others as well will return true. * @param args */ - calledWith(...args: TArgs): boolean; + calledWith(...args: any[]): boolean; /** * Returns true if spy was called at least once with the provided arguments and no others. */ - calledWithExactly(...args: TArgs): boolean; + calledWithExactly(...args: any[]): boolean; /** * Returns true if spy/stub was called the new operator. * Beware that this is inferred based on the value of the this object and the spy function’s prototype, @@ -53,31 +53,31 @@ declare namespace Sinon { * Returns true if spy was called at exactly once with the provided arguments. * @param args */ - calledOnceWith(...args: TArgs): boolean; - calledOnceWithExactly(...args: TArgs): boolean; + calledOnceWith(...args: any[]): boolean; + calledOnceWithExactly(...args: any[]): boolean; /** * Returns true if spy was called with matching arguments (and possibly others). * This behaves the same as spy.calledWith(sinon.match(arg1), sinon.match(arg2), ...). * @param args */ - calledWithMatch(...args: TArgs): boolean; + calledWithMatch(...args: any[]): boolean; /** * Returns true if call did not receive provided arguments. * @param args */ - notCalledWith(...args: TArgs): boolean; + notCalledWith(...args: any[]): boolean; /** * Returns true if call did not receive matching arguments. * This behaves the same as spyCall.notCalledWith(sinon.match(arg1), sinon.match(arg2), ...). * @param args */ - notCalledWithMatch(...args: TArgs): boolean; + notCalledWithMatch(...args: any[]): boolean; /** * Returns true if spy returned the provided value at least once. * Uses deep comparison for objects and arrays. Use spy.returned(sinon.match.same(obj)) for strict comparison (see matchers). * @param value */ - returned(value: TReturnValue): boolean; + returned(value: any): boolean; /** * Returns true if spy threw an exception at least once. */ @@ -118,8 +118,7 @@ declare namespace Sinon { yieldToOn(property: string, obj: any, ...args: any[]): void; } - interface SinonSpyCall - extends SinonSpyCallApi { + interface SinonSpyCall extends SinonSpyCallApi { /** * The call’s this value. */ @@ -131,7 +130,7 @@ declare namespace Sinon { /** * Return value. */ - returnValue: TReturnValue; + returnValue: any; /** * This property is a convenience for a call’s callback. * When the last argument in a call is a Function, then callback will reference that. Otherwise it will be undefined. @@ -154,11 +153,7 @@ declare namespace Sinon { calledAfter(call: SinonSpyCall): boolean; } - interface SinonSpy - extends Pick< - SinonSpyCallApi, - Exclude, 'args'> - > { + interface SinonSpy extends SinonSpyCallApi { // Properties /** * The number of recorded calls. @@ -187,19 +182,19 @@ declare namespace Sinon { /** * The first call */ - firstCall: SinonSpyCall; + firstCall: SinonSpyCall; /** * The second call */ - secondCall: SinonSpyCall; + secondCall: SinonSpyCall; /** * The third call */ - thirdCall: SinonSpyCall; + thirdCall: SinonSpyCall; /** * The last call */ - lastCall: SinonSpyCall; + lastCall: SinonSpyCall; /** * Array of this objects, spy.thisValues[0] is the this object for the first call. */ @@ -207,7 +202,7 @@ declare namespace Sinon { /** * Array of arguments received, spy.args[0] is an array of arguments received in the first call. */ - args: TArgs[]; + args: any[][]; /** * Array of exception objects thrown, spy.exceptions[0] is the exception thrown by the first call. * If the call did not throw an error, the value at the call’s location in .exceptions will be undefined. @@ -217,7 +212,7 @@ declare namespace Sinon { * Array of return values, spy.returnValues[0] is the return value of the first call. * If the call did not explicitly return a value, the value at the call’s location in .returnValues will be undefined. */ - returnValues: TReturnValue[]; + returnValues: any[]; // Methods (...args: any[]): any; @@ -246,7 +241,7 @@ declare namespace Sinon { * This is useful to be more expressive in your assertions, where you can access the spy with the same call. * @param args Expected args */ - withArgs(...args: TArgs): SinonSpy; + withArgs(...args: any[]): SinonSpy; /** * Returns true if the spy was always called with @param obj as this. * @param obj @@ -255,29 +250,29 @@ declare namespace Sinon { /** * Returns true if spy was always called with the provided arguments (and possibly others). */ - alwaysCalledWith(...args: TArgs): boolean; + alwaysCalledWith(...args: any[]): boolean; /** * Returns true if spy was always called with the exact provided arguments. * @param args */ - alwaysCalledWithExactly(...args: TArgs): boolean; + alwaysCalledWithExactly(...args: any[]): boolean; /** * Returns true if spy was always called with matching arguments (and possibly others). * This behaves the same as spy.alwaysCalledWith(sinon.match(arg1), sinon.match(arg2), ...). * @param args */ - alwaysCalledWithMatch(...args: TArgs): boolean; + alwaysCalledWithMatch(...args: any[]): boolean; /** * Returns true if the spy/stub was never called with the provided arguments. * @param args */ - neverCalledWith(...args: TArgs): boolean; + neverCalledWith(...args: any[]): boolean; /** * Returns true if the spy/stub was never called with matching arguments. * This behaves the same as spy.neverCalledWith(sinon.match(arg1), sinon.match(arg2), ...). * @param args */ - neverCalledWithMatch(...args: TArgs): boolean; + neverCalledWithMatch(...args: any[]): boolean; /** * Returns true if spy always threw an exception. */ @@ -300,22 +295,22 @@ declare namespace Sinon { * If the stub was never called with a function argument, yield throws an error. * Returns an Array with all callbacks return values in the order they were called, if no error is thrown. */ - invokeCallback(...args: TArgs): void; + invokeCallback(...args: any[]): void; /** * Set the displayName of the spy or stub. * @param name */ - named(name: string): SinonSpy; + named(name: string): SinonSpy; /** * Returns the nth call. * Accessing individual calls helps with more detailed behavior verification when the spy is called more than once. * @param n */ - getCall(n: number): SinonSpyCall; + getCall(n: number): SinonSpyCall; /** * Returns an Array of all calls recorded by the spy. */ - getCalls(): Array>; + getCalls(): SinonSpyCall[]; /** * Resets the state of a spy. */ @@ -355,15 +350,10 @@ declare namespace Sinon { * The original method can be restored by calling object.method.restore(). * The returned spy is the function object which replaced the original method. spy === object.method. */ - (obj: T, method: K): T[K] extends ( - ...args: infer TArgs - ) => infer TReturnValue - ? SinonSpy - : SinonSpy; + (obj: T, method: keyof T): SinonSpy; } - interface SinonStub - extends SinonSpy { + interface SinonStub extends SinonSpy { /** * Resets the stub’s behaviour to the default behaviour * You can reset behaviour of all stubs using sinon.resetBehavior() @@ -381,13 +371,13 @@ declare namespace Sinon { * Causes the stub to return promises using a specific Promise library instead of the global one when using stub.rejects or stub.resolves. * Returns the stub to allow chaining. */ - usingPromise(promiseLibrary: any): SinonStub; + usingPromise(promiseLibrary: any): SinonStub; /** * Makes the stub return the provided @param obj value. * @param obj */ - returns(obj: TReturnValue): SinonStub; + returns(obj: any): SinonStub; /** * Causes the stub to return the argument at the provided @param index. * stub.returnsArg(0); causes the stub to return the first argument. @@ -395,12 +385,12 @@ declare namespace Sinon { * starting from sinon@6.1.2, a TypeError will be thrown. * @param index */ - returnsArg(index: number): SinonStub; + returnsArg(index: number): SinonStub; /** * Causes the stub to return its this value. * Useful for stubbing jQuery-style fluent APIs. */ - returnsThis(): SinonStub; + returnsThis(): SinonStub; /** * Causes the stub to return a Promise which resolves to the provided value. * When constructing the Promise, sinon uses the Promise.resolve method. @@ -408,26 +398,26 @@ declare namespace Sinon { * The Promise library can be overwritten using the usingPromise method. * Since sinon@2.0.0 */ - resolves(value?: any): SinonStub; + resolves(value?: any): SinonStub; /** * Causes the stub to return a Promise which resolves to the argument at the provided index. * stub.resolvesArg(0); causes the stub to return a Promise which resolves to the first argument. * If the argument at the provided index is not available, a TypeError will be thrown. */ - resolvesArg(index: number): SinonStub; + resolvesArg(index: number): SinonStub; /** * Causes the stub to return a Promise which resolves to its this value. */ - resolvesThis(): SinonStub; + resolvesThis(): SinonStub; /** * Causes the stub to throw an exception (Error). * @param type */ - throws(type?: string): SinonStub; + throws(type?: string): SinonStub; /** * Causes the stub to throw the provided exception object. */ - throws(obj: any): SinonStub; + throws(obj: any): SinonStub; /** * Causes the stub to throw the argument at the provided index. * stub.throwsArg(0); causes the stub to throw the first argument as the exception. @@ -435,9 +425,9 @@ declare namespace Sinon { * Since sinon@2.3.0 * @param index */ - throwsArg(index: number): SinonStub; - throwsException(type?: string): SinonStub; - throwsException(obj: any): SinonStub; + throwsArg(index: number): SinonStub; + throwsException(type?: string): SinonStub; + throwsException(obj: any): SinonStub; /** * Causes the stub to return a Promise which rejects with an exception (Error). * When constructing the Promise, sinon uses the Promise.reject method. @@ -445,57 +435,53 @@ declare namespace Sinon { * The Promise library can be overwritten using the usingPromise method. * Since sinon@2.0.0 */ - rejects(): SinonStub; + rejects(): SinonStub; /** * Causes the stub to return a Promise which rejects with an exception of the provided type. * Since sinon@2.0.0 */ - rejects(errorType: string): SinonStub; + rejects(errorType: string): SinonStub; /** * Causes the stub to return a Promise which rejects with the provided exception object. * Since sinon@2.0.0 */ - rejects(value: any): SinonStub; + rejects(value: any): SinonStub; /** * Causes the stub to call the argument at the provided index as a callback function. * stub.callsArg(0); causes the stub to call the first argument as a callback. * If the argument at the provided index is not available or is not a function, a TypeError will be thrown. */ - callsArg(index: number): SinonStub; + callsArg(index: number): SinonStub; /** * Causes the original method wrapped into the stub to be called when none of the conditional stubs are matched. */ - callThrough(): SinonStub; + callThrough(): SinonStub; /** * Like stub.callsArg(index); but with an additional parameter to pass the this context. * @param index * @param context */ - callsArgOn(index: number, context: any): SinonStub; + callsArgOn(index: number, context: any): SinonStub; /** * Like callsArg, but with arguments to pass to the callback. * @param index * @param args */ - callsArgWith(index: number, ...args: any[]): SinonStub; + callsArgWith(index: number, ...args: any[]): SinonStub; /** * Like above but with an additional parameter to pass the this context. * @param index * @param context * @param args */ - callsArgOnWith( - index: number, - context: any, - ...args: any[] - ): SinonStub; + callsArgOnWith(index: number, context: any, ...args: any[]): SinonStub; /** * Same as their corresponding non-Async counterparts, but with callback being deferred at called after all instructions in the current call stack are processed. * In Node environment the callback is deferred with process.nextTick. * In a browser the callback is deferred with setTimeout(callback, 0). * @param index */ - callsArgAsync(index: number): SinonStub; + callsArgAsync(index: number): SinonStub; /** * Same as their corresponding non-Async counterparts, but with callback being deferred at called after all instructions in the current call stack are processed. * In Node environment the callback is deferred with process.nextTick. @@ -503,99 +489,91 @@ declare namespace Sinon { * @param index * @param context */ - callsArgOnAsync(index: number, context: any): SinonStub; + callsArgOnAsync(index: number, context: any): SinonStub; /** * Same as their corresponding non-Async counterparts, but with callback being deferred at called after all instructions in the current call stack are processed. * In Node environment the callback is deferred with process.nextTick. * In a browser the callback is deferred with setTimeout(callback, 0). */ - callsArgWithAsync(index: number, ...args: any[]): SinonStub; + callsArgWithAsync(index: number, ...args: any[]): SinonStub; /** * Same as their corresponding non-Async counterparts, but with callback being deferred at called after all instructions in the current call stack are processed. * In Node environment the callback is deferred with process.nextTick. * In a browser the callback is deferred with setTimeout(callback, 0). */ - callsArgOnWithAsync( - index: number, - context: any, - ...args: any[] - ): SinonStub; + callsArgOnWithAsync(index: number, context: any, ...args: any[]): SinonStub; /** * Makes the stub call the provided @param func when invoked. * @param func */ - callsFake(func: (...args: TArgs) => TReturnValue): SinonStub; + callsFake(func: (...args: any[]) => any): SinonStub; /** * Replaces a new getter for this stub. */ - get(func: () => any): SinonStub; + get(func: () => any): SinonStub; /** * Defines a new setter for this stub. * @param func */ - set(func: (v: any) => void): SinonStub; + set(func: (v: any) => void): SinonStub; /** * Defines the behavior of the stub on the @param n call. Useful for testing sequential interactions. * There are methods onFirstCall, onSecondCall,onThirdCall to make stub definitions read more naturally. * onCall can be combined with all of the behavior defining methods in this section. In particular, it can be used together with withArgs. * @param n */ - onCall(n: number): SinonStub; + onCall(n: number): SinonStub; /** * Alias for stub.onCall(0); */ - onFirstCall(): SinonStub; + onFirstCall(): SinonStub; /** * Alias for stub.onCall(1); */ - onSecondCall(): SinonStub; + onSecondCall(): SinonStub; /** * Alias for stub.onCall(2); */ - onThirdCall(): SinonStub; + onThirdCall(): SinonStub; /** * Defines a new value for this stub. * @param val */ - value(val: any): SinonStub; + value(val: any): SinonStub; /** * Set the displayName of the spy or stub. * @param name */ - named(name: string): SinonStub; + named(name: string): SinonStub; /** * Similar to callsArg. * Causes the stub to call the first callback it receives with the provided arguments (if any). * If a method accepts more than one callback, you need to use callsArg to have the stub invoke other callbacks than the first one. */ - yields(...args: any[]): SinonStub; + yields(...args: any[]): SinonStub; /** * Like above but with an additional parameter to pass the this context. */ - yieldsOn(context: any, ...args: any[]): SinonStub; - yieldsRight(...args: any[]): SinonStub; + yieldsOn(context: any, ...args: any[]): SinonStub; + yieldsRight(...args: any[]): SinonStub; /** * Causes the spy to invoke a callback passed as a property of an object to the spy. * Like yields, yieldsTo grabs the first matching argument, finds the callback and calls it with the (optional) arguments. * @param property * @param args */ - yieldsTo(property: string, ...args: any[]): SinonStub; + yieldsTo(property: string, ...args: any[]): SinonStub; /** * Like above but with an additional parameter to pass the this context. */ - yieldsToOn( - property: string, - context: any, - ...args: any[] - ): SinonStub; + yieldsToOn(property: string, context: any, ...args: any[]): SinonStub; /** * Same as their corresponding non-Async counterparts, but with callback being deferred at called after all instructions in the current call stack are processed. * In Node environment the callback is deferred with process.nextTick. * In a browser the callback is deferred with setTimeout(callback, 0). * @param args */ - yieldsAsync(...args: any[]): SinonStub; + yieldsAsync(...args: any[]): SinonStub; /** * Same as their corresponding non-Async counterparts, but with callback being deferred at called after all instructions in the current call stack are processed. * In Node environment the callback is deferred with process.nextTick. @@ -603,7 +581,7 @@ declare namespace Sinon { * @param context * @param args */ - yieldsOnAsync(context: any, ...args: any[]): SinonStub; + yieldsOnAsync(context: any, ...args: any[]): SinonStub; /** * Same as their corresponding non-Async counterparts, but with callback being deferred at called after all instructions in the current call stack are processed. * In Node environment the callback is deferred with process.nextTick. @@ -611,7 +589,7 @@ declare namespace Sinon { * @param property * @param args */ - yieldsToAsync(property: string, ...args: any[]): SinonStub; + yieldsToAsync(property: string, ...args: any[]): SinonStub; /** * Same as their corresponding non-Async counterparts, but with callback being deferred at called after all instructions in the current call stack are processed. * In Node environment the callback is deferred with process.nextTick. @@ -620,18 +598,14 @@ declare namespace Sinon { * @param context * @param args */ - yieldsToOnAsync( - property: string, - context: any, - ...args: any[] - ): SinonStub; + yieldsToOnAsync(property: string, context: any, ...args: any[]): SinonStub; /** * Stubs the method only for the provided arguments. * This is useful to be more expressive in your assertions, where you can access the spy with the same call. * It is also useful to create a stub that can act differently in response to different arguments. * @param args */ - withArgs(...args: TArgs): SinonStub; + withArgs(...args: any[]): SinonStub; } interface SinonStubStatic { @@ -651,11 +625,7 @@ declare namespace Sinon { * An exception is thrown if the property is not already a function. * The original function can be restored by calling object.method.restore(); (or stub.restore();). */ - (obj: T, method: K): T[K] extends ( - ...args: infer TArgs - ) => infer TReturnValue - ? SinonStub - : SinonStub; + (obj: T, method: keyof T): SinonStub; } interface SinonExpectation extends SinonStub { @@ -757,22 +727,11 @@ declare namespace Sinon { interface SinonFakeTimers { now: number; - setTimeout( - callback: (...args: any[]) => void, - timeout: number, - ...args: any[] - ): SinonTimerId; + setTimeout(callback: (...args: any[]) => void, timeout: number, ...args: any[]): SinonTimerId; clearTimeout(id: SinonTimerId): void; - setInterval( - callback: (...args: any[]) => void, - timeout: number, - ...args: any[] - ): SinonTimerId; + setInterval(callback: (...args: any[]) => void, timeout: number, ...args: any[]): SinonTimerId; clearInterval(id: SinonTimerId): void; - setImmediate( - callback: (...args: any[]) => void, - ...args: any[] - ): SinonTimerId; + setImmediate(callback: (...args: any[]) => void, ...args: any[]): SinonTimerId; clearImmediate(id: SinonTimerId): void; requestAnimationFrame(callback: (...args: any[]) => void): number; cancelAnimationFrame(id: number): void; @@ -806,30 +765,9 @@ declare namespace Sinon { Date(year: number, month: number): Date; Date(year: number, month: number, day: number): Date; Date(year: number, month: number, day: number, hour: number): Date; - Date( - year: number, - month: number, - day: number, - hour: number, - minute: number - ): Date; - Date( - year: number, - month: number, - day: number, - hour: number, - minute: number, - second: number - ): Date; - Date( - year: number, - month: number, - day: number, - hour: number, - minute: number, - second: number, - ms: number - ): Date; + Date(year: number, month: number, day: number, hour: number, minute: number): Date; + Date(year: number, month: number, day: number, hour: number, minute: number, second: number): Date; + Date(year: number, month: number, day: number, hour: number, minute: number, second: number, ms: number): Date; /** * Restore the faked methods. @@ -950,7 +888,7 @@ declare namespace Sinon { } interface SinonFakeXMLHttpRequestStatic { - new (): SinonFakeXMLHttpRequest; + new(): SinonFakeXMLHttpRequest; /** * Default false. * When set to true, Sinon will check added filters if certain requests should be “unfaked” @@ -962,15 +900,7 @@ declare namespace Sinon { * If the filter returns true, the request will not be faked. * @param filter */ - addFilter( - filter: ( - method: string, - url: string, - async: boolean, - username: string, - password: string - ) => boolean - ): void; + addFilter(filter: (method: string, url: string, async: boolean, username: string, password: string) => boolean): void; /** * By assigning a function to the onCreate property of the returned object from useFakeXMLHttpRequest() * you can subscribe to newly created FakeXMLHttpRequest objects. See below for the fake xhr object API. @@ -1036,10 +966,7 @@ declare namespace Sinon { /** * Responds to all requests to given URL, e.g. /posts/1. */ - respondWith( - url: string, - fn: (xhr: SinonFakeXMLHttpRequest) => void - ): void; + respondWith(url: string, fn: (xhr: SinonFakeXMLHttpRequest) => void): void; /** * Responds to all method requests to the given URL with the given response. * method is an HTTP verb. @@ -1054,11 +981,7 @@ declare namespace Sinon { * Responds to all method requests to the given URL with the given response. * method is an HTTP verb. */ - respondWith( - method: string, - url: string, - fn: (xhr: SinonFakeXMLHttpRequest) => void - ): void; + respondWith(method: string, url: string, fn: (xhr: SinonFakeXMLHttpRequest) => void): void; /** * URL may be a regular expression, e.g. /\\/post\\//\\d+ * If the response is a Function, it will be passed any capture groups from the regular expression along with the XMLHttpRequest object: @@ -1073,10 +996,7 @@ declare namespace Sinon { * URL may be a regular expression, e.g. /\\/post\\//\\d+ * If the response is a Function, it will be passed any capture groups from the regular expression along with the XMLHttpRequest object: */ - respondWith( - url: RegExp, - fn: (xhr: SinonFakeXMLHttpRequest) => void - ): void; + respondWith(url: RegExp, fn: (xhr: SinonFakeXMLHttpRequest) => void): void; /** * Responds to all method requests to URLs matching the regular expression. */ @@ -1088,11 +1008,7 @@ declare namespace Sinon { /** * Responds to all method requests to URLs matching the regular expression. */ - respondWith( - method: string, - url: RegExp, - fn: (xhr: SinonFakeXMLHttpRequest) => void - ): void; + respondWith(method: string, url: RegExp, fn: (xhr: SinonFakeXMLHttpRequest) => void): void; /** * Causes all queued asynchronous requests to receive a response. * If none of the responses added through respondWith match, the default response is [404, {}, ""]. @@ -1221,10 +1137,7 @@ declare namespace Sinon { * @param spyOrSpyCall * @param args */ - calledWithExactly( - spyOrSpyCall: SinonSpy | SinonSpyCall, - ...args: any[] - ): void; + calledWithExactly(spyOrSpyCall: SinonSpy | SinonSpyCall, ...args: any[]): void; /** * Passes if spy was always called with the provided arguments and no others. */ @@ -1234,10 +1147,7 @@ declare namespace Sinon { * This behaves the same way as sinon.assert.calledWith(spy, sinon.match(arg1), sinon.match(arg2), ...). * It’s possible to assert on a dedicated spy call: sinon.assert.calledWithMatch(spy.secondCall, arg1, arg2, ...);. */ - calledWithMatch( - spyOrSpyCall: SinonSpy | SinonSpyCall, - ...args: any[] - ): void; + calledWithMatch(spyOrSpyCall: SinonSpy | SinonSpyCall, ...args: any[]): void; /** * Passes if spy was always called with matching arguments. * This behaves the same way as sinon.assert.alwaysCalledWith(spy, sinon.match(arg1), sinon.match(arg2), ...). @@ -1529,7 +1439,7 @@ declare namespace Sinon { * @template TType Object type being stubbed. */ type SinonStubbedInstance = { - [P in keyof TType]: SinonStubbedMember + [P in keyof TType]: SinonStubbedMember; }; /** @@ -1619,9 +1529,7 @@ declare namespace Sinon { * You would have to call either clock.next(), clock.tick(), clock.runAll() or clock.runToLast() (see example below). Please refer to the lolex documentation for more information. * @param config */ - useFakeTimers( - config?: number | Date | Partial - ): SinonFakeTimers; + useFakeTimers(config?: number | Date | Partial): SinonFakeTimers; /** * Causes Sinon to replace the native XMLHttpRequest object in browsers that support it with a custom implementation which does not send actual requests. * In browsers that support ActiveXObject, this constructor is replaced, and fake objects are returned for XMLHTTP progIds. @@ -1675,8 +1583,7 @@ declare namespace Sinon { replace( obj: T, prop: TKey, - replacement: T[TKey] - ): T[TKey]; + replacement: T[TKey]): T[TKey]; /** * Replaces getter for property on object with replacement argument. Attempts to replace an already replaced getter cause an exception. * replacement must be a Function, and can be instances of spies, stubs and fakes. @@ -1687,8 +1594,7 @@ declare namespace Sinon { replaceGetter( obj: T, prop: TKey, - replacement: () => T[TKey] - ): () => T[TKey]; + replacement: () => T[TKey]): () => T[TKey]; /** * Replaces setter for property on object with replacement argument. Attempts to replace an already replaced setter cause an exception. * replacement must be a Function, and can be instances of spies, stubs and fakes. @@ -1699,8 +1605,7 @@ declare namespace Sinon { replaceSetter( obj: T, prop: TKey, - replacement: (val: T[TKey]) => void - ): (val: T[TKey]) => void; + replacement: (val: T[TKey]) => void): (val: T[TKey]) => void; /** * Creates a new object with the given functions as the prototype and stubs all implemented functions. @@ -1710,9 +1615,7 @@ declare namespace Sinon { * @returns A stubbed version of the constructor. * @remarks The given constructor function is not invoked. See also the stub API. */ - createStubInstance( - constructor: StubbableType - ): SinonStubbedInstance; + createStubInstance(constructor: StubbableType): SinonStubbedInstance; } interface SinonApi { diff --git a/types/sinon/package.json b/types/sinon/package.json new file mode 100644 index 0000000000..bb80441dc0 --- /dev/null +++ b/types/sinon/package.json @@ -0,0 +1,7 @@ +{ + "private": true, + "types": "index", + "typesVersions": { + ">=3.1.0-0": { "*": ["ts3.1/*"] } + } +} diff --git a/types/sinon/sinon-tests.ts b/types/sinon/sinon-tests.ts index d5ae4b0eb2..b892f22980 100644 --- a/types/sinon/sinon-tests.ts +++ b/types/sinon/sinon-tests.ts @@ -288,6 +288,41 @@ function testAssert() { sinon.assert.expose(obj, { includeFail: true }); } +function testTypedSpy() { + const cls = class { + foo(a: number, b: string): number { + return 3; + } + }; + + const instance = new cls(); + const spy = sinon.spy(instance, 'foo'); + + spy.calledWith(5, 'x'); + spy.calledWith(sinon.match(5), 'x'); + spy.calledWithExactly(5, 'x'); + spy.calledWithExactly(5, sinon.match('x')); + spy.calledOnceWith(5, 'x'); + spy.calledOnceWith(sinon.match(5), 'x'); + spy.notCalledWith(5, 'x'); + spy.notCalledWith(sinon.match(5), 'x'); + spy.returned(5); + spy.returned(sinon.match(5)); + + spy.withArgs(sinon.match(5), 'x').calledWith(5, 'x'); + spy.alwaysCalledWith(sinon.match(5), 'x'); + spy.alwaysCalledWith(5, 'x'); + spy.alwaysCalledWithExactly(sinon.match(5), 'x'); + spy.alwaysCalledWithExactly(5, 'x'); + spy.neverCalledWith(sinon.match(5), 'x'); + spy.neverCalledWith(5, 'x'); + + const stub = sinon.stub(instance, 'foo'); + + stub.withArgs(5, 'x').returns(3); + stub.withArgs(sinon.match(5), 'x').returns(5); +} + function testSpy() { const fn = () => { }; const obj = class { diff --git a/types/sinon/ts3.1/index.d.ts b/types/sinon/ts3.1/index.d.ts new file mode 100644 index 0000000000..bc91a3285a --- /dev/null +++ b/types/sinon/ts3.1/index.d.ts @@ -0,0 +1,1747 @@ +// sinon uses DOM dependencies which are absent in browser-less environment like node.js +// to avoid compiler errors this monkey patch is used +// see more details in https://github.com/DefinitelyTyped/DefinitelyTyped/issues/11351 +interface Event {} // tslint:disable-line no-empty-interface +interface Document {} // tslint:disable-line no-empty-interface + +declare namespace Sinon { + type MatchArguments = { + [K in keyof T]: SinonMatcher | T[K]; + }; + + interface SinonSpyCallApi { + // Properties + /** + * Array of received arguments. + */ + args: TArgs; + + // Methods + /** + * Returns true if the spy was called at least once with @param obj as this. + * calledOn also accepts a matcher spyCall.calledOn(sinon.match(fn)) (see matchers). + * @param obj + */ + calledOn(obj: any): boolean; + /** + * Returns true if spy was called at least once with the provided arguments. + * Can be used for partial matching, Sinon only checks the provided arguments against actual arguments, + * so a call that received the provided arguments (in the same spots) and possibly others as well will return true. + * @param args + */ + calledWith(...args: MatchArguments): boolean; + /** + * Returns true if spy was called at least once with the provided arguments and no others. + */ + calledWithExactly(...args: MatchArguments): boolean; + /** + * Returns true if spy/stub was called the new operator. + * Beware that this is inferred based on the value of the this object and the spy function’s prototype, + * so it may give false positives if you actively return the right kind of object. + */ + calledWithNew(): boolean; + /** + * Returns true if spy was called at exactly once with the provided arguments. + * @param args + */ + calledOnceWith(...args: MatchArguments): boolean; + calledOnceWithExactly(...args: MatchArguments): boolean; + /** + * Returns true if spy was called with matching arguments (and possibly others). + * This behaves the same as spy.calledWith(sinon.match(arg1), sinon.match(arg2), ...). + * @param args + */ + calledWithMatch(...args: TArgs): boolean; + /** + * Returns true if call did not receive provided arguments. + * @param args + */ + notCalledWith(...args: MatchArguments): boolean; + /** + * Returns true if call did not receive matching arguments. + * This behaves the same as spyCall.notCalledWith(sinon.match(arg1), sinon.match(arg2), ...). + * @param args + */ + notCalledWithMatch(...args: TArgs): boolean; + /** + * Returns true if spy returned the provided value at least once. + * Uses deep comparison for objects and arrays. Use spy.returned(sinon.match.same(obj)) for strict comparison (see matchers). + * @param value + */ + returned(value: TReturnValue|SinonMatcher): boolean; + /** + * Returns true if spy threw an exception at least once. + */ + threw(): boolean; + /** + * Returns true if spy threw an exception of the provided type at least once. + */ + threw(type: string): boolean; + /** + * Returns true if spy threw the provided exception object at least once. + */ + threw(obj: any): boolean; + /** + * Like yield, but with an explicit argument number specifying which callback to call. + * Useful if a function is called with more than one callback, and simply calling the first callback is not desired. + * @param pos + */ + callArg(pos: number): void; + callArgOn(pos: number, obj: any, ...args: any[]): void; + /** + * Like callArg, but with arguments. + */ + callArgWith(pos: number, ...args: any[]): void; + callArgOnWith(pos: number, obj: any, ...args: any[]): void; + /** + * Invoke callbacks passed to the stub with the given arguments. + * If the stub was never called with a function argument, yield throws an error. + * Returns an Array with all callbacks return values in the order they were called, if no error is thrown. + * Also aliased as invokeCallback. + */ + yield(...args: any[]): void; + yieldOn(obj: any, ...args: any[]): void; + /** + * Invokes callbacks passed as a property of an object to the stub. + * Like yield, yieldTo grabs the first matching argument, finds the callback and calls it with the (optional) arguments. + */ + yieldTo(property: string, ...args: any[]): void; + yieldToOn(property: string, obj: any, ...args: any[]): void; + } + + interface SinonSpyCall + extends SinonSpyCallApi { + /** + * The call’s this value. + */ + thisValue: any; + /** + * Exception thrown, if any. + */ + exception: any; + /** + * Return value. + */ + returnValue: TReturnValue; + /** + * This property is a convenience for a call’s callback. + * When the last argument in a call is a Function, then callback will reference that. Otherwise it will be undefined. + */ + callback: Function | undefined; + /** + * This property is a convenience for the last argument of the call. + */ + lastArg: any; + + /** + * Returns true if the spy call occurred before another spy call. + * @param call + */ + calledBefore(call: SinonSpyCall): boolean; + /** + * Returns true if the spy call occurred after another spy call. + * @param call + */ + calledAfter(call: SinonSpyCall): boolean; + } + + interface SinonSpy + extends Pick< + SinonSpyCallApi, + Exclude, 'args'> + > { + // Properties + /** + * The number of recorded calls. + */ + callCount: number; + /** + * true if the spy was called at least once + */ + called: boolean; + /** + * true if the spy was not called + */ + notCalled: boolean; + /** + * true if spy was called exactly once + */ + calledOnce: boolean; + /** + * true if the spy was called exactly twice + */ + calledTwice: boolean; + /** + * true if the spy was called exactly thrice + */ + calledThrice: boolean; + /** + * The first call + */ + firstCall: SinonSpyCall; + /** + * The second call + */ + secondCall: SinonSpyCall; + /** + * The third call + */ + thirdCall: SinonSpyCall; + /** + * The last call + */ + lastCall: SinonSpyCall; + /** + * Array of this objects, spy.thisValues[0] is the this object for the first call. + */ + thisValues: any[]; + /** + * Array of arguments received, spy.args[0] is an array of arguments received in the first call. + */ + args: TArgs[]; + /** + * Array of exception objects thrown, spy.exceptions[0] is the exception thrown by the first call. + * If the call did not throw an error, the value at the call’s location in .exceptions will be undefined. + */ + exceptions: any[]; + /** + * Array of return values, spy.returnValues[0] is the return value of the first call. + * If the call did not explicitly return a value, the value at the call’s location in .returnValues will be undefined. + */ + returnValues: TReturnValue[]; + + // Methods + (...args: any[]): any; + /** + * Returns true if the spy was called before @param anotherSpy + * @param anotherSpy + */ + calledBefore(anotherSpy: SinonSpy): boolean; + /** + * Returns true if the spy was called after @param anotherSpy + * @param anotherSpy + */ + calledAfter(anotherSpy: SinonSpy): boolean; + /** + * Returns true if spy was called before @param anotherSpy, and no spy calls occurred between spy and @param anotherSpy. + * @param anotherSpy + */ + calledImmediatelyBefore(anotherSpy: SinonSpy): boolean; + /** + * Returns true if spy was called after @param anotherSpy, and no spy calls occurred between @param anotherSpy and spy. + * @param anotherSpy + */ + calledImmediatelyAfter(anotherSpy: SinonSpy): boolean; + /** + * Creates a spy that only records calls when the received arguments match those passed to withArgs. + * This is useful to be more expressive in your assertions, where you can access the spy with the same call. + * @param args Expected args + */ + withArgs(...args: MatchArguments): SinonSpy; + /** + * Returns true if the spy was always called with @param obj as this. + * @param obj + */ + alwaysCalledOn(obj: any): boolean; + /** + * Returns true if spy was always called with the provided arguments (and possibly others). + */ + alwaysCalledWith(...args: MatchArguments): boolean; + /** + * Returns true if spy was always called with the exact provided arguments. + * @param args + */ + alwaysCalledWithExactly(...args: MatchArguments): boolean; + /** + * Returns true if spy was always called with matching arguments (and possibly others). + * This behaves the same as spy.alwaysCalledWith(sinon.match(arg1), sinon.match(arg2), ...). + * @param args + */ + alwaysCalledWithMatch(...args: TArgs): boolean; + /** + * Returns true if the spy/stub was never called with the provided arguments. + * @param args + */ + neverCalledWith(...args: MatchArguments): boolean; + /** + * Returns true if the spy/stub was never called with matching arguments. + * This behaves the same as spy.neverCalledWith(sinon.match(arg1), sinon.match(arg2), ...). + * @param args + */ + neverCalledWithMatch(...args: TArgs): boolean; + /** + * Returns true if spy always threw an exception. + */ + alwaysThrew(): boolean; + /** + * Returns true if spy always threw an exception of the provided type. + */ + alwaysThrew(type: string): boolean; + /** + * Returns true if spy always threw the provided exception object. + */ + alwaysThrew(obj: any): boolean; + /** + * Returns true if spy always returned the provided value. + * @param obj + */ + alwaysReturned(obj: any): boolean; + /** + * Invoke callbacks passed to the stub with the given arguments. + * If the stub was never called with a function argument, yield throws an error. + * Returns an Array with all callbacks return values in the order they were called, if no error is thrown. + */ + invokeCallback(...args: TArgs): void; + /** + * Set the displayName of the spy or stub. + * @param name + */ + named(name: string): SinonSpy; + /** + * Returns the nth call. + * Accessing individual calls helps with more detailed behavior verification when the spy is called more than once. + * @param n + */ + getCall(n: number): SinonSpyCall; + /** + * Returns an Array of all calls recorded by the spy. + */ + getCalls(): Array>; + /** + * Resets the state of a spy. + */ + resetHistory(): void; + /** + * Returns the passed format string with the following replacements performed: + * * %n - the name of the spy "spy" by default) + * * %c - the number of times the spy was called, in words ("once", "twice", etc.) + * * %C - a list of string representations of the calls to the spy, with each call prefixed by a newline and four spaces + * * %t - a comma-delimited list of this values the spy was called on + * * %n - the formatted value of the nth argument passed to printf + * * %* - a comma-delimited list of the (non-format string) arguments passed to printf + * * %D - a multi-line list of the arguments received by all calls to the spy + * @param format + * @param args + */ + printf(format: string, ...args: any[]): string; + /** + * Replaces the spy with the original method. Only available if the spy replaced an existing method. + */ + restore(): void; + } + + interface SinonSpyStatic { + /** + * Creates an anonymous function that records arguments, this value, exceptions and return values for all calls. + */ + (): SinonSpy; + /** + * Spies on the provided function + */ + (func: Function): SinonSpy; + /** + * Creates a spy for object.method and replaces the original method with the spy. + * An exception is thrown if the property is not already a function. + * The spy acts exactly like the original method in all cases. + * The original method can be restored by calling object.method.restore(). + * The returned spy is the function object which replaced the original method. spy === object.method. + */ + (obj: T, method: K): T[K] extends ( + ...args: infer TArgs + ) => infer TReturnValue + ? SinonSpy + : SinonSpy; + } + + interface SinonStub + extends SinonSpy { + /** + * Resets the stub’s behaviour to the default behaviour + * You can reset behaviour of all stubs using sinon.resetBehavior() + */ + resetBehavior(): void; + /** + * Resets both behaviour and history of the stub. + * This is equivalent to calling both stub.resetBehavior() and stub.resetHistory() + * Updated in sinon@2.0.0 + * Since sinon@5.0.0 + * As a convenience, you can apply stub.reset() to all stubs using sinon.reset() + */ + reset(): void; + /** + * Causes the stub to return promises using a specific Promise library instead of the global one when using stub.rejects or stub.resolves. + * Returns the stub to allow chaining. + */ + usingPromise(promiseLibrary: any): SinonStub; + + /** + * Makes the stub return the provided @param obj value. + * @param obj + */ + returns(obj: TReturnValue): SinonStub; + /** + * Causes the stub to return the argument at the provided @param index. + * stub.returnsArg(0); causes the stub to return the first argument. + * If the argument at the provided index is not available, prior to sinon@6.1.2, an undefined value will be returned; + * starting from sinon@6.1.2, a TypeError will be thrown. + * @param index + */ + returnsArg(index: number): SinonStub; + /** + * Causes the stub to return its this value. + * Useful for stubbing jQuery-style fluent APIs. + */ + returnsThis(): SinonStub; + /** + * Causes the stub to return a Promise which resolves to the provided value. + * When constructing the Promise, sinon uses the Promise.resolve method. + * You are responsible for providing a polyfill in environments which do not provide Promise. + * The Promise library can be overwritten using the usingPromise method. + * Since sinon@2.0.0 + */ + resolves(value?: any): SinonStub; + /** + * Causes the stub to return a Promise which resolves to the argument at the provided index. + * stub.resolvesArg(0); causes the stub to return a Promise which resolves to the first argument. + * If the argument at the provided index is not available, a TypeError will be thrown. + */ + resolvesArg(index: number): SinonStub; + /** + * Causes the stub to return a Promise which resolves to its this value. + */ + resolvesThis(): SinonStub; + /** + * Causes the stub to throw an exception (Error). + * @param type + */ + throws(type?: string): SinonStub; + /** + * Causes the stub to throw the provided exception object. + */ + throws(obj: any): SinonStub; + /** + * Causes the stub to throw the argument at the provided index. + * stub.throwsArg(0); causes the stub to throw the first argument as the exception. + * If the argument at the provided index is not available, a TypeError will be thrown. + * Since sinon@2.3.0 + * @param index + */ + throwsArg(index: number): SinonStub; + throwsException(type?: string): SinonStub; + throwsException(obj: any): SinonStub; + /** + * Causes the stub to return a Promise which rejects with an exception (Error). + * When constructing the Promise, sinon uses the Promise.reject method. + * You are responsible for providing a polyfill in environments which do not provide Promise. + * The Promise library can be overwritten using the usingPromise method. + * Since sinon@2.0.0 + */ + rejects(): SinonStub; + /** + * Causes the stub to return a Promise which rejects with an exception of the provided type. + * Since sinon@2.0.0 + */ + rejects(errorType: string): SinonStub; + /** + * Causes the stub to return a Promise which rejects with the provided exception object. + * Since sinon@2.0.0 + */ + rejects(value: any): SinonStub; + /** + * Causes the stub to call the argument at the provided index as a callback function. + * stub.callsArg(0); causes the stub to call the first argument as a callback. + * If the argument at the provided index is not available or is not a function, a TypeError will be thrown. + */ + callsArg(index: number): SinonStub; + /** + * Causes the original method wrapped into the stub to be called when none of the conditional stubs are matched. + */ + callThrough(): SinonStub; + /** + * Like stub.callsArg(index); but with an additional parameter to pass the this context. + * @param index + * @param context + */ + callsArgOn(index: number, context: any): SinonStub; + /** + * Like callsArg, but with arguments to pass to the callback. + * @param index + * @param args + */ + callsArgWith(index: number, ...args: any[]): SinonStub; + /** + * Like above but with an additional parameter to pass the this context. + * @param index + * @param context + * @param args + */ + callsArgOnWith( + index: number, + context: any, + ...args: any[] + ): SinonStub; + /** + * Same as their corresponding non-Async counterparts, but with callback being deferred at called after all instructions in the current call stack are processed. + * In Node environment the callback is deferred with process.nextTick. + * In a browser the callback is deferred with setTimeout(callback, 0). + * @param index + */ + callsArgAsync(index: number): SinonStub; + /** + * Same as their corresponding non-Async counterparts, but with callback being deferred at called after all instructions in the current call stack are processed. + * In Node environment the callback is deferred with process.nextTick. + * In a browser the callback is deferred with setTimeout(callback, 0). + * @param index + * @param context + */ + callsArgOnAsync(index: number, context: any): SinonStub; + /** + * Same as their corresponding non-Async counterparts, but with callback being deferred at called after all instructions in the current call stack are processed. + * In Node environment the callback is deferred with process.nextTick. + * In a browser the callback is deferred with setTimeout(callback, 0). + */ + callsArgWithAsync(index: number, ...args: any[]): SinonStub; + /** + * Same as their corresponding non-Async counterparts, but with callback being deferred at called after all instructions in the current call stack are processed. + * In Node environment the callback is deferred with process.nextTick. + * In a browser the callback is deferred with setTimeout(callback, 0). + */ + callsArgOnWithAsync( + index: number, + context: any, + ...args: any[] + ): SinonStub; + /** + * Makes the stub call the provided @param func when invoked. + * @param func + */ + callsFake(func: (...args: TArgs) => TReturnValue): SinonStub; + /** + * Replaces a new getter for this stub. + */ + get(func: () => any): SinonStub; + /** + * Defines a new setter for this stub. + * @param func + */ + set(func: (v: any) => void): SinonStub; + /** + * Defines the behavior of the stub on the @param n call. Useful for testing sequential interactions. + * There are methods onFirstCall, onSecondCall,onThirdCall to make stub definitions read more naturally. + * onCall can be combined with all of the behavior defining methods in this section. In particular, it can be used together with withArgs. + * @param n + */ + onCall(n: number): SinonStub; + /** + * Alias for stub.onCall(0); + */ + onFirstCall(): SinonStub; + /** + * Alias for stub.onCall(1); + */ + onSecondCall(): SinonStub; + /** + * Alias for stub.onCall(2); + */ + onThirdCall(): SinonStub; + /** + * Defines a new value for this stub. + * @param val + */ + value(val: any): SinonStub; + /** + * Set the displayName of the spy or stub. + * @param name + */ + named(name: string): SinonStub; + /** + * Similar to callsArg. + * Causes the stub to call the first callback it receives with the provided arguments (if any). + * If a method accepts more than one callback, you need to use callsArg to have the stub invoke other callbacks than the first one. + */ + yields(...args: any[]): SinonStub; + /** + * Like above but with an additional parameter to pass the this context. + */ + yieldsOn(context: any, ...args: any[]): SinonStub; + yieldsRight(...args: any[]): SinonStub; + /** + * Causes the spy to invoke a callback passed as a property of an object to the spy. + * Like yields, yieldsTo grabs the first matching argument, finds the callback and calls it with the (optional) arguments. + * @param property + * @param args + */ + yieldsTo(property: string, ...args: any[]): SinonStub; + /** + * Like above but with an additional parameter to pass the this context. + */ + yieldsToOn( + property: string, + context: any, + ...args: any[] + ): SinonStub; + /** + * Same as their corresponding non-Async counterparts, but with callback being deferred at called after all instructions in the current call stack are processed. + * In Node environment the callback is deferred with process.nextTick. + * In a browser the callback is deferred with setTimeout(callback, 0). + * @param args + */ + yieldsAsync(...args: any[]): SinonStub; + /** + * Same as their corresponding non-Async counterparts, but with callback being deferred at called after all instructions in the current call stack are processed. + * In Node environment the callback is deferred with process.nextTick. + * In a browser the callback is deferred with setTimeout(callback, 0). + * @param context + * @param args + */ + yieldsOnAsync(context: any, ...args: any[]): SinonStub; + /** + * Same as their corresponding non-Async counterparts, but with callback being deferred at called after all instructions in the current call stack are processed. + * In Node environment the callback is deferred with process.nextTick. + * In a browser the callback is deferred with setTimeout(callback, 0). + * @param property + * @param args + */ + yieldsToAsync(property: string, ...args: any[]): SinonStub; + /** + * Same as their corresponding non-Async counterparts, but with callback being deferred at called after all instructions in the current call stack are processed. + * In Node environment the callback is deferred with process.nextTick. + * In a browser the callback is deferred with setTimeout(callback, 0). + * @param property + * @param context + * @param args + */ + yieldsToOnAsync( + property: string, + context: any, + ...args: any[] + ): SinonStub; + /** + * Stubs the method only for the provided arguments. + * This is useful to be more expressive in your assertions, where you can access the spy with the same call. + * It is also useful to create a stub that can act differently in response to different arguments. + * @param args + */ + withArgs(...args: MatchArguments): SinonStub; + } + + interface SinonStubStatic { + /** + * Creates an anonymous stub function + */ + (): SinonStub; + /** + * Stubs all the object’s methods. + * Note that it’s usually better practice to stub individual methods, particularly on objects that you don’t understand or control all the methods for (e.g. library dependencies). + * Stubbing individual methods tests intent more precisely and is less susceptible to unexpected behavior as the object’s code evolves. + * If you want to create a stub object of MyConstructor, but don’t want the constructor to be invoked, use this utility function. + */ + (obj: T): SinonStubbedInstance; + /** + * Replaces obj.method with a stub function. + * An exception is thrown if the property is not already a function. + * The original function can be restored by calling object.method.restore(); (or stub.restore();). + */ + (obj: T, method: K): T[K] extends ( + ...args: infer TArgs + ) => infer TReturnValue + ? SinonStub + : SinonStub; + } + + interface SinonExpectation extends SinonStub { + /** + * Specify the minimum amount of calls expected. + */ + atLeast(n: number): SinonExpectation; + /** + * Specify the maximum amount of calls expected. + * @param n + */ + atMost(n: number): SinonExpectation; + /** + * Expect the method to never be called. + */ + never(): SinonExpectation; + /** + * Expect the method to be called exactly once. + */ + once(): SinonExpectation; + /** + * Expect the method to be called exactly twice. + */ + twice(): SinonExpectation; + /** + * Expect the method to be called exactly thrice. + */ + thrice(): SinonExpectation; + /** + * Expect the method to be called exactly @param n times. + */ + exactly(n: number): SinonExpectation; + /** + * Expect the method to be called with the provided arguments and possibly others. + * An expectation instance only holds onto a single set of arguments specified with withArgs. + * Subsequent calls will overwrite the previously-specified set of arguments (even if they are different), + * so it is generally not intended that this method be invoked more than once per test case. + * @param args + */ + withArgs(...args: any[]): SinonExpectation; + /** + * Expect the method to be called with the provided arguments and no others. + * An expectation instance only holds onto a single set of arguments specified with withExactArgs. + * Subsequent calls will overwrite the previously-specified set of arguments (even if they are different), + * so it is generally not intended that this method be invoked more than once per test case. + * @param args + */ + withExactArgs(...args: any[]): SinonExpectation; + on(obj: any): SinonExpectation; + /** + * Verifies all expectations on the mock. + * If any expectation is not satisfied, an exception is thrown. + * Also restores the mocked methods. + */ + verify(): SinonExpectation; + /** + * Restores all mocked methods. + */ + restore(): void; + } + + interface SinonExpectationStatic { + /** + * Creates an expectation without a mock object, basically an anonymous mock function. + * Method name is optional and is used in exception messages to make them more readable. + * @param methodName + */ + create(methodName?: string): SinonExpectation; + } + + interface SinonMock { + /** + * Overrides obj.method with a mock function and returns it. + */ + expects(method: string): SinonExpectation; + /** + * Restores all mocked methods. + */ + restore(): void; + /** + * Verifies all expectations on the mock. + * If any expectation is not satisfied, an exception is thrown. + * Also restores the mocked methods. + */ + verify(): void; + } + + interface SinonMockStatic { + (): SinonExpectation; + /** + * Creates a mock for the provided object. + * Does not change the object, but returns a mock object to set expectations on the object’s methods. + */ + (obj: any): SinonMock; + } + + type SinonTimerId = number | { id: number }; + + interface SinonFakeTimers { + now: number; + + setTimeout( + callback: (...args: any[]) => void, + timeout: number, + ...args: any[] + ): SinonTimerId; + clearTimeout(id: SinonTimerId): void; + setInterval( + callback: (...args: any[]) => void, + timeout: number, + ...args: any[] + ): SinonTimerId; + clearInterval(id: SinonTimerId): void; + setImmediate( + callback: (...args: any[]) => void, + ...args: any[] + ): SinonTimerId; + clearImmediate(id: SinonTimerId): void; + requestAnimationFrame(callback: (...args: any[]) => void): number; + cancelAnimationFrame(id: number): void; + nextTick(callback: () => void): void; + + /** + * Tick the clock ahead time milliseconds. + * Causes all timers scheduled within the affected time range to be called. + * time may be the number of milliseconds to advance the clock by or a human-readable string. + * Valid string formats are “08” for eight seconds, “01:00” for one minute and “02:34:10” for two hours, 34 minutes and ten seconds. + * time may be negative, which causes the clock to change but won’t fire any callbacks. + * @param ms + */ + tick(ms: number | string): void; + /** + * Advances the clock to the the moment of the first scheduled timer, firing it. + */ + next(): void; + /** + * This runs all pending timers until there are none remaining. If new timers are added while it is executing they will be run as well. + * This makes it easier to run asynchronous tests to completion without worrying about the number of timers they use, or the delays in those timers. + */ + runAll(): void; + runToLast(): void; + reset(): void; + runMicrotasks(): void; + runToFrame(): void; + + Date(): Date; + Date(year: number): Date; + Date(year: number, month: number): Date; + Date(year: number, month: number, day: number): Date; + Date(year: number, month: number, day: number, hour: number): Date; + Date( + year: number, + month: number, + day: number, + hour: number, + minute: number + ): Date; + Date( + year: number, + month: number, + day: number, + hour: number, + minute: number, + second: number + ): Date; + Date( + year: number, + month: number, + day: number, + hour: number, + minute: number, + second: number, + ms: number + ): Date; + + /** + * Restore the faked methods. + * Call in e.g. tearDown. + */ + restore(): void; + uninstall(): void; + + /** + * Simulate the user changing the system clock while your program is running. It changes the 'now' timestamp + * without affecting timers, intervals or immediates. + * @param now The new 'now' in unix milliseconds + */ + setSystemTime(now: number): void; + /** + * Simulate the user changing the system clock while your program is running. It changes the 'now' timestamp + * without affecting timers, intervals or immediates. + * @param now The new 'now' as a JavaScript Date + */ + setSystemTime(date: Date): void; + } + + interface SinonFakeTimersConfig { + now: number | Date; + toFake: string[]; + shouldAdvanceTime: boolean; + } + + interface SinonFakeUploadProgress { + eventListeners: { + progress: any[]; + load: any[]; + abort: any[]; + error: any[]; + }; + + addEventListener(event: string, listener: (e: Event) => any): void; + removeEventListener(event: string, listener: (e: Event) => any): void; + dispatchEvent(event: Event): void; + } + + interface SinonFakeXMLHttpRequest { + // Properties + /** + * The URL set on the request object. + */ + url: string; + /** + * The request method as a string. + */ + method: string; + /** + * An object of all request headers, i.e.: + */ + requestHeaders: any; + /** + * The request body + */ + requestBody: string; + /** + * The request’s status code. + * undefined if the request has not been handled (see respond below) + */ + status: number; + /** + * Only populated if the respond method is called (see below). + */ + statusText: string; + /** + * Whether or not the request is asynchronous. + */ + async: boolean; + /** + * Username, if any. + */ + username: string; + /** + * Password, if any. + */ + password: string; + withCredentials: boolean; + upload: SinonFakeUploadProgress; + /** + * When using respond, this property is populated with a parsed document if response headers indicate as much (see the spec) + */ + responseXML: Document; + /** + * The value of the given response header, if the request has been responded to (see respond). + * @param header + */ + getResponseHeader(header: string): string; + /** + * All response headers as an object. + */ + getAllResponseHeaders(): any; + + // Methods + /** + * Sets response headers (e.g. { "Content-Type": "text/html", ... }, updates the readyState property and fires onreadystatechange. + * @param headers + */ + setResponseHeaders(headers: any): void; + /** + * Sets the respond body, updates the readyState property and fires onreadystatechange. + * Additionally, populates responseXML with a parsed document if response headers indicate as much. + */ + setResponseBody(body: string): void; + /** + * Calls the above three methods. + */ + respond(status: number, headers: any, body: string): void; + autoRespond(ms: number): void; + /** + * Simulates a network error on the request. The onerror handler will be called and the status will be 0. + */ + error(): void; + onerror(): void; + } + + interface SinonFakeXMLHttpRequestStatic { + new (): SinonFakeXMLHttpRequest; + /** + * Default false. + * When set to true, Sinon will check added filters if certain requests should be “unfaked” + */ + useFilters: boolean; + /** + * Add a filter that will decide whether or not to fake a request. + * The filter will be called when xhr.open is called, with the exact same arguments (method, url, async, username, password). + * If the filter returns true, the request will not be faked. + * @param filter + */ + addFilter( + filter: ( + method: string, + url: string, + async: boolean, + username: string, + password: string + ) => boolean + ): void; + /** + * By assigning a function to the onCreate property of the returned object from useFakeXMLHttpRequest() + * you can subscribe to newly created FakeXMLHttpRequest objects. See below for the fake xhr object API. + * Using this observer means you can still reach objects created by e.g. jQuery.ajax (or other abstractions/frameworks). + * @param xhr + */ + onCreate(xhr: SinonFakeXMLHttpRequest): void; + /** + * Restore original function(s). + */ + restore(): void; + } + + interface SinonFakeServer extends SinonFakeServerOptions { + // Properties + /** + * Used internally to determine the HTTP method used with the provided request. + * By default this method simply returns request.method. + * When server.fakeHTTPMethods is true, the method will return the value of the _method parameter if the method is “POST”. + * This method can be overridden to provide custom behavior. + * @param request + */ + getHTTPMethod(request: SinonFakeXMLHttpRequest): string; + /** + * You can inspect the server.requests to verify request ordering, find unmatched requests or check that no requests has been done. + * server.requests is an array of all the FakeXMLHttpRequest objects that have been created. + */ + requests: SinonFakeXMLHttpRequest[]; + + // Methods + /** + * Causes the server to respond to any request not matched by another response with the provided data. The default catch-all response is [404, {}, ""]. + * A String representing the response body + * An Array with status, headers and response body, e.g. [200, { "Content-Type": "text/html", "Content-Length": 2 }, "OK"] + * A Function. + * Default status is 200 and default headers are none. + * When the response is a Function, it will be passed the request object. You must manually call respond on it to complete the request. + * @param body A String representing the response body + */ + respondWith(body: string): void; + /** + * Causes the server to respond to any request not matched by another response with the provided data. The default catch-all response is [404, {}, ""]. + * Default status is 200 and default headers are none. + * When the response is a Function, it will be passed the request object. You must manually call respond on it to complete the request. + * @param response An Array with status, headers and response body, e.g. [200, { "Content-Type": "text/html", "Content-Length": 2 }, "OK"] + */ + respondWith(response: any[]): void; + /** + * Causes the server to respond to any request not matched by another response with the provided data. The default catch-all response is [404, {}, ""]. + * Default status is 200 and default headers are none. + * When the response is a Function, it will be passed the request object. You must manually call respond on it to complete the request. + * @param fn A Function. + */ + respondWith(fn: (xhr: SinonFakeXMLHttpRequest) => void): void; + /** + * Responds to all requests to given URL, e.g. /posts/1. + */ + respondWith(url: string, body: string): void; + /** + * Responds to all requests to given URL, e.g. /posts/1. + */ + respondWith(url: string, response: any[]): void; + /** + * Responds to all requests to given URL, e.g. /posts/1. + */ + respondWith( + url: string, + fn: (xhr: SinonFakeXMLHttpRequest) => void + ): void; + /** + * Responds to all method requests to the given URL with the given response. + * method is an HTTP verb. + */ + respondWith(method: string, url: string, body: string): void; + /** + * Responds to all method requests to the given URL with the given response. + * method is an HTTP verb. + */ + respondWith(method: string, url: string, response: any[]): void; + /** + * Responds to all method requests to the given URL with the given response. + * method is an HTTP verb. + */ + respondWith( + method: string, + url: string, + fn: (xhr: SinonFakeXMLHttpRequest) => void + ): void; + /** + * URL may be a regular expression, e.g. /\\/post\\//\\d+ + * If the response is a Function, it will be passed any capture groups from the regular expression along with the XMLHttpRequest object: + */ + respondWith(url: RegExp, body: string): void; + /** + * URL may be a regular expression, e.g. /\\/post\\//\\d+ + * If the response is a Function, it will be passed any capture groups from the regular expression along with the XMLHttpRequest object: + */ + respondWith(url: RegExp, response: any[]): void; + /** + * URL may be a regular expression, e.g. /\\/post\\//\\d+ + * If the response is a Function, it will be passed any capture groups from the regular expression along with the XMLHttpRequest object: + */ + respondWith( + url: RegExp, + fn: (xhr: SinonFakeXMLHttpRequest) => void + ): void; + /** + * Responds to all method requests to URLs matching the regular expression. + */ + respondWith(method: string, url: RegExp, body: string): void; + /** + * Responds to all method requests to URLs matching the regular expression. + */ + respondWith(method: string, url: RegExp, response: any[]): void; + /** + * Responds to all method requests to URLs matching the regular expression. + */ + respondWith( + method: string, + url: RegExp, + fn: (xhr: SinonFakeXMLHttpRequest) => void + ): void; + /** + * Causes all queued asynchronous requests to receive a response. + * If none of the responses added through respondWith match, the default response is [404, {}, ""]. + * Synchronous requests are responded to immediately, so make sure to call respondWith upfront. + * If called with arguments, respondWith will be called with those arguments before responding to requests. + */ + respond(): void; + restore(): void; + } + + interface SinonFakeServerOptions { + /** + * When set to true, causes the server to automatically respond to incoming requests after a timeout. + * The default timeout is 10ms but you can control it through the autoRespondAfter property. + * Note that this feature is intended to help during mockup development, and is not suitable for use in tests. + */ + autoRespond: boolean; + /** + * When autoRespond is true, respond to requests after this number of milliseconds. Default is 10. + */ + autoRespondAfter: number; + /** + * If set to true, server will find _method parameter in POST body and recognize that as the actual method. + * Supports a pattern common to Ruby on Rails applications. For custom HTTP method faking, override server.getHTTPMethod(request). + */ + fakeHTTPMethods: boolean; + /** + * If set, the server will respond to every request immediately and synchronously. + * This is ideal for faking the server from within a test without having to call server.respond() after each request made in that test. + * As this is synchronous and immediate, this is not suitable for simulating actual network latency in tests or mockups. + * To simulate network latency with automatic responses, see server.autoRespond and server.autoRespondAfter. + */ + respondImmediately: boolean; + } + + interface SinonFakeServerStatic { + create(options?: Partial): SinonFakeServer; + } + + interface SinonExposeOptions { + prefix: string; + includeFail: boolean; + } + + interface SinonAssert { + // Properties + /** + * Defaults to AssertError. + */ + failException: string; + /** + * Every assertion fails by calling this method. + * By default it throws an error of type sinon.assert.failException. + * If the test framework looks for assertion errors by checking for a specific exception, you can simply override the kind of exception thrown. + * If that does not fit with your testing framework of choice, override the fail method to do the right thing. + */ + fail(message?: string): void; // Overridable + /** + * Called every time assertion passes. + * Default implementation does nothing. + */ + pass(assertion: any): void; // Overridable + + // Methods + /** + * Passes if spy was never called + * @param spy + */ + notCalled(spy: SinonSpy): void; + /** + * Passes if spy was called at least once. + */ + called(spy: SinonSpy): void; + /** + * Passes if spy was called once and only once. + */ + calledOnce(spy: SinonSpy): void; + /** + * Passes if spy was called exactly twice. + */ + calledTwice(spy: SinonSpy): void; + /** + * Passes if spy was called exactly three times. + */ + calledThrice(spy: SinonSpy): void; + /** + * Passes if spy was called exactly num times. + */ + callCount(spy: SinonSpy, count: number): void; + /** + * Passes if provided spies were called in the specified order. + * @param spies + */ + callOrder(...spies: SinonSpy[]): void; + /** + * Passes if spy was ever called with obj as its this value. + * It’s possible to assert on a dedicated spy call: sinon.assert.calledOn(spy.firstCall, arg1, arg2, ...);. + */ + calledOn(spyOrSpyCall: SinonSpy | SinonSpyCall, obj: any): void; + /** + * Passes if spy was always called with obj as its this value. + */ + alwaysCalledOn(spy: SinonSpy, obj: any): void; + /** + * Passes if spy was called with the provided arguments. + * It’s possible to assert on a dedicated spy call: sinon.assert.calledWith(spy.firstCall, arg1, arg2, ...);. + * @param spyOrSpyCall + * @param args + */ + calledWith(spyOrSpyCall: SinonSpy | SinonSpyCall, ...args: any[]): void; + /** + * Passes if spy was always called with the provided arguments. + * @param spy + * @param args + */ + alwaysCalledWith(spy: SinonSpy, ...args: any[]): void; + /** + * Passes if spy was never called with the provided arguments. + * @param spy + * @param args + */ + neverCalledWith(spy: SinonSpy, ...args: any[]): void; + /** + * Passes if spy was called with the provided arguments and no others. + * It’s possible to assert on a dedicated spy call: sinon.assert.calledWithExactly(spy.getCall(1), arg1, arg2, ...);. + * @param spyOrSpyCall + * @param args + */ + calledWithExactly( + spyOrSpyCall: SinonSpy | SinonSpyCall, + ...args: any[] + ): void; + /** + * Passes if spy was always called with the provided arguments and no others. + */ + alwaysCalledWithExactly(spy: SinonSpy, ...args: any[]): void; + /** + * Passes if spy was called with matching arguments. + * This behaves the same way as sinon.assert.calledWith(spy, sinon.match(arg1), sinon.match(arg2), ...). + * It’s possible to assert on a dedicated spy call: sinon.assert.calledWithMatch(spy.secondCall, arg1, arg2, ...);. + */ + calledWithMatch( + spyOrSpyCall: SinonSpy | SinonSpyCall, + ...args: any[] + ): void; + /** + * Passes if spy was always called with matching arguments. + * This behaves the same way as sinon.assert.alwaysCalledWith(spy, sinon.match(arg1), sinon.match(arg2), ...). + */ + alwaysCalledWithMatch(spy: SinonSpy, ...args: any[]): void; + /** + * Passes if spy was never called with matching arguments. + * This behaves the same way as sinon.assert.neverCalledWith(spy, sinon.match(arg1), sinon.match(arg2), ...). + * @param spy + * @param args + */ + neverCalledWithMatch(spy: SinonSpy, ...args: any[]): void; + /** + * Passes if spy was called with the new operator. + * It’s possible to assert on a dedicated spy call: sinon.assert.calledWithNew(spy.secondCall, arg1, arg2, ...);. + * @param spyOrSpyCall + */ + calledWithNew(spyOrSpyCall: SinonSpy | SinonSpyCall): void; + /** + * Passes if spy threw any exception. + */ + threw(spyOrSpyCall: SinonSpy | SinonSpyCall): void; + /** + * Passes if spy threw the given exception. + * The exception is an actual object. + * It’s possible to assert on a dedicated spy call: sinon.assert.threw(spy.thirdCall, exception);. + */ + threw(spyOrSpyCall: SinonSpy | SinonSpyCall, exception: string): void; + /** + * Passes if spy threw the given exception. + * The exception is a String denoting its type. + * It’s possible to assert on a dedicated spy call: sinon.assert.threw(spy.thirdCall, exception);. + */ + threw(spyOrSpyCall: SinonSpy | SinonSpyCall, exception: any): void; + /** + * Like threw, only required for all calls to the spy. + */ + alwaysThrew(spy: SinonSpy): void; + /** + * Like threw, only required for all calls to the spy. + */ + alwaysThrew(spy: SinonSpy, exception: string): void; + /** + * Like threw, only required for all calls to the spy. + */ + alwaysThrew(spy: SinonSpy, exception: any): void; + /** + * Uses sinon.match to test if the arguments can be considered a match. + */ + match(actual: any, expected: any): void; + /** + * Exposes assertions into another object, to better integrate with the test framework. + * For instance, JsTestDriver uses global assertions, and to make Sinon.JS assertions appear alongside them, you can do. + * @example sinon.assert.expose(this); + * This will give you assertCalled(spy),assertCallOrder(spy1, spy2, ...) and so on. + * The method accepts an optional options object with two options. + */ + expose(obj: any, options?: Partial): void; + } + + interface SinonMatcher { + /** + * All matchers implement and and or. This allows to logically combine mutliple matchers. + * The result is a new matchers that requires both (and) or one of the matchers (or) to return true. + * @example var stringOrNumber = sinon.match.string.or(sinon.match.number); + * var bookWithPages = sinon.match.instanceOf(Book).and(sinon.match.has("pages")); + */ + and(expr: SinonMatcher): SinonMatcher; + /** + * All matchers implement and and or. This allows to logically combine mutliple matchers. + * The result is a new matchers that requires both (and) or one of the matchers (or) to return true. + * @example var stringOrNumber = sinon.match.string.or(sinon.match.number); + * var bookWithPages = sinon.match.instanceOf(Book).and(sinon.match.has("pages")); + */ + or(expr: SinonMatcher): SinonMatcher; + test(val: any): boolean; + } + + interface SinonArrayMatcher extends SinonMatcher { + /** + * Requires an Array to be deep equal another one. + */ + deepEquals(expected: any[]): SinonMatcher; + /** + * Requires an Array to start with the same values as another one. + */ + startsWith(expected: any[]): SinonMatcher; + /** + * Requires an Array to end with the same values as another one. + */ + endsWith(expected: any[]): SinonMatcher; + /** + * Requires an Array to contain each one of the values the given array has. + */ + contains(expected: any[]): SinonMatcher; + } + + interface SimplifiedSet { + has(el: any): boolean; + } + + interface SimplifiedMap extends SimplifiedSet { + get(key: any): any; + } + + interface SinonMapMatcher extends SinonMatcher { + /** + * Requires a Map to be deep equal another one. + */ + deepEquals(expected: SimplifiedMap): SinonMatcher; + /** + * Requires a Map to contain each one of the items the given map has. + */ + contains(expected: SimplifiedMap): SinonMatcher; + } + + interface SinonSetMatcher extends SinonMatcher { + /** + * Requires a Set to be deep equal another one. + */ + deepEquals(expected: SimplifiedSet): SinonMatcher; + /** + * Requires a Set to contain each one of the items the given set has. + */ + contains(expected: SimplifiedSet): SinonMatcher; + } + + interface SinonMatch { + /** + * Requires the value to be == to the given number. + */ + (value: number): SinonMatcher; + /** + * Requires the value to be a string and have the expectation as a substring. + */ + (value: string): SinonMatcher; + /** + * Requires the value to be a string and match the given regular expression. + */ + (expr: RegExp): SinonMatcher; + /** + * See custom matchers. + */ + (callback: (value: any) => boolean, message?: string): SinonMatcher; + /** + * Requires the value to be not null or undefined and have at least the same properties as expectation. + * This supports nested matchers. + */ + (obj: object): SinonMatcher; + /** + * Matches anything. + */ + any: SinonMatcher; + /** + * Requires the value to be defined. + */ + defined: SinonMatcher; + /** + * Requires the value to be truthy. + */ + truthy: SinonMatcher; + /** + * Requires the value to be falsy. + */ + falsy: SinonMatcher; + /** + * Requires the value to be a Boolean + */ + bool: SinonMatcher; + /** + * Requires the value to be a Number. + */ + number: SinonMatcher; + /** + * Requires the value to be a String. + */ + string: SinonMatcher; + /** + * Requires the value to be an Object. + */ + object: SinonMatcher; + /** + * Requires the value to be a Function. + */ + func: SinonMatcher; + /** + * Requires the value to be a Map. + */ + map: SinonMapMatcher; + /** + * Requires the value to be a Set. + */ + set: SinonSetMatcher; + /** + * Requires the value to be an Array. + */ + array: SinonArrayMatcher; + /** + * Requires the value to be a regular expression. + */ + regexp: SinonMatcher; + /** + * Requires the value to be a Date object. + */ + date: SinonMatcher; + /** + * Requires the value to be a Symbol. + */ + symbol: SinonMatcher; + /** + * Requires the value to strictly equal ref. + */ + same(obj: any): SinonMatcher; + /** + * Requires the value to be of the given type, where type can be one of "undefined", "null", "boolean", "number", "string", "object", "function", "array", "regexp", "date" or "symbol". + */ + typeOf(type: string): SinonMatcher; + /** + * Requires the value to be an instance of the given type. + */ + instanceOf(type: any): SinonMatcher; + /** + * Requires the value to define the given property. + * The property might be inherited via the prototype chain. + * If the optional expectation is given, the value of the property is deeply compared with the expectation. + * The expectation can be another matcher. + * @param property + * @param expect + */ + has(property: string, expect?: any): SinonMatcher; + /** + * Same as sinon.match.has but the property must be defined by the value itself. Inherited properties are ignored. + * @param property + * @param expect + */ + hasOwn(property: string, expect?: any): SinonMatcher; + /** + * Requires the value to define the given propertyPath. Dot (prop.prop) and bracket (prop[0]) notations are supported as in Lodash.get. + * The propertyPath might be inherited via the prototype chain. + * If the optional expectation is given, the value at the propertyPath is deeply compared with the expectation. + * The expectation can be another matcher. + */ + hasNested(path: string, expect?: any): SinonMatcher; + /** + * Requires every element of an Array, Set or Map, or alternatively every value of an Object to match the given matcher. + */ + every(matcher: SinonMatcher): SinonMatcher; + /** + * Requires any element of an Array, Set or Map, or alternatively any value of an Object to match the given matcher. + */ + some(matcher: SinonMatcher): SinonMatcher; + } + + interface SinonSandboxConfig { + /** + * The sandbox’s methods can be injected into another object for convenience. + * The injectInto configuration option can name an object to add properties to. + */ + injectInto: object | null; + /** + * What properties to inject. + * Note that simply naming “server” here is not sufficient to have a server property show up in the target object, + * you also have to set useFakeServer to true. + */ + properties: string[]; + /** + * If set to true, the sandbox will have a clock property. + * You can optionally pass in a configuration object that follows the specification for fake timers, such as { toFake: ["setTimeout", "setInterval"] }. + */ + useFakeTimers: boolean | Partial; + /** + * If true, server and requests properties are added to the sandbox. Can also be an object to use for fake server. + * The default one is sinon.fakeServer, but if you’re using jQuery 1.3.x or some other library that does not set the XHR’s onreadystatechange handler, + * you might want to do: + */ + useFakeServer: boolean | SinonFakeServer; + } + + /** + * Stubbed type of an object with members replaced by stubs. + * + * @template TType Type being stubbed. + */ + type StubbableType = Function & { prototype: TType }; + + /** + * An instance of a stubbed object type with functions replaced by stubs. + * + * @template TType Object type being stubbed. + */ + type SinonStubbedInstance = { + [P in keyof TType]: SinonStubbedMember + }; + + /** + * Replaces a type with a Sinon stub if it's a function. + */ + type SinonStubbedMember = T extends Function ? SinonStub : T; + + interface SinonFake { + /** + * Creates a basic fake, with no behavior + */ + (): SinonSpy; + /** + * Wraps an existing Function to record all interactions, while leaving it up to the func to provide the behavior. + * This is useful when complex behavior not covered by the sinon.fake.* methods is required or when wrapping an existing function or method. + */ + (fn: Function): SinonSpy; + /** + * Creates a fake that returns the val argument + * @param val Returned value + */ + returns(val: any): SinonSpy; + /** + * Creates a fake that throws an Error with the provided value as the message property. + * If an Error is passed as the val argument, then that will be the thrown value. If any other value is passed, then that will be used for the message property of the thrown Error. + * @param val Returned value or throw value if an Error + */ + throws(val: Error | string): SinonSpy; + /** + * Creates a fake that returns a resolved Promise for the passed value. + * @param val Resolved promise + */ + resolves(val: any): SinonSpy; + /** + * Creates a fake that returns a rejected Promise for the passed value. + * If an Error is passed as the value argument, then that will be the value of the promise. + * If any other value is passed, then that will be used for the message property of the Error returned by the promise. + * @param val Rejected promise + */ + rejects(val: any): SinonSpy; + /** + * fake expects the last argument to be a callback and will invoke it with the given arguments. + */ + yields(...args: any[]): SinonSpy; + /** + * fake expects the last argument to be a callback and will invoke it asynchronously with the given arguments. + */ + yieldsAsync(...args: any[]): SinonSpy; + } + + interface SinonSandbox { + /** + * A convenience reference for sinon.assert + * Since sinon@2.0.0 + */ + assert: SinonAssert; + clock: SinonFakeTimers; + requests: SinonFakeXMLHttpRequest[]; + server: SinonFakeServer; + /** + * Works exactly like sinon.spy + */ + spy: SinonSpyStatic; + /** + * Works exactly like sinon.stub. + */ + stub: SinonStubStatic; + /** + * Works exactly like sinon.mock + */ + mock: SinonMockStatic; + + /** + * * No param : Causes Sinon to replace the global setTimeout, clearTimeout, setInterval, clearInterval, setImmediate, clearImmediate, process.hrtime, performance.now(when available) + * and Date with a custom implementation which is bound to the returned clock object. + * Starts the clock at the UNIX epoch (timestamp of 0). + * * Now : As above, but rather than starting the clock with a timestamp of 0, start at the provided timestamp now. + * Since sinon@2.0.0 + * You can also pass in a Date object, and its getTime() will be used for the starting timestamp. + * * Config : As above, but allows further configuration options, some of which are: + * * config.now - Number/Date - installs lolex with the specified unix epoch (default: 0) + * * config.toFake - String[ ] - an array with explicit function names to fake. + * By default lolex will automatically fake all methods except process.nextTick. You could, however, still fake nextTick by providing it explicitly + * * config.shouldAdvanceTime - Boolean - tells lolex to increment mocked time automatically based on the real system time shift (default: false) + * * Please visit the lolex.install documentation for the full feature set. + * * Important note: when faking nextTick, normal calls to process.nextTick() would not execute automatically as they would during normal event-loop phases. + * You would have to call either clock.next(), clock.tick(), clock.runAll() or clock.runToLast() (see example below). Please refer to the lolex documentation for more information. + * @param config + */ + useFakeTimers( + config?: number | Date | Partial + ): SinonFakeTimers; + /** + * Causes Sinon to replace the native XMLHttpRequest object in browsers that support it with a custom implementation which does not send actual requests. + * In browsers that support ActiveXObject, this constructor is replaced, and fake objects are returned for XMLHTTP progIds. + * Other progIds, such as XMLDOM are left untouched. + * The native XMLHttpRequest object will be available at sinon.xhr.XMLHttpRequest + */ + useFakeXMLHttpRequest(): SinonFakeXMLHttpRequestStatic; + /** + * Fakes XHR and binds a server object to the sandbox such that it too is restored when calling sandbox.restore(). + * Access requests through sandbox.requests and server through sandbox.server + */ + useFakeServer(): SinonFakeServer; + /** + * Restores all fakes created through sandbox. + */ + restore(): void; + /** + * Resets the internal state of all fakes created through sandbox. + */ + reset(): void; + /** + * Resets the history of all stubs created through the sandbox. + * Since sinon@2.0.0 + */ + resetHistory(): void; + /** + * Resets the behaviour of all stubs created through the sandbox. + * Since sinon@2.0.0 + */ + resetBehavior(): void; + /** + * Causes all stubs created from the sandbox to return promises using a specific Promise library instead of the global one when using stub.rejects or stub.resolves. + * Returns the stub to allow chaining. + * Since sinon@2.0.0 + */ + usingPromise(promiseLibrary: any): SinonSandbox; + /** + * Verifies all mocks created through the sandbox. + */ + verify(): void; + /** + * Verifies all mocks and restores all fakes created through the sandbox. + */ + verifyAndRestore(): void; + + /** + * Replaces property on object with replacement argument. Attempts to replace an already replaced value cause an exception. + * replacement can be any value, including spies, stubs and fakes. + * This method only works on non-accessor properties, for replacing accessors, use sandbox.replaceGetter() and sandbox.replaceSetter(). + */ + replace( + obj: T, + prop: TKey, + replacement: T[TKey] + ): T[TKey]; + /** + * Replaces getter for property on object with replacement argument. Attempts to replace an already replaced getter cause an exception. + * replacement must be a Function, and can be instances of spies, stubs and fakes. + * @param obj + * @param prop + * @param replacement + */ + replaceGetter( + obj: T, + prop: TKey, + replacement: () => T[TKey] + ): () => T[TKey]; + /** + * Replaces setter for property on object with replacement argument. Attempts to replace an already replaced setter cause an exception. + * replacement must be a Function, and can be instances of spies, stubs and fakes. + * @param obj + * @param prop + * @param replacement + */ + replaceSetter( + obj: T, + prop: TKey, + replacement: (val: T[TKey]) => void + ): (val: T[TKey]) => void; + + /** + * Creates a new object with the given functions as the prototype and stubs all implemented functions. + * + * @template TType Type being stubbed. + * @param constructor Object or class to stub. + * @returns A stubbed version of the constructor. + * @remarks The given constructor function is not invoked. See also the stub API. + */ + createStubInstance( + constructor: StubbableType + ): SinonStubbedInstance; + } + + interface SinonApi { + fake: SinonFake; + match: SinonMatch; + spyCall(...args: any[]): SinonSpyCall; + expectation: SinonExpectationStatic; + + clock: { + create(now: number | Date): SinonFakeTimers; + }; + + FakeXMLHttpRequest: SinonFakeXMLHttpRequestStatic; + + fakeServer: SinonFakeServerStatic; + fakeServerWithClock: SinonFakeServerStatic; + + /** + * Creates a new sandbox object with spies, stubs, and mocks. + * @param config + */ + createSandbox(config?: Partial): SinonSandbox; + defaultConfig: Partial; + } + + interface LegacySandbox { + sandbox: { + /** + * @deprecated Since 5.0, use `sinon.createSandbox` instead + */ + create(config?: Partial): SinonSandbox; + }; + } + + type SinonStatic = SinonSandbox & LegacySandbox & SinonApi; +} + +declare const Sinon: Sinon.SinonStatic; + +export = Sinon; +export as namespace sinon; diff --git a/types/sinon/ts3.1/sinon-tests.ts b/types/sinon/ts3.1/sinon-tests.ts new file mode 100644 index 0000000000..b892f22980 --- /dev/null +++ b/types/sinon/ts3.1/sinon-tests.ts @@ -0,0 +1,488 @@ +import sinon = require("sinon"); + +function testSandbox() { + const obj = {}; + + sinon.createSandbox({ + injectInto: obj, + properties: ['spy', 'stub'], + useFakeTimers: true, + useFakeServer: true + }); + sinon.createSandbox({ + injectInto: null + }); + sinon.createSandbox({ + useFakeTimers: { + now: 1000, + shouldAdvanceTime: false + }, + useFakeServer: sinon.fakeServer.create() + }); + sinon.createSandbox(sinon.defaultConfig); + sinon.sandbox.create(); + sinon.sandbox.create(sinon.defaultConfig); + + const sb = sinon.createSandbox(); + + sb.assert.pass('foo'); + sb.clock.tick(1000); + sb.spy(); + sb.stub(); + sb.mock(obj); + + sb.useFakeTimers(); + sb.useFakeTimers(1000); + sb.useFakeTimers(new Date()); + sb.useFakeTimers({ + now: 1000 + }); + + const xhr = sb.useFakeXMLHttpRequest(); + xhr.useFilters = true; + xhr.restore(); + + const server = sb.useFakeServer(); + server.respondWith('foo'); + + sb.restore(); + sb.reset(); + sb.resetHistory(); + sb.resetBehavior(); + sb.usingPromise(Promise); + sb.verify(); + sb.verifyAndRestore(); + + const replaceMe = { + prop: 5, + method() { return 6; }, + get getter() { return 7; }, + get setter() { return true; }, + set setter(val) { } + }; + + sb.replace(replaceMe, 'prop', 10); + sb.replace(replaceMe, 'method', sb.spy()); + sb.replaceGetter(replaceMe, 'getter', () => 14); + sb.replaceSetter(replaceMe, 'setter', (v) => { }); + + const cls = class { + foo() { } + bar: number; + }; + const PrivateFoo = class { + private constructor() { } + foo() { } + bar: number; + static create() { + return new PrivateFoo(); + } + }; + + const stubInstance = sb.createStubInstance(cls); + const privateFooStubbedInstance = sb.createStubInstance(PrivateFoo); + stubInstance.foo.calledWith('foo'); + privateFooStubbedInstance.foo.calledWith('foo'); + const clsFoo: sinon.SinonStub = stubInstance.foo; + const privateFooFoo: sinon.SinonStub = privateFooStubbedInstance.foo; + const clsBar: number = stubInstance.bar; + const privateFooBar: number = privateFooStubbedInstance.bar; +} + +function testFakeServer() { + let s = sinon.fakeServer.create(); + s = sinon.fakeServerWithClock.create(); + + sinon.fakeServer.create({ + autoRespond: true, + autoRespondAfter: 3, + fakeHTTPMethods: true, + respondImmediately: false + }); + + sinon.fakeServer.create({ + autoRespond: true, + autoRespondAfter: 3 + }); +} + +function testXHR() { + const xhr = new sinon.FakeXMLHttpRequest(); + const headers = xhr.getAllResponseHeaders(); + const header = xhr.getResponseHeader('foo'); + + xhr.setResponseHeaders({ 'Content-Type': 'text/html' }); + xhr.setResponseBody('foo'); + xhr.respond(200, { 'Content-Type': 'foo' }, 'bar'); + xhr.error(); + + sinon.FakeXMLHttpRequest.useFilters = true; + sinon.FakeXMLHttpRequest.addFilter((method, url, async, user, pass) => true); + sinon.FakeXMLHttpRequest.onCreate = (xhr) => { }; + sinon.FakeXMLHttpRequest.restore(); +} + +function testClock() { + let clock = sinon.clock.create(1000); + clock = sinon.clock.create(new Date()); + + let now = 0; + now = clock.now; + + const fn = () => { }; + + clock.setTimeout(fn, 0); + clock.setTimeout(fn, 0, 'a', 'b'); + clock.setInterval(fn, 0); + clock.setInterval(fn, 0, 'a', 'b'); + clock.setImmediate(fn); + clock.setImmediate(fn, 'a', 'b'); + clock.requestAnimationFrame(fn); + + let timer = clock.setTimeout(fn, 0); + clock.clearTimeout(timer); + timer = clock.setInterval(fn, 0); + clock.clearInterval(timer); + timer = clock.setImmediate(fn); + clock.clearImmediate(timer); + + const animTimer = clock.requestAnimationFrame(fn); + clock.cancelAnimationFrame(animTimer); + + clock.nextTick(fn); + clock.tick(1); + clock.tick('00:10'); + clock.next(); + clock.runAll(); + clock.runToLast(); + clock.reset(); + clock.runMicrotasks(); + clock.runToFrame(); + clock.restore(); + clock.uninstall(); + clock.setSystemTime(1000); + clock.setSystemTime(new Date()); +} + +function testExpectation() { + const obj = {}; + + let ex = sinon.expectation.create(); + ex = sinon.expectation.create('some name'); + + ex.atLeast(5).atMost(10); + ex.never(); + ex.once(); + ex.twice(); + ex.thrice(); + ex.exactly(5); + ex.withArgs('a', 'b'); + ex.withExactArgs('a', 'b'); + ex.on(obj); + ex.verify(); + ex.restore(); +} + +function testMatch() { + const obj = {}; + const fn = () => { }; + + sinon.match(5).test(5); + sinon.match('str').test('foo'); + sinon.match(/foo/).test('foo'); + sinon.match({ a: 5, b: 6 }).test({}); + sinon.match((v) => true).test('foo'); + sinon.match((v) => true, 'some message').test('foo'); + sinon.match.any.test('foo'); + sinon.match.defined.test('foo'); + sinon.match.truthy.test('foo'); + sinon.match.falsy.test('foo'); + sinon.match.bool.test('foo'); + sinon.match.number.test('foo'); + sinon.match.string.test('foo'); + sinon.match.object.test('foo'); + sinon.match.func.test(fn); + sinon.match.map.test(new Map([['a', 1], ['b', 2]])); + sinon.match.set.test(new Set([1, 2, 3])); + sinon.match.array.test([1, 2, 3]); + sinon.match.regexp.test('foo'); + sinon.match.date.test('foo'); + sinon.match.symbol.test('foo'); + sinon.match.same(obj); + sinon.match.typeOf('string').test('foo'); + sinon.match.instanceOf(fn).test('foo'); + sinon.match.has('prop').test(obj); + sinon.match.has('prop', 123).test(obj); + sinon.match.hasOwn('prop').test(obj); + sinon.match.hasOwn('prop', 123).test(obj); + sinon.match.hasNested('prop.foo.bar').test(obj); + sinon.match.hasNested('prop.foo.bar', 123).test(obj); + sinon.match.every(sinon.match.number).test([1, 2, 'three']); + sinon.match.some(sinon.match.number).test([1, 2, 'three']); + sinon.match.array.deepEquals([{ a: 'b' }]).test([]); + sinon.match.array.startsWith([{ a: 'b' }]).test([]); + sinon.match.array.deepEquals([{ a: 'b' }]).test([]); + sinon.match.array.contains([{ a: 'b' }]).test([]); + sinon.match.map.deepEquals(new Map([['a', true], ['b', false]])).test(new Map()); + sinon.match.map.contains(new Map([['a', true]])).test(new Map()); +} + +function testFake() { + const fn = () => { }; + let fake = sinon.fake(); + + fake = sinon.fake(() => true); + fake = sinon.fake.returns(5); + fake = sinon.fake.throws('foo'); + fake = sinon.fake.throws(new Error('foo')); + fake = sinon.fake.resolves('foo'); + fake = sinon.fake.rejects('foo'); + fake = sinon.fake.yields(1, 2, fn); + fake = sinon.fake.yieldsAsync(1, 2, fn); + + fake.calledWith('foo'); +} + +function testAssert() { + const spy = sinon.spy(); + const spyTwo = sinon.spy(); + const obj = {}; + + sinon.assert.fail(); + sinon.assert.fail('foo'); + sinon.assert.pass('foo'); + sinon.assert.notCalled(spy); + sinon.assert.called(spy); + sinon.assert.calledOnce(spy); + sinon.assert.calledTwice(spy); + sinon.assert.calledThrice(spy); + sinon.assert.callCount(spy, 3); + sinon.assert.callOrder(spy, spyTwo); + sinon.assert.calledOn(spy, obj); + sinon.assert.calledOn(spy.firstCall, obj); + sinon.assert.alwaysCalledOn(spy, obj); + sinon.assert.alwaysCalledWith(spy, 'a', 'b', 'c'); + sinon.assert.neverCalledWith(spy, 'a', 'b', 'c'); + sinon.assert.calledWithExactly(spy, 'a', 'b', 'c'); + sinon.assert.alwaysCalledWithExactly(spy, 'a', 'b', 'c'); + sinon.assert.calledWithMatch(spy, 'a', 'b', 'c'); + sinon.assert.calledWithMatch(spy.firstCall, 'a', 'b', 'c'); + sinon.assert.alwaysCalledWithMatch(spy, 'a', 'b', 'c'); + sinon.assert.neverCalledWithMatch(spy, 'a', 'b', 'c'); + sinon.assert.calledWithNew(spy); + sinon.assert.calledWithNew(spy.firstCall); + sinon.assert.threw(spy); + sinon.assert.threw(spy.firstCall); + sinon.assert.threw(spy, 'foo error'); + sinon.assert.threw(spy.firstCall, 'foo error'); + sinon.assert.threw(spy, new Error('foo')); + sinon.assert.threw(spy.firstCall, new Error('foo')); + sinon.assert.alwaysThrew(spy); + sinon.assert.alwaysThrew(spy, 'foo error'); + sinon.assert.alwaysThrew(spy, new Error('foo')); + sinon.assert.match('a', 'b'); + sinon.assert.match(1, 1 + 1); + sinon.assert.match({ a: 1 }, { b: 2, c: 'abc' }); + sinon.assert.expose(obj); + sinon.assert.expose(obj, { prefix: 'blah' }); + sinon.assert.expose(obj, { includeFail: true }); +} + +function testTypedSpy() { + const cls = class { + foo(a: number, b: string): number { + return 3; + } + }; + + const instance = new cls(); + const spy = sinon.spy(instance, 'foo'); + + spy.calledWith(5, 'x'); + spy.calledWith(sinon.match(5), 'x'); + spy.calledWithExactly(5, 'x'); + spy.calledWithExactly(5, sinon.match('x')); + spy.calledOnceWith(5, 'x'); + spy.calledOnceWith(sinon.match(5), 'x'); + spy.notCalledWith(5, 'x'); + spy.notCalledWith(sinon.match(5), 'x'); + spy.returned(5); + spy.returned(sinon.match(5)); + + spy.withArgs(sinon.match(5), 'x').calledWith(5, 'x'); + spy.alwaysCalledWith(sinon.match(5), 'x'); + spy.alwaysCalledWith(5, 'x'); + spy.alwaysCalledWithExactly(sinon.match(5), 'x'); + spy.alwaysCalledWithExactly(5, 'x'); + spy.neverCalledWith(sinon.match(5), 'x'); + spy.neverCalledWith(5, 'x'); + + const stub = sinon.stub(instance, 'foo'); + + stub.withArgs(5, 'x').returns(3); + stub.withArgs(sinon.match(5), 'x').returns(5); +} + +function testSpy() { + const fn = () => { }; + const obj = class { + foo() { } + }; + const instance = new obj(); + + let spy = sinon.spy(); + const spyTwo = sinon.spy().named('spyTwo'); + + spy = sinon.spy(fn); + spy = sinon.spy(instance, 'foo'); + + let count = 0; + count = spy.callCount; + + let called = false; + called = spy.called; + called = spy.notCalled; + called = spy.calledOnce; + called = spy.calledTwice; + called = spy.calledThrice; + + let arr: any[] = []; + arr = spy.thisValues; + arr = spy.args; + arr = spy.exceptions; + arr = spy.returnValues; + + spy('a', 'b'); + spy(1, 2); + spy(true); + + spy.calledBefore(spyTwo); + spy.calledAfter(spyTwo); + spy.calledImmediatelyBefore(spyTwo); + spy.calledImmediatelyAfter(spyTwo); + spy.calledWithNew(); + spy.withArgs('a', 1).calledBefore(spyTwo); + spy.alwaysCalledOn(instance); + spy.alwaysCalledWith('a', 1); + spy.alwaysCalledWith('a'); + spy.alwaysCalledWithExactly('a', 1); + spy.alwaysCalledWithMatch('foo'); + spy.neverCalledWith('b', 2); + spy.neverCalledWith('b'); + spy.neverCalledWithMatch('foo', 'bar'); + spy.alwaysThrew(); + spy.alwaysThrew('foo'); + spy.alwaysThrew(new Error('foo')); + spy.alwaysReturned('foo'); + spy.invokeCallback('a', 'b'); + spy.calledOn(instance); + spy.calledWith('a', 2); + spy.calledWithExactly('a', 2); + spy.calledOnceWith('a', 2); + spy.calledOnceWithExactly('a', 2); + spy.calledWithMatch('bar', 2); + spy.notCalledWith('a', 2); + spy.notCalledWithMatch('a', 2); + spy.returned(true); + spy.returned('foo'); + spy.returned(2); + spy.threw(); + spy.threw('foo'); + spy.threw(new Error('foo')); + spy.callArg(1); + spy.callArgOn(1, instance); + spy.callArgOn(1, instance, 'a', 2); + spy.callArgWith(1, 'a', 2); + spy.callArgOnWith(1, instance, 'a', 2); + spy.yield('a', 2); + spy.yieldOn(instance, 'a', 2); + spy.yieldTo('prop', 'a', 2); + spy.yieldToOn('prop', instance, 'a', 2); + + let call = spy.firstCall; + call = spy.secondCall; + call = spy.thirdCall; + call = spy.lastCall; + call = spy.getCall(1); + call = spy.getCalls()[0]; + + call.calledBefore(call); + call.calledAfter(call); + call.calledWithNew(); + + spy.resetHistory(); + spy.restore(); +} + +function testStub() { + const obj = class { + foo() { } + }; + const instance = new obj(); + + let stub = sinon.stub(); + stub = sinon.stub(instance, 'foo').named('namedStub'); + + const spy: sinon.SinonSpy = stub; + + sinon.stub(instance); + + stub.reset(); + stub.resetBehavior(); + stub.usingPromise(Promise); + + stub.returns(true); + stub.returns(5); + stub.returns('foo'); + stub.returnsArg(1); + stub.returnsThis(); + stub.resolves(); + stub.resolves('foo'); + stub.resolvesArg(1); + stub.resolvesThis(); + stub.throws(); + stub.throws('err'); + stub.throws(new Error('err')); + stub.throwsArg(1); + stub.throwsException('err'); + stub.throwsException(new Error('err')); + stub.rejects(); + stub.rejects('TypeError'); + stub.rejects(1234); + stub.callsArg(1); + stub.callThrough(); + stub.callsArgOn(1, instance); + stub.callsArgWith(1, 'a', 2); + stub.callsArgAsync(1); + stub.callsArgOnAsync(1, instance); + stub.callsArgWithAsync(1, 'a', 2); + stub.callsArgOnWithAsync(1, instance, 'a', 2); + stub.callsFake((s1, s2, s3) => { }); + stub.callsFake(() => { }); + stub.get(() => true); + stub.set((v) => { }); + stub.onCall(1).returns(true); + stub.onFirstCall().resolves('foo'); + stub.onSecondCall().resolves('foo'); + stub.onThirdCall().resolves('foo'); + stub.value('foo'); + stub.yields('a', 2); + stub.yieldsOn(instance, 'a', 2); + stub.yieldsRight('a', 2); + stub.yieldsTo('foo', 'a', 2); + stub.yieldsToOn('foo', instance, 'a', 2); + stub.yieldsAsync('a', 2); + stub.yieldsOnAsync(instance, 'a', 2); + stub.yieldsToAsync('foo', 'a', 2); + stub.yieldsToOnAsync('foo', instance, 'a', 2); + stub.withArgs('a', 2).returns(true); +} + +function testMock() { + const obj = {}; + const mock = sinon.mock(obj); + + mock.expects('method').atLeast(2).atMost(5); + mock.restore(); + mock.verify(); +} diff --git a/types/sinon/ts3.1/tsconfig.json b/types/sinon/ts3.1/tsconfig.json new file mode 100644 index 0000000000..7468efa8bf --- /dev/null +++ b/types/sinon/ts3.1/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "target": "es5", + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "sinon-tests.ts" + ] +} diff --git a/types/sinon/ts3.1/tslint.json b/types/sinon/ts3.1/tslint.json new file mode 100644 index 0000000000..1b62a88e52 --- /dev/null +++ b/types/sinon/ts3.1/tslint.json @@ -0,0 +1,7 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "ban-types": false, + "unified-signatures": false + } +} diff --git a/types/sip.js/index.d.ts b/types/sip.js/index.d.ts index 65466ee840..7ca7c2eb98 100644 --- a/types/sip.js/index.d.ts +++ b/types/sip.js/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for sip.js 0.8 +// Type definitions for sip.js 0.9 // Project: http://sipjs.com // Definitions by: Kir Dergachev // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -75,6 +75,8 @@ export namespace C { export type DescriptionModifier = (description: RTCSessionDescription) => Promise; export interface SessionDescriptionHandler { + peerConnection: any; + getDescription(options: SessionDescriptionHandlerParameters, modifiers: DescriptionModifier[]): Promise; setDescription(sessionDescription: string, options: SessionDescriptionHandlerParameters, modifiers: DescriptionModifier[]): Promise; hasDescription: (contentType: string) => boolean; @@ -128,11 +130,16 @@ export interface Session { on(name: 'accepted', callback: (data: { code: number, response: IncomingResponse }) => void): void; on(name: 'failed' | 'rejected', callback: (response: IncomingResponse, cause: string) => void): void; on(name: 'terminated', callback: (message: IncomingResponse, cause: string) => void): void; - on(name: 'cancel' | string, callback: () => void): void; - on(name: 'replaced', callback: (newSession: Session) => void): void; + on(name: 'cancel' | 'directionChanged' | 'trackAdded' | 'SessionDescriptionHandler-created' | string, callback: () => void): void; + on(name: 'replaced' | 'reinvite', callback: (newSession: Session) => void): void; on(name: 'dtmf', callback: (request: IncomingRequest, dtmf: Session.DTMF) => void): void; on(name: 'muted' | 'unmuted', callback: (data: Session.Muted) => void): void; - on(name: 'refer' | 'bye', callback: (request: IncomingRequest) => void): void; + on(name: 'refer' | 'bye' | 'notify', callback: (request: IncomingRequest) => void): void; + on(name: 'referRequested', callback: (request: ClientContext | ServerContext) => void): void; + + /* these come from the ClientContext that is on the session somehow */ + on(name: 'referAccepted' | 'referRejected' | 'referRequestAccepted' | 'referRequestRejected' | 'referProgress', + callback: (ClientContext: ClientContext) => void): void; } export namespace Session { @@ -164,7 +171,10 @@ export namespace Session { }; } - interface DTMF extends Object { } + interface DTMF extends Object { + direction: string | 'incoming'; + tone: any; + } interface Muted { audio?: boolean; @@ -364,27 +374,40 @@ export interface Subscription extends ClientContext { } /* Context */ -export interface Context { +export class Context { ua: UA; method: string; request: OutgoingRequest; localIdentity: NameAddrHeader; remoteIdentity: NameAddrHeader; data: {}; +} + +export class ClientContext extends Context { + cancel(options?: { status_code?: number, reason_phrase?: string }): ClientContext; + + // This exists on all Context, but I cant make it work right on(name: 'progress' | 'accepted' | 'rejected' | 'failed', callback: (response: IncomingMessage, cause: string) => void): void; on(name: 'notify', callback: (request: IncomingRequest) => void): void; on(name: string, callback: () => void): void; + + on(name: 'referAccepted' | 'referRejected' | 'referRequestAccepted' | 'referRequestRejected' | 'referProgress', + callback: (ClientContext: ClientContext) => void): void; } -export interface ClientContext extends Context { - cancel(options?: { status_code?: number, reason_phrase?: string }): ClientContext; -} - -export interface ServerContext extends Context { +export class ServerContext extends Context { progress(options?: Session.ProgressOptions): void; accept(options?: Session.AcceptOptions): void; reject(options?: Session.CommonOptions): void; reply(options?: Session.CommonOptions): void; + + // This exists on all Context, but I cant make it work right + on(name: 'progress' | 'accepted' | 'rejected' | 'failed', callback: (response: IncomingMessage, cause: string) => void): void; + on(name: 'notify', callback: (request: IncomingRequest) => void): void; + on(name: string, callback: () => void): void; + + on(name: 'referRequestAccepted' | 'referRequestRejected' | 'referInviteSent' | 'referProgress' | 'referAccepted' | 'referRejected', + callback: (ServerContext: ServerContext) => void): void; } /* Request */ @@ -398,6 +421,7 @@ export interface OutgoingRequest extends Request { } export interface IncomingResponse extends Request { + reason_phrase: string | 'Ringing'; } export interface IncomingMessage extends Request { diff --git a/types/sketchapp/index.d.ts b/types/sketchapp/index.d.ts new file mode 100644 index 0000000000..6d9776aaa7 --- /dev/null +++ b/types/sketchapp/index.d.ts @@ -0,0 +1,516 @@ +// Type definitions for the SketchApp 1.0 +// Project: https://github.com/xlayers/xlayers +// Definitions by: Wassim Chegham +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +type SketchMSBorderPositionEnum = 0 | 1 | 2 | 3; +type SketchMSBorderLineCapStyle = 0 | 1 | 2; +type SketchMSBorderLineJoinStyle = 0 | 1 | 2; +type SketchMSFillTypeEnum = 0 | 1 | 4 | 5; +type SketchMSPatternFillTypeEnum = 0 | 1 | 2 | 3; +type SketchMSBlendModeEnum = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15; +type SketchMSLineDecorationTypeEnum = 0 | 1 | 2 | 3; +type SketchMSBooleanOperation = -1 | 0 | 1 | 2 | 3; +type SketchMSCurveMode = 0 | 1 | 2 | 3 | 4; +type SketchMSResizingType = 0 | 1 | 2 | 3; +type SketchMSLayerListExpandedType = 0 | 1 | 2; +type SketchMSEncodedBase64BinaryPlist = string; +type SketchMSNSColorArchive = SketchMSKeyValueArchive; +type SketchMSLayer = SketchMSPage | SketchMSSymbolMaster; +interface SketchMSNestedSymbolOverride { + symbolID: string; +} +interface SketchMSStringAttribute { + _class: 'stringAttribute'; + attributes: { + MSAttributedStringFontAttribute: { + _class: 'fontDescriptor'; + attributes: { + name: string; + size: number; + } + }; + paragraphStyle: { + _class: 'paragraphStyle', + allowsDefaultTighteningForTruncation: number + }, + foregroundColor: SketchMSKeyValueArchive + }; +} +interface SketchMSAttributedString { + _class: 'attributedString'; + string: string; + attributes: SketchMSStringAttribute[]; + archivedAttributedString?: SketchMSKeyValueArchive; +} +interface SketchMSKeyValueArchive { + _archive: SketchMSEncodedBase64BinaryPlist; +} +interface SketchMSFontAttribute { + _class: 'fontDescriptor'; + _archive?: string; + attributes: { + name: string; + size: number; + }; +} +interface SketchMSBorder { + _class: 'border'; + isEnabled: boolean; + color: SketchMSColor; + fillType: SketchMSFillTypeEnum; + position: SketchMSBorderPositionEnum; + thickness: number; +} +interface SketchMSBorderOptions { + _class: 'borderOptions'; + isEnabled: boolean; + dashPattern: number[]; + lineCapStyle: SketchMSBorderLineCapStyle; + lineJoinStyle: SketchMSBorderLineJoinStyle; +} + +interface SketchMSImageDataReference { + _class: 'jSONOriginalDataReference'; + _ref: string; + _ref_class: 'imageData'; + data: { + _data: string; + }; + sha1: { + _data: string; + }; +} +type SketchMSPointString = string; +interface SketchMSPath { + _class: 'path'; + isClosed: boolean; + points: SketchMSCurvePoint[]; +} +interface SketchMSCurvePoint { + _class: 'curvePoint'; + cornerRadius: number; + curveFrom: SketchMSPointString; + curveMode: SketchMSCurveMode; + curveTo: SketchMSPointString; + hasCurveFrom: boolean; + hasCurveTo: boolean; + point: SketchMSPointString; +} + +interface SketchMSFill { + _class: 'fill'; + isEnabled: boolean; + color?: SketchMSColor; + fillType: SketchMSFillTypeEnum; + image?: SketchMSImageDataReference; + noiseIndex: number; + noiseIntensity: number; + patternFillType: SketchMSPatternFillTypeEnum; + patternTileScale: number; +} +interface SketchMSShadow { + _class: 'shadow' | 'MSInnerShadow'; + isEnabled: boolean; + blurRadius: number; + color: SketchMSColor; + contextSettings: SketchMSGraphicsContextSettings; + offsetX: number; + offsetY: number; + spread: number; +} +interface SketchMSImageCollection { + do_objectID?: string; + _class: 'imageCollection'; + images: any[]; +} +interface SketchMSAssetCollection { + do_objectID?: string; + _class: 'assetCollection'; + gradients: any[]; + colors: any[]; + imageCollection: SketchMSImageCollection; + images: any[]; +} +interface SketchMSStyleBorder { + position: number; + color: SketchMSColor; + do_objectID?: string; + _class: 'styleBorder'; + gradient: SketchMSGradient; + fillType: number; + thickness: number; + contextSettings: SketchMSGraphicsContextSettings; + isEnabled: number; +} +interface SketchMSGradientStop { + do_objectID?: string; + _class: 'gradientStop'; + color: SketchMSColor; + position: number; +} +interface SketchMSGradient { + from: { + x: number; + y: number; + }; + shouldSmoothenOpacity: boolean; + gradientType: number; + do_objectID?: string; + _class: 'gradient'; + stops: SketchMSGradientStop[]; + to: { + x: number; + y: number; + }; + elipseLength: number; +} +interface SketchMSStyleFill { + contextSettings: SketchMSGraphicsContextSettings; + color: SketchMSColor; + do_objectID?: string; + _class: 'styleFill'; + gradient: SketchMSGradient; + fillType: number; + noiseIntensity: number; + patternFillType: number; + patternTileScale: number; + noiseIndex: number; + isEnabled: number; +} +interface SketchMSStyleShadow { + spread: number; + color: SketchMSColor; + offsetY: number; + offsetX: number; + do_objectID?: string; + _class: 'styleShadow'; + blurRadius: number; + contextSettings: SketchMSGraphicsContextSettings; + isEnabled: number; +} +interface SketchMSSharedStyle { + do_objectID?: string; + _class: 'sharedStyle'; + value: SketchMSStyle; + objectID: string; + name: string; +} +interface SketchMSTextStyle { + _class: 'textStyle'; + encodedAttributes: { + MSAttributedStringColorAttribute?: SketchMSColor; + NSColor: SketchMSKeyValueArchive; + MSAttributedStringFontAttribute?: SketchMSFontAttribute; + NSParagraphStyle?: SketchMSKeyValueArchive; + NSKern: number; + }; +} +interface SketchMSSharedStyleContainer { + do_objectID?: string; + _class: 'sharedStyleContainer'; + objects: SketchMSSharedStyle[]; +} +interface SketchMSStyleBorderOptions { + lineJoinStyle: number; + do_objectID?: string; + _class: 'styleBorderOptions'; + isEnabled: number; + lineCapStyle: number; + dashPattern: any[]; +} +interface SketchMSGraphicsContextSettings { + do_objectID?: string; + _class: 'graphicsContextSettings'; + opacity: number; + blendMode: number; +} +interface SketchMSStyleBlur { + radius: number; + do_objectID?: string; + _class: 'styleBlur'; + motionAngle: number; + isEnabled: number; + type: number; + center: { + x: number; + y: number; + }; +} +interface SketchMSStyleReflection { + do_objectID?: string; + _class: 'styleReflection'; + strength: number; + isEnabled: number; + distance: number; +} +interface SketchMSStyleColorControls { + hue: number; + do_objectID?: string; + _class: 'styleColorControls'; + brightness: number; + contrast: number; + isEnabled: number; + saturation: number; +} +interface SketchMSStyle { + startDecorationType: number; + borderOptions: SketchMSStyleBorderOptions; + endDecorationType: number; + contextSettings: SketchMSGraphicsContextSettings; + blur: SketchMSStyleBlur; + textStyle: SketchMSTextStyle; + reflection: SketchMSStyleReflection; + do_objectID?: string; + _class: 'style'; + miterLimit: number; + colorControls: SketchMSStyleColorControls; + fills: SketchMSStyleFill[]; + borders: SketchMSStyleBorder[]; + innerShadows: SketchMSStyleShadow[]; + shadows: SketchMSStyleShadow[]; +} +interface SketchMSRulerData { + do_objectID?: string; + _class: 'rulerData'; + base: number; + guides: any[]; +} +interface SketchMSRect { + y: number; + do_objectID?: string; + _class: 'rect'; + constrainProportions: boolean; + height: number; + width: number; + x: number; +} +interface SketchMSExportOptions { + shouldTrim: boolean; + do_objectID?: string; + _class: 'exportOptions'; + includedLayerIds: any[]; + layerOptions: number; + exportFormats: any[]; +} +interface SketchMSColor { + do_objectID?: string; + _class: 'color'; + + /** + * ex: "#FFFFFF" + * ex: rgb(1,0,1) + */ + value: string; + red: number; + green: number; + blue: number; + alpha: number; +} +interface SketchMSSimpleGrid { + do_objectID?: string; + _class: 'simpleGrid'; + thickGridTimes: number; + objectID: string; + isEnabled: number; + gridSize: number; +} +interface SketchMSLayoutGrid { + columnWidth: number; + totalWidth: number; + drawHorizontalLines: number; + objectID: string; + gutterWidth: number; + horizontalOffset: number; + isEnabled: number; + do_objectID?: string; + _class: 'layoutGrid'; + gutterHeight: number; + drawHorizontal: number; + guttersOutside: number; + numberOfColumns: number; + drawVertical: number; + rowHeightMultiplication: number; +} +interface SketchMSSymbolMaster { + isFlippedHorizontal: number; + includeBackgroundColorInInstance: number; + objectID: string; + horizontalRulerData: SketchMSRulerData; + frame: SketchMSRect; + hasClickThrough: number; + includeInCloudUpload: number; + exportOptions: SketchMSExportOptions; + hasBackgroundColor: number; + layerListExpandedType: number; + resizesContent: number; + backgroundColor: SketchMSColor; + rotation: number; + style: SketchMSStyle; + verticalRulerData: SketchMSRulerData; + constrainProportions: boolean; + isFlippedVertical: number; + do_objectID?: string; + _class: 'symbolMaster'; + attributedString: SketchMSAttributedString; + name: string; + layers: SketchMSLayer[]; + isVisible: boolean; + nameIsFixed: boolean; + grid: SketchMSSimpleGrid; + resizingType: number; + userInfo: any; + isLocked: boolean; + layout: SketchMSLayoutGrid; + shouldBreakMaskChain: number; + resizingConstraint: 63 | number; + includeBackgroundColorInExport: number; + flow?: SketchMSImmutableFlowConnection; + + // add this property to hold all CSS properties + // of the current layer + css?: { [key: string]: string }; +} +interface SketchMSSymbolInstanceLayer { + _class: 'symbolInstance'; + frame: SketchMSRect; + horizontalSpacing: number; + verticalSpacing: number; + masterInfluenceEdgeMinXPadding?: number; + masterInfluenceEdgeMaxXPadding?: number; + masterInfluenceEdgeMinYPadding?: number; + masterInfluenceEdgeMaxYPadding?: number; + symbolID: string; + overrides?: { + [objectId: string]: string | SketchMSNestedSymbolOverride | SketchMSImageDataReference; + }; + isFlippedHorizontal: number; + includeBackgroundColorInInstance: number; + objectID: string; + horizontalRulerData: SketchMSRulerData; + hasClickThrough: number; + includeInCloudUpload: number; + exportOptions: SketchMSExportOptions; + hasBackgroundColor: number; + layerListExpandedType: number; + resizesContent: number; + backgroundColor: SketchMSColor; + rotation: number; + style: SketchMSStyle; + verticalRulerData: SketchMSRulerData; + isFlippedVertical: number; + do_objectID?: string; + name: string; + layers: SketchMSLayer[]; + isVisible: boolean; + nameIsFixed: boolean; + grid: SketchMSSimpleGrid; + resizingType: number; + userInfo: any; + isLocked: boolean; + layout: SketchMSLayoutGrid; + shouldBreakMaskChain: number; + resizingConstraint: 63 | number; + includeBackgroundColorInExport: number; + flow?: SketchMSImmutableFlowConnection; +} +interface SketchMSPage { + isFlippedHorizontal: number; + style: SketchMSStyle; + horizontalRulerData: SketchMSRulerData; + frame: SketchMSRect; + hasClickThrough: number; + includeInCloudUpload: number; + exportOptions: SketchMSExportOptions; + objectID: string; + id: string; + rotation: number; + layerListExpandedType: number; + verticalRulerData: SketchMSRulerData; + isFlippedVertical: number; + resizingType: number; + do_objectID?: string; + _class: 'page' | 'layer'; + layers: SketchMSLayer[]; + isVisible: boolean; + nameIsFixed: number; + name: string; + constrainProportions: boolean; + attributedString: SketchMSAttributedString; + isLocked: boolean; + shouldBreakMaskChain: number; + resizingConstraint: number; + fixedRadius: number; + + // add this property to hold all CSS properties + // of the current layer + css?: { [key: string]: string }; +} +interface SketchMSSharedTextStyleContainer { + do_objectID?: string; + _class: 'sharedTextStyleContainer'; + objects: any[]; +} +interface SketchMSSymbolContainers { + do_objectID?: string; + _class: 'symbolContainer'; + objects: any[]; +} +interface SketchMSDocumentData { + assets: SketchMSAssetCollection; + currentPageIndex: number; + foreignSymbols: any[]; + layerStyles: SketchMSSharedStyleContainer; + pages: SketchMSPage[]; + enableSliceInteraction: number; + do_objectID?: string; + _class: 'documentData'; + layerTextStyles: SketchMSSharedTextStyleContainer; + enableLayerInteraction: number; + layerSymbols: SketchMSSymbolContainers; + objectID: string; +} +interface SketchMSArtboards { + name: string; + artboards: SketchMSArtboard; +} +interface SketchMSArtboard { + frame: SketchMSRect; + backgroundColor: SketchMSColor; + hasBackgroundColor: boolean; + horizontalRulerData?: SketchMSRulerData; + verticalRulerData?: SketchMSRulerData; + includeBackgroundColorInExport?: boolean; + includeInCloudUpload?: boolean; + isFlowHome?: boolean; +} +interface SketchMSPagesAndArtboards { + [key: string]: SketchMSArtboards; +} +interface SketchMSMetadata { + commit: string; + pagesAndArtboards: SketchMSPagesAndArtboards; + version: number; + fonts: string[]; + compatibilityVersion: number; + app: string; + autosaved: number; + variant: string; + created: { + commit: string; + appVersion: string; + build: number; + app: string; + compatibilityVersion: number; + version: number; + variant: string; + }; + saveHistory: string[]; + appVersion: string; + build: number; +} +interface SketchMSImmutableFlowConnection { + _class: 'immutableFlowConnection'; + animationType: number; + destinationArtboardID?: string | 'back'; +} diff --git a/types/sketchapp/sketchapp-tests.ts b/types/sketchapp/sketchapp-tests.ts new file mode 100644 index 0000000000..14a2be96a9 --- /dev/null +++ b/types/sketchapp/sketchapp-tests.ts @@ -0,0 +1,5 @@ +console.log(` +In order to test thie SketchApp types, we need to parse a SketchApp file. +See the following repo for a real worl test case: +https://github.com/xlayers/xlayers/blob/develop/src/app/editor/viewer/lib/parsers/sketch-style-parser.service.spec.ts +`); diff --git a/types/sketchapp/tsconfig.json b/types/sketchapp/tsconfig.json new file mode 100644 index 0000000000..6f22fec54b --- /dev/null +++ b/types/sketchapp/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "sketchapp-tests.ts" + ] +} diff --git a/types/sketchapp/tslint.json b/types/sketchapp/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/sketchapp/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/slate-react/index.d.ts b/types/slate-react/index.d.ts index 540316befc..30e54f2a02 100644 --- a/types/slate-react/index.d.ts +++ b/types/slate-react/index.d.ts @@ -6,7 +6,7 @@ // Patrick Sachs // Brandon Shelton // Irwan Fario Subastian -// Sebastian Greaves +// Hanna Greaves // Francesco Agnoletto // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -18,8 +18,7 @@ import { Block, Inline, Operations, - Schema, - Stack, + SchemaProperties, Value, Operation, MarkProperties, @@ -112,7 +111,7 @@ export interface BasicEditorProps { plugins?: Plugin[]; readOnly?: boolean; role?: string; - schema?: Schema; + schema?: SchemaProperties; spellCheck?: boolean; style?: React.CSSProperties; tabIndex?: number; @@ -121,15 +120,11 @@ export interface BasicEditorProps { export type EditorProps = BasicEditorProps & Plugin; export interface EditorState { - schema: Schema; value: Value; - stack: Stack; } export class Editor extends React.Component implements Controller { controller: CoreEditor; - schema: Schema; - stack: Stack; readonly plugins: Plugin[]; readonly operations: Immutable.List; @@ -137,7 +132,7 @@ export class Editor extends React.Component implements readonly value: Value; // Instance methods - resolveController(plugins: Plugin[], schema: Schema, commands: any[], queries: any[]): void; + resolveController(plugins: Plugin[], schema: SchemaProperties, commands: any[], queries: any[]): void; // Controller addMark: CoreEditor['addMark']; diff --git a/types/slate/index.d.ts b/types/slate/index.d.ts index 5656c58bb3..2538bea6f9 100644 --- a/types/slate/index.d.ts +++ b/types/slate/index.d.ts @@ -7,7 +7,7 @@ // Kalley Powell // Francesco Agnoletto // Irwan Fario Subastian -// Sebastian Greaves +// Hanna Greaves // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 import * as Immutable from "immutable"; @@ -53,39 +53,9 @@ export interface SchemaProperties { inlines?: RulesByNodeType; } -export class Schema extends Immutable.Record({}) { - stack: Stack; - rules: Rules[]; - - static create(properties: SchemaProperties | Schema): Schema; - static fromJSON(object: SchemaProperties): Schema; - static fromJS(object: SchemaProperties): Schema; - static isSchema(maybeSchema: any): maybeSchema is Schema; - - validateNode(node: Node): Error | void; - testNode(node: Node): boolean; - assertNode(node: Node): boolean; - getNodeRules(node: Node): any[]; - isVoid(node: Node): boolean; - isAtomic(mark: Mark): boolean; - normalizeNode(node: Node): () => void; - testRules(object: any, rules: object | any[]): boolean; - validateRules( - object: any, - rule: object | any[], - rules: any[] | null, - options?: object - ): Error | void; - - toJSON(): SchemaProperties; - toJS(): SchemaProperties; -} - export interface ValueProperties { document?: Document; selection?: Selection; - history?: History; - schema?: Schema; data?: Data; decorations?: Immutable.List | null; } @@ -93,8 +63,6 @@ export interface ValueProperties { export interface ValueJSON { document?: DocumentJSON; selection?: Selection; - history?: History; - schema?: Schema; data?: Data; decorations?: Immutable.List | null; object?: "value"; @@ -105,8 +73,6 @@ export type Path = Immutable.List | string; export class Value extends Immutable.Record({}) { document: Document; selection: Selection; - history: History; - schema: Schema; data: Data; object: "value"; decorations: Immutable.List; @@ -319,7 +285,7 @@ export class Text extends Immutable.Record({}) { addMark(index: number, length: number, mark: Mark): Text; addMarks(index: number, lenght: number, marks: Immutable.Set): Text; getLeaves(decorations?: Range[]): Immutable.List; - getActiveMarksBetweenOffset( + getActiveMarksBetweenOffsets( startOffset: number, endOffset: number ): Immutable.Set; @@ -350,9 +316,6 @@ export class Text extends Immutable.Record({}) { ): Text; splitText(offset: number): Text[]; mergeText(text: Text): Text; - normalize(schema: Schema): () => void | null; - validate(schema: Schema): Error | null; - getFirstInvalidNode(schema: Schema): Text | null; setLeaves(leaves: Immutable.List): Text; } @@ -446,13 +409,12 @@ declare class BaseNode< getChild(path: Path): Node | null; getClosestBlock(path: Path): Block | null; getClosestInline(path: Path): Inline | null; - getClosestVoid(path: Path, schema: Schema): Node | null; + getClosestVoid(key: string | Path): Node | null; getClosest(path: Path, iterator: (node: Node) => boolean): Node | null; getCommonAncestor(a: Path, b: Path): Node; - getDecorations(stack: Stack): Immutable.List; + getDecorations(editor: Editor): Immutable.List; getDepth(path: Path, startAt?: number): number; getDescendant(path: Path): Node | null; - getFirstInvalidNode(schema: Schema): Node | null; getFirstText(): Text | null; getFragmentAtRange(range: Range): Document; getFurthest(path: Path, iterator: (node: Node) => boolean): Node | null; @@ -514,7 +476,7 @@ declare class BaseNode< hasInlineChildren(): boolean; hasDescendant(path: Path): boolean; hasNode(path: Path): boolean; - hasVoidParent(path: Path, schema: Schema): boolean; + hasVoidParent(path: Path, editor: Editor): boolean; insertNode(path: Path, node: Node): Node; insertText( path: Path, @@ -528,7 +490,7 @@ declare class BaseNode< mapDescendants(iterator: () => void): Node; mergeNode(path: Path): Node; moveNode(path: Path, newPath: Path, newIndex?: number): Node; - normalize(schema: Schema): () => void | void; + normalize(editor: Editor): () => void | void; refinedNOde(path: Path, key: string): Node | null; refindPath(path: Path, key: string): Immutable.List | null; regenerateKey(): Node; @@ -548,7 +510,7 @@ declare class BaseNode< properties: MarkProperties ): Node; splitNode(path: Path, position: number, properties: NodeProperties): Node; - validate(schema: Schema): Error | void; + validate(editor: Editor): Error | void; } export interface MarkProperties { @@ -914,61 +876,6 @@ export interface Operations { invert: (operation: Operation) => Operation; } -export interface StackProperties { - plugins?: any[]; -} - -export interface StackJSON { - object: "stack"; - plugins: any[]; -} - -export class Stack extends Immutable.Record({}) { - object: "stack"; - plugins: any[]; - - static create(attrs: StackProperties): Stack; - static isStack(maybeStack: any): maybeStack is Stack; - - static fromJSON(properties: StackJSON): Stack; - static fromJS(properties: StackJSON): Stack; - toJSON(options: any): object; -} - -export interface HistoryProperties { - undos?: Operation[]; - redos?: Operation[]; -} - -export interface HistoryJSON { - object: "history"; - undos: any[]; - redos: any[]; -} - -export interface HistoryOptions { - merge?: boolean; - skip?: boolean; -} - -export class History extends Immutable.Record({}) { - redos: Stack; - undos: Stack; - object: "history"; - - static create(attrs: History | HistoryProperties): History; - static createOperationsList( - oeprations?: Immutable.List | Operation[] - ): Immutable.List; - static fromJSON(object: HistoryJSON): History; - static fromJS(object: HistoryJSON): History; - static isHistory(maybeHistory: any): maybeHistory is History; - - save(operation: Operation, options?: HistoryOptions): History; - toJSON(): HistoryJSON; - toJS(): HistoryJSON; -} - export type ErrorCode = | "child_object_invalid" | "child_required" diff --git a/types/snakecase-keys/index.d.ts b/types/snakecase-keys/index.d.ts new file mode 100644 index 0000000000..d9afe0a2fd --- /dev/null +++ b/types/snakecase-keys/index.d.ts @@ -0,0 +1,19 @@ +// Type definitions for snakecase-keys 2.1 +// Project: https://github.com/bendrucker/snakecase-keys#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +export = snakecaseKeys; + +declare function snakecaseKeys( + obj: object, + options?: snakecaseKeys.Options +): { [key: string]: any }; + +declare namespace snakecaseKeys { + interface Options { + deep?: boolean; + exclude?: Array; + } +} diff --git a/types/snakecase-keys/snakecase-keys-tests.ts b/types/snakecase-keys/snakecase-keys-tests.ts new file mode 100644 index 0000000000..e74d13404f --- /dev/null +++ b/types/snakecase-keys/snakecase-keys-tests.ts @@ -0,0 +1,5 @@ +import snakecaseKeys = require('snakecase-keys'); + +snakecaseKeys({ fooBar: 'baz' }); +snakecaseKeys({ fooBar: 'baz' }, { deep: false }); +snakecaseKeys({ fooBar: 'baz' }, { exclude: ['fooBax', /Foo$/] }); diff --git a/types/snakecase-keys/tsconfig.json b/types/snakecase-keys/tsconfig.json new file mode 100644 index 0000000000..6d944fa502 --- /dev/null +++ b/types/snakecase-keys/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "snakecase-keys-tests.ts" + ] +} diff --git a/types/snakecase-keys/tslint.json b/types/snakecase-keys/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/snakecase-keys/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/socket.io/index.d.ts b/types/socket.io/index.d.ts index f5e6c5fd00..4ea2e0cbde 100644 --- a/types/socket.io/index.d.ts +++ b/types/socket.io/index.d.ts @@ -142,6 +142,17 @@ declare namespace SocketIO { */ origins( v: string|string[] ): Server; + /** + * Provides a function taking two arguments origin:String + * and callback(error, success), where success is a boolean + * value indicating whether origin is allowed or not. If + * success is set to false, error must be provided as a string + * value that will be appended to the server response, e.g. “Origin not allowed”. + * @param fn The function that will be called to check the origin + * return This Server + */ + origins( fn: ( origin: string, callback: ( error: string | null, success: boolean ) => void ) => void ): Server; + /** * Attaches socket.io to a server * @param srv The http.Server that we want to attach to @@ -169,7 +180,7 @@ declare namespace SocketIO { listen( port: number, opts?: ServerOptions ): Server; /** - * Binds socket.io to an engine.io intsance + * Binds socket.io to an engine.io instance * @param src The Engine.io (or compatible) server to bind to * @return This Server */ diff --git a/types/socket.io/v1/index.d.ts b/types/socket.io/v1/index.d.ts index 95a9ff1b4f..191680df46 100644 --- a/types/socket.io/v1/index.d.ts +++ b/types/socket.io/v1/index.d.ts @@ -169,7 +169,7 @@ declare namespace SocketIO { listen( port: number, opts?: ServerOptions ): Server; /** - * Binds socket.io to an engine.io intsance + * Binds socket.io to an engine.io instance * @param src The Engine.io (or compatible) server to bind to * @return This Server */ diff --git a/types/socketcluster-client/index.d.ts b/types/socketcluster-client/index.d.ts new file mode 100644 index 0000000000..9c15a45465 --- /dev/null +++ b/types/socketcluster-client/index.d.ts @@ -0,0 +1,23 @@ +// Type definitions for socketcluster-client 13.0 +// Project: https://github.com/SocketCluster/socketcluster-client +// Definitions by: Daniel Rose +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +import { SCAuthEngine } from "sc-auth"; +import { SCServer } from "socketcluster-server"; + +export import SCClientSocket = require("./lib/scclientsocket"); + +export function create(options?: SCClientSocket.ClientOptions): SCClientSocket; + +/** @deprecated */ +export function connect(options?: SCClientSocket.ClientOptions): SCClientSocket; + +export function destroy(socket: SCClientSocket): void; + +export const clients: { + [id: string]: SCClientSocket; +}; + +export const version: string; diff --git a/types/socketcluster-client/lib/scclientsocket.d.ts b/types/socketcluster-client/lib/scclientsocket.d.ts new file mode 100644 index 0000000000..19552bd102 --- /dev/null +++ b/types/socketcluster-client/lib/scclientsocket.d.ts @@ -0,0 +1,251 @@ +import Emitter = require("component-emitter"); +import { SCServer } from "socketcluster-server"; +import { SCAuthEngine } from "sc-auth"; +import { SCChannel, SCChannelOptions, ChannelState } from "sc-channel"; +import WebSocket = require("ws"); + +declare class SCClientSocket extends Emitter { + constructor(opts: SCClientSocket.ClientOptions); + + id: string; + + channels: { + [channelName: string]: SCChannel; + }; + + CONNECTING: "connecting"; + OPEN: "open"; + CLOSED: "closed"; + + state: SCClientSocket.States; + getState(): SCClientSocket.States; + + AUTHENTICATED: "authenticated"; + UNAUTHENTICATED: "unauthenticated"; + + authState: SCClientSocket.AuthStates; + + PENDING: "pending"; + + pendingReconnect: boolean; + pendingReconnectTimeout: number; + + getBytesReceived(): number; + + deauthenticate(callback?: (err: Error) => void): void; + + connect(): void; + open(): void; + disconnect(code?: number, data?: string | object): void; + reconnect(code?: number, data?: string | object): void; + destroy(code?: number, data?: string | object): void; + + decodeBase64(encodedString: string): string; + encodeBase64(decodedString: string): string; + + getAuthToken(): object | null; + authToken: object | null; + + getSignedAuthToken(): string | null; + signedAuthToken: string | null; + + // Perform client-initiated authentication by providing an encrypted token string. + authenticate(signedAuthToken: string, callback?: (err: Error, authStatus: SCClientSocket.AuthStatus) => void): void; + + decode(message: any): any; + encode(object: any): any; + + send(data: any): void; + + emit(event: string, data: any, callback?: (err: Error, responseData: any) => void): void; + + publish(channelName: string, data: any, callback?: (err: Error, ackData: any) => void): void; + + subscribe(channelName: string, options?: SCChannelOptions): SCChannel; + unsubscribe(channelName: string): void; + + channel(channelName: string, options?: SCChannelOptions): SCChannel; + + destroyChannel(channelName: string): void; + + subscriptions(includePending?: boolean): string[]; + isSubscribed(channelName: string, includePending?: boolean): boolean; + + processPendingSubscriptions(): void; + + watch(channelName: string, handler: SCClientSocket.WatcherFunction): void; + unwatch(channelName: string, handler?: SCClientSocket.WatcherFunction): void; + watchers(channelName: string): SCClientSocket.WatcherFunction[]; + + on(event: "connecting", listener: () => void): this; + on(event: "connect", listener: (status: SCClientSocket.ConnectStatus, processSubscriptions: () => void) => void): this; + on(event: "connectAbort" | "disconnect" | "close", listener: (code: number, data: string | object) => void): this; + + on(event: "kickOut", listener: (message: string, channelName: string) => void): this; + + on(event: "authenticate", listener: (signedAuthToken: string | null) => void): this; + on(event: "deauthenticate", listener: (oldSignedToken: string | null) => void): this; + on(event: "authStateChange", listener: (stateChangeData: SCClientSocket.AuthStateChangeData) => void): this; + on(event: "removeAuthToken", listener: (oldToken: object | null) => void): this; + + on(event: "subscribe" | "subscribeRequest", listener: (channelName: string, subscriptionOptions: SCChannelOptions) => void): this; + on(event: "subscribeStateChange", listener: (stateChangeData: SCClientSocket.SubscribeStateChangeData) => void): this; + on(event: "subscribeFail", listener: (err: Error, channelName: string, subscriptionOptions: SCChannelOptions) => void): this; + on(event: "unsubscribe", listener: (channelName: string) => void): this; + + on(event: "error", listener: (err: Error) => void): this; + + on(event: "raw", listener: (data: any) => void): this; + on(event: "message", listener: (message: WebSocket.Data) => void): this; + + // Implements Emitter interface + + // tslint:disable:ban-types + // tslint:disable:adjacent-overload-signatures + on(event: string, listener: Function): this; + once(event: string, listener: Function): this; + off(event?: string, listener?: Function): this; + emit(event: string, ...args: any[]): boolean; + listeners(event: string): Function[]; + hasListeners(event: string): boolean; + // tslint:enable:adjacent-overload-signatures + // tslint:enable:ban-types +} + +export = SCClientSocket; + +declare namespace SCClientSocket { + interface ClientOptions { + host?: string; + + // Defaults to the current host (read from the URL). + hostname?: string; + + // Defaults to false. + secure?: boolean; + + // Defaults to 80 if !secure otherwise defaults to 443. + port?: number; + + // The URL which SC uses to make the initial handshake for the WebSocket. Defaults to '/socketcluster/'. + path?: string; + + // A map of key-value pairs which will be used as query parameters for the initial HTTP handshake which will initiate the WebSocket connection. + query?: string | { [key: string]: string }; + + // (milliseconds) - This is the timeout for getting a response to a SCSocket emit event (when a callback is provided). + ackTimeout?: number; + + // (milliseconds) + connectTimeout?: number; + + // Whether or not to automatically connect the socket as soon as it is created. Default is true. + autoConnect?: boolean; + + // Whether or not to automatically reconnect the socket when it loses the connection. + autoReconnect?: boolean; + + // Valid properties are: initialDelay (milliseconds), randomness (milliseconds), multiplier (decimal; default is 1.5) and maxDelay (milliseconds). + autoReconnectOptions?: AutoReconnectOptions; + + // Whether or not a client automatically disconnects on page unload. If enabled, the client will disconnect when a user navigates away from the page. + // This can happen when a user closes the tab/window, clicks a link to leave the page, or types a new URL into the address bar. Defaults to true. + disconnectOnUnload?: boolean; + + // Turn on/off per-message deflate compression. If this is true, you need to make sure that this property is also set to true on the server-side. + // Note that this option is only relevant when running the client from Node.js. Most modern browsers will automatically use perMessageDeflate so + // you only need to turn it on from the server-side. + perMessageDeflate?: boolean; + + // Defaults to true; multiplexing allows you to reuse a socket instead of creating a second socket to the same address. + multiplex?: boolean; + + // Defaults to null (0 milliseconds); this property affects channel subscription batching; it determines the period in milliseconds for batching + // multiple subscription requests together. It only affects channels that have the batch option set to true. A value of null or 0 means that all + // subscribe or unsubscribe requests which were made within the same call stack will be batched together. This property was introduced on the + // client-side in SC version 8 (both the client and server versions need to be >= 8.0.0). Note that there is also a separate property with the + // same name which can be configured on the server. + pubSubBatchDuration?: number; + + // Whether or not to add a timestamp to the WebSocket handshake request. + timestampRequests?: boolean; + + // The query parameter name to use to hold the timestamp. + timestampParam?: string; + + // A custom engine to use for storing and loading JWT auth tokens on the client side. + authEngine?: SCAuthEngine | null; + + // The name of the JWT auth token (provided to the authEngine - By default this is the localStorage variable name); defaults to 'socketCluster.authToken'. + authTokenName?: string; + + // The type to use to represent binary on the client. Defaults to 'arraybuffer'. + binaryType?: string; + + // Set this to false during debugging - Otherwise client connection will fail when using self-signed certificates. + rejectUnauthorized?: boolean; + + // If you set this to true, any data/objects/arrays that you pass to the client socket will be cloned before being sent/queued up. If the socket + // is disconnected and you emit an event, it will be added to a queue which will be processed upon reconnection. The cloneData option is false + // by default; this means that if you emit/publish an object and that object changes somewhere else in your code before the queue is processed, + // then the changed version of that object will be sent out to the server. + cloneData?: boolean; + + // This is true by default. If you set this to false, then the socket will not automatically try to subscribe to pending subscriptions on + // connect - Instead, you will have to manually invoke the processSubscriptions callback from inside the 'connect' event handler on the client side. + // See SCSocket Client API. This gives you more fine-grained control with regards to when pending subscriptions are processed after the socket + // connection is established (or re-established). + autoSubscribeOnConnect?: boolean; + + // Lets you set a custom codec engine. This allows you to specify how data gets encoded before being sent over the wire and how it gets decoded + // once it reaches the other side. The codecEngine must be an object which exposes an encode(object) and a decode(encodedData) function. + // The encode function can return any data type - Commonly a string or a Buffer/ArrayBuffer. The decode function needs to return a JavaScript + // object which adheres to the SC protocol. The idea of using a custom codec is that it allows you to compress SC packets in any format you like + // (optimized for any use case) - By decoding these packets back into their original protocol form, SC will be able process them appropriately. + // Note that if you provide a codecEngine when creating a client socket see 'codecEngine', you will need to make sure that the server uses the + // same codec by passing the same engine to `worker.scServer.setCodecEngine(codecEngine)` when your SC worker initializes on the server side + // (see 'setCodecEngine' method here). The default codec engine used by SC is here. + codecEngine?: SCServer.SCCodecEngine | null; + + // A prefix to add to the channel names. + channelPrefix?: string | null; + + subscriptionRetryOptions?: object | null; + } + + interface AutoReconnectOptions { + initialDelay?: number; + randomness?: number; + multiplier?: number; + maxDelay?: number; + } + + interface AuthStatus { + isAuthenticated: AuthStates; + authError: Error; + } + + interface AuthStateChangeData { + oldState: AuthStates; + newState: AuthStates; + } + + interface ConnectStatus { + id: string; + pingTimeout: number; + isAuthenticated: boolean; + authToken?: object; + authError?: Error; + } + + interface SubscribeStateChangeData { + channel: string; + oldState: ChannelState; + newState: ChannelState; + subscriptionOptions: SCChannelOptions; + } + + type WatcherFunction = (data: any) => void; + type AuthStates = "authenticated" | "unauthenticated"; + type States = "connecting" | "open" | "closed"; +} diff --git a/types/socketcluster-client/socketcluster-client-tests.ts b/types/socketcluster-client/socketcluster-client-tests.ts new file mode 100644 index 0000000000..527385a5eb --- /dev/null +++ b/types/socketcluster-client/socketcluster-client-tests.ts @@ -0,0 +1,75 @@ +// Adapted from README + +import { create, destroy } from "socketcluster-client"; +import { ClientOptions } from "socketcluster-client/lib/scclientsocket"; + +const secureClientOptions: ClientOptions = { + hostname: "securedomain.com", + secure: true, + port: 443, + rejectUnauthorized: false +}; + +let socket = create(secureClientOptions); + +socket.on("connect", () => { + console.log("CONNECTED"); +}); + +// Listen to an event called 'rand' from the server +socket.on("rand", (num: any) => { + console.log("RANDOM: " + num); +}); + +const options: ClientOptions = { + path: "/socketcluster/", + port: 8000, + hostname: "127.0.0.1", + autoConnect: true, + secure: false, + rejectUnauthorized: false, + connectTimeout: 10000, // milliseconds + ackTimeout: 10000, // milliseconds + channelPrefix: null, + disconnectOnUnload: true, + multiplex: true, + autoReconnectOptions: { + initialDelay: 10000, // milliseconds + randomness: 10000, // milliseconds + multiplier: 1.5, // decimal + maxDelay: 60000 // milliseconds + }, + authEngine: null, + codecEngine: null, + subscriptionRetryOptions: {}, + query: { + yourparam: "hello" + } +}; +socket = create(options); + +socket.on("subscribe", channelname => { + console.log("subscribe:" + channelname); +}); + +socket.on("subscribeFail", channelname => { + console.log("subscribeFail:" + channelname); +}); + +socket.on("unsubscribe", channelname => { + console.log("unsubscribe:" + channelname); +}); + +socket.on("subscribeStateChange", data => { + console.log("subscribeStateChange:" + JSON.stringify(data)); +}); + +socket.on("message", data => { + console.log("message:" + data); +}); + +const channels = socket.channels; +const testChannel = channels["test"]; +const state = testChannel.getState(); + +destroy(socket); diff --git a/types/socketcluster-client/tsconfig.json b/types/socketcluster-client/tsconfig.json new file mode 100644 index 0000000000..54fc6ea8af --- /dev/null +++ b/types/socketcluster-client/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "lib/scclientsocket.d.ts", + "socketcluster-client-tests.ts" + ] +} diff --git a/types/socketcluster-client/tslint.json b/types/socketcluster-client/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/socketcluster-client/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/socketcluster-server/index.d.ts b/types/socketcluster-server/index.d.ts new file mode 100644 index 0000000000..7466d1daed --- /dev/null +++ b/types/socketcluster-server/index.d.ts @@ -0,0 +1,15 @@ +// Type definitions for socketcluster-server 13.1 +// Project: https://github.com/SocketCluster/socketcluster-server +// Definitions by: Daniel Rose +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +import { Server } from "http"; + +export import SCServer = require("./scserver"); +export import SCServerSocket = require("./scserversocket"); + +export function listen(port?: number, options?: SCServer.SCServerOptions, listeningListener?: () => void): SCServer; +export function listen(port?: number, listeningListener?: () => void): SCServer; + +export function attach(server: Server, options?: SCServer.SCServerOptions): SCServer; diff --git a/types/socketcluster-server/scserver.d.ts b/types/socketcluster-server/scserver.d.ts new file mode 100644 index 0000000000..a7147aa2dd --- /dev/null +++ b/types/socketcluster-server/scserver.d.ts @@ -0,0 +1,315 @@ +import { EventEmitter } from "events"; +import { Secret } from "jsonwebtoken"; +import { ServerOptions } from "https"; +import { IncomingMessage, Server } from "http"; +import { SCAuthEngine } from "sc-auth"; +import { SCExchange } from "sc-broker-cluster"; +import WebSocket = require("ws"); + +import SCServerSocket = require("./scserversocket"); + +declare class SCServer extends EventEmitter { + readonly MIDDLEWARE_HANDSHAKE_WS: "handshakeWS"; + readonly MIDDLEWARE_HANDSHAKE_SC: "handshakeSC"; + readonly MIDDLEWARE_AUTHENTICATE: "authenticate"; + readonly MIDDLEWARE_SUBSCRIBE: "subscribe"; + readonly MIDDLEWARE_PUBLISH_IN: "publishIn"; + readonly MIDDLEWARE_PUBLISH_OUT: "publishOut"; + readonly MIDDLEWARE_EMIT: "emit"; + + options: SCServer.SCServerOptions; + exchange: SCExchange; + + clients: { + [id: string]: SCServerSocket; + }; + clientsCount: number; + + pendingClients: { + [id: string]: SCServerSocket; + }; + pendingClientsCount: number; + + constructor(options?: SCServer.SCServerOptions); + + on(event: "connection", listener: SCServer.connectionListenerFunction): this; + + addMiddleware(type: "handshakeWS", middlewareFn: (req: IncomingMessage, next: SCServer.nextMiddlewareFunction) => void): void; + addMiddleware(type: "handshakeSC", middlewareFn: (req: SCServer.HandshakeSCRequest, next: SCServer.nextHandshakeSCMiddlewareFunction) => void): void; + addMiddleware(type: "authenticate", middlewareFn: (req: SCServer.AuthenticateRequest, next: SCServer.nextAuthenticateMiddlewareFunction) => void): void; + addMiddleware(type: "subscribe", middlewareFn: (req: SCServer.SubscribeRequest, next: SCServer.nextMiddlewareFunction) => void): void; + addMiddleware(type: "publishIn", middlewareFn: (req: SCServer.PublishInRequest, next: SCServer.nextMiddlewareFunction) => void): void; + addMiddleware(type: "publishOut", middlewareFn: (req: SCServer.PublishOutRequest, next: SCServer.nextMiddlewareFunction) => void): void; + addMiddleware(type: "emit", middlewareFn: (req: SCServer.EmitRequest, next: SCServer.nextMiddlewareFunction) => void): void; + + setAuthEngine(authEngine: SCAuthEngine): void; + setCodecEngine(codecEngine: SCServer.SCCodecEngine): void; +} + +export = SCServer; + +declare namespace SCServer { + interface AuthToken { + [x: string]: any; + } + + interface SCServerOptions { + // The port on which to listen for outside connections/requests + port?: number; + + // Number of worker processes + workers?: number; + + // Number of broker processes + brokers?: number; + + // Should be either 'dev' or 'prod' - This affects the shutdown procedure + // when a 'SIGUSR2' signal is received by master. In 'dev', a SIGUSR2 will + // trigger an immediate shutdown of workers. In 'prod' workers will + // be terminated progressively in accordance with processTermTimeout. + environment?: string; + + // Setting this to true will cause the master process to shut down when + // it receives a SIGUSR2 signal (instead of just the workers). + // If you're using nodemon, set this to true. + killMasterOnSignal?: boolean; + + // A unique name for your app (this is used internally for + // various things such as the directory name in which to store socket + // file descriptors) - If you don't provide an appName, SC will + // generate a random one (UUID v4) + appName?: string; + + // This can be the name of an npm module or a path to a Node.js module + // to use as the WebSocket server engine. + // You can now set this to 'sc-uws' for a massive speedup of at least 2x! + wsEngine?: string; + + // An ID to associate with this specific instance of SC + // this may be useful if you are running an SC app on multiple + // hosts - You can access the instanceId from the Broker object + // (inside brokerController) - If you don't provide an instanceId, + // SC will generate a random one (UUID v4) + instanceId?: string; + + // A key which various SC processes will use to interact with + // scBroker broker processes securely, defaults to a 256 bits + // cryptographically random hex string + secretKey?: string; + + // The key which SC will use to encrypt/decrypt authTokens, defaults + // to a 256 bits cryptographically random hex string + // The default JWT algorithm used is 'HS256'. + // If you want to use RSA or ECDSA, you should provide a authPrivateKey + // and authPublicKey instead of authKey. + authKey?: Secret; + + // perMessageDeflate compression. Note that this option is passed directly to the wsEngine's + // Server object. So if you're using 'ws' as the engine, you can pass an object instead of + // a boolean. Search for perMessageDeflate here: + // https://github.com/websockets/ws/blob/master/doc/ws.md#new-websocketserveroptions-callback + // Note that by default, per-message deflate only kicks in for messages > 1024 bytes. + perMessageDeflate?: boolean; + + // If using an RSA or ECDSA algorithm to sign the authToken, you will need + // to provide an authPrivateKey and authPublicKey in PEM format (string or Buffer). + authPrivateKey?: Secret; + authPublicKey?: Secret; + + // The default expiry for auth tokens in seconds + authDefaultExpiry?: number; + + // The algorithm to use to sign and verify JWT tokens. + authAlgorithm?: string; + + // Crash workers when an error happens - This is the most sensible default + crashWorkerOnError?: boolean; + + // Reboot workers when they crash - This is a necessity + // in production but can be turned off for debugging + rebootWorkerOnCrash?: boolean; + + // Kill/respawn a worker process if its memory consumption exceeds this + // threshold (in bytes) - If this is null (default), this behavior + // will be switched off + killWorkerMemoryThreshold?: number; + + // Can be 'http' or 'https' + protocol?: "http" | "https"; + + // This is the same as the object provided to Node.js's https server + protocolOptions?: ServerOptions; + + // A log level of 3 will log everything, 2 will show notices and errors, + // 1 will only log errors, 0 will log nothing + logLevel?: 0 | 1 | 2 | 3; + + // In milliseconds, how long a client has to connect to SC before timing out + connectTimeout?: number; + + // In milliseconds - If the socket handshake hasn't been completed before + // this timeout is reached, the new connection attempt will be terminated. + handshakeTimeout?: number; + + // In milliseconds, the timeout for calling res(err, data) when + // your emit() call expects an ACK response from the other side + // (when callback is provided to emit) + ackTimeout?: number; + + // In milliseconds, the timeout for calling res(err, data) when + // your sendToWorker, sendToBroker or sendToMaster (IPC) call + // expects an ACK response from the other process + // (when callback is provided) + ipcAckTimeout?: number; + + // In milliseconds - If the socket cannot upgrade transport + // within this period, it will stop trying + socketUpgradeTimeout?: number; + + // Origins which are allowed to connect to the real-time scServer + origins?: string; + + // The maximum number of unique channels which a single + // socket can subscribe to + socketChannelLimit?: number; + + // The interval in milliseconds on which to + // send a ping to the client to check that + // it is still alive + pingInterval?: number; + + // How many milliseconds to wait without receiving a ping + // before closing the socket + pingTimeout?: number; + + // Maximum amount of milliseconds to wait before force-killing + // a process after it was passed a 'SIGTERM' or 'SIGUSR2' signal + processTermTimeout?: number; + + // Whether or not errors from child processes (workers and brokers) + // should be passed to the current master process + propagateErrors?: boolean; + + // Whether or not warnings from child processes (workers and brokers) + // should be passed to the current master process + propagateWarnings?: number; + + // Whether or not a 'warning' event should be emitted (and logged to console) + // whenever an action is blocked by a middleware function + middlewareEmitWarnings?: number; + + // Lets you specify a host name to bind to - Defaults to + // 127.0.0.1 (localhost) + host?: string; + + // The path to a file used to bootstrap worker processes + workerController?: string; + + // The path to a file used to bootstrap broker processes + brokerController?: string; + + // The path to a file used to bootstrap the workerCluster process + workerClusterController?: string; + + // By default, SC will reboot all workers when it receives a 'SIGUSR2' signal - + // This can be used for updating workers with fresh source code in production + rebootOnSignal?: boolean; + + // If you run your master process (server.js) as super user, this option + // lets you downgrade worker and broker processes to run under + // the specified user (with fewer permissions than master) - You can provide + // a Linux UID or username + downgradeToUser?: number | string; + + // The URL path reserved by SocketCluster clients to interact with the server + path?: string; + + // The root directory in which to store your socket files in Linux. + socketRoot?: string; + + // Defaults to "rr", but can be set to "none" + schedulingPolicy?: "rr" | "none"; + + // Whether or not clients are allowed to publish messages to channels + allowClientPublish?: boolean; + + // This option is passed to the Node.js HTTP server if provided + tcpSynBacklog?: number; + + // SC keeps track of request per minutes internally - This allows you to change + // how often this gets updated + workerStatusInterval?: number; + + // This allows you to batch multiple messages together when passing them across + // message brokers. This may improve the efficiency of your pub/sub operations. + // This value is in milliseconds. 5 is generally a safe value to set this to. + pubSubBatchDuration?: number; + + // The default clustering/brokering engine (Node.js module name) which provides the + // SCWorker.exchange object and manages brokers behind the scenes. + // You shouldn't need to change this unless you want to build your own + // process clustering engine (which is difficult to do). + brokerEngine?: string; + + wsEngineServerOptions?: WebSocket.ClientOptions; + maxPayload?: number; + pingTimeoutDisabled?: boolean; + authSignAsync?: boolean; + authVerifyAsync?: boolean; + httpServer?: Server; + } + + interface SCServerSocketStatus { + id: string; + pingTimeout: number; + } + + interface HandshakeSCRequest { + socket: SCServerSocket; + } + + interface AuthenticateRequest { + socket: SCServerSocket; + authToken: AuthToken; + } + + interface SubscribeRequest { + socket: SCServerSocket; + authTokenExpiredError?: Error; + channel?: string; + waitForAuth?: boolean; + data?: any; + } + + interface PublishInRequest { + socket: SCServerSocket; + authTokenExpiredError?: Error; + channel?: string; + data?: any; + ackData?: any; + } + + interface PublishOutRequest { + socket: SCServerSocket; + channel?: string; + data?: any; + useCache?: boolean; + } + + interface EmitRequest { + socket: SCServerSocket; + authTokenExpiredError?: Error; + event: string; + data?: any; + } + + type nextMiddlewareFunction = (error?: true | string | Error) => void; + type nextHandshakeSCMiddlewareFunction = (error?: true | string | Error | null, statusCode?: number) => void; + type nextAuthenticateMiddlewareFunction = (error?: true | string | Error | null, isBadToken?: boolean) => void; + type connectionListenerFunction = (scSocket: SCServerSocket, serverSocketStatus: SCServerSocketStatus) => void; + + interface SCCodecEngine { + decode: (input: any) => any; + ncode: (object: any) => any; + } +} diff --git a/types/socketcluster-server/scserversocket.d.ts b/types/socketcluster-server/scserversocket.d.ts new file mode 100644 index 0000000000..7b32cef72c --- /dev/null +++ b/types/socketcluster-server/scserversocket.d.ts @@ -0,0 +1,43 @@ +import Emitter = require("component-emitter"); +import { IncomingMessage } from "http"; +import { SCExchange } from "sc-broker-cluster"; +import { SignOptions } from "jsonwebtoken"; +import WebSocket = require("ws"); + +import SCServer = require("./scserver"); + +declare class SCServerSocket extends Emitter { + readonly CONNECTING: "connecting"; + readonly OPEN: "open"; + readonly CLOSED: "closed"; + + readonly AUTHENTICATED: "authenticated"; + readonly UNAUTHENTICATED: "unauthenticated"; + + id: string; + request: IncomingMessage; + + remoteAddress: string; + remoteFamily: string; + remotePort: number; + + exchange: SCExchange; + + state: "connecting" | "open" | "closed"; + authState: "authenticated" | "unauthenticated"; + authToken?: SCServer.AuthToken; + + constructor(id: string, server: SCServer, socket: WebSocket); + + getState(): "connecting" | "open" | "closed"; + disconnect(code?: number, data?: any): void; + send(data: any, options: { mask?: boolean; binary?: boolean; compress?: boolean; fin?: boolean }): void; + getAuthToken(): SCServer.AuthToken; + setAuthToken(data: SCServer.AuthToken, options?: SignOptions): void; + deauthenticate(): void; + kickOut(channel?: string, message?: string, callback?: () => void): void; + subscriptions(): string[]; + isSubscribed(channel?: string): boolean; +} + +export = SCServerSocket; diff --git a/types/socketcluster-server/socketcluster-server-tests.ts b/types/socketcluster-server/socketcluster-server-tests.ts new file mode 100644 index 0000000000..3d62fe9041 --- /dev/null +++ b/types/socketcluster-server/socketcluster-server-tests.ts @@ -0,0 +1,39 @@ +// Adapted from README + +// Using with basic http(s) module (example) + +import http = require("http"); +import * as socketClusterServer from "socketcluster-server"; + +let httpServer = http.createServer(); +let scServer = socketClusterServer.attach(httpServer); + +scServer.on("connection", socket => { + // ... Handle new socket connections here +}); + +httpServer.listen(8000); + +// Using with Express (example) + +import serveStatic = require("serve-static"); +import path = require("path"); +import express = require("express"); + +const app = express(); + +app.use(serveStatic(path.resolve(__dirname, "public"))); + +httpServer = http.createServer(); + +// Attach express to our httpServer +httpServer.on("request", app); + +// Attach socketcluster-server to our httpServer +scServer = socketClusterServer.attach(httpServer); + +scServer.on("connection", socket => { + // ... Handle new socket connections here +}); + +httpServer.listen(8000); diff --git a/types/socketcluster-server/tsconfig.json b/types/socketcluster-server/tsconfig.json new file mode 100644 index 0000000000..be1a6bdcb0 --- /dev/null +++ b/types/socketcluster-server/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "scserver.d.ts", + "scserversocket.d.ts", + "socketcluster-server-tests.ts" + ] +} diff --git a/types/socketcluster-server/tslint.json b/types/socketcluster-server/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/socketcluster-server/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/socketcluster/fsutil.d.ts b/types/socketcluster/fsutil.d.ts new file mode 100644 index 0000000000..bcfcbfc59f --- /dev/null +++ b/types/socketcluster/fsutil.d.ts @@ -0,0 +1,11 @@ +import { PathLike } from "fs"; + +export function fileExists(filePath: PathLike, callback: (exists: boolean) => void): void; + +export function waitForFile( + filePath: PathLike, + checkInterval: number, + startTime: number, + maxWaitDuration: number, + timeoutErrorMessage?: string +): Promise; diff --git a/types/socketcluster/index.d.ts b/types/socketcluster/index.d.ts new file mode 100644 index 0000000000..0ec8485cfa --- /dev/null +++ b/types/socketcluster/index.d.ts @@ -0,0 +1,84 @@ +// Type definitions for socketcluster 14.0 +// Project: https://github.com/SocketCluster/socketcluster +// Definitions by: Daniel Rose +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +import { EventEmitter } from "events"; +import { SCServer } from "socketcluster-server"; +import { ChildProcess } from "child_process"; + +interface WorkerStartInfo { + id: number; + pid: number; + respawn: boolean; +} + +interface WorkerClusterStartInfo { + pid: number; + childProcess: ChildProcess; +} + +interface WorkerClusterReadyInfo { + pid: number; + childProcess: ChildProcess; +} + +interface WorkerClusterExitInfo { + pid: number; + code: number; + signal: string; + childProcess: ChildProcess; +} + +export = SocketCluster; + +declare class SocketCluster extends EventEmitter { + readonly EVENT_FAIL: "fail"; + readonly EVENT_WARNING: "warning"; + readonly EVENT_READY: "ready"; + readonly EVENT_WORKER_START: "workerStart"; + readonly EVENT_WORKER_EXIT: "workerExit"; + readonly EVENT_BROKER_START: "brokerStart"; + readonly EVENT_BROKER_EXIT: "brokerExit"; + readonly EVENT_WORKER_CLUSTER_START: "workerClusterStart"; + readonly EVENT_WORKER_CLUSTER_READY: "workerClusterReady"; + readonly EVENT_WORKER_CLUSTER_EXIT: "workerClusterExit"; + + options: SCServer.SCServerOptions; + + constructor(options?: SCServer.SCServerOptions); + + on(event: "fail", listener: (err: Error) => void): this; + on(event: "warning", listener: (warning: Error) => void): this; + on(event: "ready", listener: () => void): this; + on(event: "workerStart", listener: (workerInfo: WorkerStartInfo) => void): this; + on(event: "workerExit", listener: (workerInfo: SocketCluster.WorkerExitInfo) => void): this; + on(event: "brokerStart", listener: (brokerInfo: SocketCluster.BrokerStartInfo) => void): this; + on(event: "brokerExit", listener: (brokerInfo: SocketCluster.BrokerExitInfo) => void): this; + on(event: "workerClusterStart", listener: (workerClusterInfo: WorkerClusterStartInfo) => void): this; + on(event: "workerClusterReady", listener: (workerClusterInfo: WorkerClusterReadyInfo) => void): this; + on(event: "workerClusterExit", listener: (workerClusterInfo: WorkerClusterExitInfo) => void): this; +} + +declare namespace SocketCluster { + interface WorkerExitInfo { + id: number; + pid: number; + code: number; + signal: string; + } + + interface BrokerStartInfo { + id: number; + pid: number; + respawn: boolean; + } + + interface BrokerExitInfo { + id: number; + pid: number; + code: number; + signal: string; + } +} diff --git a/types/socketcluster/scbroker.d.ts b/types/socketcluster/scbroker.d.ts new file mode 100644 index 0000000000..461801aa63 --- /dev/null +++ b/types/socketcluster/scbroker.d.ts @@ -0,0 +1,3 @@ +import SCBroker = require("sc-broker-cluster/scbroker"); + +export = SCBroker; diff --git a/types/socketcluster/scworker.d.ts b/types/socketcluster/scworker.d.ts new file mode 100644 index 0000000000..48502692be --- /dev/null +++ b/types/socketcluster/scworker.d.ts @@ -0,0 +1,63 @@ +import { EventEmitter } from "events"; +import { Server as httpServer } from "http"; +import { Server as httpsServer } from "https"; +import { SCServer, SCServerSocket } from "socketcluster-server"; +import { SCAuthEngine } from "sc-auth"; +import { SCExchange } from "sc-broker-cluster"; + +export = SCWorker; + +type middlewareFunction = (options: SCServer.SCServerOptions, next: (error?: string | Error) => void) => void; + +declare class SCWorker extends EventEmitter { + readonly EVENT_ERROR: "error"; + readonly EVENT_WARNING: "warning"; + readonly EVENT_EXIT: "exit"; + readonly EVENT_READY: "ready"; + readonly EVENT_CONNECTION: "connection"; + + readonly MIDDLEWARE_START: "start"; + + id: number; + isLeader: boolean; + options: SCServer.SCServerOptions; + httpServer: httpServer | httpsServer; + scServer: SCServer; + exchange: SCExchange; + auth: SCAuthEngine; + + constructor(options?: SCServer.SCServerOptions); + + run(): void; + + getSCServer(): SCServer; + getHTTPServer(): httpServer | httpsServer; + getSocketPath(): string; + + setAuthEngine(authEngine: SCAuthEngine): void; + setCodecEngine(codecEngine: SCServer.SCCodecEngine): void; + + open(): void; + close(callback?: () => void): void; + + addMiddleware(type: "start", middlewareFn: middlewareFunction): void; + removeMiddleware(type: "start", middlewareFn: middlewareFunction): void; + + startHTTPServer(): void; + start(): Promise; + + getStatus(): { + clientCount: any; + httpRPM: number; + wsRPM: number; + }; + + sendToMaster(data: any, callback: (err: Error | null, data: any) => void): void; + respondToMaster(err: Error | null, data: any, rid: number): void; + + on(event: "connection", listener: (scSocket: SCServerSocket) => void): this; + on(event: "ready", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "warning", listener: (warning: Error) => void): this; + on(event: "masterMessage", listener: (data: any, respond: (err: Error | null, responseData: any) => void) => void): this; +} diff --git a/types/socketcluster/socketcluster-tests.ts b/types/socketcluster/socketcluster-tests.ts new file mode 100644 index 0000000000..85ad9c3d05 --- /dev/null +++ b/types/socketcluster/socketcluster-tests.ts @@ -0,0 +1,76 @@ +import * as fsutil from "socketcluster/fsutil"; +import SocketCluster = require("socketcluster"); +import { SCServer } from "socketcluster-server"; +import { ChildProcess } from "child_process"; + +//////////////////////////////////////////////////// +/// SocketCluster tests +//////////////////////////////////////////////////// + +{ + const options: SCServer.SCServerOptions = { port: 80 }; + + let sc = new SocketCluster(); + sc = new SocketCluster(options); + sc.options = { environment: "prod" }; + + sc.on(sc.EVENT_FAIL, err => { + const error: Error = err; + }); + sc.on(sc.EVENT_WARNING, warning => { + const warn: Error = warning; + }); + + sc.on(sc.EVENT_READY, () => {}); + + sc.on(sc.EVENT_WORKER_START, workerInfo => { + const id: number = workerInfo.id; + const pid: number = workerInfo.pid; + const respawn: boolean = workerInfo.respawn; + }); + sc.on(sc.EVENT_WORKER_EXIT, workerInfo => { + const id: number = workerInfo.id; + const pid: number = workerInfo.pid; + const code: number = workerInfo.code; + const signal: string = workerInfo.signal; + }); + + sc.on(sc.EVENT_BROKER_START, brokerInfo => { + const id: number = brokerInfo.id; + const pid: number = brokerInfo.pid; + const respawn: boolean = brokerInfo.respawn; + }); + sc.on(sc.EVENT_BROKER_EXIT, brokerInfo => { + const id: number = brokerInfo.id; + const pid: number = brokerInfo.pid; + const code: number = brokerInfo.code; + const signal: string = brokerInfo.signal; + }); + + sc.on(sc.EVENT_WORKER_CLUSTER_START, workerClusterInfo => { + const pid: number = workerClusterInfo.pid; + const childProcess: ChildProcess = workerClusterInfo.childProcess; + }); + sc.on(sc.EVENT_WORKER_CLUSTER_READY, workerClusterInfo => { + const pid: number = workerClusterInfo.pid; + const childProcess: ChildProcess = workerClusterInfo.childProcess; + }); + sc.on(sc.EVENT_WORKER_CLUSTER_EXIT, workerClusterInfo => { + const pid: number = workerClusterInfo.pid; + const code: number = workerClusterInfo.code; + const signal: string = workerClusterInfo.signal; + const childProcess: ChildProcess = workerClusterInfo.childProcess; + }); +} + +//////////////////////////////////////////////////// +/// fsutil tests +//////////////////////////////////////////////////// + +{ + fsutil.fileExists("/path/to/folder", err => {}); + fsutil.fileExists(Buffer.from(""), err => {}); + + const pathPromise: Promise = fsutil.waitForFile("/path/to/folder", 100, 0, 100); + const bufferPromise: Promise = fsutil.waitForFile(Buffer.from(""), 0, 0, 0, "timeout"); +} diff --git a/types/socketcluster/tsconfig.json b/types/socketcluster/tsconfig.json new file mode 100644 index 0000000000..1a0267f5f0 --- /dev/null +++ b/types/socketcluster/tsconfig.json @@ -0,0 +1,26 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "fsutil.d.ts", + "scbroker.d.ts", + "scworker.d.ts", + "socketcluster-tests.ts" + ] +} diff --git a/types/socketcluster/tslint.json b/types/socketcluster/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/socketcluster/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/space-pen/tslint.json b/types/space-pen/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/space-pen/tslint.json +++ b/types/space-pen/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/spectacle/index.d.ts b/types/spectacle/index.d.ts index e00b5dd3c0..621f08f67e 100644 --- a/types/spectacle/index.d.ts +++ b/types/spectacle/index.d.ts @@ -1,164 +1,321 @@ -// Type definitions for Spectacle 1.2.0 -// Project: https://github.com/FormidableLabs/victory +// Type definitions for Spectacle 5.2.2 +// Project: https://github.com/FormidableLabs/spectacle // Definitions by: Zachary Maybury +// Kylie Stewart // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 /// declare module "spectacle" { - import * as React from "react"; + import * as React from "react"; + import * as CSS from "csstype"; + /** + * Alignment Types for Spectacle + */ + type alignType = + | "flex-start flex-start" + | "flex-start center" + | "flex-start flex-end" + | "center flex-start" + | "center center" + | "center flex-end" + | "flex-end flex-start" + | "flex-end center" + | "flex-end flex-end"; - /** - * Transition Types for Spectacle - */ - type transitionType = "slide"|"zoom"|"fade"|"spin"; + /** + * Animation Types for Spectacle + */ + type easeType = + | "back" + | "backIn" + | "backOut" + | "backInOut" + | "bounce" + | "bounceIn" + | "bounceOut" + | "bounceInOut" + | "circle" + | "circleIn" + | "circleOut" + | "circleInOut" + | "linear" + | "linearIn" + | "linearOut" + | "linearInOut" + | "cubic" + | "cubicIn" + | "cubicOut" + | "cubicInOut" + | "elastic" + | "elasticIn" + | "elasticOut" + | "elasticInOut" + | "exp" + | "expIn" + | "expOut" + | "expInOut" + | "poly" + | "polyIn" + | "polyOut" + | "polyInOut" + | "quad" + | "quadIn" + | "quadOut" + | "quadInOut" + | "sin" + | "sinIn" + | "sinOut" + | "sinInOut"; - /** - * Progress Types for Spectacle - */ - type progressType = "pacman"|"bar"|"number"|"none"; + /** + * Progress Types for Spectacle + */ + type progressType = "pacman" | "bar" | "number" | "none"; - /** - * Alignment Types for Spectacle - */ - type alignType = - "flex-start flex-start"|"flex-start center"|"flex-start flex-end"| - "center flex-start"|"center center"|"center flex-end"| - "flex-end flex-start"|"flex-end center"|"flex-end flex-end"; + /** + * S Types for StyledS in Spectacle + */ + type sType = "italic" | "bold" | "line-through" | "underline"; - /** - * Base props for many Spectacle components - */ - export interface BaseProps { - italic?:boolean, - bold?:boolean, - caps?:boolean, - margin?:number|string, - padding?:number|string, - textColor?:string, - textSize?:string, - textAlign?:string, - textFont?:string, - bgColor?:string, - bgImage?:string, - bgDarken?:number - } + /** + * Target Types for links + */ + type targetType = "_blank" | "_self" | "_parent" | "_top"; - export type Theme = { [key: string ]: string | number } + /** + * Theme Types for CodePane in Spectacle + */ + type themeType = "dark" | "light" | "external"; - export interface SpectacleProps { - theme?: Theme - } + /** + * Transition Types for Spectacle + */ + type transitionType = "slide" | "zoom" | "fade" | "spin"; - export interface DeckProps { - transition?:transitionType[], - transitionDuration?:number, - progress?:progressType, - controls?:boolean, - theme?: Theme - } + /** + * All available DOM style properties and their types + * https://www.npmjs.com/package/csstype + */ + export interface CSSProperties extends CSS.Properties {} - export interface SlideProps extends BaseProps { - align?:alignType, - transition?:transitionType[], - transitionDuration?:number, - notes?:string, - id?:string - } + export interface AnimProps { + easing: easeType; + fromStyle: CSSProperties | CSSProperties[]; + onAnim?: (forwards?: boolean, animIndex?: number) => void; + order?: number; + route?: object; + style?: CSSProperties; + toStyle: CSSProperties | CSSProperties[]; + transitionDuration: number; + } - export interface MarkdownProps { - source?:string, - mdastConfig?:{ [key: string ]: string | number } - } + export interface AppearProps { + easing?: easeType; + endValue?: object; + fid?: string; + order?: number; + startValue?: object; + style?: BaseProps["style"]; + transitionDuration?: number; + } - export interface CodePaneProps extends BaseProps { - lang?:string, - source?:string - } + /** + * Base props for many Spectacle components + */ + export interface BaseProps { + bgColor?: string; + bgDarken?: number; + bgImage?: string; + bold?: boolean; + caps?: boolean; + className?: string; + italic?: boolean; + margin?: number | string; + padding?: number | string; + style?: CSSProperties; + textAlign?: string; + textColor?: string; + textFont?: string; + textSize?: string; + } + export interface CodePaneProps { + className?: BaseProps["className"]; + contentEditable?: boolean; + lang?: string; + source?: string; + style?: BaseProps["style"]; + theme?: themeType; + } - export interface HeadingProps extends BaseProps { - fit?:boolean, - lineHeight?:number - size?:number; - } + export interface ComponentPlaygroundProps { + code?: string; + previewBackgroundColor?: string; + scope?: object; + theme?: themeType; + transformCode?: (code: string) => string; + } - export interface ImageProps extends BaseProps { - display?:string, - height?:number, - src?:string, - width?:number|string - } + export interface DeckProps { + autoplay?: boolean; + autoplayDuration?: number; + autoplayLoop?: boolean; + controls?: boolean; + globalStyles?: boolean; + history?: any; // Needs a type, see https://github.com/ReactTraining/history + progress?: progressType; + theme?: Theme; + transition?: transitionType[]; + transitionDuration?: number; + } - export interface LinkProps extends BaseProps { - href?:string - } + export interface FillProps { + className?: string; + style?: CSSProperties; + } - export interface SProps extends BaseProps { - type?:string - } + export interface FitProps extends FillProps {} - export interface TextProps extends BaseProps { - fit?:boolean, - lineHeight?:number - } + export interface GoToActionProps { + margin?: BaseProps["margin"]; + padding?: BaseProps["padding"]; + render?: (goToSlide?: (slide: number | string) => void) => void; + slide?: number | string; + style?: BaseProps["style"]; + } - export class Spectacle extends React.Component {} + export interface HeadingProps extends BaseProps { + fit?: boolean; + lineHeight?: number; + size?: number; + } - export class Deck extends React.Component {} + export interface ImageProps { + alt?: string; + className?: BaseProps["className"]; + display?: string; + height?: number | string; + margin?: BaseProps["margin"]; + padding?: BaseProps["padding"]; + src?: string; + width?: number | string; + } - export class Slide extends React.Component {} + export interface LayoutProps { + style?: CSSProperties; + } - export class Layout extends React.Component {} + export interface LinkProps extends BaseProps { + href?: string; + target?: targetType; + } - export class Fit extends React.Component {} + export interface MarkdownProps { + mdastConfig?: { [key: string]: number | string }; + source?: string; + } - export class Fill extends React.Component {} + export interface SlideProps extends BaseProps { + align?: alignType; + contentStyles?: CSSProperties; + controlColor?: string; + dispatch?: () => void; + hash?: number | string; + progressColor?: string; + history?: any; // Needs a type, see https://github.com/ReactTraining/history + id?: string; + lastSlideIndex?: number; + notes?: string; + onActive?: (slideIndex: string | number) => void; + slideIndex?: number; + transition?: transitionType[]; + transitionDuration?: number; + transitionIn?: transitionType[]; + transitionOut?: transitionType[]; + } - export class Markdown extends React.Component {} + export interface SProps extends BaseProps { + type?: sType | sType[]; + } - export class Appear extends React.Component {} + export interface TextProps extends BaseProps { + fit?: boolean; + lineHeight?: number; + } - export class BlockQuote extends React.Component {} + export type Theme = { [key: string]: number | string }; - export class Quote extends React.Component {} + export class Anim extends React.Component {} - export class Cite extends React.Component {} + export class Appear extends React.Component {} - export class CodePane extends React.Component {} + export class BlockQuote extends React.Component {} - export class Code extends React.Component {} + export class Cite extends React.Component {} - export class Heading extends React.Component {} + export class Code extends React.Component {} - export class Image extends React.Component {} + export class CodePane extends React.Component {} - export class Link extends React.Component {} + export class ComponentPlayground extends React.Component< + ComponentPlaygroundProps + > {} - export class List extends React.Component {} + export class Deck extends React.Component {} - export class ListItem extends React.Component {} + export class Fill extends React.Component {} - export class S extends React.Component {} + export class Fit extends React.Component {} - export class Table extends React.Component {} + export class GoToAction extends React.Component {} - export class TableRow extends React.Component {} + export class Heading extends React.Component {} - export class TableHeaderItem extends React.Component {} + export class Image extends React.Component {} - export class TableItem extends React.Component {} + export class Layout extends React.Component {} - export class Text extends React.Component {} + export class Link extends React.Component {} + + export class List extends React.Component {} + + export class ListItem extends React.Component {} + + export class Markdown extends React.Component {} + + export class Notes extends React.Component {} + + export class Quote extends React.Component {} + + export class S extends React.Component {} + + export class Slide extends React.Component {} + + export class SlideSet extends React.Component {} + + export class Table extends React.Component {} + + export class TableBody extends React.Component {} + + export class TableHeader extends React.Component {} + + export class TableHeaderItem extends React.Component {} + + export class TableItem extends React.Component {} + + export class TableRow extends React.Component {} + + export class Text extends React.Component {} } declare module "spectacle/lib/utils/preloader" { - const preloader: (obj: object) => void; - export default preloader; + const preloader: (obj: object) => void; + export default preloader; } declare module "spectacle/lib/themes/default" { - import { Theme } from "spectacle"; - const createTheme: (...args: object[]) => Theme; - export default createTheme; + import { Theme } from "spectacle"; + const createTheme: (...args: object[]) => Theme; + export default createTheme; } diff --git a/types/react-bootstrap-typeahead/package.json b/types/spectacle/package.json similarity index 62% rename from types/react-bootstrap-typeahead/package.json rename to types/spectacle/package.json index 4d9ec4a338..9de3dd17fa 100644 --- a/types/react-bootstrap-typeahead/package.json +++ b/types/spectacle/package.json @@ -1,6 +1,6 @@ { "private": true, "dependencies": { - "csstype": "^2.2.0" + "csstype": "^2.2.0" } -} + } diff --git a/types/spectacle/spectacle-tests.tsx b/types/spectacle/spectacle-tests.tsx index f0a0b65e5a..04c3403f41 100644 --- a/types/spectacle/spectacle-tests.tsx +++ b/types/spectacle/spectacle-tests.tsx @@ -1,133 +1,377 @@ -/** - * Spectacle Test Examples - * - */ - -import * as React from 'react'; +import * as React from "react"; import { - Appear, - BlockQuote, - Cite, - Deck, - Fill, - Heading, - Layout, - Link, - ListItem, - List, - Quote, - Slide, - Spectacle, - Text + Anim, + Appear, + BlockQuote, + Cite, + CodePane, + ComponentPlayground, + Deck, + Fill, + GoToAction, + Heading, + Image, + Layout, + Link, + List, + ListItem, + Markdown, + Notes, + Quote, + Slide, + SlideSet, + Table, + TableBody, + TableHeader, + TableHeaderItem, + TableItem, + TableRow, + Text } from "spectacle"; // Import image preloader util -import preloader from 'spectacle/lib/utils/preloader' +import preloader from "spectacle/lib/utils/preloader"; // Import theme -import createTheme from 'spectacle/lib/themes/default' +import createTheme from "spectacle/lib/themes/default"; const images = { - city: 'a-url' -} + city: "a-url", + logo: "another-url" +}; -preloader(images) +preloader(images); -const theme = createTheme({ - primary: 'white', - secondary: '#1F2022', - tertiary: '#03A9FC', - quartenary: '#CECECE' -}, { - primary: 'Montserrat', - secondary: 'Helvetica' -}) +const theme = createTheme( + { + primary: "white", + secondary: "#1F2022", + tertiary: "#03A9FC", + quartenary: "#CECECE" + }, + { + primary: "Montserrat", + secondary: "Helvetica" + } +); export class SpectacleTest extends React.Component { - callback() { - alert('Callback: ' + JSON.stringify(arguments)); - } - - public render() { - return ( - - - - Spectacle - - - A ReactJS Presentation Library - - - Where You Can Write Your Decks In JSX - - - View on Github - - Hit Your Right Arrow To Begin! - - - - Wait what? - - - - - - Full Width - - - - - Adjustable Darkness - - - - - Background Imagery - - - - - Flexible Layouts - - - - Left - - - - - Right - - - - - -
    - Wonderfully formatted quotes - Ken Wheeler -
    -
    - - - Smooth - - - Combinable Transitions - - - - - Inline style based theme system - Autofit text - Flexbox layout system - React-Router navigation - PDF export - And... - - -
    -
    ); - } + public render() { + return ( + + + + Spectacle + + + A ReactJS Presentation Library + + + Where You Can Write Your Decks In JSX + + + + View on Github + + + + Hit Your Right Arrow To Begin! + + + + + Wait what? + + + + + + Full Width + + + + + Adjustable Darkness + + + + + Background Imagery + + + + + + + + + This is a component playground + + + + Flexible Layouts + + + + + Left + + + + + Right + + + + + + + Inline Markdown + + + {` + You can write inline images, [Markdown Links](http://commonmark.org), paragraph text and most other markdown syntax + * Lists too! + * With ~~strikethrough~~ and _italic_ + * And let's not forget **bold** + * Add some \`inline code\` to your sldes! + `} + + + + { + /* eslint-disable */ + console.log("forwards ", forwards); + console.log("animIndex ", animIndex); + /* eslint-enable */ + }} + fromStyle={{ + opacity: 0, + transform: + "translate3d(0px, -100px, 0px) scale(1) rotate(0deg)" + }} + toStyle={[ + { + opacity: 1, + transform: + "translate3d(0px, 0px, 0px) scale(1) rotate(0deg)" + }, + { + opacity: 1, + transform: + "translate3d(0px, 0px, 0px) scale(1.6) rotate(-15deg)" + }, + { + opacity: 1, + transform: + "translate3d(0px, 0px, 0px) scale(0.8) rotate(0deg)" + } + ]} + easing={"bounceOut"} + transitionDuration={500} + > + + + Flexible +
    + animations +
    +
    +
    +
    + + + Mix it up! + + + You can even jump to different slides with a standard + button or custom component! + + + Jump to Slide 8 + + ( + + )} + /> + + +
    + Wonderfully formatted quotes + Ken Wheeler +
    +
    + +
    + Wonderfully formatted quotes + Ken Wheeler +
    +
    + + + + + + Inline style based theme system + + + + Autofit text + + + Flexbox layout system + + + PDF export + + + And... + + + + + + You can even share styles with SlideSet + + + + + + Pizza Toppings + + + + + + + 2011 + 2013 + 2015 + + + + + None + 61.8% + 39.6% + 35.0% + + + Pineapple + 28.3% + 54.5% + 61.5% + + + Pepperoni + + 50.2% + 77.2% + + + Olives + + 24.9% + 55.9% + + +
    +
    +
    + + + Made with love in Seattle by + + + + + +
    + ); + } } diff --git a/types/ssh2-sftp-client/index.d.ts b/types/ssh2-sftp-client/index.d.ts index 2dcaee74e6..c568571eb5 100644 --- a/types/ssh2-sftp-client/index.d.ts +++ b/types/ssh2-sftp-client/index.d.ts @@ -1,39 +1,71 @@ -// Type definitions for ssh2-sftp-client 2.3 +// Type definitions for ssh2-sftp-client 2.4 // Project: https://www.npmjs.com/package/ssh2-sftp-client -// Definitions by: igrayson , Ascari Andrea , Kartik Malik +// Definitions by: igrayson +// Ascari Andrea +// Kartik Malik +// Michael Pertl // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped import * as ssh2 from 'ssh2'; import * as ssh2Stream from 'ssh2-streams'; + export = sftp; declare class sftp { - connect(options: ssh2.ConnectConfig): Promise; - list(remoteFilePath: string): Promise; - get(remoteFilePath: string, useCompression?: boolean, encoding?: string | null): Promise; - fastGet(remoteFilePath: string, localPath: string, options?: ssh2Stream.TransferOptions): Promise; - put(input: string | Buffer | NodeJS.ReadableStream, remoteFilePath: string, useCompression?: boolean, encoding?: string): Promise; - fastPut(localPath: string, emoteFilePath: string, options?: ssh2Stream.TransferOptions): Promise; - mkdir(remoteFilePath: string, recursive?: boolean): Promise; - rmdir(remoteFilePath: string, recursive?: boolean): Promise; - delete(remoteFilePath: string): Promise; - rename(remoteSourcePath: string, remoteDestPath: string): Promise; - end(): Promise; - on(event: string, callback: (...args: any[]) => void): void; + connect(options: ssh2.ConnectConfig): Promise; + + list(remoteFilePath: string): Promise; + + exists(remotePath: string): Promise; + + stat(remotePath: string): Promise; + + get(remoteFilePath: string, useCompression?: boolean, encoding?: string | null): Promise; + + fastGet(remoteFilePath: string, localPath: string, options?: ssh2Stream.TransferOptions): Promise; + + put(input: string | Buffer | NodeJS.ReadableStream, remoteFilePath: string, useCompression?: boolean, encoding?: string): Promise; + + fastPut(localPath: string, emoteFilePath: string, options?: ssh2Stream.TransferOptions): Promise; + + mkdir(remoteFilePath: string, recursive?: boolean): Promise; + + rmdir(remoteFilePath: string, recursive?: boolean): Promise; + + delete(remoteFilePath: string): Promise; + + rename(remoteSourcePath: string, remoteDestPath: string): Promise; + + chmod(remotePath: string, mode: number | string): Promise; + + end(): Promise; + + on(event: string, callback: (...args: any[]) => void): void; } + declare namespace sftp { - interface FileInfo { - type: string; - name: string; - size: number; - modifyTime: number; - accessTime: number; - rights: { - user: string; - group: string; - other: string; - }; - owner: number; - group: number; - } + interface FileInfo { + type: string; + name: string; + size: number; + modifyTime: number; + accessTime: number; + rights: { + user: string; + group: string; + other: string; + }; + owner: number; + group: number; + } + + interface FileStats { + mode: number; + permissions?: any; + owner: number; + group: number; + size: number; + accessTime: number; + modifyTime: number; + } } diff --git a/types/ssh2-sftp-client/ssh2-sftp-client-tests.ts b/types/ssh2-sftp-client/ssh2-sftp-client-tests.ts index 8a9c99fde1..d59e552990 100644 --- a/types/ssh2-sftp-client/ssh2-sftp-client-tests.ts +++ b/types/ssh2-sftp-client/ssh2-sftp-client-tests.ts @@ -1,5 +1,6 @@ import Client = require('ssh2-sftp-client'); import * as fs from 'fs'; + const client = new Client(); client.connect({ @@ -11,6 +12,10 @@ client.connect({ client.list('/remote/path').then(() => null); +client.exists('/remote/path').then(() => null); + +client.stat('/remote/path').then(() => null); + client.get('/remote/path').then(stream => stream.read(0)); client.get('/remote/path', true, 'utf8').then(stream => stream.read(0)); client.get('/remote/path', true, null).then(stream => stream.read(0)); @@ -30,6 +35,8 @@ client.delete('remote/path').then(() => null); client.rename('/remote/from', '/remote/to').then(() => null); +client.chmod('/remote/path', 777).then(() => null); + client.end().then(() => null); client.on('event', () => null); diff --git a/types/ssh2-streams/index.d.ts b/types/ssh2-streams/index.d.ts index a780273591..df1e001e0a 100644 --- a/types/ssh2-streams/index.d.ts +++ b/types/ssh2-streams/index.d.ts @@ -1044,6 +1044,24 @@ export class SFTPStream extends stream.Transform { */ fastPut(localPath: string, remotePath: string, callback: (err: any) => void): void; + /** + * (Client-only) + * Reads a file in memory and returns its contents + */ + readFile(remotePath: string, options: ReadFileOptions, callback: (err: any, handle: Buffer) => void): void; + + /** + * (Client-only) + * Reads a file in memory and returns its contents + */ + readFile(remotePath: string, encoding: string, callback: (err: any, handle: Buffer) => void): void; + + /** + * (Client-only) + * Reads a file in memory and returns its contents + */ + readFile(remotePath: string, callback: (err: any, handle: Buffer) => void): void; + /** * (Client-only) * Returns a new readable stream for `path`. @@ -1680,4 +1698,9 @@ export interface ParsedKey { publicOrig: Buffer; ppk?: boolean; privateMAC?: string; +} + +export interface ReadFileOptions { + encoding?: string; + flag?: string; } \ No newline at end of file diff --git a/types/ssh2/index.d.ts b/types/ssh2/index.d.ts index 25bcfef52e..cf88fff5f1 100644 --- a/types/ssh2/index.d.ts +++ b/types/ssh2/index.d.ts @@ -3,6 +3,7 @@ // Definitions by: Qubo // Ron Buckton // Will Boyce +// Lucas Motta // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -21,6 +22,7 @@ import { Attributes, Stats, TransferOptions, + ReadFileOptions, ReadStreamOptions, WriteStreamOptions, FileEntry @@ -1273,6 +1275,24 @@ export interface SFTPWrapper extends events.EventEmitter { */ fastPut(localPath: string, remotePath: string, callback: (err: any) => void): void; + /** + * (Client-only) + * Reads a file in memory and returns its contents + */ + readFile(remotePath: string, options: ReadFileOptions, callback: (err: any, handle: Buffer) => void): void; + + /** + * (Client-only) + * Reads a file in memory and returns its contents + */ + readFile(remotePath: string, encoding: string, callback: (err: any, handle: Buffer) => void): void; + + /** + * (Client-only) + * Reads a file in memory and returns its contents + */ + readFile(remotePath: string, callback: (err: any, handle: Buffer) => void): void; + /** * (Client-only) * Returns a new readable stream for `path`. diff --git a/types/storybook__addon-options/index.d.ts b/types/storybook__addon-options/index.d.ts index 61f9f11def..968b003543 100644 --- a/types/storybook__addon-options/index.d.ts +++ b/types/storybook__addon-options/index.d.ts @@ -1,10 +1,14 @@ -// Type definitions for @storybook/addon-options 3.2 +// Type definitions for @storybook/addon-options 4.0 // Project: https://github.com/storybooks/storybook // Definitions by: Joscha Feth // Simon Helle Nielsen // A.MacLeay +// Gaetan Maisse +// Adam Misiorny // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.8 + +import { StoryDecorator } from '@storybook/react'; export interface Options { name?: string; @@ -20,7 +24,14 @@ export interface Options { sortStoriesByKind?: boolean; hierarchySeparator?: RegExp | string; hierarchyRootSeparator?: RegExp | string; + sidebarAnimations?: boolean; selectedAddonPanel?: string; + enableShortcuts?: boolean; } +/** + * @deprecated Use withOptions instead + */ export function setOptions(options: Options): void; + +export function withOptions(options: Options): StoryDecorator; diff --git a/types/storybook__addon-options/storybook__addon-options-tests.ts b/types/storybook__addon-options/storybook__addon-options-tests.ts index a3003c913f..4321ecd72d 100644 --- a/types/storybook__addon-options/storybook__addon-options-tests.ts +++ b/types/storybook__addon-options/storybook__addon-options-tests.ts @@ -1,4 +1,23 @@ -import { setOptions } from '@storybook/addon-options'; +import { addDecorator } from '@storybook/react'; +import { setOptions, withOptions } from '@storybook/addon-options'; + +addDecorator( + withOptions({ + name: 'My Storybook', + url: 'https://example.com', + goFullScreen: false, + showStoriesPanel: false, + showAddonPanel: false, + showSearchBox: false, + addonPanelInRight: false, + sortStoriesByKind: false, + hierarchySeparator: /\//, + hierarchyRootSeparator: /\|/, + sidebarAnimations: false, + selectedAddonPanel: 'storybook/actions/action-panel', + enableShortcuts: false + }) +); setOptions({ name: 'My Storybook', @@ -11,7 +30,9 @@ setOptions({ sortStoriesByKind: false, hierarchySeparator: /\//, hierarchyRootSeparator: /\|/, + sidebarAnimations: false, selectedAddonPanel: 'storybook/actions/action-panel', + enableShortcuts: false }); setOptions({ diff --git a/types/storybook__addon-options/tsconfig.json b/types/storybook__addon-options/tsconfig.json index 936a535725..df1a88f769 100644 --- a/types/storybook__addon-options/tsconfig.json +++ b/types/storybook__addon-options/tsconfig.json @@ -15,6 +15,9 @@ "paths": { "@storybook/addon-options": [ "storybook__addon-options" + ], + "@storybook/react": [ + "storybook__react" ] }, "types": [], @@ -25,4 +28,4 @@ "index.d.ts", "storybook__addon-options-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/storybook__react-native/index.d.ts b/types/storybook__react-native/index.d.ts index 3f46866129..fc308fa69b 100644 --- a/types/storybook__react-native/index.d.ts +++ b/types/storybook__react-native/index.d.ts @@ -4,18 +4,98 @@ // Anton Izmailov // Alec Hill // Kyle Roach +// Ceyhun Ozugur // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 import * as React from 'react'; export interface StorybookUIOptions { + /** + * display navigator and addons on the device + * + * @default true + */ onDeviceUI?: boolean; + + /** + * allows to display stories without running storybook server. Should be used with onDeviceUI + * + * @default false + */ disableWebsockets?: boolean; + + /** + * use wss/https instead of ws/http + * + * @default false + */ secured?: boolean; + + /** + * host to use + * + * @default NativeModules.SourceCode.scriptURL + */ host?: string; + + /** + * port to use + * + * @default 7007 + */ port?: number; + + /** + * additional query string to pass to websockets + * + * @default "" + */ query?: string; + + /** + * should the ui be closed initialy. + * + * @default false + */ + isUIHidden?: boolean; + + /** + * which tab should be open. -1 Navigator, 0 Preview, 1 Addons + * + * @default 0 + */ + tabOpen?: number; + + /** + * initialize storybook with a specific story. + * In case a valid object is passed, it will take precedence over `shouldPersistSelection`. + * ex: `{ kind: 'Knobs', story: 'with knobs' }` + * + * @default null + */ + initialSelection?: object; + + /** + * initialize storybook with the last selected story. + * + * @default true + */ + shouldPersistSelection?: boolean; + + /** + * disable KeyboardAvoidingView wrapping Storybook's view + * + * @default false + */ + shouldDisableKeyboardAvoidingView?: boolean; + + /** + * this will set the keyboardverticaloffset (https://facebook.github.io/react-native/docs/keyboardavoidingview#keyboardverticaloffset) value for KeyboardAvoidingView wrapping Storybook's view + * + * @default 0 + */ + keyboardAvoidingViewVerticalOffset?: number; } export function getStorybookUI( diff --git a/types/styled-components/index.d.ts b/types/styled-components/index.d.ts index 2f6fa61317..ca3ff22c0e 100644 --- a/types/styled-components/index.d.ts +++ b/types/styled-components/index.d.ts @@ -73,7 +73,7 @@ export type SimpleInterpolation = | InterpolationValue | FlattenSimpleInterpolation; // must be an interface to be self-referential -interface FlattenSimpleInterpolation +export interface FlattenSimpleInterpolation extends ReadonlyArray {} export type InterpolationFunction

    = (props: P) => Interpolation

    ; @@ -176,10 +176,9 @@ export interface ThemedStyledFunctionBase< ( first: | TemplateStringsArray - | NonNullable< - Interpolation< - ThemedStyledProps & O, T> - > + | CSSObject + | InterpolationFunction< + ThemedStyledProps & O, T> >, ...rest: Array< Interpolation< @@ -187,17 +186,12 @@ export interface ThemedStyledFunctionBase< > > ): StyledComponent; - // at least the first argument is required, whatever it is ( first: | TemplateStringsArray - | NonNullable< - Interpolation< - ThemedStyledProps< - StyledComponentPropsWithRef & O & U, - T - > - > + | CSSObject + | InterpolationFunction< + ThemedStyledProps & O & U, T> >, ...rest: Array< Interpolation< @@ -288,19 +282,21 @@ export type StyledInterface = ThemedStyledInterface; export interface BaseThemedCssFunction { ( - first: TemplateStringsArray | NonNullable, + first: TemplateStringsArray | CSSObject, ...interpolations: SimpleInterpolation[] ): FlattenSimpleInterpolation; ( first: | TemplateStringsArray - | NonNullable>>, + | CSSObject + | InterpolationFunction>, ...interpolations: Array>> ): FlattenInterpolation>;

    ( first: | TemplateStringsArray - | NonNullable>>, + | CSSObject + | InterpolationFunction>, ...interpolations: Array>> ): FlattenInterpolation>; } @@ -333,7 +329,8 @@ export interface ThemedStyledComponentsModule< createGlobalStyle

    ( first: | TemplateStringsArray - | NonNullable>>, + | CSSObject + | InterpolationFunction>, ...interpolations: Array>> ): GlobalStyleComponent; @@ -405,7 +402,8 @@ export function keyframes( export function createGlobalStyle

    ( first: | TemplateStringsArray - | NonNullable>>, + | CSSObject + | InterpolationFunction>, ...interpolations: Array>> ): GlobalStyleComponent; @@ -468,7 +466,7 @@ export class StyleSheetManager extends React.Component< */ // ONLY string literals and inline invocations of css`` are supported, anything else crashes the plugin export type CSSProp> = - string | - FlattenInterpolation>; + | string + | FlattenInterpolation>; export default styled; diff --git a/types/styled-components/test/index.tsx b/types/styled-components/test/index.tsx index 2d70f74106..d382b42628 100644 --- a/types/styled-components/test/index.tsx +++ b/types/styled-components/test/index.tsx @@ -14,7 +14,10 @@ import styled, { withTheme, ThemeConsumer, StyledComponent, - ThemedStyledComponentsModule + ThemedStyledComponentsModule, + FlattenSimpleInterpolation, + SimpleInterpolation, + FlattenInterpolation } from "styled-components"; import {} from "styled-components/cssprop"; @@ -101,13 +104,13 @@ const fadeIn = keyframes` `; const showAnimation = css` - opacity: 1; - transform: scale(1) translateY(0); + opacity: 1; + transform: scale(1) translateY(0); `; const hideAnimation = css` - opacity: 0; - transform: scale(0.95, 0.8) translateY(20px); + opacity: 0; + transform: scale(0.95, 0.8) translateY(20px); `; const entryAnimation = keyframes` @@ -694,6 +697,8 @@ async function typedThemes() { return props.theme.color; }}; `; + // can't use a FlattenInterpolation as the first argument, would make broken css + // $ExpectError const ThemedDiv4 = styled.div(themedCss); const themedCssWithNesting = css(props => ({ @@ -714,7 +719,6 @@ async function typedThemes() { - {theme => { // $ExpectType string @@ -867,3 +871,78 @@ function cssProp() { ); } + +function validateArgumentsAndReturns() { + const t1: FlattenSimpleInterpolation[] = [ + css({ color: "blue" }), + css` + color: blue; + `, + css` + color: ${"blue"}; + ` + ]; + const t4: FlattenInterpolation = [ + css` + color: ${() => "blue"}; + `, + css(() => ({ color: "blue" })), + css( + () => + css` + color: "blue"; + ` + ) + ]; + + // if the first argument is array-like it's always treated as a string[], this breaks things + css( + // $ExpectError + css` + ${{ color: "blue" }} + ` + ); + // _technically_ valid as styled-components doesn't look at .raw but best not to support it + // $ExpectError + css([]); + + styled.div({ color: "blue" }); + styled.div(props => ({ color: props.theme.color })); + styled.div` + color: ${"blue"}; + `; + // These don't work for the same reason css doesn't work + styled.div( + // $ExpectError + css` + ${{ color: "blue" }} + ` + ); + // $ExpectError + styled.div([]); + + createGlobalStyle({ + ":root": { + color: "blue" + } + }); + createGlobalStyle` + :root { + color: blue; + } + `; + createGlobalStyle(() => ({ + ":root": { + color: "blue" + } + })); + // these are invalid for the same reason as in styled.div + // $ExpectError + createGlobalStyle(css` + :root { + color: ${() => "blue"}; + } + `); + // $ExpectError + createGlobalStyle([]); +} diff --git a/types/subsume/index.d.ts b/types/subsume/index.d.ts index 7ec2f9d568..e42c97cd4f 100644 --- a/types/subsume/index.d.ts +++ b/types/subsume/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for subsume 1.0 +// Type definitions for subsume 2.0 // Project: https://github.com/sindresorhus/subsume#readme // Definitions by: BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -7,6 +7,7 @@ export = Subsume; declare class Subsume { static parse(text: string, id: string): Subsume.ParseResult; + static parseAll(text: string, ids?: string[]): Subsume.ParseResults; id: string; prefix: string; @@ -23,4 +24,9 @@ declare namespace Subsume { data?: string; rest: string; } + + interface ParseResults { + data: Map; + rest: string; + } } diff --git a/types/subsume/subsume-tests.ts b/types/subsume/subsume-tests.ts index 263553733a..56234d275b 100644 --- a/types/subsume/subsume-tests.ts +++ b/types/subsume/subsume-tests.ts @@ -18,5 +18,13 @@ res; // $ExpectType ParseResult res.data; // $ExpectType string | undefined res.rest; // $ExpectType string -const input = 'some@@[7febcd0b3806fbc48c01d7cea4ed1219]@@🦄##[7febcd0b3806fbc48c01d7cea4ed1219]## random text'; -Subsume.parse(text, '7febcd0b3806fbc48c01d7cea4ed1219'); // $ExpectType ParseResult +const input = + 'some@@[7febcd0b3806fbc48c01d7cea4ed1219]@@🦄##[7febcd0b3806fbc48c01d7cea4ed1219]## random text'; +Subsume.parse(input, '7febcd0b3806fbc48c01d7cea4ed1219'); // $ExpectType ParseResult + +const input2 = + 'some@@[7febcd0b3806fbc48c01d7cea4ed1219]@@🦄##[7febcd0b3806fbc48c01d7cea4ed1219]## ' + + 'random@@[7febcd0b3806fbc48c01d7cea4ed1218]@@🦄##[7febcd0b3806fbc48c01d7cea4ed1218]## ' + + 'text@@[7febcd0b3806fbc48c01d7cea4ed1217]@@🦄##[7febcd0b3806fbc48c01d7cea4ed1217]##'; +Subsume.parseAll(input2); // $ExpectType ParseResults +Subsume.parseAll(input2, ['7febcd0b3806fbc48c01d7cea4ed1219']); // $ExpectType ParseResults diff --git a/types/subsume/tsconfig.json b/types/subsume/tsconfig.json index b29ec71ee8..7eefbf76e9 100644 --- a/types/subsume/tsconfig.json +++ b/types/subsume/tsconfig.json @@ -20,4 +20,4 @@ "index.d.ts", "subsume-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/subsume/v1/index.d.ts b/types/subsume/v1/index.d.ts new file mode 100644 index 0000000000..7ec2f9d568 --- /dev/null +++ b/types/subsume/v1/index.d.ts @@ -0,0 +1,26 @@ +// Type definitions for subsume 1.0 +// Project: https://github.com/sindresorhus/subsume#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = Subsume; + +declare class Subsume { + static parse(text: string, id: string): Subsume.ParseResult; + + id: string; + prefix: string; + postfix: string; + regex: RegExp; + + constructor(id?: string); + compose(text: string): string; + parse(text: string): Subsume.ParseResult; +} + +declare namespace Subsume { + interface ParseResult { + data?: string; + rest: string; + } +} diff --git a/types/subsume/v1/subsume-tests.ts b/types/subsume/v1/subsume-tests.ts new file mode 100644 index 0000000000..263553733a --- /dev/null +++ b/types/subsume/v1/subsume-tests.ts @@ -0,0 +1,22 @@ +import Subsume = require('subsume'); + +const subsume = new Subsume(); +new Subsume('foo'); + +subsume.id; // $ExpectType string +subsume.prefix; // $ExpectType string +subsume.postfix; // $ExpectType string +subsume.regex; // $ExpectType RegExp + +const text = subsume.compose('🦄'); +text; // $ExpectType string + +const output = `some${text} random text`; + +const res = subsume.parse(output); +res; // $ExpectType ParseResult +res.data; // $ExpectType string | undefined +res.rest; // $ExpectType string + +const input = 'some@@[7febcd0b3806fbc48c01d7cea4ed1219]@@🦄##[7febcd0b3806fbc48c01d7cea4ed1219]## random text'; +Subsume.parse(text, '7febcd0b3806fbc48c01d7cea4ed1219'); // $ExpectType ParseResult diff --git a/types/subsume/v1/tsconfig.json b/types/subsume/v1/tsconfig.json new file mode 100644 index 0000000000..0e0565e161 --- /dev/null +++ b/types/subsume/v1/tsconfig.json @@ -0,0 +1,28 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "paths": { + "subsume": [ + "subsume/v1" + ] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "subsume-tests.ts" + ] +} diff --git a/types/subsume/v1/tslint.json b/types/subsume/v1/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/subsume/v1/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/superagent/index.d.ts b/types/superagent/index.d.ts index 971cc3c4c2..7c1898cdc2 100644 --- a/types/superagent/index.d.ts +++ b/types/superagent/index.d.ts @@ -6,6 +6,7 @@ // Shrey Jain // Alec Zopf // Adam Haglund +// Lukas Elmer // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -45,7 +46,7 @@ declare namespace request { // tslint:disable-next-line:unified-signatures (method: string, url: string): SuperAgentRequest; - agent(): SuperAgent; + agent(): this & Request; serialize: { [type: string]: Serializer }; parse: { [type: string]: Parser }; } diff --git a/types/superagent/superagent-tests.ts b/types/superagent/superagent-tests.ts index c063c819be..44ef7cf773 100644 --- a/types/superagent/superagent-tests.ts +++ b/types/superagent/superagent-tests.ts @@ -421,3 +421,16 @@ request .get('/echo') .use(echoPlugin) .end(); + +async function testDefaultOptions() { + // Default options for multiple requests + const agentWithDefaultOptions = request + .agent() + .use(() => null) + .auth('digest', 'secret', { type: 'auto' }); + + await agentWithDefaultOptions.get('/with-plugin-and-auth'); + await agentWithDefaultOptions.get('/also-with-plugin-and-auth'); +} + +testDefaultOptions(); diff --git a/types/supertest/index.d.ts b/types/supertest/index.d.ts index 77418352f9..5ac03df42d 100644 --- a/types/supertest/index.d.ts +++ b/types/supertest/index.d.ts @@ -24,7 +24,7 @@ declare namespace supertest { serverAddress(app: any, path: string): string; expect(status: number, callback?: CallbackHandler): this; expect(status: number, body: any, callback?: CallbackHandler): this; - expect(checker: (res: Response) => any): this; + expect(checker: (res: Response) => any, callback?: CallbackHandler): this; expect(body: string, callback?: CallbackHandler): this; expect(body: RegExp, callback?: CallbackHandler): this; expect(body: Object, callback?: CallbackHandler): this; diff --git a/types/swiper/index.d.ts b/types/swiper/index.d.ts index 9e77516978..74b8d928b9 100644 --- a/types/swiper/index.d.ts +++ b/types/swiper/index.d.ts @@ -1,10 +1,11 @@ -// Type definitions for Swiper 4.2 +// Type definitions for Swiper 4.4 // Project: https://github.com/nolimits4web/Swiper // Definitions by: Sebastián Galiano // Luca Trazzi // Eugene Matseruk // Luiz M. // Justin Abene +// Asif Rahman // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.9 @@ -221,6 +222,7 @@ export interface SwiperOptions { slidesOffsetBefore?: number; slidesOffsetAfter?: number; normalizeSlideIndex?: boolean; + centerInsufficientSlides?: boolean; // Grab Cursor grabCursor?: boolean; @@ -238,6 +240,8 @@ export interface SwiperOptions { followFinger?: boolean; allowTouchMove?: boolean; threshold?: number; + touchStartPreventDefault?: boolean; + touchStartForcePreventDefault?: boolean; touchMoveStopPropagation?: boolean; iOSEdgeSwipeDetection?: boolean; iOSEdgeSwipeThreshold?: number; @@ -249,11 +253,12 @@ export interface SwiperOptions { resistanceRatio?: number; // Swiping / No swiping + preventInteractionOnTransition?: boolean; allowSlidePrev?: boolean; allowSlideNext?: boolean; noSwiping?: boolean; noSwipingClass?: string; - // noSwipingSelector?: string; + noSwipingSelector?: string; swipeHandler?: SelectableElement; // Clicks @@ -289,6 +294,7 @@ export interface SwiperOptions { breakpoints?: { [index: number]: SwiperOptions; }; + breakpointsInverse?: boolean; // Observer observer?: boolean; @@ -1073,6 +1079,44 @@ export default class Swiper { */ slideTo(index: number, speed?: number, runCallbacks?: boolean): void; + /** + * Does the same as .slideTo but for the case when used with enabled loop. So this + * method will slide to slides with realIndex matching to passed index + * + * @param index Index number of slide. + * @param speed Transition duration (in ms). + * @param runCallbacks Set it to false (by default it is true) and transition will + * not produce transition events. + */ + slideToLoop(index: number, speed?: number, runCallbacks?: boolean): void; + + /** + * Reset swiper position to currently active slide for the duration equal to 'speed' + * parameter. + * + * @param speed Transition duration (in ms). + * @param runCallbacks Set it to false (by default it is true) and transition will + * not produce transition events. + */ + slideReset(speed?: number, runCallbacks?: boolean): void; + + /** + * Reset swiper position to closest slide/snap point for the duration equal to 'speed' parameter. + * + * @param speed Transition duration (in ms). + * @param runCallbacks Set it to false (by default it is true) and transition will + * not produce transition events. + */ + slideToClosest(speed?: number, runCallbacks?: boolean): void; + + /** + * Force swiper to update its height (when autoHeight enabled) for the duration equal to + * 'speed' parameter + * + * @param speed Transition duration (in ms). + */ + updateAutoHeight(speed?: number): void; + /** * You should call it after you add/remove slides * manually, or after you hide/show it, or do any @@ -1162,6 +1206,17 @@ export default class Swiper { */ prependSlide(slides: HTMLElement | string | string[]): void; + /** + * Add new slides to the required index. slides could be HTMLElement or HTML string with new slide or array with such slides, for example: + * + * @example addSlide(1, '

    Slide 10"
    ') + * @example addSlide(1, [ + * '
    Slide 10"
    ', + * '
    Slide 11"
    ' + * ]); + */ + addSlide(index: number, slides: HTMLElement | string | string[]): void; + /** * Remove selected slides. slideIndex could be a number with slide index to remove or array with indexes. * @@ -1171,6 +1226,11 @@ export default class Swiper { */ removeSlide(slideIndex: number | number[]): void; + /** + * Remove all slides + */ + removeAllSlides(): any; + /** * Set custom css3 transform's translate value for swiper wrapper */ diff --git a/types/three-tds-loader/index.d.ts b/types/three-tds-loader/index.d.ts new file mode 100644 index 0000000000..33e679a377 --- /dev/null +++ b/types/three-tds-loader/index.d.ts @@ -0,0 +1,202 @@ +// Type definitions for three-tds-loader 1.1 +// Project: https://github.com/codetheorist/three-tds-loader +// Definitions by: Konstantin Lukaschenko +// Stefan Schönsee +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import * as THREE from 'three'; + +export = TDSLoader; + +declare class TDSLoader { + constructor(three: typeof THREE); + + /** + * Load 3ds file from url. + * + * @param url URL for the file. + * @param onLoad onLoad callback, receives group object3D as argument. + * @param onProgress onProgress callback. + * @param onError onError callback. + */ + load: (url: string, onLoad: (object3D: THREE.Object3D) => void, onProgress?: (progress: ProgressEvent) => void, onError?: (event: ErrorEvent) => void) => void; + + /** + * Parse arraybuffer data and load 3ds file. + * + * @param arraybuffer Arraybuffer data to be loaded. + * @param path Path for external resources. + * @return Group loaded from 3ds file. + */ + parse: (arraybuffer: ArrayBuffer, path: string) => THREE.Object3D; + + /** + * Decode file content to read 3ds data. + * + * @param arraybuffer Arraybuffer data to be loaded. + */ + readFile: (arraybuffer: ArrayBuffer, path: string) => void; + + /** + * Read mesh data chunk. + * + * @param data Dataview in use. + */ + readMeshData: (data: DataView, path: string) => void; + + /** + * Read named object chunk. + * + * @param data Dataview in use. + */ + readNamedobject: (data: DataView) => void; + + /** + * Read material data chunk and add it to the material list. + * + * @param data Dataview in use. + */ + readMaterialEntry: (data: DataView, path: string) => void; + + /** + * Read mesh data chunk. + * + * @param data Dataview in use. + */ + readMesh: (data: DataView) => void; + + /** + * Read face array data chunk. + * + * @param data Dataview in use. + * @param mesh Mesh to be filled with the data read. + */ + readFaceArray: (data: DataView, mesh: THREE.Mesh) => void; + + /** + * Read texture map data chunk. + * + * @param data Dataview in use. + * @return Texture read from this data chunk. + */ + readMap: (data: DataView, path: string) => THREE.Texture; + + /** + * Read material group data chunk. + * + * @param data Dataview in use. + * @return object with name and index of the object. + */ + readMaterialGroup: (data: DataView) => object; + + /** + * Read a color value. + * + * @param data Dataview. + * @return Color value read.. + */ + readColor: (data: DataView) => THREE.Color; + + /** + * Read next chunk of data. + * + * @param data Dataview. + * @return Chunk of data read. + */ + readChunk: (data: DataView) => object; + + /** + * Set position to the end of the current chunk of data. + * + * @param chunk Data chunk. + */ + endChunk: (chunk: object) => void; + + /** + * Move to the next data chunk. + * + * @param data Dataview. + * @param chunk Data chunk. + */ + nextChunk: (data: DataView, chunk: object) => number; + + /** + * Reset dataview position. + */ + resetPosition: () => void; + + /** + * Read byte value. + * + * @param data Dataview to read data from. + * @return Data read from the dataview. + */ + readByte: (data: DataView) => number; + + /** + * Read 32 bit float value. + * + * @param data Dataview to read data from. + * @return Data read from the dataview. + */ + readFloat: (data: DataView) => number; + + /** + * Read 32 bit signed integer value. + * + * @param data Dataview to read data from. + * @return Data read from the dataview. + */ + readInt: (data: DataView) => number; + + /** + * Read 16 bit signed integer value. + * + * @param data Dataview to read data from. + * @return Data read from the dataview. + */ + readShort: (data: DataView) => number; + + /** + * Read 64 bit unsigned integer value. + * + * @param data Dataview to read data from. + * @return Data read from the dataview. + */ + readDWord: (data: DataView) => number; + + /** + * Read 32 bit unsigned integer value. + * + * @param data Dataview to read data from. + * @return Data read from the dataview. + */ + readWord: (data: DataView) => number; + + /** + * Read string value. + * + * @param data Dataview to read data from. + * @param maxLength Max size of the string to be read. + * @return Data read from the dataview. + */ + readString: (data: DataView, maxLength: number) => string; + + /** + * Set resource path used to determine the file path to attached resources. + * + * @param path Path to resources. + * @return Self for chaining. + */ + setPath: (path: string) => TDSLoader; + + /** + * Print debug message to the console. + * + * Is controlled by a flag to show or hide debug messages. + * + * @param message Debug message to print to the console. + */ + debugMessage: (message: string) => void; +} diff --git a/types/three-tds-loader/three-tds-loader-tests.ts b/types/three-tds-loader/three-tds-loader-tests.ts new file mode 100644 index 0000000000..a4e9d61797 --- /dev/null +++ b/types/three-tds-loader/three-tds-loader-tests.ts @@ -0,0 +1,15 @@ +import * as THREE from 'three'; +import TDSLoader = require('three-tds-loader'); + +const loader = new TDSLoader(THREE); + +const onSuccess = (object3D: THREE.Object3D) => {}; +const onProgress = (progress: ProgressEvent) => {}; +const onError = (event: ErrorEvent) => {}; + +loader.load( + 'folder/file.3ds', + onSuccess, + onProgress, + onError +); diff --git a/types/three-tds-loader/tsconfig.json b/types/three-tds-loader/tsconfig.json new file mode 100644 index 0000000000..cab037513c --- /dev/null +++ b/types/three-tds-loader/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "three-tds-loader-tests.ts" + ] +} diff --git a/types/three-tds-loader/tslint.json b/types/three-tds-loader/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/three-tds-loader/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/three/index.d.ts b/types/three/index.d.ts index b8c5dfa961..08b64250c8 100644 --- a/types/three/index.d.ts +++ b/types/three/index.d.ts @@ -23,6 +23,8 @@ // Dilip Ramirez // Julian Strecker // Zhang Hao +// Konstantin Lukaschenko +// Daniel Yim // Definitions: https://github.com//DefinitelyTyped // TypeScript Version: 2.8 @@ -34,6 +36,7 @@ export * from "./three-copyshader"; export * from "./three-css3drenderer"; export * from "./three-ctmloader"; export * from "./three-ddsloader"; +export * from "./three-tdsloader"; export * from "./three-dragcontrols"; export * from "./three-editorcontrols"; export * from "./three-effectcomposer"; @@ -43,6 +46,7 @@ export * from "./three-FirstPersonControls"; export * from "./three-gltfexporter"; export * from "./three-gltfloader"; export * from "./three-lensflare"; +export * from "./three-mapcontrols"; export * from "./three-maskpass"; export * from "./three-mtlloader"; export * from "./three-objloader"; diff --git a/types/three/test/examples/loaders/tdsloader.ts b/types/three/test/examples/loaders/tdsloader.ts new file mode 100644 index 0000000000..72666d4003 --- /dev/null +++ b/types/three/test/examples/loaders/tdsloader.ts @@ -0,0 +1,14 @@ +import * as THREE from '../../../index' + +const onSuccess = (object3D: THREE.Object3D) => {}; +const onProgress = (progress: ProgressEvent) => {}; +const onError = (event: ErrorEvent) => {}; + +() => { + new THREE.TDSLoader(THREE).load( + 'folder/file.3ds', + onSuccess, + onProgress, + onError + ); +} \ No newline at end of file diff --git a/types/three/three-core.d.ts b/types/three/three-core.d.ts index 955eb45faf..003c6a70f6 100755 --- a/types/three/three-core.d.ts +++ b/types/three/three-core.d.ts @@ -3562,7 +3562,7 @@ export class Euler { fromArray(xyzo: any[]): Euler; toArray(array?: number[], offset?: number): number[]; toVector3(optionalResult?: Vector3): Vector3; - onChange(callback: Function): void; + onChange(callback: Function): this; static RotationOrders: string[]; static DefaultOrder: string; diff --git a/types/three/three-mapcontrols.d.ts b/types/three/three-mapcontrols.d.ts new file mode 100644 index 0000000000..66ff8a0982 --- /dev/null +++ b/types/three/three-mapcontrols.d.ts @@ -0,0 +1,71 @@ +import { + Camera, + EventDispatcher, + MOUSE, + Object3D, + Vector3 +} from "./three-core"; + +export class MapControls extends EventDispatcher { + constructor(object: Camera, domElement?: HTMLElement); + + object: Camera; + domElement: HTMLElement | HTMLDocument; + + // API + enabled: boolean; + target: Vector3; + + enableZoom: boolean; + zoomSpeed: number; + minDistance: number; + maxDistance: number; + enableRotate: boolean; + rotateSpeed: number; + enablePan: boolean; + keyPanSpeed: number; + maxZoom: number; + minZoom: number; + panSpeed: number; + autoRotate: boolean; + autoRotateSpeed: number; + minPolarAngle: number; + maxPolarAngle: number; + minAzimuthAngle: number; + maxAzimuthAngle: number; + enableKeys: boolean; + screenSpacePanning: boolean; + keys: { LEFT: number; UP: number; RIGHT: number; BOTTOM: number }; + mouseButtons: { LEFT: MOUSE; MIDDLE: MOUSE; RIGHT: MOUSE }; + enableDamping: boolean; + dampingFactor: number; + target0: Vector3; + position0: Vector3; + zoom0: number; + + rotateLeft(angle?: number): void; + + rotateUp(angle?: number): void; + + panLeft(distance?: number): void; + + panUp(distance?: number): void; + + pan(deltaX: number, deltaY: number): void; + + dollyIn(dollyScale: number): void; + + dollyOut(dollyScale: number): void; + + saveState(): void; + + update(): boolean; + + reset(): void; + + dispose(): void; + + getPolarAngle(): number; + + getAzimuthalAngle(): number; +} diff --git a/types/three/three-tdsloader.d.ts b/types/three/three-tdsloader.d.ts new file mode 100644 index 0000000000..c1911a7003 --- /dev/null +++ b/types/three/three-tdsloader.d.ts @@ -0,0 +1,195 @@ +// https://github.com/codetheorist/three-tds-loader/blob/master/src/index.js + +import * as THREE from "./index"; + +export class TDSLoader { + constructor(three: typeof THREE); + + /** + * Load 3ds file from url. + * + * @param url URL for the file. + * @param onLoad onLoad callback, receives group object3D as argument. + * @param onProgress onProgress callback. + * @param onError onError callback. + */ + load: (url: string, onLoad: (object3D: THREE.Object3D) => void, onProgress?: (progress: ProgressEvent) => void, onError?: (event: ErrorEvent) => void) => void; + + /** + * Parse arraybuffer data and load 3ds file. + * + * @param arraybuffer Arraybuffer data to be loaded. + * @param path Path for external resources. + * @return Group loaded from 3ds file. + */ + parse: (arraybuffer: ArrayBuffer, path: string) => THREE.Object3D; + + /** + * Decode file content to read 3ds data. + * + * @param arraybuffer Arraybuffer data to be loaded. + */ + readFile: (arraybuffer: ArrayBuffer, path: string) => void; + + /** + * Read mesh data chunk. + * + * @param data Dataview in use. + */ + readMeshData: (data: DataView, path: string) => void; + + /** + * Read named object chunk. + * + * @param data Dataview in use. + */ + readNamedobject: (data: DataView) => void; + + /** + * Read material data chunk and add it to the material list. + * + * @param data Dataview in use. + */ + readMaterialEntry: (data: DataView, path: string) => void; + + /** + * Read mesh data chunk. + * + * @param data Dataview in use. + */ + readMesh: (data: DataView) => void; + + /** + * Read face array data chunk. + * + * @param data Dataview in use. + * @param mesh Mesh to be filled with the data read. + */ + readFaceArray: (data: DataView, mesh: THREE.Mesh) => void; + + /** + * Read texture map data chunk. + * + * @param data Dataview in use. + * @return Texture read from this data chunk. + */ + readMap: (data: DataView, path: string) => THREE.Texture; + + /** + * Read material group data chunk. + * + * @param data Dataview in use. + * @return object with name and index of the object. + */ + readMaterialGroup: (data: DataView) => object; + + /** + * Read a color value. + * + * @param data Dataview. + * @return Color value read.. + */ + readColor: (data: DataView) => THREE.Color; + + /** + * Read next chunk of data. + * + * @param data Dataview. + * @return Chunk of data read. + */ + readChunk: (data: DataView) => object; + + /** + * Set position to the end of the current chunk of data. + * + * @param chunk Data chunk. + */ + endChunk: (chunk: object) => void; + + /** + * Move to the next data chunk. + * + * @param data Dataview. + * @param chunk Data chunk. + */ + nextChunk: (data: DataView, chunk: object) => number; + + /** + * Reset dataview position. + */ + resetPosition: () => void; + + /** + * Read byte value. + * + * @param data Dataview to read data from. + * @return Data read from the dataview. + */ + readByte: (data: DataView) => number; + + /** + * Read 32 bit float value. + * + * @param data Dataview to read data from. + * @return Data read from the dataview. + */ + readFloat: (data: DataView) => number; + + /** + * Read 32 bit signed integer value. + * + * @param data Dataview to read data from. + * @return Data read from the dataview. + */ + readInt: (data: DataView) => number; + + /** + * Read 16 bit signed integer value. + * + * @param data Dataview to read data from. + * @return Data read from the dataview. + */ + readShort: (data: DataView) => number; + + /** + * Read 64 bit unsigned integer value. + * + * @param data Dataview to read data from. + * @return Data read from the dataview. + */ + readDWord: (data: DataView) => number; + + /** + * Read 32 bit unsigned integer value. + * + * @param data Dataview to read data from. + * @return Data read from the dataview. + */ + readWord: (data: DataView) => number; + + /** + * Read string value. + * + * @param data Dataview to read data from. + * @param maxLength Max size of the string to be read. + * @return Data read from the dataview. + */ + readString: (data: DataView, maxLength: number) => string; + + /** + * Set resource path used to determine the file path to attached resources. + * + * @param path Path to resources. + * @return Self for chaining. + */ + setPath: (path: string) => TDSLoader; + + /** + * Print debug message to the console. + * + * Is controlled by a flag to show or hide debug messages. + * + * @param message Debug message to print to the console. + */ + debugMessage: (message: string) => void; +} \ No newline at end of file diff --git a/types/three/tsconfig.json b/types/three/tsconfig.json index a7a79e68f5..814dd8f824 100644 --- a/types/three/tsconfig.json +++ b/types/three/tsconfig.json @@ -57,6 +57,7 @@ "test/examples/ctm/ctmloader.ts", "test/examples/octree.ts", "test/examples/loaders/webgl_loader_obj_mtl.ts", + "test/examples/loaders/tdsloader.ts", "test/examples/exporters/gltf-exporter.ts", "test/webvr/webvr.ts" ] diff --git a/types/tildify/index.d.ts b/types/tildify/index.d.ts new file mode 100644 index 0000000000..a0dd100bf9 --- /dev/null +++ b/types/tildify/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for tildify 1.2 +// Project: https://github.com/sindresorhus/tildify#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = tildify; + +declare function tildify(str: string): string; diff --git a/types/tildify/tildify-tests.ts b/types/tildify/tildify-tests.ts new file mode 100644 index 0000000000..109f5f6c6e --- /dev/null +++ b/types/tildify/tildify-tests.ts @@ -0,0 +1,4 @@ +import tildify = require('tildify'); + +// $ExpectType string +tildify('/Users/sindresorhus/dev'); diff --git a/types/tildify/tsconfig.json b/types/tildify/tsconfig.json new file mode 100644 index 0000000000..4375409ba0 --- /dev/null +++ b/types/tildify/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "tildify-tests.ts" + ] +} diff --git a/types/tildify/tslint.json b/types/tildify/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/tildify/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/toastr/tslint.json b/types/toastr/tslint.json index a41bf5d19a..67293bd146 100644 --- a/types/toastr/tslint.json +++ b/types/toastr/tslint.json @@ -74,6 +74,7 @@ "typedef-whitespace": false, "unified-signatures": false, "void-return": false, - "whitespace": false + "whitespace": false, + "no-angle-bracket-type-assertion": false } } diff --git a/types/toobusy-js/index.d.ts b/types/toobusy-js/index.d.ts index 2d7f2688a7..2e6aca6c4b 100644 --- a/types/toobusy-js/index.d.ts +++ b/types/toobusy-js/index.d.ts @@ -1,19 +1,66 @@ // Type definitions for toobusy-js 0.5 // Project: https://github.com/STRML/node-toobusy // Definitions by: Arne Schubert +// BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export = toobusy_js; +/** + * Main export function. + * @return True if node process is too busy. + */ declare function toobusy_js(): boolean; declare namespace toobusy_js { - function interval(newInterval: number): number; + /** + * Sets or gets the current check interval. + * If you want more sensitive checking, set a faster (lower) interval. A lower maxLag can also create a more + * sensitive check. + * @param [newInterval] New interval to set. If not provided, will return the existing interval. + * @return New or existing interval. + */ + function interval(newInterval?: number): number; + /** + * Returns last lag reading from last check interval. + * @return Lag in ms. + */ function lag(): number; - function maxLag(newLag: number): number; - function smoothingFactor(newFactor: number): number; + /** + * Set or get the current max latency threshold. Default is 70ms. + * + * Note that if event loop lag goes over this threshold, the process is not always 'too busy' - the farther + * it goes over the threshold, the more likely the process will be considered too busy. + * + * The percentage is equal to the percent over the max lag threshold. So 1.25x over the maxLag will indicate + * too busy 25% of the time. 2x over the maxLag threshold will indicate too busy 100% of the time. + * @param [newLag] New maxLag (highwater) threshold. + * @return New or existing maxLag (highwater) threshold. + */ + function maxLag(newLag?: number): number; + /** + * Set or get the smoothing factor. Default is 0.3333.... + * + * The smoothing factor per the standard exponential smoothing formula "αtn + (1-α)tn-1" + * See: https://en.wikipedia.org/wiki/Exponential_smoothing + * + * @param [newFactor] New smoothing factor. + * @return New or existing smoothing factor. + */ + function smoothingFactor(newFactor?: number): number; + /** + * Shuts down toobusy. + * + * Not necessary to call this manually, only do this if you know what you're doing. `unref()` is called + * on toobusy's check interval, so it will never keep the server open. + */ function shutdown(): void; + /** + * Registers an event listener for lag events, + * optionally specify a minimum value threshold for events being emitted + * @param fn Function of form onLag(value: number) => void + * @param [threshold=maxLag] Optional minimum lag value for events to be emitted + */ function onLag(fn: (lag: number) => void, threshold?: number): void; - function started(): boolean; } diff --git a/types/toobusy-js/toobusy-js-tests.ts b/types/toobusy-js/toobusy-js-tests.ts index 121b84ddb4..2678dcc777 100644 --- a/types/toobusy-js/toobusy-js-tests.ts +++ b/types/toobusy-js/toobusy-js-tests.ts @@ -1,4 +1,4 @@ -import toobusy = require("toobusy-js"); +import toobusy = require('toobusy-js'); let numberValue = 1; let booleanValue = true; @@ -7,11 +7,19 @@ booleanValue = toobusy(); booleanValue = toobusy.started(); numberValue = toobusy.interval(numberValue); +numberValue = toobusy.interval(); numberValue = toobusy.lag(); numberValue = toobusy.maxLag(numberValue); +numberValue = toobusy.maxLag(); numberValue = toobusy.smoothingFactor(numberValue); - -toobusy.onLag((duration: number) => {}); -toobusy.onLag((duration: number) => {}, numberValue); - +numberValue = toobusy.smoothingFactor(); toobusy.shutdown(); + +toobusy.onLag(duration => { + // $ExpectType number + duration; +}); +toobusy.onLag(duration => { + // $ExpectType number + duration; +}, numberValue); diff --git a/types/underscore.string/index.d.ts b/types/underscore.string/index.d.ts index 2d067679d5..eb0774b49a 100644 --- a/types/underscore.string/index.d.ts +++ b/types/underscore.string/index.d.ts @@ -207,7 +207,7 @@ declare module 'underscore' { * ('-moz-transform') => 'MozTransform' * @param str */ - camelize(str: string): string; + camelize(str: string, decapitalize?: boolean): string; /** * Converts a camelized or dasherized string into an underscored one. diff --git a/types/underscore.string/underscore.string-tests.ts b/types/underscore.string/underscore.string-tests.ts index 545f6362d6..5b827cd880 100644 --- a/types/underscore.string/underscore.string-tests.ts +++ b/types/underscore.string/underscore.string-tests.ts @@ -52,6 +52,7 @@ _.succ('A'); _.titleize('my name is epeli'); _.camelize('-moz-transform'); +_.camelize('-moz-transform', true); _.classify('some_class_name'); diff --git a/types/unique-random-array/index.d.ts b/types/unique-random-array/index.d.ts new file mode 100644 index 0000000000..7e4ddacb0f --- /dev/null +++ b/types/unique-random-array/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for unique-random-array 1.0 +// Project: https://github.com/sindresorhus/unique-random-array#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = uniqueRandomArray; + +declare function uniqueRandomArray(input: T[]): () => T; diff --git a/types/unique-random-array/tsconfig.json b/types/unique-random-array/tsconfig.json new file mode 100644 index 0000000000..40257f7e47 --- /dev/null +++ b/types/unique-random-array/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "unique-random-array-tests.ts" + ] +} diff --git a/types/unique-random-array/tslint.json b/types/unique-random-array/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/unique-random-array/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/unique-random-array/unique-random-array-tests.ts b/types/unique-random-array/unique-random-array-tests.ts new file mode 100644 index 0000000000..de4563532c --- /dev/null +++ b/types/unique-random-array/unique-random-array-tests.ts @@ -0,0 +1,6 @@ +import uniqueRandomArray = require('unique-random-array'); + +// $ExpectType () => number +uniqueRandomArray([1, 2, 3, 4]); +// $ExpectType () => string | number +uniqueRandomArray(["1", 2, 3, 4]); diff --git a/types/unist-util-is/index.d.ts b/types/unist-util-is/index.d.ts new file mode 100644 index 0000000000..82e6e1fdc8 --- /dev/null +++ b/types/unist-util-is/index.d.ts @@ -0,0 +1,36 @@ +// Type definitions for unist-util-is 2.1 +// Project: https://github.com/syntax-tree/unist-util-is#readme +// Definitions by: Junyoung Choi +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 3.0 + +/// + +import * as Unist from 'unist'; + +declare namespace unistUtilIs { + /** + * @param node Node to test + * @param index Position of node in parent + * @param parent Parent of node + */ + type TestFunction = (node: unknown, index?: number, parent?: Unist.Parent) => boolean | void; + type Test = TestFunction | Partial | string | null; +} + +/** + * Unist utility to check if a node passes a test. + * + * @param test When not given, checks if `node` is a `Node`. + * When `string`, works like passing `function (node) {return node.type === test}`. + * When `array`, checks any one of the subtests pass. + * When `object`, checks that all keys in test are in node, and that they have (strictly) equal values + * @param node Node to check. `false` is returned + * @param index Position of `node` in `parent` + * @param parent Parent of `node` + * @param context Context object to invoke `test` with + * @returns Whether test passed and `node` is a `Node` (object with `type` set to non-empty `string`). + */ +declare function unistUtilIs(test: unistUtilIs.Test | unistUtilIs.Test[], node: unknown, index?: number, parent?: Unist.Parent, context?: any): boolean; + +export = unistUtilIs; diff --git a/types/unist-util-is/tsconfig.json b/types/unist-util-is/tsconfig.json new file mode 100644 index 0000000000..dbe499fef0 --- /dev/null +++ b/types/unist-util-is/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "unist-util-is-tests.ts" + ] +} diff --git a/types/unist-util-is/tslint.json b/types/unist-util-is/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/unist-util-is/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/unist-util-is/unist-util-is-tests.ts b/types/unist-util-is/unist-util-is-tests.ts new file mode 100644 index 0000000000..9f3eecc680 --- /dev/null +++ b/types/unist-util-is/unist-util-is-tests.ts @@ -0,0 +1,26 @@ +import is = require('unist-util-is'); + +const node = {type: 'strong'}; +const parent = {type: 'paragraph', children: [node]}; + +function test(node: unknown, n?: number) { + return n === 5; +} + +is(null, {children: []}); +is(null, node); +is('strong', node); +is('emphasis', node); + +is(node, node); +is({type: 'paragraph'}, parent); +is({type: 'strong'}, parent); + +is(test, node); +is(test, node, 4, parent); +is(test, node, 5, parent); + +function testFunc(node: unknown) {} +is(testFunc, node); + +const wrongTestFunc: is.TestFunction = (node: unknown, n: string) => {}; // $ExpectError diff --git a/types/unist/index.d.ts b/types/unist/index.d.ts index 7433ddcc13..2d7d37e17f 100644 --- a/types/unist/index.d.ts +++ b/types/unist/index.d.ts @@ -2,39 +2,97 @@ // Project: https://github.com/syntax-tree/unist // Definitions by: bizen241 // Jun Lu +// Hernan Rajchert +// Titus Wormer +// Junyoung Choi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.4 +// TypeScript Version: 3.0 +/** + * Syntactic units in unist syntax trees are called nodes. + */ export interface Node { + /** + * The variant of a node. + */ type: string; + + /** + * Information from the ecosystem. + */ data?: Data; + + /** + * Location of a node in a source document. + * Must not be present if a node is generated. + */ position?: Position; + + [key: string]: unknown; } +/** + * Information associated by the ecosystem with the node. + * Space is guaranteed to never be specified by unist or specifications + * implementing unist. + */ export interface Data { - [key: string]: any; + [key: string]: unknown; } +/** + * Location of a node in a source file. + */ export interface Position { + /** + * Place of the first character of the parsed source region. + */ start: Point; + + /** + * Place of the first character after the parsed source region. + */ end: Point; - /** >= 1 */ + + /** + * Start column at each index (plus start line) in the source region, + * for elements that span multiple lines. + */ indent?: number[]; } +/** + * One place in a source file. + */ export interface Point { - /** >= 1 */ + /** + * Line in a source file (1-indexed integer). + */ line: number; - /** >= 1 */ + + /** + * Column in a source file (1-indexed integer). + */ column: number; - /** >= 0 */ + /** + * Character in a source file (0-indexed integer). + */ offset?: number; } +/** + * Nodes containing other nodes. + */ export interface Parent extends Node { + /** + * List representing the children of a node. + */ children: Node[]; } +/** + * Nodes containing a value. + */ export interface Literal extends Node { - value: any; + value: unknown; } diff --git a/types/unist/unist-tests.ts b/types/unist/unist-tests.ts index 3cb69bcc76..1c27db2a58 100644 --- a/types/unist/unist-tests.ts +++ b/types/unist/unist-tests.ts @@ -1,6 +1,6 @@ -import * as Unist from 'unist'; +import { Data, Point, Position, Node, Literal, Parent } from 'unist'; -const data: Unist.Data = { +const data: Data = { string: 'string', number: 1, object: { @@ -11,32 +11,32 @@ const data: Unist.Data = { null: null }; -const point: Unist.Point = { +const point: Point = { line: 1, column: 1, offset: 0 }; -const position: Unist.Position = { +const position: Position = { start: point, end: point, indent: [1] }; -const node: Unist.Node = { +const node: Node = { type: 'node', data, position }; -const text: Unist.Literal = { +const text: Literal = { type: 'text', data, position, value: 'value' }; -const parent: Unist.Parent = { +const parent: Parent = { type: 'parent', data, position, diff --git a/types/universal-router/index.d.ts b/types/universal-router/index.d.ts index eb698fc8bf..8dd2357f03 100644 --- a/types/universal-router/index.d.ts +++ b/types/universal-router/index.d.ts @@ -1,8 +1,9 @@ -// Type definitions for universal-router 6.0 +// Type definitions for universal-router 7.0 // Project: https://github.com/kriasoft/universal-router // Definitions by: Jack Moore // Tomek Łaziuk // Lodin +// acidghost // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -101,7 +102,7 @@ export interface Options { context?: C; baseUrl?: string; resolveRoute?: (context: ActionContext & C, params: Params) => any; - errorHandler?: (error: Error & { context: C, code: number }) => any; + errorHandler?: (error: Error & { status: number }, context: C) => any; } /** diff --git a/types/universal-router/universal-router-tests.ts b/types/universal-router/universal-router-tests.ts index 02c79fb062..40b5ac32c1 100644 --- a/types/universal-router/universal-router-tests.ts +++ b/types/universal-router/universal-router-tests.ts @@ -12,10 +12,10 @@ new UniversalRouter( user: 'name', }, baseUrl: '/base', - errorHandler: (error) => { + errorHandler: (error, context) => { console.error(error); - console.dir(error.context); - return error.code === 404 + console.dir(context); + return error.status === 404 ? '

    Page Not Found

    ' : '

    Oops! Something went wrong

    '; }, diff --git a/types/url-assembler/index.d.ts b/types/url-assembler/index.d.ts index 3f33bf921a..e27fbbe58d 100644 --- a/types/url-assembler/index.d.ts +++ b/types/url-assembler/index.d.ts @@ -7,8 +7,8 @@ interface UrlAssembler { template(template: string): UrlAssembler; prefix(subPath: string): UrlAssembler; segment(subPathTemplate: string): UrlAssembler; - param(key: string, value: string, strict: boolean): UrlAssembler; - param(params: {[s: string]: any}, strict: boolean): UrlAssembler; + param(key: string, value: string, strict?: boolean): UrlAssembler; + param(params: {[s: string]: any}, strict?: boolean): UrlAssembler; query(key: string, value: any): UrlAssembler; query(params: {[s: string]: any}): UrlAssembler; toString(): string; diff --git a/types/v8flags/index.d.ts b/types/v8flags/index.d.ts new file mode 100644 index 0000000000..409b51d60b --- /dev/null +++ b/types/v8flags/index.d.ts @@ -0,0 +1,13 @@ +// Type definitions for v8flags 3.1 +// Project: https://github.com/tkellen/node-v8flags +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = v8flags; + +declare function v8flags(cb: (err: any, flags: string[]) => void): void; + +declare namespace v8flags { + const configfile: string; + const configPath: string; +} diff --git a/types/v8flags/tsconfig.json b/types/v8flags/tsconfig.json new file mode 100644 index 0000000000..e0673d15d0 --- /dev/null +++ b/types/v8flags/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "v8flags-tests.ts" + ] +} diff --git a/types/v8flags/tslint.json b/types/v8flags/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/v8flags/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/v8flags/v8flags-tests.ts b/types/v8flags/v8flags-tests.ts new file mode 100644 index 0000000000..cc95ac734d --- /dev/null +++ b/types/v8flags/v8flags-tests.ts @@ -0,0 +1,6 @@ +import v8flags = require('v8flags'); + +v8flags((err, results) => { + // $ExpectType string[] + results; +}); diff --git a/types/validator/index.d.ts b/types/validator/index.d.ts index 1b51669d14..8ee398d850 100644 --- a/types/validator/index.d.ts +++ b/types/validator/index.d.ts @@ -83,7 +83,7 @@ declare namespace ValidatorJS { isEmail(str: string, options?: IsEmailOptions): boolean; // check if the string has a length of zero. - isEmpty(str: string): boolean; + isEmpty(str: string, options?: IsEmptyOptions): boolean; // check if the string is a fully qualified domain name (e.g. domain.com). isFQDN(str: string, options?: IsFQDNOptions): boolean; @@ -310,6 +310,11 @@ declare namespace ValidatorJS { require_tld?: boolean; } + // options for isEmpty + interface IsEmptyOptions { + ignore_whitespace?: boolean; + } + // options for isFQDN interface IsFQDNOptions { require_tld?: boolean; diff --git a/types/validator/validator-tests.ts b/types/validator/validator-tests.ts index 61c1c59e92..09a9a7ba17 100644 --- a/types/validator/validator-tests.ts +++ b/types/validator/validator-tests.ts @@ -425,7 +425,9 @@ let any: any; result = validator.isEmail('sample'); result = validator.isEmail('sample', isEmailOptions); + let isEmptyOptions: ValidatorJS.IsEmptyOptions = {}; result = validator.isEmpty('sample'); + result = validator.isEmpty('sample', isEmptyOptions); let isFQDNOptions: ValidatorJS.IsFQDNOptions = {}; result = validator.isFQDN('sample'); diff --git a/types/vfile-message/index.d.ts b/types/vfile-message/index.d.ts new file mode 100644 index 0000000000..5f4467e007 --- /dev/null +++ b/types/vfile-message/index.d.ts @@ -0,0 +1,75 @@ +// Type definitions for vfile-message 1.0 +// Project: https://github.com/vfile/vfile-message#readme +// Definitions by: Junyoung Choi +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 3.0 + +/// + +import * as Unist from 'unist'; + +declare namespace vfileMessage { + /** + * Create a virtual message. + */ + interface VFileMessage extends Error { + /** + * Constructor of a message for `reason` at `position` from `origin`. + * When an error is passed in as `reason`, copies the `stack`. + * + * @param reason Reason for message (`string` or `Error`). Uses the stack and message of the error if given. + * @param position Place at which the message occurred in a file (`Node`, `Position`, or `Point`, optional). + * @param origin Place in code the message originates from (`string`, optional). + */ + (reason: string | Error, position?: Unist.Node | Unist.Position | Unist.Point, origin?: string): VFileMessage; + /** + * Category of message. + */ + ruleId: string | null; + /** + * Reason for message. + */ + reason: string; + /** + * Starting line of error. + */ + line: number | null; + /** + * Starting column of error. + */ + column: number | null; + /** + * Full range information, when available. + * Has start and end properties, both set to an object with line and column, set to number?. + */ + location: Unist.Position; + /** + * Namespace of warning. + */ + source: string | null; + /** + * If true, marks associated file as no longer processable. + */ + fatal?: boolean | null; + /** + * You may add a file property with a path of a file (used throughout the VFile ecosystem). + */ + file?: string; + /** + * You may add a note property with a long form description of the message (supported by vfile-reporter). + */ + note?: string; + /** + * You may add a url property with a link to documentation for the message. + */ + url?: string; + /** + * It’s OK to store custom data directly on the VMessage, some of those are handled by utilities. + */ + [key: string]: unknown; + } +} + +declare const vfileMessage: vfileMessage.VFileMessage; + +export = vfileMessage; diff --git a/types/vfile-message/tsconfig.json b/types/vfile-message/tsconfig.json new file mode 100644 index 0000000000..9e35438c08 --- /dev/null +++ b/types/vfile-message/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "vfile-message-tests.ts" + ] +} diff --git a/types/vfile-message/tslint.json b/types/vfile-message/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/vfile-message/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/vfile-message/vfile-message-tests.ts b/types/vfile-message/vfile-message-tests.ts new file mode 100644 index 0000000000..ed9086631f --- /dev/null +++ b/types/vfile-message/vfile-message-tests.ts @@ -0,0 +1,32 @@ +import vfileMessage = require('vfile-message'); + +const message = vfileMessage('Error!'); +vfileMessage(new Error()); +vfileMessage('Error!', { + type: 'random node' +}); +vfileMessage('Error!', { + start: { + line: 1, + column: 1 + }, + end: { + line: 1, + column: 1 + } +}); +vfileMessage('Error!', { + line: 1, + column: 1 +}); +vfileMessage('Error!', undefined, 'test'); + +message.file = ''; +message.name = ''; +message.reason = ''; +message.message = ''; +message.stack = ''; +message.fatal = null; +message.fatal = true; +message.column = 1; +message.line = 1; diff --git a/types/vfile/index.d.ts b/types/vfile/index.d.ts index df729e0a49..aec7ca88f9 100644 --- a/types/vfile/index.d.ts +++ b/types/vfile/index.d.ts @@ -8,15 +8,11 @@ /// import * as Unist from 'unist'; +import * as vfileMessage from 'vfile-message'; declare namespace vfile { type VFileContents = string | Buffer; - interface NodeWithPosition extends Unist.Node { - position: Unist.Position; - [key: string]: any; - } - interface VFileOptions { contents?: VFileContents; path?: string; @@ -29,86 +25,18 @@ declare namespace vfile { [key: string]: any; } - /** - * File-related message describing something at certain position. - */ - interface VFileMessage { - /** - * File-path, when the message was triggered. - */ - file: string; - /** - * Category of message. - */ - ruleId: string | null; - /** - * Reason for message. - */ - reason: string; - /** - * Starting line of error. - */ - line: number | null; - /** - * Starting column of error. - */ - column: number | null; - /** - * Full range information, when available. - * Has start and end properties, both set to an object with line and column, set to number?. - */ - location: Unist.Position; - /** - * Namespace of warning. - */ - source: string | null; - /** - * If true, marks associated file as no longer processable. - */ - fatal?: boolean | null; - } - - /** - * Associates a message with the file for `reason` at `position`. - * When an error is passed in as `reason`, copies the stack. - * Each message has a `fatal` property which by default is set to `false` (ie. `warning`). - * @param reason Reason for message. Uses the stack and message of the error if given. - * @param position Place at which the message occurred in `vfile`. - * @param ruleId Category of message. - */ - type Message = (reason: string, position?: Unist.Point | Unist.Position | NodeWithPosition, ruleId?: string) => VFileMessage; - /** - * Associates a fatal message with the file, then immediately throws it. - * Note: fatal errors mean a file is no longer processable. - * Calls `message()` internally. - * @param reason Reason for message. Uses the stack and message of the error if given. - * @param position Place at which the message occurred in `vfile`. - * @param ruleId Category of message. - */ - type Fail = (reason: string, position?: Unist.Point | Unist.Position | NodeWithPosition, ruleId?: string) => never; - /** - * Associates an informational message with the file, where `fatal` is set to `null`. - * Calls `message()` internally. - * @param reason Reason for message. Uses the stack and message of the error if given. - * @param position Place at which the message occurred in `vfile`. - * @param ruleId Category of message. - */ - type Info = (reason: string, position?: Unist.Point | Unist.Position | NodeWithPosition, ruleId?: string) => void; - - /** - * Convert contents of `vfile` to string. - * @param encoding If `contents` is a buffer, `encoding` is used to stringify buffers (default: `'utf8'`). - */ - type ToString = (encoding?: BufferEncoding) => string; - interface VFile { /** + * Create a new virtual file. If `options` is `string` or `Buffer`, treats it as `{contents: options}`. + * If `options` is a `VFile`, returns it. All other options are set on the newly created `vfile`. + * + * Path related properties are set in the following order (least specific to most specific): `history`, `path`, `basename`, `stem`, `extname`, `dirname`. + * + * It’s not possible to set either `dirname` or `extname` without setting either `history`, `path`, `basename`, or `stem` as well. + * * @param options If `options` is `string` or `Buffer`, treats it as `{contents: options}`. If `options` is a `VFile`, returns it. All other options are set on the newly created `vfile`. */ (input?: VFileContents | F | VFileOptions): F; - message: Message; - fail: Fail; - info: Info; /** * List of file-paths the file moved between. */ @@ -121,7 +49,7 @@ declare namespace vfile { /** * List of messages associated with the file. */ - messages: VFileMessage[]; + messages: vfileMessage.VFileMessage[]; /** * Raw value. */ @@ -157,15 +85,40 @@ declare namespace vfile { * Defaults to `process.cwd()`. */ cwd: string; - toString: ToString; + /** + * Convert contents of `vfile` to string. + * @param encoding If `contents` is a buffer, `encoding` is used to stringify buffers (default: `'utf8'`). + */ + toString: (encoding?: BufferEncoding) => string; + /** + * Associates a message with the file for `reason` at `position`. + * When an error is passed in as `reason`, copies the stack. + * Each message has a `fatal` property which by default is set to `false` (ie. `warning`). + * @param reason Reason for message. Uses the stack and message of the error if given. + * @param position Place at which the message occurred in `vfile`. + * @param ruleId Category of message. + */ + message: (reason: string, position?: Unist.Point | Unist.Position | Unist.Node, ruleId?: string) => vfileMessage.VFileMessage; + /** + * Associates a fatal message with the file, then immediately throws it. + * Note: fatal errors mean a file is no longer processable. + * Calls `message()` internally. + * @param reason Reason for message. Uses the stack and message of the error if given. + * @param position Place at which the message occurred in `vfile`. + * @param ruleId Category of message. + */ + fail: (reason: string, position?: Unist.Point | Unist.Position | Unist.Node, ruleId?: string) => never; + /** + * Associates an informational message with the file, where `fatal` is set to `null`. + * Calls `message()` internally. + * @param reason Reason for message. Uses the stack and message of the error if given. + * @param position Place at which the message occurred in `vfile`. + * @param ruleId Category of message. + */ + info: (reason: string, position?: Unist.Point | Unist.Position | Unist.Node, ruleId?: string) => vfileMessage.VFileMessage; } } -/** - * Create a new virtual file. - * Path related properties are set in the following order (least specific to most specific): `history`, `path`, `basename`, `stem`, `extname`, `dirname`. - * It’s not possible to set either `dirname` or `extname` without setting either `history`, `path`, `basename`, or `stem` as well. - */ declare const vfile: vfile.VFile; export = vfile; diff --git a/types/vfile/vfile-tests.ts b/types/vfile/vfile-tests.ts index 5c14c8502b..b89df6db23 100644 --- a/types/vfile/vfile-tests.ts +++ b/types/vfile/vfile-tests.ts @@ -1,5 +1,6 @@ import vfile = require('vfile'); import * as Unist from 'unist'; +import vfileMessage = require('vfile-message'); // Instantiation const file: vfile.VFile = vfile(); @@ -15,24 +16,7 @@ file.dirname = '~'; file.extname = '.md'; file.basename = 'test.text'; file.history = ['~/test.txt']; // => ['~/example.txt', '~/example.md', '~/index.text'] -file.messages = [{ - file: '~/test.txt', - ruleId: '', - reason: '', - line: 1, - column: 1, - location: { - start: { - line: 1, - column: 1, - }, - end: { - line: 1, - column: 1, - } - }, - source: '' -}]; +file.messages = [vfileMessage('random error')]; const startPoint: Unist.Point = { line: 1, @@ -46,7 +30,7 @@ const position: Unist.Position = { }, }; -file.message('test', startPoint); +const message: vfileMessage.VFileMessage = file.message('test', startPoint, 'test origin'); file.message('test', position); file.message('test', { type: 'ramdom node', @@ -56,6 +40,10 @@ file.message('test', { file.message('test', { start: 'invalid point' }); // $ExpectError +file.fail('test'); + +const infoMessage: vfileMessage.VFileMessage = file.info('test'); + // Using `data` prop interface CustomData { message: string; diff --git a/types/victory/index.d.ts b/types/victory/index.d.ts index 5670547317..d002a3d695 100644 --- a/types/victory/index.d.ts +++ b/types/victory/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Victory 0.9.3 +// Type definitions for Victory 31.0 // Project: https://github.com/FormidableLabs/victory // Definitions by: Alexey Svetliakov // snerks @@ -269,16 +269,16 @@ declare module "victory" { */ cursorLabel?: (point: CursorData) => void; /** - * The cursorLabelComponent prop takes a component instance which will be - * used to render a label for the cursor. The new element created from the passed + * The cursorLabelComponent prop takes a component instance which will be + * used to render a label for the cursor. The new element created from the passed * cursorLabelComponent will be supplied with the following props: x, y, * active, text. If cursorLabelComponent is omitted, a new VictoryLabel will be created with the props described above. * @default cursorLabelComponent={} */ cursorLabelComponent?: React.ReactElement; /** - * The cursorLabelOffset prop determines the pixel offset of the cursor label - * from the cursor point. This prop should be an Object with x and y properties, or a + * The cursorLabelOffset prop determines the pixel offset of the cursor label + * from the cursor point. This prop should be an Object with x and y properties, or a * number to be used for both dimensions. * @default "{ x: 5, y: -10 }" */ @@ -315,45 +315,45 @@ declare module "victory" { */ allowDrag?: boolean; /** - * The optional allowResize prop accepts a boolean that enables resizing the + * The optional allowResize prop accepts a boolean that enables resizing the * highlighted brush area. Dragging will still be enabled when the allowResize * prop is set to false, but the dimensions of the brush area will be fixed. * @default true */ allowResize?: boolean; /** - * The brushComponent prop specifies the component to be rendered for the - * highlighted area. This component will be supplied with the following props: x, y, + * The brushComponent prop specifies the component to be rendered for the + * highlighted area. This component will be supplied with the following props: x, y, * width, height, and style. When this prop is not specified, a will be rendered. * @default brushComponent={} */ brushComponent?: React.ReactElement; /** - * When the brushDimension prop is set, brushing will only be specific to the to - * the given dimension (either "x" or "y"), and the entire domain of the other + * When the brushDimension prop is set, brushing will only be specific to the to + * the given dimension (either "x" or "y"), and the entire domain of the other * dimension will be highlighted. When this prop is not specified, highlighting will * occur along both dimensions. * @example brushDimension="x" */ brushDimension?: 'x' | 'y'; /** - * The optional brushDomain prop describes the highlighted state. This prop is an - * object that specifies separate arrays for x and y. Each array is a tuple that - * describes the minimum and maximum values to render. If this prop is not provided - * initially, the chart will render with the entire domain highlighted. When this prop + * The optional brushDomain prop describes the highlighted state. This prop is an + * object that specifies separate arrays for x and y. Each array is a tuple that + * describes the minimum and maximum values to render. If this prop is not provided + * initially, the chart will render with the entire domain highlighted. When this prop * changes, the chart will render with a new highlighted domain. * @example brushDomain={{ x: [50, 100], y: [0, 100] }} */ brushDomain?: DomainPropType; /** - * The brushStyle adds custom styles to the brushComponent. This prop + * The brushStyle adds custom styles to the brushComponent. This prop * should be given as an object of SVG style attributes. * @default "brushStyle={{ stroke: "transparent", fill: "black", fillOpacity: 0.1 }}" */ brushStyle?: React.CSSProperties; /** - * The defaultBrushArea prop specifies how the container will behave when a - * region outside the active brush is clicked without selecting a new area. When the + * The defaultBrushArea prop specifies how the container will behave when a + * region outside the active brush is clicked without selecting a new area. When the * prop is set to "all", the entire domain will be selected. When the prop is set to "none", * no new region will be selected, and any existing active brush will be cleared. When * the prop is set to "disable" the new selected region will default to the current active brush. @@ -364,8 +364,8 @@ declare module "victory" { */ disable?: boolean; /** - * The handleComponent prop specifies the component to be rendered for each - * handle for the highlighted area. This component will be supplied with the following + * The handleComponent prop specifies the component to be rendered for each + * handle for the highlighted area. This component will be supplied with the following * props: x, y, width, height, cursor, and style. When this prop is not * specified, a will be rendered. * @default handleComponent={} @@ -373,7 +373,7 @@ declare module "victory" { handleComponent?: React.ReactElement; /** * The handleStyle adds custom styles to the handleComponents. This prop should be given as an object of SVG style attributes. - * + * * Handles refer to the region on each highlighted area where the area may be * expanded. Only handles relevant to the given dimension will be rendered. For * example, when brushDimension="x" only "left" and "right" handles will be @@ -382,8 +382,8 @@ declare module "victory" { */ handleStyle?: React.CSSProperties; /** - * The optional onBrushDomainChange prop accepts an function to be called on - * each update to the highlighted domain. The function accepts the parameters of + * The optional onBrushDomainChange prop accepts an function to be called on + * each update to the highlighted domain. The function accepts the parameters of * domain (the updated domain), and props (the props used by VictoryBrushContainer). * @example onBrushDomainChange={(domain, props) => handleDomainChange(domain, props)} */ @@ -394,7 +394,7 @@ declare module "victory" { export interface VictoryZoomContainerProps extends VictoryContainerProps { /** - * The optional allowPan prop accepts a boolean that enables the panning + * The optional allowPan prop accepts a boolean that enables the panning * functionality. Zooming will still be enabled when the allowPan prop is set to false. * @default true */ @@ -406,7 +406,7 @@ declare module "victory" { */ allowZoom?: boolean; /** - * VictoryZoomContainer works by clipping data outside of a given domain. + * VictoryZoomContainer works by clipping data outside of a given domain. * VictoryZoomContainer uses VictoryClipContainer by default. * This prop should not be replaced with a custom component, but you may want to set * props on VictoryClipContainer, such as clipPadding. @@ -414,30 +414,30 @@ declare module "victory" { */ clipContainerComponent?: React.ReactElement; /** - * When the zoomDimension prop is set, panning and zooming will be restricted to - * the given dimension (either x or y), and the domain of the other dimension will + * When the zoomDimension prop is set, panning and zooming will be restricted to + * the given dimension (either x or y), and the domain of the other dimension will * remain static. When this prop is not specified, both x and y dimensions will pan and zoom. * @example zoomDimension="x" */ zoomDimension?: 'x' | 'y'; /** - * The zoomDomain prop describes the zoomed state. This prop is an object that - * specifies separate arrays for x and y. Each array is a tuple that describes the - * minimum and maximum values to render. If this prop is not provided initially, the - * chart will render without an initial zoom, displaying the entire dataset. Updates to + * The zoomDomain prop describes the zoomed state. This prop is an object that + * specifies separate arrays for x and y. Each array is a tuple that describes the + * minimum and maximum values to render. If this prop is not provided initially, the + * chart will render without an initial zoom, displaying the entire dataset. Updates to * zoomDomain will trigger a re-render of the chart with the new domain. * @example zoomDomain={{x: [0, 100]}} */ zoomDomain?: DomainPropType; /** - * The brushStyle adds custom styles to the brushComponent. This prop + * The brushStyle adds custom styles to the brushComponent. This prop * should be given as an object of SVG style attributes. * @default "brushStyle={{ stroke: 'transparent', fill: 'black', fillOpacity: 0.1 }}" */ brushStyle?: React.CSSProperties; /** - * The defaultBrushArea prop specifies how the container will behave when a - * region outside the active brush is clicked without selecting a new area. When the + * The defaultBrushArea prop specifies how the container will behave when a + * region outside the active brush is clicked without selecting a new area. When the * prop is set to "all", the entire domain will be selected. When the prop is set to "none", * no new region will be selected, and any existing active brush will be cleared. When * the prop is set to "disable" the new selected region will default to the current active brush. @@ -452,10 +452,10 @@ declare module "victory" { */ downsample?: number | boolean; /** - * The minimumZoom prop sets a minimum domain extent for the zoomed chart. + * The minimumZoom prop sets a minimum domain extent for the zoomed chart. * When the difference between the maximum and minimum of a zoomed domain is equal to the minimumZoom * in either dimension, the component will stop responding to events that would normally trigger zooming in. - * Zooming out and panning will still be enabled. When this prop is not specified, the default minimum + * Zooming out and panning will still be enabled. When this prop is not specified, the default minimum * zoom will cover 1 / 1000th of the original domain. This prop should be given as an object * with numeric values for x and y. * @example minimumZoom={{x: 1, y: 0.01}} @@ -650,10 +650,10 @@ declare module "victory" { */ y?: number; } - - + + /** - * VictoryTooltip renders a tooltip component with a set of default events. When VictoryTooltip is used as a label component for any Victory component that renders data, it will attach events to rendered data components that will activate the tooltip when hovered. + * VictoryTooltip renders a tooltip component with a set of default events. When VictoryTooltip is used as a label component for any Victory component that renders data, it will attach events to rendered data components that will activate the tooltip when hovered. * VictoryTooltip renders text as well as a configurable Flyout container. */ export class VictoryTooltip extends React.Component< @@ -1317,6 +1317,21 @@ declare module "victory" { * @example {data: {fill: "red", width: 8}, labels: {fontSize: 12}} */ style?: VictoryStyleInterface; + /** + * The barRatio prop specifies an approximate ratio between bar widths and spaces between bars. + * When width is not specified via the barWidth prop or in bar styles, the barRatio prop will + * be used to calculate a default width for each bar given the total number of bars in the data series + * and the overall width of the chart. + */ + barRatio?: number; + /** + * The barWidth prop is used to specify the width of each bar. This prop may be given as + * a number of pixels or as a function that returns a number. When this prop is given as + * a function, it will be evaluated with the arguments datum, and active. When this value + * is not given, a default value will be calculated based on the overall dimensions of + * the chart, and the number of bars. + */ + barWidth?: NumberOrCallback; } /** diff --git a/types/victory/tslint.json b/types/victory/tslint.json index a41bf5d19a..a0357daa61 100644 --- a/types/victory/tslint.json +++ b/types/victory/tslint.json @@ -7,7 +7,6 @@ "ban-types": false, "callable-types": false, "comment-format": false, - "dt-header": false, "eofline": false, "export-just-namespace": false, "import-spacing": false, diff --git a/types/victory/victory-tests.tsx b/types/victory/victory-tests.tsx index 3b882c7583..d7ddd7c33b 100644 --- a/types/victory/victory-tests.tsx +++ b/types/victory/victory-tests.tsx @@ -253,6 +253,8 @@ test = ( {x: 4, y: 2}, {x: 5, y: 1} ]} + barWidth={20} + barRatio={100} /> ); diff --git a/types/w3c-generic-sensor/index.d.ts b/types/w3c-generic-sensor/index.d.ts index 40f6db6301..70e41c87bf 100644 --- a/types/w3c-generic-sensor/index.d.ts +++ b/types/w3c-generic-sensor/index.d.ts @@ -2,12 +2,10 @@ // Project: https://www.w3.org/TR/generic-sensor/ // Definitions by: Kenneth Rohde Christiansen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.2 +// TypeScript Version: 3.0 // Explainer: https://www.w3.org/TR/motion-sensors/ -/// - declare class SensorErrorEvent extends Event { constructor(type: string, errorEventInitDict: SensorErrorEventInit); readonly error: Error; @@ -82,7 +80,7 @@ declare class UncalibratedMagnetometer extends Sensor { // Orientation Sensor: https://www.w3.org/TR/orientation-sensor/ -type RotationMatrixType = Float32Array | Float64Array | GeometryDom.DOMMatrix; +type RotationMatrixType = Float32Array | Float64Array | DOMMatrix; declare class OrientationSensor extends Sensor { readonly quaternion?: number[]; diff --git a/types/w3c-generic-sensor/package.json b/types/w3c-generic-sensor/package.json new file mode 100644 index 0000000000..ac057ed75f --- /dev/null +++ b/types/w3c-generic-sensor/package.json @@ -0,0 +1,14 @@ +{ + "private": true, + "types": "index", + "typesVersions": { + ">=3.2.0-0": { + "*": [ + "ts3.2/*" + ] + } + }, + "dependencies": { + "typescript": "^2.2.2" + } +} diff --git a/types/w3c-generic-sensor/ts3.2/index.d.ts b/types/w3c-generic-sensor/ts3.2/index.d.ts new file mode 100644 index 0000000000..12a22260ee --- /dev/null +++ b/types/w3c-generic-sensor/ts3.2/index.d.ts @@ -0,0 +1,90 @@ +// Explainer: https://www.w3.org/TR/motion-sensors/ + +declare class SensorErrorEvent extends Event { + constructor(type: string, errorEventInitDict: SensorErrorEventInit); + readonly error: Error; +} + +interface SensorErrorEventInit extends EventInit { + error: Error; +} + +declare class Sensor extends EventTarget { + readonly activated: boolean; + readonly timestamp?: number; // Should be DOMHighResTimeStamp. + start(): void; + stop(): void; + + onreading: (this: this, ev: Event) => any; + onactivate: (this: this, ev: Event) => any; + onerror: (this: this, ev: SensorErrorEvent) => any; + + addEventListener(type: "reading" | "activate", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (this: this, ev: SensorErrorEvent) => any, useCapture?: boolean): void; +} + +interface SensorOptions { + frequency?: number; +} + +// Accelerometer: https://www.w3.org/TR/accelerometer/ + +declare class Accelerometer extends Sensor { + constructor(options?: SensorOptions); + readonly x?: number; + readonly y?: number; + readonly z?: number; +} + +declare class LinearAccelerationSensor extends Accelerometer { + constructor(options?: SensorOptions); +} + +declare class GravitySensor extends Accelerometer { + constructor(options?: SensorOptions); +} + +// Gyroscope: https://www.w3.org/TR/gyroscope/ + +declare class Gyroscope extends Sensor { + constructor(options?: SensorOptions); + readonly x?: number; + readonly y?: number; + readonly z?: number; +} + +// Magnetometer: https://www.w3.org/TR/magnetometer/ + +declare class Magnetometer extends Sensor { + constructor(options?: SensorOptions); + readonly x?: number; + readonly y?: number; + readonly z?: number; +} + +declare class UncalibratedMagnetometer extends Sensor { + constructor(options?: SensorOptions); + readonly x?: number; + readonly y?: number; + readonly z?: number; + readonly xBias?: number; + readonly yBias?: number; + readonly zBias?: number; +} + +// Orientation Sensor: https://www.w3.org/TR/orientation-sensor/ + +type RotationMatrixType = Float32Array | Float64Array | DOMMatrix; + +declare class OrientationSensor extends Sensor { + readonly quaternion?: number[]; + populateMatrix(targetMatrix: RotationMatrixType): void; +} + +declare class AbsoluteOrientationSensor extends OrientationSensor { + constructor(options?: SensorOptions); +} + +declare class RelativeOrientationSensor extends OrientationSensor { + constructor(options?: SensorOptions); +} diff --git a/types/w3c-generic-sensor/ts3.2/tsconfig.json b/types/w3c-generic-sensor/ts3.2/tsconfig.json new file mode 100644 index 0000000000..c40f91a278 --- /dev/null +++ b/types/w3c-generic-sensor/ts3.2/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "w3c-generic-sensor-tests.ts" + ] +} diff --git a/types/w3c-generic-sensor/ts3.2/tslint.json b/types/w3c-generic-sensor/ts3.2/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/w3c-generic-sensor/ts3.2/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/w3c-generic-sensor/ts3.2/w3c-generic-sensor-tests.ts b/types/w3c-generic-sensor/ts3.2/w3c-generic-sensor-tests.ts new file mode 100644 index 0000000000..84f6891a46 --- /dev/null +++ b/types/w3c-generic-sensor/ts3.2/w3c-generic-sensor-tests.ts @@ -0,0 +1,246 @@ +// Accelerometer: https://www.w3.org/TR/accelerometer/ + +const accelerometer1 = () => { + const sensor = new Accelerometer(); + sensor.start(); + + sensor.onreading = () => { + console.log("Acceleration along X-axis: " + sensor.x); + console.log("Acceleration along Y-axis: " + sensor.y); + console.log("Acceleration along Z-axis: " + sensor.z); + }; + + sensor.onerror = event => console.log(event.error.name, event.error.message); +}; + +// Gyroscope: https://www.w3.org/TR/gyroscope/ + +const gyroscope1 = () => { + const sensor = new Gyroscope(); + sensor.start(); + + sensor.onreading = () => { + console.log("Angular velocity around the X-axis " + sensor.x); + console.log("Angular velocity around the Y-axis " + sensor.y); + console.log("Angular velocity around the Z-axis " + sensor.z); + }; + + sensor.onerror = event => console.log(event.error.name, event.error.message); +}; + +// From Magnetometer spec: https://www.w3.org/TR/magnetometer/ + +const magnetometer1 = () => { + const sensor = new Magnetometer(); + sensor.start(); + + sensor.onreading = () => { + console.log("Magnetic field along the X-axis " + sensor.x); + console.log("Magnetic field along the Y-axis " + sensor.y); + console.log("Magnetic field along the Z-axis " + sensor.z); + }; + + sensor.onerror = event => console.log(event.error.name, event.error.message); +}; + +const magnetometer2 = () => { + const sensor = new Magnetometer(); + sensor.start(); + + sensor.onreading = () => { + if (!sensor.y || !sensor.x) { + return; + } + const heading = Math.atan2(sensor.y, sensor.x) * (180 / Math.PI); + console.log('Heading in degrees: ' + heading); + }; +}; + +const magnetometer3 = () => { + const sensor = new Magnetometer(); + sensor.start(); + + sensor.onreading = async () => { + if (!sensor.y || !sensor.x) { + return; + } + const heading = Math.atan2(sensor.y, sensor.x) * (180 / Math.PI); + + // Get the latitude and longitude, omitted for brevity here. + const latitude = 0; + const longitude = 0; + + // Get the magnetic declination at the given latitude and longitude. + const response = await fetch('https://www.ngdc.noaa.gov/geomag-web/calculators/calculateDeclination' + + `?lat1=${latitude}&lon1=${longitude}&resultFormat=csv`); + const text = await response.text(); + + const declination = parseFloat(text.replace(/^#.*$/gm, '').trim().split(',')[4]); + + // Compensate for the magnetic declination to get the geographic north. + console.log('True heading in degrees: ' + (heading + declination)); + }; +}; + +// From Orientation Sensor spec: https://www.w3.org/TR/orientation-sensor/ + +const orientation1 = () => { + const sensor = new AbsoluteOrientationSensor(); + const mat4 = new Float32Array(16); + sensor.start(); + sensor.onerror = event => console.log(event.error.name, event.error.message); + + sensor.onreading = () => { + sensor.populateMatrix(mat4); + }; +}; + +const orientation2 = () => { + const sensor = new AbsoluteOrientationSensor({ frequency: 60 }); + const mat4 = new Float32Array(16); + sensor.start(); + sensor.onerror = event => console.log(event.error.name, event.error.message); + + function draw() { + window.requestAnimationFrame(draw); + try { + sensor.populateMatrix(mat4); + } catch (err) { + console.log("mat4 has not been updated: " + err); + } + // Drawing... + } + + window.requestAnimationFrame(draw); +}; + +// From Explainer: https://www.w3.org/TR/motion-sensors/ + +const explainer1 = () => { + class LowPassFilterData { + x: number; + y: number; + z: number; + bias: number; + + constructor(reading: Accelerometer | Gyroscope | Magnetometer, bias: number) { + Object.assign(this, { x: reading.x, y: reading.y, z: reading.z }); + this.bias = bias; + } + + update(reading: Accelerometer | Gyroscope | Magnetometer) { + if (!reading.x || !reading.y || !reading.z) { + return; + } + + this.x = this.x * this.bias + reading.x * (1 - this.bias); + this.y = this.y * this.bias + reading.y * (1 - this.bias); + this.z = this.z * this.bias + reading.z * (1 - this.bias); + } + } + + const accl = new Accelerometer({ frequency: 20 }); + + // Isolate gravity with low-pass filter. + const filter = new LowPassFilterData(accl, 0.8); + + accl.onreading = () => { + filter.update(accl); // Pass latest values through filter. + console.log(`Isolated gravity (${filter.x}, ${filter.y}, ${filter.z})`); + }; + + accl.start(); +}; + +const explainer2 = () => { + class HighPassFilterData { + cutoff: number; + timestamp?: number; + x?: number; + y?: number; + z?: number; + + constructor(reading: Accelerometer | Gyroscope | Magnetometer, cutoffFrequency: number) { + this.x = reading.x; + this.y = reading.y; + this.z = reading.z; + this.cutoff = cutoffFrequency; + this.timestamp = reading.timestamp; + } + + update(reading: Accelerometer | Gyroscope | Magnetometer) { + if (!this.timestamp || !this.x || !this.y || !this.z) { + this.x = reading.x; + this.y = reading.y; + this.z = reading.z; + this.timestamp = reading.timestamp; + return; + } + + if (!reading.timestamp || !reading.x || ! reading.y || !reading.z) { + return; + } + + const dt = reading.timestamp - this.timestamp / 1000; + this.timestamp = reading.timestamp; + + const alpha = this.cutoff / (this.cutoff + dt); + this.x = this.x + alpha * (reading.x - this.x); + this.y = this.y + alpha * (reading.y - this.y); + this.z = this.z + alpha * (reading.z - this.z); + } + } + + const gyro = new Gyroscope({ frequency: 20 }); + + // Remove drift with a high pass filter. + const filter = new HighPassFilterData(gyro, 0.8); + + gyro.onreading = () => { + filter.update(gyro); // Pass latest values through filter. + console.log(`Steady gyroscope (${filter.x}, ${filter.y}, ${filter.z})`); + }; + + gyro.start(); +}; + +const explainer3 = () => { + const options = { frequency: 50 }; + + const accl = new Accelerometer(options); + const gyro = new Gyroscope(options); + + let timestamp = 0; + let alpha = 0; + let beta = 0; + let gamma = 0; + const bias = 0.98; + + gyro.onreading = () => { + if (!gyro.timestamp || !gyro.x || !gyro.y || !gyro.z || !accl.x || !accl.y || !accl.z) { + return; + } + + const dt = timestamp ? (gyro.timestamp - timestamp) / 1000 : 0; + timestamp = gyro.timestamp; + + // Treat the acceleration vector as an orientation vector by normalizing it. + // Keep in mind that the if the device is flipped, the vector will just be + // pointing in the other direction, so we have no way to know from the + // accelerometer data which way the device is oriented. + const norm = Math.sqrt(accl.x ** 2 + accl.y ** 2 + accl.z ** 2); + + // As we only can cover half (PI rad) of the full spectrum (2*PI rad) we multiply + // the unit vector with values from [-1, 1] with PI/2, covering [-PI/2, PI/2]. + const scale = Math.PI / 2; + + alpha = alpha + gyro.z * dt; + beta = bias * (beta + gyro.x * dt) + (1.0 - bias) * (accl.x * scale / norm); + gamma = bias * (gamma + gyro.y * dt) + (1.0 - bias) * (accl.y * -scale / norm); + + // Do something with Euler angles (alpha, beta, gamma). + }; + + accl.start(); + gyro.start(); +}; diff --git a/types/w3c-generic-sensor/tsconfig.json b/types/w3c-generic-sensor/tsconfig.json index 4a33837faa..35ab867a63 100644 --- a/types/w3c-generic-sensor/tsconfig.json +++ b/types/w3c-generic-sensor/tsconfig.json @@ -21,4 +21,4 @@ "index.d.ts", "w3c-generic-sensor-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/w3c-image-capture/index.d.ts b/types/w3c-image-capture/index.d.ts index 8f04fad534..24a7d917c4 100644 --- a/types/w3c-image-capture/index.d.ts +++ b/types/w3c-image-capture/index.d.ts @@ -2,7 +2,7 @@ // Project: https://www.w3.org/TR/image-capture/ // Definitions by: Cosium // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 3.0 /// diff --git a/types/w3c-screen-orientation/package.json b/types/w3c-screen-orientation/package.json new file mode 100644 index 0000000000..aedf75343b --- /dev/null +++ b/types/w3c-screen-orientation/package.json @@ -0,0 +1,8 @@ +{ + "private": true, + "types": "index", + "typesVersions": { + ">=3.1.0-0": { "*": ["ts3.1/*"] }, + ">=3.2.0-0": { "*": ["ts3.2/*"] } + } +} diff --git a/types/w3c-screen-orientation/ts3.1/index.d.ts b/types/w3c-screen-orientation/ts3.1/index.d.ts new file mode 100644 index 0000000000..6d88f98715 --- /dev/null +++ b/types/w3c-screen-orientation/ts3.1/index.d.ts @@ -0,0 +1,13 @@ +type ScreenOrientationLockType = "any" | "natural" | "landscape" | "portrait" | "portrait-primary" | "portrait-secondary" | "landscape-primary" | "landscape-secondary"; + +interface ScreenOrientation extends EventTarget { + lock(orientation: ScreenOrientationLockType): Promise; + unlock(): void; + readonly type: OrientationType; + readonly angle: number; + addEventListener(type: "change", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; +} + +interface Screen { + readonly orientation: ScreenOrientation; +} diff --git a/types/w3c-screen-orientation/ts3.1/tsconfig.json b/types/w3c-screen-orientation/ts3.1/tsconfig.json new file mode 100644 index 0000000000..2786c93736 --- /dev/null +++ b/types/w3c-screen-orientation/ts3.1/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "w3c-screen-orientation-tests.ts" + ] +} diff --git a/types/w3c-screen-orientation/ts3.1/tslint.json b/types/w3c-screen-orientation/ts3.1/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/w3c-screen-orientation/ts3.1/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/w3c-screen-orientation/ts3.1/w3c-screen-orientation-tests.ts b/types/w3c-screen-orientation/ts3.1/w3c-screen-orientation-tests.ts new file mode 100644 index 0000000000..63963da5ac --- /dev/null +++ b/types/w3c-screen-orientation/ts3.1/w3c-screen-orientation-tests.ts @@ -0,0 +1,36 @@ +// Example 1 (from the spec): +const show = () => { + console.log("Orientation type is " + screen.orientation.type); + console.log("Orientation angle is " + screen.orientation.angle); +}; + +screen.orientation.addEventListener("change", show); +window.onload = show; + +// Example 2 (from the spec): +const start = () => { + document.onfullscreenchange = () => { + screen.orientation.lock('natural').then(startInternal); + }; + document.documentElement.requestFullscreen(); +}; + +// Example 3 (from the spec): +const startInternal = () => {}; + +const start2 = () => { + screen.orientation.lock('landscape-primary').then(startInternal, () => { + alert('To start, rotate your screen to landscape.'); + + const orientationChangeHandler = () => { + if (!screen.orientation.type.startsWith('landscape')) { + return; + } + screen.orientation.removeEventListener('change', orientationChangeHandler); + startInternal(); + }; + + screen.orientation.addEventListener('change', orientationChangeHandler); + }); +}; +window.onload = start2; diff --git a/types/w3c-screen-orientation/ts3.2/index.d.ts b/types/w3c-screen-orientation/ts3.2/index.d.ts new file mode 100644 index 0000000000..6d88f98715 --- /dev/null +++ b/types/w3c-screen-orientation/ts3.2/index.d.ts @@ -0,0 +1,13 @@ +type ScreenOrientationLockType = "any" | "natural" | "landscape" | "portrait" | "portrait-primary" | "portrait-secondary" | "landscape-primary" | "landscape-secondary"; + +interface ScreenOrientation extends EventTarget { + lock(orientation: ScreenOrientationLockType): Promise; + unlock(): void; + readonly type: OrientationType; + readonly angle: number; + addEventListener(type: "change", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; +} + +interface Screen { + readonly orientation: ScreenOrientation; +} diff --git a/types/w3c-screen-orientation/ts3.2/tsconfig.json b/types/w3c-screen-orientation/ts3.2/tsconfig.json new file mode 100644 index 0000000000..2786c93736 --- /dev/null +++ b/types/w3c-screen-orientation/ts3.2/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "w3c-screen-orientation-tests.ts" + ] +} diff --git a/types/w3c-screen-orientation/ts3.2/tslint.json b/types/w3c-screen-orientation/ts3.2/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/w3c-screen-orientation/ts3.2/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/w3c-screen-orientation/ts3.2/w3c-screen-orientation-tests.ts b/types/w3c-screen-orientation/ts3.2/w3c-screen-orientation-tests.ts new file mode 100644 index 0000000000..63963da5ac --- /dev/null +++ b/types/w3c-screen-orientation/ts3.2/w3c-screen-orientation-tests.ts @@ -0,0 +1,36 @@ +// Example 1 (from the spec): +const show = () => { + console.log("Orientation type is " + screen.orientation.type); + console.log("Orientation angle is " + screen.orientation.angle); +}; + +screen.orientation.addEventListener("change", show); +window.onload = show; + +// Example 2 (from the spec): +const start = () => { + document.onfullscreenchange = () => { + screen.orientation.lock('natural').then(startInternal); + }; + document.documentElement.requestFullscreen(); +}; + +// Example 3 (from the spec): +const startInternal = () => {}; + +const start2 = () => { + screen.orientation.lock('landscape-primary').then(startInternal, () => { + alert('To start, rotate your screen to landscape.'); + + const orientationChangeHandler = () => { + if (!screen.orientation.type.startsWith('landscape')) { + return; + } + screen.orientation.removeEventListener('change', orientationChangeHandler); + startInternal(); + }; + + screen.orientation.addEventListener('change', orientationChangeHandler); + }); +}; +window.onload = start2; diff --git a/types/web-animations-js/index.d.ts b/types/web-animations-js/index.d.ts index 54c0b8c01b..f809b1cd3e 100644 --- a/types/web-animations-js/index.d.ts +++ b/types/web-animations-js/index.d.ts @@ -2,10 +2,10 @@ // Project: https://github.com/web-animations/web-animations-js // Definitions by: Kristian Moerch // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 3.0 type AnimationEffectTimingFillMode = "none" | "forwards" | "backwards" | "both" | "auto"; type AnimationEffectTimingPlaybackDirection = "normal" | "reverse" | "alternate" | "alternate-reverse"; -type AnimationPlayState = "idle" | "running" | "paused" | "finished"; interface AnimationPlaybackEvent { target: Animation; @@ -68,18 +68,7 @@ interface ComputedTimingProperties { currentIteration: number | null; } -declare class KeyframeEffect implements AnimationEffectReadOnly { - constructor(target: HTMLElement, effect: AnimationKeyFrame | AnimationKeyFrame[], timing: number | AnimationEffectTiming, id?: string); - activeDuration: number; - onsample: (timeFraction: number | null, effect: KeyframeEffect, animation: Animation) => void | undefined; - parent: KeyframeEffect | null; - target: HTMLElement; - timing: number; - getComputedTiming(): ComputedTimingProperties; - getFrames(): AnimationKeyFrame[]; - remove(): void; -} -type AnimationEventListener = (this: Animation, evt: AnimationPlaybackEvent) => any; +type AnimationEventListener = ((this: Animation, evt: AnimationPlaybackEvent) => any) | null; interface Animation extends EventTarget { currentTime: number | null; @@ -88,7 +77,7 @@ interface Animation extends EventTarget { onfinish: AnimationEventListener; readonly playState: AnimationPlayState; playbackRate: number; - startTime: number; + startTime: number | null; cancel(): void; finish(): void; pause(): void; @@ -96,15 +85,15 @@ interface Animation extends EventTarget { reverse(): void; addEventListener(type: "finish" | "cancel", handler: EventListener): void; removeEventListener(type: "finish" | "cancel", handler: EventListener): void; - effect: AnimationEffectReadOnly; + effect: AnimationEffect | null; readonly finished: Promise; readonly ready: Promise; - timeline: AnimationTimeline; + timeline: AnimationTimeline | null; } declare var Animation: { prototype: Animation; - new(effect?: AnimationEffectReadOnly, timeline?: AnimationTimeline): Animation; + new(effect?: AnimationEffect | null, timeline?: AnimationTimeline | null): Animation; }; declare class SequenceEffect extends KeyframeEffect { @@ -114,9 +103,10 @@ declare class GroupEffect extends KeyframeEffect { constructor(effects: KeyframeEffect[]); } interface Element { - animate(effect: AnimationKeyFrame | AnimationKeyFrame[], timing: number | AnimationEffectTiming): Animation; + animate(effect: AnimationKeyFrame | AnimationKeyFrame[] | null, timing: number | AnimationEffectTiming): Animation; + animate(keyframes: Keyframe[] | PropertyIndexedKeyframes | null, options?: number | KeyframeAnimationOptions): Animation; getAnimations(): Animation[]; } interface Document { - timeline: AnimationTimeline; + readonly timeline: AnimationTimeline; } diff --git a/types/web-animations-js/package.json b/types/web-animations-js/package.json new file mode 100644 index 0000000000..d27d838dc6 --- /dev/null +++ b/types/web-animations-js/package.json @@ -0,0 +1,7 @@ +{ + "private": true, + "types": "index", + "typesVersions": { + ">=3.2.0-0": { "*": ["ts3.2/*"] } + } +} diff --git a/types/web-animations-js/ts3.2/index.d.ts b/types/web-animations-js/ts3.2/index.d.ts new file mode 100644 index 0000000000..f0c0b24517 --- /dev/null +++ b/types/web-animations-js/ts3.2/index.d.ts @@ -0,0 +1,105 @@ +type AnimationEffectTimingFillMode = "none" | "forwards" | "backwards" | "both" | "auto"; +type AnimationEffectTimingPlaybackDirection = "normal" | "reverse" | "alternate" | "alternate-reverse"; + +interface AnimationPlaybackEvent { + target: Animation; + readonly currentTime: number | null; + readonly timelineTime: number | null; + type: string; + bubbles: boolean; + cancelable: boolean; + currentTarget: Animation; + defaultPrevented: boolean; + eventPhase: number; + timeStamp: number; +} + +interface AnimationPlaybackEventInit extends EventInit { + currentTime?: number | null; + timelineTime?: number | null; +} + +declare var AnimationPlaybackEvent: { + prototype: AnimationPlaybackEvent; + new(type: string, eventInitDict?: AnimationPlaybackEventInit): AnimationPlaybackEvent; +}; + +interface AnimationKeyFrame { + easing?: string | string[]; + offset?: number | Array | null; + opacity?: number | number[]; + transform?: string | string[]; + // [key: string]: string | number | [string | number, string | number] | undefined; (duplicate string indexer in TypeScript 2.7+) +} + +interface AnimationTimeline { + readonly currentTime: number | null; + getAnimations(): Animation[]; + play(effect: KeyframeEffect): Animation; +} +interface AnimationEffectTiming { + delay?: number; + direction?: AnimationEffectTimingPlaybackDirection; + duration?: number; + easing?: string; + endDelay?: number; + fill?: AnimationEffectTimingFillMode; + iterationStart?: number; + iterations?: number; + playbackRate?: number; +} + +interface AnimationEffectReadOnly { + readonly timing: number; + getComputedTiming(): ComputedTimingProperties; +} + +interface ComputedTimingProperties { + endTime: number; + activeDuration: number; + localTime: number | null; + progress: number | null; + currentIteration: number | null; +} + +type AnimationEventListener = ((this: Animation, evt: AnimationPlaybackEvent) => any) | null; + +interface Animation extends EventTarget { + currentTime: number | null; + id: string; + oncancel: AnimationEventListener; + onfinish: AnimationEventListener; + readonly playState: AnimationPlayState; + playbackRate: number; + startTime: number | null; + cancel(): void; + finish(): void; + pause(): void; + play(): void; + reverse(): void; + addEventListener(type: "finish" | "cancel", handler: EventListener): void; + removeEventListener(type: "finish" | "cancel", handler: EventListener): void; + effect: AnimationEffect | null; + readonly finished: Promise; + readonly ready: Promise; + timeline: AnimationTimeline | null; +} + +declare var Animation: { + prototype: Animation; + new(effect?: AnimationEffect | null, timeline?: AnimationTimeline | null): Animation; +}; + +declare class SequenceEffect extends KeyframeEffect { + constructor(effects: KeyframeEffect[]); +} +declare class GroupEffect extends KeyframeEffect { + constructor(effects: KeyframeEffect[]); +} +interface Element { + animate(effect: AnimationKeyFrame | AnimationKeyFrame[] | null, timing: number | AnimationEffectTiming): Animation; + getAnimations(): Animation[]; +} +interface Document { + readonly timeline: AnimationTimeline; +} diff --git a/types/web-animations-js/ts3.2/tsconfig.json b/types/web-animations-js/ts3.2/tsconfig.json new file mode 100644 index 0000000000..d78a0d3aaf --- /dev/null +++ b/types/web-animations-js/ts3.2/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es5", + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "web-animations-js-tests.ts" + ] +} diff --git a/types/web-animations-js/ts3.2/tslint.json b/types/web-animations-js/ts3.2/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/web-animations-js/ts3.2/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/web-animations-js/ts3.2/web-animations-js-tests.ts b/types/web-animations-js/ts3.2/web-animations-js-tests.ts new file mode 100644 index 0000000000..aa51fa14d1 --- /dev/null +++ b/types/web-animations-js/ts3.2/web-animations-js-tests.ts @@ -0,0 +1,90 @@ +// From the documentation +function test_doc() { + const elem = document.createElement('div'); + const animation = elem.animate({ + opacity: [0.5, 1], + transform: ['scale(0.5)', 'scale(1)'] + }, { + direction: 'alternate', + duration: 500, + iterations: Infinity + }); +} +// From https://io2015codelabs.appspot.com/codelabs/web-animations-transitions-playbackcontrol +// To test KeyframeEffect, SequenceEffect and GroupEffect +function test_AnimationsApiNext() { + function buildFadeIn(target: HTMLElement) { + const steps = [ + { opacity: 0, transform: 'translate(0, 20em)' }, + { opacity: 1, transform: 'translate(0)' } + ]; + return new KeyframeEffect(target, steps, { + duration: 500, + delay: -1000, + fill: 'backwards', + easing: 'cubic-bezier(0.175, 0.885, 0.32, 1.275)' + }); + } + function buildFadeOut(target: HTMLElement) { + const angle = Math.pow((Math.random() * 16) - 6, 3); + const offset = (Math.random() * 20) - 10; + const transform = `translate(${offset}em, 20em) rotate(${angle}deg) scale(0)`; + const steps = [ + { visibility: 'visible', opacity: 1, transform: 'none' }, + { visibility: 'visible', opacity: 0, transform } + ]; + return new KeyframeEffect(target, steps, { + duration: 1500, + easing: 'ease-in' + }); + } + const effectNode = document.createElement('div'); + effectNode.className = 'circleEffect'; + const bounds = document.documentElement.getBoundingClientRect(); + effectNode.style.left = `${bounds.left + bounds.width / 2}px`; + effectNode.style.top = `${bounds.top + bounds.height / 2}px`; + const header = document.querySelector('header'); + if (header) { + header.appendChild(effectNode); + } + const newColor = `hsl(${Math.round(Math.random() * 255)}, 46%, 42%)`; + effectNode.style.background = newColor; + const scaleSteps = [{ transform: 'scale(0)' }, { transform: 'scale(1)' }]; + const timing: AnimationEffectTiming = { duration: 2500, easing: 'ease-in-out', fill: "backwards" }; + const scaleEffect = new KeyframeEffect(effectNode, scaleSteps, timing); + const fadeEffect = new SequenceEffect([buildFadeOut(effectNode), buildFadeIn(effectNode)]); + const allEffects = [scaleEffect, fadeEffect]; + // Play all animations within this group. + const groupEffect = new GroupEffect(allEffects); + const anim = document.timeline.play(groupEffect); +} + +// https://developer.mozilla.org/en-US/docs/Web/API/Animation/Animation +// http://codepen.io/rachelnabors/pen/eJyWzm/?editors=0010 +function test_whiteRabbit() { + const whiteRabbit = document.getElementById("rabbit"); + if (whiteRabbit) { + const rabbitDownKeyframes = new KeyframeEffect( + whiteRabbit, + [ + { transform: 'translateY(0%)' }, + { transform: 'translateY(100%)' } + ], + { duration: 3000, fill: 'forwards' } + ); + const rabbitDownAnimation = new Animation(rabbitDownKeyframes, document.timeline); + // On tap or click, + whiteRabbit.addEventListener("mousedown", downHeGoes, false); + whiteRabbit.addEventListener("touchstart", downHeGoes, false); + + // Trigger a single-fire animation + function downHeGoes(event: Event) { + // Remove those event listeners + whiteRabbit!.removeEventListener("mousedown", downHeGoes, false); + whiteRabbit!.removeEventListener("touchstart", downHeGoes, false); + + // Play rabbit animation + rabbitDownAnimation.play(); + } + } +} diff --git a/types/web-animations-js/web-animations-js-tests.ts b/types/web-animations-js/web-animations-js-tests.ts index 934bc944d1..39d0e21faf 100644 --- a/types/web-animations-js/web-animations-js-tests.ts +++ b/types/web-animations-js/web-animations-js-tests.ts @@ -14,10 +14,7 @@ function test_doc() { // To test KeyframeEffect, SequenceEffect and GroupEffect function test_AnimationsApiNext() { function buildFadeIn(target: HTMLElement) { - const steps = [ - { opacity: 0, transform: 'translate(0, 20em)' }, - { opacity: 1, transform: 'translate(0)' } - ]; + const steps: Keyframe[] = []; return new KeyframeEffect(target, steps, { duration: 500, delay: -1000, @@ -29,10 +26,7 @@ function test_AnimationsApiNext() { const angle = Math.pow((Math.random() * 16) - 6, 3); const offset = (Math.random() * 20) - 10; const transform = `translate(${offset}em, 20em) rotate(${angle}deg) scale(0)`; - const steps = [ - { visibility: 'visible', opacity: 1, transform: 'none' }, - { visibility: 'visible', opacity: 0, transform } - ]; + const steps: Keyframe[] = []; return new KeyframeEffect(target, steps, { duration: 1500, easing: 'ease-in' @@ -40,7 +34,8 @@ function test_AnimationsApiNext() { } const effectNode = document.createElement('div'); effectNode.className = 'circleEffect'; - const bounds = document.documentElement.getBoundingClientRect(); + // tslint:disable-next-line:no-unnecessary-type-assertion + const bounds = document.documentElement!.getBoundingClientRect(); effectNode.style.left = `${bounds.left + bounds.width / 2}px`; effectNode.style.top = `${bounds.top + bounds.height / 2}px`; const header = document.querySelector('header'); @@ -49,7 +44,7 @@ function test_AnimationsApiNext() { } const newColor = `hsl(${Math.round(Math.random() * 255)}, 46%, 42%)`; effectNode.style.background = newColor; - const scaleSteps = [{ transform: 'scale(0)' }, { transform: 'scale(1)' }]; + const scaleSteps: Keyframe[] = []; const timing: AnimationEffectTiming = { duration: 2500, easing: 'ease-in-out', fill: "backwards" }; const scaleEffect = new KeyframeEffect(effectNode, scaleSteps, timing); const fadeEffect = new SequenceEffect([buildFadeOut(effectNode), buildFadeIn(effectNode)]); @@ -66,10 +61,7 @@ function test_whiteRabbit() { if (whiteRabbit) { const rabbitDownKeyframes = new KeyframeEffect( whiteRabbit, - [ - { transform: 'translateY(0%)' }, - { transform: 'translateY(100%)' } - ], + [], { duration: 3000, fill: 'forwards' } ); const rabbitDownAnimation = new Animation(rabbitDownKeyframes, document.timeline); @@ -88,31 +80,3 @@ function test_whiteRabbit() { } } } -// Testing onsample -// https://github.com/web-animations/web-animations-js/releases -function test_onsample_And_addEventListener() { - const elem = document.createElement("div"); - if (elem) { - elem.style.width = '150px'; - elem.style.color = 'black'; - elem.textContent = "HELLO"; - document.body.appendChild(elem); - const myEffect = new KeyframeEffect(elem, [], 1000); - myEffect.onsample = (timeFraction, effect, animation) => { - console.log("fraction", timeFraction); - // After finish event, timeFraction is null - if (timeFraction) { - effect.target.style.opacity = timeFraction.toFixed(2); - } - }; - // onsample is write only - console.log(myEffect.onsample); // => undefined - const myAnimation = document.timeline.play(myEffect); - myAnimation.addEventListener("finish", (e) => { - console.log("finished", e); - }); - myAnimation.addEventListener("cancel", (e) => { - console.log("canceled", e); - }); - } -} diff --git a/types/web-resource-inliner/index.d.ts b/types/web-resource-inliner/index.d.ts new file mode 100644 index 0000000000..009f3a5dda --- /dev/null +++ b/types/web-resource-inliner/index.d.ts @@ -0,0 +1,129 @@ +// Type definitions for web-resource-inliner 4.2 +// Project: https://github.com/jrit/web-resource-inliner#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import { CoreOptions, RequiredUriUrl } from 'request'; + +export function html(options: Options, callback: Callback): string; +export function css(options: Options, callback: Callback): string; + +export type Callback = (error: any, result: any) => void; + +export interface Options { + /** + * This is the HTML or CSS content to be inlined, you should provide HTML to the html() method and CSS to the css() method or you will get errors or garbage output. + */ + fileContent: string; + /** + * Sets the attribute that is used to include/exclude specific resources based on the default behavior for the resource type. + * + * For example, if scripts is set to false, an individual script can be inlined by adding the attribute to the script tag like . + * On the other hand, if images are set to be inlined by default, + * a specific image can be excluded by adding -ignore to the end of the inlineAttribute like . + * + * In CSS, a comment is required at the end of the line to perform the same thing, such as \/*data-inline*\/ or \/*data-inline-ignore*\/. + * + * @default "data-inline" + */ + inlineAttribute?: string; + /** + * When true, inline images unless they have an exclusion attribute (see inlineAttribute option). + * + * When false, exclude images unless they have an inclusion attribute (see inlineAttribute option). + * + * When a number, inline images only when the base64 content size is less than the number of KBs. + * + * For example, the default is to only inline images less than 8KB. + * + * @default 8 + */ + images?: boolean | number; + /** + * When true, inline SVG unless they have an exclusion attribute (see inlineAttribute option). + * + * When false, exclude SVG unless they have an inclusion attribute (see inlineAttribute option). + * + * When a number, inline SVG only when the content size is less than the number of KBs. + * + * For example, the default is to only inline SVGs less than 8KB. + * + * @default 8 + */ + svgs?: boolean | number; + /** + * When true, inline scripts unless they have an exclusion attribute (see inlineAttribute option). + * + * When false, exclude scripts unless they have an inclusion attribute (see inlineAttribute option). + * + * When a number, inline scripts only when the base64 content size is less than the number of KBs. + * + * @default true + */ + scripts?: boolean | number; + /** + * When true, inline stylesheet links unless they have an exclusion attribute (see inlineAttribute option). + * + * When false, exclude stylesheet links unless they have an inclusion attribute (see inlineAttribute option). + * + * When a number, inline stylesheet links only when the base64 content size is less than the number of KBs. + * + * @default true + */ + links?: boolean | number; + /** + * Describes the path relationship between where web-resource-inliner is running and what the relative paths in fileContent or href/src urls refer to. + * + * For example, the tests cases in this package are in test/cases/ so their relative paths start by referring to that folder, + * but the root of this project and where npm test runs from is 2 folders up, so relativeTo is set to test/cases/ in test/spec.js. + * Likewise, with href="content.css" and a relativeTo of http://github.com/ the resource retrieved would be http://github.com/content.css. + * + * @default "" + */ + relativeTo?: string; + /** + * Describes the path relationship between CSS content and the context it will be loaded in. + * + * For example, when a CSS file contains url(some-file.png) and the file is moved from a location in a folder like /css to / + * then the path to the image needs to be changed to url(css/some-file.png). + * In this case, rebaseRelativeTo would be css. You probably don't want to set this when you are using html(). + * + * @default "" + */ + rebaseRelativeTo?: string; + /** + * When strict is true, a missing resource will cause the inliner to halt and return an error in the callback. + * + * The default behavior is to log a warning to the console and continue inlining with the available resources, which is more similar to how a web page behaves. + * + * @default false + */ + strict?: boolean; + /** + * Allows to adjust issued requests. + * + * E.g., add authentication tokens to requested URLs. + * + * The function is called with the request options object as its parameter. + * + * It can modify this object or return a new one. + * + * See the [list of available options](https://www.npmjs.com/package/request#request-options-callback). + */ + requestTransform?: ( + requestOptions: RequiredUriUrl & CoreOptions + ) => RequiredUriUrl & CoreOptions; + /** + * Allows to make changes to scripts before they are inlined, such as minifying. + * + * Callback is standard node error first, second argument is transformed value. + */ + scriptTransform?: (content: string, done: Callback) => any; + /** + * Allows to make changes to links before they are inlined, such as CSS pre-and-post-processors. + * + * Callback is standard node error first, second argument is transformed value. + */ + linkTransform?: (content: string, done: Callback) => any; +} diff --git a/types/web-resource-inliner/tsconfig.json b/types/web-resource-inliner/tsconfig.json new file mode 100644 index 0000000000..cdfd6e6a41 --- /dev/null +++ b/types/web-resource-inliner/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "web-resource-inliner-tests.ts" + ] +} diff --git a/types/web-resource-inliner/tslint.json b/types/web-resource-inliner/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/web-resource-inliner/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/web-resource-inliner/web-resource-inliner-tests.ts b/types/web-resource-inliner/web-resource-inliner-tests.ts new file mode 100644 index 0000000000..a0410e151f --- /dev/null +++ b/types/web-resource-inliner/web-resource-inliner-tests.ts @@ -0,0 +1,49 @@ +import { html, css } from 'web-resource-inliner'; + +const fileContent = '

    some content

    '; +const cb = (error: any, result: any) => null; + +html({ fileContent }, cb); +html({ fileContent, inlineAttribute: 'foo' }, cb); +html({ fileContent, images: true }, cb); +html({ fileContent, images: 8 }, cb); +html({ fileContent, svgs: true }, cb); +html({ fileContent, svgs: 8 }, cb); +html({ fileContent, scripts: true }, cb); +html({ fileContent, scripts: 8 }, cb); +html({ fileContent, links: true }, cb); +html({ fileContent, links: 8 }, cb); +html({ fileContent, relativeTo: 'http://foo.bar' }, cb); +html({ fileContent, rebaseRelativeTo: 'css' }, cb); +html({ fileContent, strict: true }, cb); +html( + { + fileContent, + requestTransform(options) { + // $ExpectType (UriOptions & CoreOptions) | (UrlOptions & CoreOptions) + options; + return options; + }, + }, + cb +); +html( + { + fileContent, + scriptTransform(content, done) { + done(null, content); + }, + }, + cb +); +html( + { + fileContent, + linkTransform(content, done) { + done(null, content); + }, + }, + cb +); + +css({ fileContent }, cb); diff --git a/types/web3/eth/abi.d.ts b/types/web3/eth/abi.d.ts index b103c9e4ce..dcf644e93a 100644 --- a/types/web3/eth/abi.d.ts +++ b/types/web3/eth/abi.d.ts @@ -1,6 +1,7 @@ export interface ABIDefinition { constant?: boolean; payable?: boolean; + stateMutability?: "pure" | "view" | "nonpayable" | "payable"; anonymous?: boolean; inputs?: Array<{ name: string; type: ABIDataTypes; indexed?: boolean }>; name?: string; diff --git a/types/web3/providers.d.ts b/types/web3/providers.d.ts index 729ea09278..22a883222f 100644 --- a/types/web3/providers.d.ts +++ b/types/web3/providers.d.ts @@ -12,11 +12,13 @@ interface JsonRPCResponse { error?: string; } +interface Callback { + (error: Error): void; + (error: null, val: ResultType): void; +} + export class Provider { - send( - payload: JsonRPCRequest, - callback: (e: Error, val: JsonRPCResponse) => void - ): any; + send(payload: JsonRPCRequest, callback: Callback): any; } export class WebsocketProvider extends Provider { diff --git a/types/web3/test/abi-tests.ts b/types/web3/test/abi-tests.ts new file mode 100644 index 0000000000..357c59f3c3 --- /dev/null +++ b/types/web3/test/abi-tests.ts @@ -0,0 +1,89 @@ +import { ABIDefinition } from "web3/eth/abi.d"; + +export const OLD_ABI_STANDARD: ABIDefinition[] = [ + { + constant: true, + payable: false, + inputs: [ + { + name: "paramAddress", + type: "address" + } + ], + name: "function1", + outputs: [], + type: "function" + }, { + constant: true, + payable: false, + inputs: [], + name: "removeOwner", + outputs: [ + { + name: "paramAddress", + type: "address" + } + ], + type: "function" + }, { + constant: false, + payable: false, + inputs: [], + name: "removeOwner", + outputs: [], + type: "function" + }, { + constant: false, + payable: true, + inputs: [], + name: "removeOwner", + outputs: [], + type: "function" + }, +]; + +export const NEW_ABI_STANDARD: ABIDefinition[] = [ + { + constant: true, + payable: false, + stateMutability: "view", + inputs: [ + { + name: "paramAddress", + type: "address" + } + ], + name: "function1", + outputs: [], + type: "function" + }, { + constant: true, + payable: false, + stateMutability: "pure", + inputs: [], + name: "removeOwner", + outputs: [ + { + name: "paramAddress", + type: "address" + } + ], + type: "function" + }, { + constant: false, + payable: false, + stateMutability: "nonpayable", + inputs: [], + name: "removeOwner", + outputs: [], + type: "function" + }, { + constant: false, + payable: true, + stateMutability: "payable", + inputs: [], + name: "removeOwner", + outputs: [], + type: "function" + }, +]; diff --git a/types/web3/tsconfig.json b/types/web3/tsconfig.json index 42b54fc8c5..45fb60fda4 100644 --- a/types/web3/tsconfig.json +++ b/types/web3/tsconfig.json @@ -23,6 +23,7 @@ "eth/accounts.d.ts", "eth/contract.d.ts", "eth/index.d.ts", - "eth/types.d.ts" + "eth/types.d.ts", + "test/abi-tests.ts" ] } diff --git a/types/web3/web3-tests.ts b/types/web3/web3-tests.ts index 170a8b22c3..d2c3c92302 100644 --- a/types/web3/web3-tests.ts +++ b/types/web3/web3-tests.ts @@ -2,6 +2,8 @@ import Web3 = require("web3"); import BigNumber = require("bn.js"); import { TransactionReceipt } from "web3/types"; import PromiEvent from "web3/promiEvent"; +import { NEW_ABI_STANDARD, OLD_ABI_STANDARD } from "web3/test/abi-tests"; +import { Provider, JsonRPCResponse } from "web3/providers"; const contractAddress = "0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe"; @@ -10,6 +12,25 @@ const contractAddress = "0xde0B295669a9FD93d5F28D9Ec85E40f4cb697BAe"; // -------------------------------------------------------------------------- const web3 = new Web3(); const myProvider = new web3.providers.HttpProvider("http://localhost:5454"); + +const createFailingHttpProvider = (): Provider => ({ + send(payload, callback) { + callback(new Error("Illegal!")); + } +}); + +const createSuccesfulHttpProvider = (): Provider => ({ + send(payload, callback) { + const response = {}; + callback(null, response as JsonRPCResponse); + } +}); + +const fakeProvider: Provider = createFailingHttpProvider(); +const otherFakeProvider: Provider = createSuccesfulHttpProvider(); + +web3.setProvider(fakeProvider); +web3.setProvider(otherFakeProvider); web3.setProvider(myProvider); web3.eth.setProvider(myProvider); @@ -125,6 +146,8 @@ web3.eth.personal.unlockAccount( // // web3.eth.abi // -------------------------------------------------------------------------- +const myContractOldAbi = new web3.eth.Contract(OLD_ABI_STANDARD); +const myContractNewAbi = new web3.eth.Contract(NEW_ABI_STANDARD); // // web3.bzz diff --git a/types/webpack/index.d.ts b/types/webpack/index.d.ts index f5beb1dc63..40ce95bcad 100644 --- a/types/webpack/index.d.ts +++ b/types/webpack/index.d.ts @@ -538,12 +538,13 @@ declare namespace webpack { namespace Options { // tslint:disable-next-line:max-line-length - type Devtool = 'eval' | 'inline-source-map' | 'cheap-eval-source-map' | 'cheap-source-map' | 'cheap-module-eval-source-map' | 'cheap-module-source-map' | 'eval-source-map' | 'source-map' | - 'nosources-source-map' | 'hidden-source-map' | 'nosources-source-map' | '@eval' | '@inline-source-map' | '@cheap-eval-source-map' | '@cheap-source-map' | '@cheap-module-eval-source-map' | - '@cheap-module-source-map' | '@eval-source-map' | '@source-map' | '@nosources-source-map' | '@hidden-source-map' | '@nosources-source-map' | '#eval' | '#inline-source-map' | - '#cheap-eval-source-map' | '#cheap-source-map' | '#cheap-module-eval-source-map' | '#cheap-module-source-map' | '#eval-source-map' | '#source-map' | '#nosources-source-map' | - '#hidden-source-map' | '#nosources-source-map' | '#@eval' | '#@inline-source-map' | '#@cheap-eval-source-map' | '#@cheap-source-map' | '#@cheap-module-eval-source-map' | - '#@cheap-module-source-map' | '#@eval-source-map' | '#@source-map' | '#@nosources-source-map' | '#@hidden-source-map' | '#@nosources-source-map' | boolean; + type Devtool = 'eval' | 'inline-source-map' | 'cheap-eval-source-map' | 'cheap-source-map' | 'cheap-module-eval-source-map' | 'cheap-module-source-map' | 'eval-source-map' + | 'source-map' | 'nosources-source-map' | 'hidden-source-map' | 'nosources-source-map' | 'inline-cheap-source-map' | 'inline-cheap-module-source-map' | '@eval' + | '@inline-source-map' | '@cheap-eval-source-map' | '@cheap-source-map' | '@cheap-module-eval-source-map' | '@cheap-module-source-map' | '@eval-source-map' + | '@source-map' | '@nosources-source-map' | '@hidden-source-map' | '@nosources-source-map' | '#eval' | '#inline-source-map' | '#cheap-eval-source-map' + | '#cheap-source-map' | '#cheap-module-eval-source-map' | '#cheap-module-source-map' | '#eval-source-map' | '#source-map' | '#nosources-source-map' + | '#hidden-source-map' | '#nosources-source-map' | '#@eval' | '#@inline-source-map' | '#@cheap-eval-source-map' | '#@cheap-source-map' | '#@cheap-module-eval-source-map' + | '#@cheap-module-source-map' | '#@eval-source-map' | '#@source-map' | '#@nosources-source-map' | '#@hidden-source-map' | '#@nosources-source-map' | boolean; interface Performance { /** This property allows webpack to control what files are used to calculate performance hints. */ diff --git a/types/webrtc/RTCPeerConnection.d.ts b/types/webrtc/RTCPeerConnection.d.ts index 210ab66ddd..3df7999212 100644 --- a/types/webrtc/RTCPeerConnection.d.ts +++ b/types/webrtc/RTCPeerConnection.d.ts @@ -11,8 +11,6 @@ /// -type EventHandler = (event: Event) => void; - // https://www.w3.org/TR/webrtc/#idl-def-rtcofferansweroptions interface RTCOfferAnswerOptions { voiceActivityDetection?: boolean; // default = true @@ -27,21 +25,12 @@ interface RTCOfferOptions extends RTCOfferAnswerOptions { interface RTCAnswerOptions extends RTCOfferAnswerOptions { } -// https://www.w3.org/TR/webrtc/#idl-def-rtcpeerconnectionstate -type RTCPeerConnectionState = 'new' | 'connecting' | 'connected' | 'disconnected' | 'failed' | 'closed'; - -// https://www.w3.org/TR/webrtc/#idl-def-rtcicecredentialtype -type RTCIceCredentialType = 'password' | 'token'; - // https://www.w3.org/TR/webrtc/#idl-def-rtciceserver interface RTCIceServer { //urls: string | string[]; credentialType?: RTCIceCredentialType; // default = 'password' } -// https://www.w3.org/TR/webrtc/#idl-def-rtcrtcpmuxpolicy -type RTCRtcpMuxPolicy = 'negotiate' | 'require'; - // https://www.w3.org/TR/webrtc/#idl-def-rtciceparameters interface RTCIceParameters { //usernameFragment: string; @@ -49,6 +38,7 @@ interface RTCIceParameters { } // https://www.w3.org/TR/webrtc/#idl-def-rtcicetransport +type IceTransportEventHandler = ((this: RTCIceTransport, ev: Event) => any) | null; interface RTCIceTransport { //readonly role: RTCIceRole; //readonly component: RTCIceComponent; @@ -59,17 +49,18 @@ interface RTCIceTransport { getSelectedCandidatePair(): RTCIceCandidatePair | null; getLocalParameters(): RTCIceParameters | null; getRemoteParameters(): RTCIceParameters | null; - onstatechange: EventHandler; - ongatheringstatechange: EventHandler; - onselectedcandidatepairchange: EventHandler; + onstatechange: IceTransportEventHandler; + ongatheringstatechange: IceTransportEventHandler; + onselectedcandidatepairchange: IceTransportEventHandler; } // https://www.w3.org/TR/webrtc/#idl-def-rtcdtlstransport +type DtlsTransportEventHandler = ((this: RTCDtlsTransport, ev: Event) => any) | null; interface RTCDtlsTransport { readonly transport: RTCIceTransport; //readonly state: RTCDtlsTransportState; getRemoteCertificates(): ArrayBuffer[]; - onstatechange: EventHandler; + onstatechange: DtlsTransportEventHandler; } // https://www.w3.org/TR/webrtc/#idl-def-rtcrtpcodeccapability @@ -79,7 +70,7 @@ interface RTCRtpCodecCapability { // https://www.w3.org/TR/webrtc/#idl-def-rtcrtpheaderextensioncapability interface RTCRtpHeaderExtensionCapability { - uri: string; + uri?: string; } // https://www.w3.org/TR/webrtc/#idl-def-rtcrtpcapabilities @@ -98,18 +89,12 @@ interface RTCRtpFecParameters { //ssrc: number; } -// https://www.w3.org/TR/webrtc/#idl-def-rtcdtxstatus -type RTCDtxStatus = 'disabled' | 'enabled'; - -// https://www.w3.org/TR/webrtc/#idl-def-rtcprioritytype -type RTCPriorityType = 'very-low' | 'low' | 'medium' | 'high'; - // https://www.w3.org/TR/webrtc/#idl-def-rtcrtpencodingparameters interface RTCRtpEncodingParameters { //ssrc: number; //rtx: RTCRtpRtxParameters; //fec: RTCRtpFecParameters; - dtx: RTCDtxStatus; + dtx?: RTCDtxStatus; //active: boolean; //priority: RTCPriorityType; //maxBitrate: number; @@ -121,7 +106,7 @@ interface RTCRtpEncodingParameters { interface RTCRtpHeaderExtensionParameters { //uri: string; //id: number; - encrypted: boolean; + encrypted?: boolean; } // https://www.w3.org/TR/webrtc/#idl-def-rtcrtcpparameters @@ -136,7 +121,7 @@ interface RTCRtpCodecParameters { mimeType: string; //clockRate: number; channels?: number; // default = 1 - sdpFmtpLine: string; + sdpFmtpLine?: string; } // https://www.w3.org/TR/webrtc/#idl-def-rtcrtpparameters @@ -152,9 +137,9 @@ interface RTCRtpParameters { // https://www.w3.org/TR/webrtc/#dom-rtcrtpcontributingsource interface RTCRtpContributingSource { //readonly timestamp: number; - readonly source: number; + source: number; //readonly audioLevel: number | null; - readonly voiceActivityFlag: boolean | null; + readonly voiceActivityFlag?: boolean; } // https://www.w3.org/TR/webrtc/#idl-def-rtcrtpcapabilities @@ -182,16 +167,13 @@ interface RTCRtpReceiver { getContributingSources(): RTCRtpContributingSource[]; } -// https://www.w3.org/TR/webrtc/#idl-def-rtcrtptransceiverdirection -type RTCRtpTransceiverDirection = 'sendrecv' | 'sendonly' | 'recvonly' | 'inactive'; - // https://www.w3.org/TR/webrtc/#idl-def-rtcrtptransceiver interface RTCRtpTransceiver { readonly mid: string | null; readonly sender: RTCRtpSender; readonly receiver: RTCRtpReceiver; readonly stopped: boolean; - readonly direction: RTCRtpTransceiverDirection; + direction: RTCRtpTransceiverDirection; setDirection(direction: RTCRtpTransceiverDirection): void; stop(): void; setCodecPreferences(codecs: RTCRtpCodecCapability[]): void; @@ -200,8 +182,8 @@ interface RTCRtpTransceiver { // https://www.w3.org/TR/webrtc/#idl-def-rtcrtptransceiverinit interface RTCRtpTransceiverInit { direction?: RTCRtpTransceiverDirection; // default = 'sendrecv' - streams: MediaStream[]; - sendEncodings: RTCRtpEncodingParameters[]; + streams?: MediaStream[]; + sendEncodings?: RTCRtpEncodingParameters[]; } // https://www.w3.org/TR/webrtc/#dom-rtccertificate @@ -240,13 +222,8 @@ interface RTCDataChannelInit { id?: number; } -// https://www.w3.org/TR/webrtc/#idl-def-rtcdatachannelstate -type RTCDataChannelState = 'connecting' | 'open' | 'closing' | 'closed'; - -// https://www.w3.org/TR/websockets/#dom-websocket-binarytype -type RTCBinaryType = 'blob' | 'arraybuffer'; - // https://www.w3.org/TR/webrtc/#idl-def-rtcdatachannel +type DataChannelEventHandler = ((this: RTCDataChannel, ev: E) => any) | null; interface RTCDataChannel extends EventTarget { readonly label: string; readonly ordered: boolean; @@ -254,33 +231,33 @@ interface RTCDataChannel extends EventTarget { readonly maxRetransmits: number | null; readonly protocol: string; readonly negotiated: boolean; - readonly id: number; + readonly id: number | null; readonly readyState: RTCDataChannelState; readonly bufferedAmount: number; bufferedAmountLowThreshold: number; - binaryType: RTCBinaryType; + binaryType: string; close(): void; send(data: string | Blob | ArrayBuffer | ArrayBufferView): void; - onopen: EventHandler; - onmessage: (event: MessageEvent) => void; - onbufferedamountlow: EventHandler; - onerror: (event: ErrorEvent) => void; - onclose: EventHandler; + onopen: DataChannelEventHandler; + onmessage: DataChannelEventHandler; + onbufferedamountlow: DataChannelEventHandler; + onerror: DataChannelEventHandler; + onclose: DataChannelEventHandler; } // https://www.w3.org/TR/webrtc/#h-rtctrackevent interface RTCTrackEvent extends Event { readonly receiver: RTCRtpReceiver; readonly track: MediaStreamTrack; - readonly streams: MediaStream[]; + readonly streams: ReadonlyArray; readonly transceiver: RTCRtpTransceiver; } // https://www.w3.org/TR/webrtc/#h-rtcpeerconnectioniceevent interface RTCPeerConnectionIceEvent extends Event { - readonly url: string; + readonly url: string | null; } // https://www.w3.org/TR/webrtc/#h-rtcpeerconnectioniceerrorevent @@ -297,6 +274,7 @@ interface RTCDataChannelEvent { } // https://www.w3.org/TR/webrtc/#idl-def-rtcpeerconnection +type PeerConnectionEventHandler = ((this: RTCPeerConnection, ev: E) => any) | null; interface RTCPeerConnection extends EventTarget { createOffer(options?: RTCOfferOptions): Promise; createAnswer(options?: RTCAnswerOptions): Promise; @@ -320,8 +298,8 @@ interface RTCPeerConnection extends EventTarget { setConfiguration(configuration: RTCConfiguration): void; close(): void; - onicecandidateerror: (event: RTCPeerConnectionIceErrorEvent) => void; - onconnectionstatechange: EventHandler; + onicecandidateerror: PeerConnectionEventHandler; + onconnectionstatechange: PeerConnectionEventHandler; // Extension: https://www.w3.org/TR/webrtc/#h-rtcpeerconnection-interface-extensions getSenders(): RTCRtpSender[]; @@ -330,12 +308,12 @@ interface RTCPeerConnection extends EventTarget { addTrack(track: MediaStreamTrack, ...streams: MediaStream[]): RTCRtpSender; removeTrack(sender: RTCRtpSender): void; addTransceiver(trackOrKind: MediaStreamTrack | string, init?: RTCRtpTransceiverInit): RTCRtpTransceiver; - ontrack: (event: RTCTrackEvent) => void; + ontrack: PeerConnectionEventHandler; // Extension: https://www.w3.org/TR/webrtc/#h-rtcpeerconnection-interface-extensions-1 readonly sctp: RTCSctpTransport | null; createDataChannel(label: string | null, dataChannelDict?: RTCDataChannelInit): RTCDataChannel; - ondatachannel: (event: RTCDataChannelEvent) => void; + ondatachannel: PeerConnectionEventHandler; // Extension: https://www.w3.org/TR/webrtc/#h-rtcpeerconnection-interface-extensions-2 getStats(selector?: MediaStreamTrack | null): Promise; diff --git a/types/webrtc/index.d.ts b/types/webrtc/index.d.ts index 4a16860637..e087a03f4e 100644 --- a/types/webrtc/index.d.ts +++ b/types/webrtc/index.d.ts @@ -2,7 +2,7 @@ // Project: https://webrtc.org/ // Definitions by: Toshiya Nakakura // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 3.0 /// /// diff --git a/types/weixin-app/index.d.ts b/types/weixin-app/index.d.ts index 2e2eb35481..b40fedfd46 100644 --- a/types/weixin-app/index.d.ts +++ b/types/weixin-app/index.d.ts @@ -3306,7 +3306,7 @@ declare namespace wx { function openCard(options: OpenCardOptions): void; interface OpenSettingOptions extends BaseOptions { - success?(res: { authSetting: { [key in Scope]: string} }): void; + success?(res: { authSetting: { [key in Scope]: boolean } }): void; } /** * 调起客户端小程序设置界面,返回用户设置的操作结果。 @@ -3501,20 +3501,20 @@ declare namespace wx { */ interface InputEvent extends BuiltInEvent< - "input", - { - value: string; - cursor: number; - } - > {} + "input", + { + value: string; + cursor: number; + } + > {} interface FormEvent extends BuiltInEvent< - "form", - { - value: { [name: string]: string | boolean | number }; - } - > {} + "form", + { + value: { [name: string]: string | boolean | number }; + } + > {} interface ScrollEvent extends BuiltInEvent<"scroll", {}> {} @@ -3528,12 +3528,12 @@ declare namespace wx { interface TouchEvent extends BuiltInEvent< - T, - { - x: number; - y: number; - } - > { + T, + { + x: number; + y: number; + } + > { touches: Touch[]; changedTouches: Touch[]; } @@ -4096,6 +4096,79 @@ declare namespace wx { } // #endregion // #region App里的onLaunch、onShow回调参数 + + type SceneValues = + | 1001 + | 1005 + | 1006 + | 1007 + | 1008 + | 1011 + | 1012 + | 1013 + | 1014 + | 1017 + | 1019 + | 1020 + | 1022 + | 1023 + | 1024 + | 1025 + | 1026 + | 1027 + | 1028 + | 1029 + | 1030 + | 1031 + | 1032 + | 1034 + | 1035 + | 1036 + | 1037 + | 1038 + | 1039 + | 1042 + | 1043 + | 1044 + | 1045 + | 1046 + | 1047 + | 1048 + | 1049 + | 1052 + | 1053 + | 1054 + | 1056 + | 1057 + | 1058 + | 1059 + | 1064 + | 1067 + | 1068 + | 1069 + | 1071 + | 1072 + | 1073 + | 1074 + | 1077 + | 1078 + | 1079 + | 1081 + | 1082 + | 1084 + | 1089 + | 1090 + | 1091 + | 1092 + | 1095 + | 1096 + | 1097 + | 1099 + | 1102 + | 1103 + | 1104 + | number; + interface LaunchOptions { /** * 打开小程序的路径 @@ -4107,8 +4180,78 @@ declare namespace wx { query: object; /** * 打开小程序的[场景值](https://mp.weixin.qq.com/debug/wxadoc/dev/framework/app-service/scene.html) + * + * - 1001: 发现栏小程序主入口,「最近使用」列表(基础库2.2.4版本起包含「我的小程序」列表) + * - 1005: 顶部搜索框的搜索结果页 + * - 1006: 发现栏小程序主入口搜索框的搜索结果页 + * - 1007: 单人聊天会话中的小程序消息卡片 + * - 1008: 群聊会话中的小程序消息卡片 + * - 1011: 扫描二维码 + * - 1012: 长按图片识别二维码 + * - 1013: 手机相册选取二维码 + * - 1014: 小程序模板消息 + * - 1017: 前往体验版的入口页 + * - 1019: 微信钱包 + * - 1020: 公众号 profile 页相关小程序列表 + * - 1022: 聊天顶部置顶小程序入口 + * - 1023: 安卓系统桌面图标 + * - 1024: 小程序 profile 页 + * - 1025: 扫描一维码 + * - 1026: 附近小程序列表 + * - 1027: 顶部搜索框搜索结果页「使用过的小程序」列表 + * - 1028: 我的卡包 + * - 1029: 卡券详情页 + * - 1030: 自动化测试下打开小程序 + * - 1031: 长按图片识别一维码 + * - 1032: 手机相册选取一维码 + * - 1034: 微信支付完成页 + * - 1035: 公众号自定义菜单 + * - 1036: App 分享消息卡片 + * - 1037: 小程序打开小程序 + * - 1038: 从另一个小程序返回 + * - 1039: 摇电视 + * - 1042: 添加好友搜索框的搜索结果页 + * - 1043: 公众号模板消息 + * - 1044: 带 shareTicket 的小程序消息卡片 [详情]((转发#获取更多转发信息)) + * - 1045: 朋友圈广告 + * - 1046: 朋友圈广告详情页 + * - 1047: 扫描小程序码 + * - 1048: 长按图片识别小程序码 + * - 1049: 手机相册选取小程序码 + * - 1052: 卡券的适用门店列表 + * - 1053: 搜一搜的结果页 + * - 1054: 顶部搜索框小程序快捷入口 + * - 1056: 音乐播放器菜单 + * - 1057: 钱包中的银行卡详情页 + * - 1058: 公众号文章 + * - 1059: 体验版小程序绑定邀请页 + * - 1064: 微信连Wi-Fi状态栏 + * - 1067: 公众号文章广告 + * - 1068: 附近小程序列表广告 + * - 1069: 移动应用 + * - 1071: 钱包中的银行卡列表页 + * - 1072: 二维码收款页面 + * - 1073: 客服消息列表下发的小程序消息卡片 + * - 1074: 公众号会话下发的小程序消息卡片 + * - 1077: 摇周边 + * - 1078: 连Wi-Fi成功页 + * - 1079: 微信游戏中心 + * - 1081: 客服消息下发的文字链 + * - 1082: 公众号会话下发的文字链 + * - 1084: 朋友圈广告原生页 + * - 1089: 微信聊天主界面下拉,「最近使用」栏(基础库2.2.4版本起包含「我的小程序」栏) + * - 1090: 长按小程序右上角菜单唤出最近使用历史 + * - 1091: 公众号文章商品卡片 + * - 1092: 城市服务入口 + * - 1095: 小程序广告组件 + * - 1096: 聊天记录 + * - 1097: 微信支付签约页 + * - 1099: 页面内嵌插件 + * - 1102: 公众号 profile 页服务预览 + * - 1103: 发现栏小程序主入口,「我的小程序」列表(基础库2.2.4版本起废弃) + * - 1104: 微信聊天主界面下拉,「我的小程序」栏(基础库2.2.4版本起废弃) */ - scene: number; + scene: SceneValues; /** * shareTicket,详见 获取更多[转发信息](https://mp.weixin.qq.com/debug/wxadoc/dev/api/share.html#获取更多转发信息) */ diff --git a/types/wikidata-sdk/def/object/claim.d.ts b/types/wikidata-sdk/def/object/claim.d.ts index c397fcb0df..99ed8bf52c 100644 --- a/types/wikidata-sdk/def/object/claim.d.ts +++ b/types/wikidata-sdk/def/object/claim.d.ts @@ -1,34 +1,34 @@ -export interface TimeDataValue { - type: "time"; - value: { - time: string; - timezone: number; - before: number; - after: number; - precision: number; - calendermodel: string; - }; +export interface WikidataTimeDataValue { + type: "time"; + value: { + time: string; + timezone: number; + before: number; + after: number; + precision: number; + calendermodel: string; + }; } -export interface EntityDataValue { - type: "wikibase-entityid"; - value: { - "numeric-id": number; - "entity-type": string; - }; +export interface WikidataEntityDataValue { + type: "wikibase-entityid"; + value: { + "numeric-id": number; + "entity-type": string; + }; } -export interface MainSnak { - datatype: string; - snaktype: string; - property: string; - hash: string; - datavalue: TimeDataValue | EntityDataValue; +export interface WikidataMainSnak { + datatype: string; + snaktype: string; + property: string; + hash: string; + datavalue: WikidataTimeDataValue | WikidataEntityDataValue; } -export interface Claim { - rank: string; - id: string; - type: string; - mainsnak: MainSnak; +export interface WikidataClaim { + rank: string; + id: string; + type: string; + mainsnak: WikidataMainSnak; } diff --git a/types/wikidata-sdk/def/object/language-base-string.d.ts b/types/wikidata-sdk/def/object/language-base-string.d.ts new file mode 100644 index 0000000000..8f9606dbb1 --- /dev/null +++ b/types/wikidata-sdk/def/object/language-base-string.d.ts @@ -0,0 +1,19 @@ +import { WikidataLanguage } from "../type/language"; + +export type WikidataLanguageBaseString = { + [Key in WikidataLanguage]?: { + language: Key; + value: string; + } +}; + +export type WikidataLanguageBaseStringSimplify = { [key in WikidataLanguage]?: string }; + +export type WikidataLanguageBaseArrayString = { + [Key in WikidataLanguage]: Array<{ + language: Key; + value: string; + }> +}; + +export type WikidataLanguageBaseArrayStringSimplify = { [key in WikidataLanguage]: string[] }; diff --git a/types/wikidata-sdk/def/object/sitelink.d.ts b/types/wikidata-sdk/def/object/sitelink.d.ts new file mode 100644 index 0000000000..d0eea713e5 --- /dev/null +++ b/types/wikidata-sdk/def/object/sitelink.d.ts @@ -0,0 +1,12 @@ +import { WikidataSite } from "../type/site"; + +export type WikidataSiteLink = { [Key in WikidataSite]: { site: Key; title: string; badges: string[] } }; + +export type WikidataSiteLinkSimplify = { [key in WikidataSite]: string }; + +export type WikidataSiteLinkWithUrlSimplify = { + [key in WikidataSite]: { + title: string; + url: string; + } +}; diff --git a/types/wikidata-sdk/index.d.ts b/types/wikidata-sdk/index.d.ts index 5810bcc9de..6ed81883cc 100644 --- a/types/wikidata-sdk/index.d.ts +++ b/types/wikidata-sdk/index.d.ts @@ -2,25 +2,45 @@ // Project: https://github.com/maxlath/wikidata-sdk // Definitions by: Kamontat Chantrachirathumrong // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.2 +// TypeScript Version: 2.1 import { WikidataLanguage } from "./def/type/language"; import { WikidataProperty } from "./def/type/property"; import { WikidataSite } from "./def/type/site"; +import { WikidataSiteLink, WikidataSiteLinkSimplify, WikidataSiteLinkWithUrlSimplify } from "./def/object/sitelink"; import { UrlResultFormat } from "./def/type/format"; +import { + WikidataLanguageBaseString, + WikidataLanguageBaseStringSimplify, + WikidataLanguageBaseArrayString, + WikidataLanguageBaseArrayStringSimplify +} from "./def/object/language-base-string"; -import { Claim, MainSnak, TimeDataValue, EntityDataValue } from "./def/object/claim"; +import { WikidataClaim, WikidataMainSnak, WikidataTimeDataValue, WikidataEntityDataValue } from "./def/object/claim"; -export type WikidataLanguage = WikidataLanguage; -export type WikidataProperty = WikidataProperty; -export type WikidataSite = WikidataSite; +// ----------------------------------- // +// Export session // +// ----------------------------------- // -export type UrlResultFormat = UrlResultFormat; +export { WikidataLanguage, WikidataProperty, WikidataSite }; -export type Claim = Claim; -export type MainSnak = MainSnak; -export type TimeDataValue = TimeDataValue; -export type EntityDataValue = EntityDataValue; +export { + WikidataLanguageBaseString, + WikidataLanguageBaseStringSimplify, + WikidataLanguageBaseArrayString, + WikidataLanguageBaseArrayStringSimplify, + WikidataSiteLink, + WikidataSiteLinkSimplify, + WikidataSiteLinkWithUrlSimplify +}; + +export { UrlResultFormat }; + +export { WikidataClaim, WikidataMainSnak, WikidataTimeDataValue, WikidataEntityDataValue }; + +export interface Json { + [key: string]: any; +} export as namespace sdk; @@ -132,7 +152,7 @@ export function getManyEntities(a: { */ export function getWikidataIdsFromWikipediaTitles( titles: string | string[], - sites?: string, + sites?: WikidataSite, languages?: WikidataLanguage | WikidataLanguage[], props?: WikidataProperty | WikidataProperty[], format?: UrlResultFormat @@ -143,7 +163,7 @@ export function getWikidataIdsFromWikipediaTitles( */ export function getWikidataIdsFromWikipediaTitles(a: { titles: string | string[]; - sites?: string; + sites?: WikidataSite; languages?: WikidataLanguage | WikidataLanguage[]; props?: WikidataProperty | WikidataProperty[]; format?: UrlResultFormat; @@ -232,7 +252,7 @@ export function isSitelinkKey(a: string): boolean; * * @see {@link https://www.mediawiki.org/wiki/Wikibase/Indexing/RDF_Dump_Format#Truthy_statements | Truthy} */ -export function truthyClaims(claims: object): object; +export function truthyClaims(claims: WikidataClaim): WikidataClaim; /** * Filter-out non-truthy claims from an entity.claims[prop] array @@ -241,7 +261,7 @@ export function truthyClaims(claims: object): object; * * @see {@link https://www.mediawiki.org/wiki/Wikibase/Indexing/RDF_Dump_Format#Truthy_statements | Truthy} */ -export function truthyPropertyClaims(claims: Claim[]): Claim[]; +export function truthyPropertyClaims(claims: WikidataClaim[]): WikidataClaim[]; /** * This will get the link that represent the site of the title. @@ -252,12 +272,12 @@ export function truthyPropertyClaims(claims: Claim[]): Claim[]; * * @see {@link https://github.com/maxlath/wikidata-sdk/blob/6b0673b9bf0fcaab19db65e2cc77e33c901ef35d/docs/general_helpers.md#getsitelinkurl | Github[getsitelinkurl] } */ -export function getSitelinkUrl(site: string, title: string): string; +export function getSitelinkUrl(site: WikidataSite, title: string): string; /** * @alias getSitelinkUrl */ -export function getSitelinkUrl(a: { site: string; title: string }): string; +export function getSitelinkUrl(a: { site: WikidataSite; title: string }): string; export interface SitelinkData { lang: string; @@ -324,7 +344,7 @@ export function wikidataTimeToDateObject(a: string): Date; * @see {@link https://github.com/maxlath/wikidata-sdk/blob/6b0673b9bf0fcaab19db65e2cc77e33c901ef35d/docs/general_helpers.md#wikidatatimetosimpleday | Github[wikidatatimetosimpleday] } * */ -export function wikidataTimeToSimpleDay(a: string | object): string; +export function wikidataTimeToSimpleDay(a: string | Json): string; /** * Get an image URL from a Wikimedia Commons filename @@ -335,3 +355,114 @@ export function wikidataTimeToSimpleDay(a: string | object): string; * @returns URL from a wikimedia commons filename */ export function getImageUrl(a: string, width?: number): string; + +export interface SimplifyOption { + // claims + entityPrefix?: string; + propertyPrefix?: string; + keepRichValues?: boolean; + keepQualifiers?: boolean; + keepReferences?: boolean; + keepIds?: boolean; + keepHashes?: boolean; + keepNonTruthy?: boolean; + // sitelinks + addUrl?: boolean; +} + +/** + * Helper method, for simplify result object more reasonable + */ +export namespace simplify { + /** + * Applying all simplifiers at once: labels, descriptions, aliases, claims, sitelinks. See next sections for details. + * You can also pass options as a second argument, that will then be passed the subfunctions: + * + * @param entity the entity that receive from {@link getEntities} APIs + * @param opt simlify option. currently only simplify claims and simplify sitelinks. + * + * @see {@link https://github.com/maxlath/wikidata-sdk/blob/master/docs/simplify_entities_data.md#simplify-entity | Github[simplify-entity]} + */ + function entity(entity: T, opt?: SimplifyOption): T; + + /** + * This is a same of {@link entity} method except this input as multiple array of entities. + * + * @param entities entities from {@link getEntities} APIs + * @param opt simlify option. currently only simplify claims and simplify sitelinks. + * + * @see {@link https://github.com/maxlath/wikidata-sdk/blob/master/docs/simplify_entities_data.md#simplify-entities | Github[simplify-entities]} + */ + function entities(entities: T[], opt?: SimplifyOption): T[]; + + /** + * Make label simplifier and easier to understand + * + * @param labels label object, you will receive this from getEntities method + * + * @example + * + * const label = simplify.labels("{ pl: { language: 'pl', value: 'książka' } }"); + * console.log(label) // { pl: 'książka' } + * + * @see {@link https://github.com/maxlath/wikidata-sdk/blob/master/docs/simplify_entities_data.md#simplify-labels | Github[simplify-labels]} + */ + function labels(labels: WikidataLanguageBaseString): WikidataLanguageBaseStringSimplify; + + /** + * Make description simplifier and easier to understand + * + * @param descriptions description object, you will receive this from getEntities method + * + * @example + * + * const desc = simplify.descriptions("{ pl: { language: 'pl', value: 'dokument piśmienniczy [...]' } }"); + * console.log(desc) // { pl: 'dokument piśmienniczy [...]' } + * + * @see {@link https://github.com/maxlath/wikidata-sdk/blob/master/docs/simplify_entities_data.md#simplify-descriptions | Github[simplify-descriptions]} + */ + function descriptions(descriptions: WikidataLanguageBaseString): WikidataLanguageBaseStringSimplify; + + /** + * Make alias simplifier and easier to understand + * + * @param aliases alias object, you will receive this from getEntities method + * + * @example + * + * const alias = simplify.aliases("{ pl: [ { language: 'pl', value: 'Tom' }, { language: 'pl', value: 'Tomik' } ] }"); + * console.log(alias) // { pl: [ 'Tom', 'Tomik' ] } + * + * @see {@link https://github.com/maxlath/wikidata-sdk/blob/master/docs/simplify_entities_data.md#simplify-aliases | Github[simplify-aliases]} + */ + function aliases(aliases: WikidataLanguageBaseArrayString): WikidataLanguageBaseArrayStringSimplify; + + /** + * Make sitelink simplifier and easier to understand + * + * @param sitelinks sitelink object, you will receive this from getEntities method + * + * @example + * + * const site = simplify.sitelinks("{ plwiki: { site: 'plwiki', title: 'Książka', badges: [] } }"); + * console.log(site) // { plwiki: 'Książka' } + * + * @see {@link https://github.com/maxlath/wikidata-sdk/blob/master/docs/simplify_entities_data.md#simplify-sitelinks | Github[simplify-sitelinks]} + */ + function sitelinks(sitelinks: WikidataSiteLink): WikidataSiteLinkSimplify; + + /** + * Make sitelink simplifier and easier to understand. include URL in the result. + * + * @param sitelinks sitelink object, you will receive this from getEntities method + * @param options add url to a result + * + * @example + * + * const site = simplify.sitelinks("{ plwiki: { site: 'plwiki', title: 'Książka', badges: [] } }", {addUrl: true}); + * console.log(site) // { plwiki: { title: 'Książka', url: 'https://pl.wikipedia.org/wiki/Książka' } } + * + * @see {@link https://github.com/maxlath/wikidata-sdk/blob/master/docs/simplify_entities_data.md#add-sitelinks-urls | Github[simplify-sitelinks-with-url]} + */ + function sitelinks(sitelinks: WikidataSiteLink, options: { addUrl: true }): WikidataSiteLinkWithUrlSimplify; +} diff --git a/types/wx-js-sdk-dt/index.d.ts b/types/wx-js-sdk-dt/index.d.ts index cefc43887f..3f09527450 100644 --- a/types/wx-js-sdk-dt/index.d.ts +++ b/types/wx-js-sdk-dt/index.d.ts @@ -162,7 +162,7 @@ declare namespace wx { /** * 获取“分享到QQ空间”按钮点击状态及自定义分享内容接口 */ - function onMenuShareQzone(config: MenuShareWeibo): void; + function onMenuShareQZone(config: MenuShareWeibo): void; interface ChooseImageConfig { /** @@ -617,6 +617,14 @@ declare namespace wx { * 支付成功后的回调函数 */ success(res: any): void; + /** + * 支付取消后的回调函数 + */ + cancel?(res: any): void; + /** + * 支付失败后的回调函数 + */ + fail?(res: any): void; } /** diff --git a/types/wx-js-sdk-dt/wx-js-sdk-dt-tests.ts b/types/wx-js-sdk-dt/wx-js-sdk-dt-tests.ts index deeb753b29..212c9a79c1 100644 --- a/types/wx-js-sdk-dt/wx-js-sdk-dt-tests.ts +++ b/types/wx-js-sdk-dt/wx-js-sdk-dt-tests.ts @@ -61,7 +61,9 @@ wx.chooseWXPay({ nonceStr: '', package: '', paySign: '', - success: (res) => {} + success: (res) => {}, + cancel: (res) => {}, + fail: (res) => {} }); wx.getLocation({ diff --git a/types/xmpp__xml/index.d.ts b/types/xmpp__xml/index.d.ts new file mode 100644 index 0000000000..b69eacee0f --- /dev/null +++ b/types/xmpp__xml/index.d.ts @@ -0,0 +1,66 @@ +// Type definitions for @xmpp/xml 0.6 +// Project: https://github.com/xmppjs/xmpp.js/tree/master/packages/xml +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +/// + +export = xml; + +import * as ltx from 'ltx'; +import * as escape from 'ltx/lib/escape'; +import { EventEmitter } from 'events'; + +declare function xml( + name: string, + attrs?: string | { [key: string]: any }, + ...children: xml.ElementChild[] +): xml.Element; + +declare namespace xml { + function x( + name: string, + attrs?: string | { [key: string]: any }, + ...children: ElementChild[] + ): Element; + + const escapeXML: typeof escape.escapeXML; + const unescapeXML: typeof escape.unescapeXML; + const escapeXMLText: typeof escape.escapeXMLText; + const unescapeXMLText: typeof escape.unescapeXMLText; + + class Element extends ltx.Element { + attrs: { [key: string]: any }; + append(nodes: ElementChild): Element; + prepend(nodes: ElementChild): Element; + } + type ElementChild = Element | Element[] | string | number | boolean; + + class Parser extends EventEmitter { + readonly XMLError: typeof XMLError; + readonly parser: ltx.Parser; + root: Element | null; + cursor: Element | null; + + onStartElement(name: string, attrs?: string | { [attrName: string]: any }): void; + onEndElement(name: string): void; + onText(str: string): void; + write(data: Buffer): void; + end(data: Buffer): void; + } +} + +declare class XMLError extends Error { + readonly name: 'XMLError'; +} + +declare global { + namespace JSX { + interface IntrinsicElements { + [elemName: string]: any; + } + + type Element = xml.Element; + } +} diff --git a/types/xmpp__xml/tsconfig.json b/types/xmpp__xml/tsconfig.json new file mode 100644 index 0000000000..3fbf44dc71 --- /dev/null +++ b/types/xmpp__xml/tsconfig.json @@ -0,0 +1,30 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "paths": { + "@xmpp/xml": [ + "xmpp__xml" + ] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "jsx": "preserve" + }, + "files": [ + "index.d.ts", + "xmpp__xml-tests.ts", + "xmpp__xml-tests.tsx" + ] +} diff --git a/types/xmpp__xml/tslint.json b/types/xmpp__xml/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/xmpp__xml/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/xmpp__xml/xmpp__xml-tests.ts b/types/xmpp__xml/xmpp__xml-tests.ts new file mode 100644 index 0000000000..84820feaaa --- /dev/null +++ b/types/xmpp__xml/xmpp__xml-tests.ts @@ -0,0 +1,46 @@ +import xml = require('@xmpp/xml'); + +xml.escapeXML(''); +xml.unescapeXML(''); +xml.escapeXMLText(''); +xml.unescapeXMLText(''); + +const parser = new xml.Parser(); +parser.onStartElement('el'); +parser.onEndElement('el'); +parser.onText('text'); +parser.write((null as any) as Buffer); +parser.end((null as any) as Buffer); + +const recipient = 'user@example.com'; +const days = ['Monday', 'Tuesday']; +const message = xml( + 'message', + { to: recipient }, + xml('body', {}, 1 + 2), + xml('days', days.map(day => xml('day', {}, day))) +); +xml.x( + 'message', + { to: recipient }, + xml('body', {}, 1 + 2), + xml('days', days.map(day => xml('day', {}, day))) +); + +message.attrs; +message.getChild('body')!.text(); +message.getChild('body')!.toString(); +message.getChild('days')!.getChildren('day'); +message.getChildText('body'); + +message.attrs.type = 'chat'; +Object.assign(message.attrs, { type: 'chat' }); +message.getChild('body')!.text('Hello world'); +message.append(xml('foo')); +message.append('bar'); +message.append(days.map(day => xml('day', {}, day))); +message.prepend(xml('foo')); +message.prepend('bar'); +message.prepend(days.map(day => xml('day', {}, day))); +const body = message.getChild('body'); +message.remove(body!); diff --git a/types/xmpp__xml/xmpp__xml-tests.tsx b/types/xmpp__xml/xmpp__xml-tests.tsx new file mode 100644 index 0000000000..010cc43f2a --- /dev/null +++ b/types/xmpp__xml/xmpp__xml-tests.tsx @@ -0,0 +1,26 @@ +/** @jsx xml */ + +import xml = require('@xmpp/xml'); + +const recipient = 'user@example.com'; +const days = ['Monday', 'Tuesday']; +const message = ( + + {1 + 2} + + {days.map(day => ( + ${day} + ))} + + +); + +// write +message.append( + + {JSON.stringify(days)} + +); + +// read +JSON.parse(message.getChild('myevent', 'xmpp:example.org')!.getChildText('json', 'urn:xmpp:json:0')!); diff --git a/types/yandex-maps/index.d.ts b/types/yandex-maps/index.d.ts index 94806b9254..d3c6975e98 100644 --- a/types/yandex-maps/index.d.ts +++ b/types/yandex-maps/index.d.ts @@ -1,144 +1,145 @@ // Type definitions for yandex-maps 2.1 // Project: https://github.com/Delagen/typings-yandex-maps // Definitions by: Delagen +// gastwork13 // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.4 declare namespace ymaps { - interface IClassConstructor { - new (): T; - } + interface IClassConstructor { + new(): T; + } - type ControlSingleKey = "fullscreenControl" | "geolocationControl" | "routeEditor" | "rulerControl" | "searchControl" | "trafficControl" | "typeSelector" | "zoomControl"; - type ControlSetKey = "smallMapDefaultSet" | "mediumMapDefaultSet" | "largeMapDefaultSet" | "default"; - type ControlKey = ControlSingleKey | ControlSetKey; + type ControlSingleKey = "fullscreenControl" | "geolocationControl" | "routeEditor" | "rulerControl" | "searchControl" | "trafficControl" | "typeSelector" | "zoomControl"; + type ControlSetKey = "smallMapDefaultSet" | "mediumMapDefaultSet" | "largeMapDefaultSet" | "default"; + type ControlKey = ControlSingleKey | ControlSetKey; - type OverlayKey = - "default#placemark" | "default#pin" | "default#circle" | "default#rectangle" | "default#polyline" | "default#polygon" | - "hotspot#placemark" | "hotspot#circle" | "hotspot#rectangle" | "hotspot#polyline" | "hotspot#polygon" | "html#balloon" | "html#hint" | - "html#placemark" | "html#rectangle" | - string | IClassConstructor | ((geometry: IPixelLineStringGeometry, - data: IDataManager | object, - options: object) => Promise>); - type InteractivityModelKey = "default#opaque" | "default#geoObject" | "default#layer" | "default#transparent" | "default#silent" | string; + type OverlayKey = + "default#placemark" | "default#pin" | "default#circle" | "default#rectangle" | "default#polyline" | "default#polygon" | + "hotspot#placemark" | "hotspot#circle" | "hotspot#rectangle" | "hotspot#polyline" | "hotspot#polygon" | "html#balloon" | "html#hint" | + "html#placemark" | "html#rectangle" | + string | IClassConstructor | ((geometry: IPixelLineStringGeometry, + data: IDataManager | object, + options: object) => Promise>); + type InteractivityModelKey = "default#opaque" | "default#geoObject" | "default#layer" | "default#transparent" | "default#silent" | string; - type PresetKey = string; //option.presetStorage - //[number, number] - //[[number, number], [number, number]] + type PresetKey = string; //option.presetStorage + //[number, number] + //[[number, number], [number, number]] - namespace behavior { - class DblClickZoom implements IBehavior { - constructor(options?: IDblClickZoomOptions); + namespace behavior { + class DblClickZoom implements IBehavior { + constructor(options?: IDblClickZoomOptions); - events: IEventManager; - options: IOptionManager; + events: IEventManager; + options: IOptionManager; - disable(): void; + disable(): void; - enable(): void; + enable(): void; - isEnabled(): boolean; + isEnabled(): boolean; - getParent(): IControlParent | null; + getParent(): IControlParent | null; - setParent(parent: IControlParent): this; - } + setParent(parent: IControlParent): this; + } - interface IDblClickZoomOptions extends IMapMarginOptions { - centering?: boolean; - duration?: number; - } + interface IDblClickZoomOptions extends IMapMarginOptions { + centering?: boolean; + duration?: number; + } - class Drag implements IBehavior { - constructor(options?: IDragOptions) + class Drag implements IBehavior { + constructor(options?: IDragOptions) - events: IEventManager; - options: IOptionManager; + events: IEventManager; + options: IOptionManager; - disable(): void; + disable(): void; - enable(): void; + enable(): void; - isEnabled(): boolean; + isEnabled(): boolean; - getParent(): null | IControlParent; + getParent(): null | IControlParent; - setParent(parent: IControlParent): this; - } + setParent(parent: IControlParent): this; + } - interface IDragOptions { - actionCursor?: string; - cursor?: string; - inertia?: boolean; - inertiaDuration?: number; - tremor?: number; - } + interface IDragOptions { + actionCursor?: string; + cursor?: string; + inertia?: boolean; + inertiaDuration?: number; + tremor?: number; + } - class LeftMouseButtonMagnifier implements IBehavior { - constructor(options?: ILeftMouseButtonMagnifierOptions) + class LeftMouseButtonMagnifier implements IBehavior { + constructor(options?: ILeftMouseButtonMagnifierOptions) - events: IEventManager; - options: IOptionManager; + events: IEventManager; + options: IOptionManager; - disable(): void; + disable(): void; - enable(): void; + enable(): void; - isEnabled(): boolean; + isEnabled(): boolean; - getParent(): null | IControlParent; + getParent(): null | IControlParent; - setParent(parent: IControlParent): this; - } + setParent(parent: IControlParent): this; + } - interface ILeftMouseButtonMagnifierOptions { - actionCursor?: string; - cursor?: string; - duration?: number; - } + interface ILeftMouseButtonMagnifierOptions { + actionCursor?: string; + cursor?: string; + duration?: number; + } - class MultiTouch implements IBehavior { - constructor(options?: IMultiTouchOptions) + class MultiTouch implements IBehavior { + constructor(options?: IMultiTouchOptions) - events: IEventManager; - options: IOptionManager; + events: IEventManager; + options: IOptionManager; - disable(): void; + disable(): void; - enable(): void; + enable(): void; - isEnabled(): boolean; + isEnabled(): boolean; - getParent(): null | IControlParent; + getParent(): null | IControlParent; - setParent(parent: IControlParent): this; - } + setParent(parent: IControlParent): this; + } - interface IMultiTouchOptions { - tremor?: number; - } + interface IMultiTouchOptions { + tremor?: number; + } - class RightMouseButtonMagnifier implements IBehavior { - constructor(options?: IRightMouseButtonMagnifierOptions) + class RightMouseButtonMagnifier implements IBehavior { + constructor(options?: IRightMouseButtonMagnifierOptions) - events: IEventManager; - options: IOptionManager; + events: IEventManager; + options: IOptionManager; - disable(): void; + disable(): void; - enable(): void; + enable(): void; - isEnabled(): boolean; + isEnabled(): boolean; - getParent(): null | IControlParent; + getParent(): null | IControlParent; - setParent(parent: IControlParent): this; - } + setParent(parent: IControlParent): this; + } - interface IRightMouseButtonMagnifierOptions { - actionCursor?: string; - duration?: number; - } + interface IRightMouseButtonMagnifierOptions { + actionCursor?: string; + duration?: number; + } class RouteEditor implements IBehavior { events: IEventManager; @@ -703,12 +704,12 @@ declare namespace ymaps { namespace geometry { namespace base { class LineString implements IBaseLineStringGeometry { //tslint:disable-line no-shadowed-variable + events: IEventManager; + static fromEncodedCoordinates(encodedCoordinates: string): geometry.LineString; //tslint:disable-line function-name static toEncodedCoordinates(geometry: geometry.LineString): string; //tslint:disable-line function-name - events: IEventManager; - getBounds(): number[][] | null; getType(): string; @@ -774,12 +775,11 @@ declare namespace ymaps { simplification?: boolean; }); + events: IEventManager; + options: IOptionManager; + static fromEncodedCoordinates(encodedCoordinates: string): LineString; //tslint:disable-line function-name - - static toEncodedCoordinates(geometry: LineString): string; //tslint:disable-line function-name - - events: IEventManager; - options: IOptionManager; + static toEncodedCoordinates(geometry: LineString): string; //tslint:disable-line function-name getMap(): Map | null; @@ -848,9 +848,248 @@ declare namespace ymaps { getCoordinates(): number[] | null; - setCoordinates(coordinates: number[] | null): this; - } - } + setCoordinates(coordinates: number[] | null): this; + } + } + + namespace geometryEditor { + class Circle implements IGeometryEditor { + constructor(geometry: ICircleGeometry, options?: object); + + events: IEventManager; + geometry: IGeometry; + options: IOptionManager; + state: IDataManager; + + startDrawing(): vow.Promise; + + startEditing(): void; + + stopDrawing(): vow.Promise; + + stopEditing(): void; + } + + class LineString implements IGeometryEditor { + constructor(geometry: ILineStringGeometry, options?: object); + + events: IEventManager; + geometry: IGeometry; + options: IOptionManager; + state: IDataManager; + + getModel(): vow.Promise; + + getModelSync(): model.RootLineString | null; + + getView(): vow.Promise; + + getViewSync(): view.Path | null; + + startDrawing(): vow.Promise; + + startEditing(): vow.Promise; + + startFraming(): vow.Promise; + + stopDrawing(): void; + + stopEditing(): void; + + stopFraming(): void; + } + + namespace model { + class ChildLinearRing extends ChildLineString {} + + class ChildLineString implements IGeometryEditorChildModel { + editor: IGeometryEditor; + events: IEventManager; + geometry: IBaseGeometry; + + destroy(): void; + + getAllVerticesNumber(): number; + + getEdgeModels(): Edge[]; + + getIndex(): number; + + getParent(): IGeometryEditorModel; + + getPixels(): number[]; + + getVertexModels(): ChildVertex[]; + + setIndex(index: number): void; + + setPixels(pixels: number[]): void; + + spliceVertices(start: number, deleteCount: number): number[][]; + } + + class ChildVertex implements IGeometryEditorChildModel { + editor: IGeometryEditor; + events: IEventManager; + geometry: IBaseGeometry; + + destroy(): void; + + getAllVerticesNumber(): number; + + getIndex(): number; + + getNextVertex(): ChildVertex | null; + + getParent(): IGeometryEditorModel; + + getPixels(): number[]; + + getPrevVertex(): ChildVertex | null; + + setGlobalPixels(pixels: number[]): void; + + setIndex(index: number): void; + + setNextVertex(nextVertex: ChildVertex): void; + + setPixels(pixels: number[]): void; + + setPrevVertex(prevVertex: ChildVertex): void; + } + + class Edge implements IGeometryEditorRootModel { + events: IEventManager; + + destroy(): void; + + getNextVertex(): ChildVertex | null; + + getPixels(): number[]; + + getPrevVertex(): ChildVertex | null; + + setNextVertex(nextVertex: ChildVertex): void; + + setPrevVertex(prevVertex: ChildVertex): void; + } + + class EdgeGeometry implements IGeometry { + events: IEventManager; + options: IOptionManager; + + getBounds(): number[][] | null; + + getMap(): Map | null; + + getPixelGeometry(options?: object): IPixelGeometry; + + getType(): string; + + setMap(map: Map): void; + } + + class RootLineString implements IGeometryEditorRootModel { + events: IEventManager; + + destroy(): void; + + getAllVerticesNumber(): number; + + getPixels(): number[]; + + getVertexModels(): ChildVertex[]; + + spliceVertices(start: number, deleteCount: number): number[][]; + } + + class RootPolygon implements IGeometryEditorRootModel { + events: IEventManager; + + destroy(): void; + + getAllVerticesNumber(): number; + + getPathModels(): ChildLinearRing[]; + + getPixels(): number[]; + + splicePaths(start: number, deleteCount: number): number[][]; + } + } + + class Point implements IGeometryEditor { + events: IEventManager; + geometry: IGeometry; + options: IOptionManager; + state: IDataManager; + + startDrawing(): vow.Promise; + + startEditing(): void; + + stopDrawing(): vow.Promise; + + stopEditing(): void; + } + + class Polygon implements IGeometryEditor { + constructor(geometry: IPolygonGeometry, options: object) + + events: IEventManager; + geometry: IGeometry; + options: IOptionManager; + state: IDataManager; + + getModel(): vow.Promise; + + getModelSync(): model.RootPolygon | null; + + getView(): vow.Promise; + + getViewSync(): view.MultiPath | null; + + startDrawing(): vow.Promise; + + startEditing(): vow.Promise; + + startFraming(): vow.Promise; + + stopDrawing(): void; + + stopEditing(): void; + + stopFraming(): void; + } + + namespace view { + class Edge { + getPlacemark(): GeoObject; + } + + class MultiPath { + getEdgePlacemarks(): GeoObjectCollection; + + getPathViews(): Path[]; + + getVertexPlacemarks(): GeoObjectCollection; + } + + class Path { + getEdgePlacemarks(): GeoObjectCollection; + + getEdgeViews(): Edge[]; + + getVertexPlacemarks(): GeoObjectCollection; + + getVertexViews(): Vertex[]; + } + + class Vertex { + getPlacemark(): GeoObject; + } + } + } namespace geoObject { class Balloon implements IBalloonManager { //tslint:disable-line no-shadowed-variable @@ -1003,7 +1242,7 @@ declare namespace ymaps { } } - namespace behavior { // tslint:disable-line no-shadowed-variable + namespace behavior { //tslint:disable-line no-shadowed-variable class Manager implements ICustomizable, IEventEmitter, IParentOnMap { constructor(map: Map, behaviors?: string[][] | string[], options?: object); @@ -2343,10 +2582,96 @@ declare namespace ymaps { interface IPlacemarkOptions { cursor?: string; draggable?: boolean; - - [index: string]: any; + hasBalloon?: boolean; + hasHint?: boolean; + hideIconOnBalloonOpen?: boolean; + iconOffset?: number[]; + iconShape?: IGeometryJson | null; + interactiveZIndex?: boolean; + interactivityModel?: string; + openBalloonOnClick?: boolean; + openEmptyBalloon?: boolean; + openEmptyHint?: boolean; + openHintOnHover?: boolean; + pane?: string; + pointOverlay?: string; + syncOverlayInit?: boolean; + useMapMarginInDragging?: boolean; + visible?: boolean; + zIndex?: number; + zIndexActive?: number; + zIndexDrag?: number; + zIndexHover?: number; } + class Polygon extends GeoObject { + constructor(geometry: number[][][] | object| IPolygonGeometry, properties?: object | IDataManager, options?: IPolygonOptions) + } + + interface IPolygonOptions { + cursor?: string; + draggable?: boolean; + fill?: boolean; + fillColor?: string; + fillImageHref?: string; + fillMethod?: 'stretch' | 'tile'; + fillOpacity?: number; + hasBalloon?: boolean; + hasHint?: boolean; + interactiveZIndex?: boolean; + interactivityModel?: string; + opacity?: number; + openBalloonOnClick?: boolean; + openEmptyBalloon?: boolean; + openEmptyHint?: boolean; + openHintOnHover?: boolean; + outline?: boolean; + pane?: string; + polygonOverlay?: string; + strokeColor?: string | string[]; + strokeOpacity?: number | number[]; + strokeStyle?: string | string[] | object | object[]; + strokeWidth?: number | number[]; + syncOverlayInit?: boolean; + useMapMarginInDragging?: boolean; + visible?: boolean; + zIndex?: number; + zIndexActive?: number; + zIndexDrag?: number; + zIndexHover?: number; + } + + class Polyline extends GeoObject { + constructor(geometry: number[][]| object | ILineStringGeometry, properties?: object | IDataManager, options?: IPolylineOptions) + } + + interface IPolylineOptions { + cursor?: string; + draggable?: boolean; + hasBalloon?: boolean; + hasHint?: boolean; + interactiveZIndex?: boolean; + interactivityModel?: string; + lineStringOverlay?: () => object | string; + opacity?: number; + openBalloonOnClick?: boolean; + openEmptyBalloon?: boolean; + openEmptyHint?: boolean; + openHintOnHover?: boolean; + pane?: string; + strokeColor?: string | string[]; + strokeOpacity?: number | number[]; + strokeStyle?: string | string[] | object | object[]; + strokeWidth?: number | number[]; + syncOverlayInit?: boolean; + useMapMarginInDragging?: boolean; + visible?: boolean; + zIndex?: number; + zIndexActive?: number; + zIndexDrag?: number; + zIndexHover?: number; + } + class Popup implements IPopup { constructor(map: Map, options?: IPopupOptions); @@ -2424,6 +2749,28 @@ declare namespace ymaps { } } + namespace vow { + class Deferred { + promise(): Promise; + + reject(reason: object): void; + + resolve(value: object): void; + } + + class Promise { + constructor(resolver?: () => void); + + done(onFulfilled?: () => void, onRejected?: () => void, onProgress?: () => void, ctx?: object): void; + + spread(onFulfilled?: () => void, onRejected?: () => void, ctx?: object): Promise; + + then(onFulfilled?: () => void, onRejected?: () => void, onProgress?: () => void, ctx?: object): Promise; + + valueOf(): object; + } + } + /*Interfaces*/ interface IBaloon extends IPopup, ICustomizable, IChild, IFreezable { @@ -2616,11 +2963,32 @@ declare namespace ymaps { } interface IGeometryEditor extends ICustomizable, IEventEmitter { + geometry: IGeometry; + state: IDataManager; + startEditing(): void; stopEditing(): void; } + interface IGeometryEditorChildModel extends IGeometryEditorModel { + editor: IGeometryEditor; + geometry: IBaseGeometry; + + getParent(): IGeometryEditorModel; + + setPixels(pixels: number[]): void; + } + + interface IGeometryEditorModel extends IEventEmitter { + destroy(): void; + + getPixels(): number[]; + } + + interface IGeometryEditorRootModel extends IGeometryEditorModel { //tslint:disable-line no-empty-interface no-empty-interfaces + } + interface IGeometryJson { type: string; } @@ -2709,6 +3077,40 @@ declare namespace ymaps { setParentElement(parent: HTMLElement | null): void; } + interface ILinearRingGeometryAccess extends IFreezable { + contain(position: number): boolean; + + freeze(): IFreezable; + + get(index: number): number[]; + + getChildGeometry(index: number): IPointGeometryAccess; + + getClosest(anchorPosition: number[]): object; + + getCoordinates(): number[][]; + + getFillRule(): string; + + getLength(): number; + + insert(index: number, coordinates: number[]): ILinearRingGeometryAccess; + + isFrozen(): boolean; + + remove(index: number): number[]; + + set(index: number, coordinates: number[]): ILinearRingGeometryAccess; + + setCoordinates(coordinates: number[][]): ILinearRingGeometryAccess; + + setFillRule(fillRule: string): ILinearRingGeometryAccess; + + splice(index: number, number: number): number[][]; + + unfreeze(): IFreezable; + } + interface ILineStringGeometry extends IGeometry, ILineStringGeometryAccess { //tslint:disable-line no-empty-interface no-empty-interfaces } @@ -2928,6 +3330,37 @@ declare namespace ymaps { setCoordinates(coordinates: number[] | null): this; } + interface IPolygonGeometry extends IGeometry, IPolygonGeometryAccess { //tslint:disable-line no-empty-interface no-empty-interfaces + } + + interface IPolygonGeometryAccess extends IFreezable { + contains(position: number[]): boolean; + + get(index: number): number[][]; + + getChildGeometry(index: number): ILinearRingGeometryAccess; + + getClosest(anchorPosition: number[]): object; + + getCoordinates(): number[][][]; + + getFillRule(): string; + + getLength(): number; + + insert(index: number, path: number[][]): IPolygonGeometryAccess; + + remove(index: number): ILinearRingGeometryAccess; + + set(index: number, path: number[][]): IPolygonGeometryAccess; + + setCoordinates(coordinates: number[][][]): IPolygonGeometryAccess; + + setFillRule(fillRule: string): IPolygonGeometryAccess; + + splice(index: number, number: number): ILinearRingGeometryAccess[]; + } + interface IPopup extends ICustomizable, IEventEmitter { close(force?: boolean): Promise; diff --git a/types/yandex-maps/yandex-maps-tests.ts b/types/yandex-maps/yandex-maps-tests.ts index 2406ef6cd6..c300679d35 100644 --- a/types/yandex-maps/yandex-maps-tests.ts +++ b/types/yandex-maps/yandex-maps-tests.ts @@ -22,8 +22,8 @@ const balloonLayout = ymaps.templateLayoutFactory.createClass( "
    ", { build(this: ymaps.ILayout): void { - ( ( this.constructor).superclass).build.call(this); - this.getParentElement().children.item(0)!.children.item(0)!.appendChild(( this.getData()).properties.get("balloonContent")); + ((this.constructor as any).superclass as ymaps.layout.templateBased.Base).build.call(this); + this.getParentElement().children.item(0)!.children.item(0)!.appendChild((this.getData() as any).properties.get("balloonContent")); } } ); @@ -52,6 +52,6 @@ mapMarker.events.add("click", (event: ymaps.Event) => { map.geoObjects.add(mapMarker); -map.setCenter(( mapMarker.geometry).getCoordinates() || [55.76, 37.64]); +map.setCenter((mapMarker.geometry as ymaps.IPointGeometry).getCoordinates() || [55.76, 37.64]); map.setZoom(13); diff --git a/types/yeoman-test/index.d.ts b/types/yeoman-test/index.d.ts index d6b2d50a09..abaad9ddb3 100644 --- a/types/yeoman-test/index.d.ts +++ b/types/yeoman-test/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for yeoman-test 1.7 +// Type definitions for yeoman-test 2.0 // Project: https://github.com/yeoman/yeoman-test // Definitions by: Ika // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -10,10 +10,17 @@ import Generator = require('yeoman-generator'); export interface Dictionary { [key: string]: T; } + export interface Constructor { new (...args: any[]): T; } +// Environment from yeoman-environment +export interface Env extends EventEmitter { + queues: string[]; + enforceUpdate(env: Env): this; +} + /** * Dependecies can be path (autodiscovery) or an array [, ] */ @@ -37,7 +44,7 @@ export function setUpTestDirectory(dir: string): (done: (...args: any[]) => void * @param options - Grunt configuration * @param done - callback to call on completion */ -export function gruntfile(options: Dictionary, done: (...args: any[]) => void): void; +export function gruntfile(options: Dictionary, done?: (...args: any[]) => void): void; /** * Clean-up the test directory and cd into it. @@ -49,7 +56,7 @@ export function gruntfile(options: Dictionary, done: (...args: any[]) => vo * fs.writeFileSync('testfile', 'Roses are red.'); * }); */ -export function testDirectory(dir: string, cb: (error?: any) => void): void; +export function testDirectory(dir: string, cb?: (error?: any) => void): void; /** * Answer prompt questions for the passed-in generator @@ -60,7 +67,7 @@ export function testDirectory(dir: string, cb: (error?: any) => void): void; * @example * mockPrompt(angular, {'bootstrap': 'Y', 'compassBoostrap': 'Y'}); */ -export function mockPrompt(generator: Generator, answers: Dictionary): void; +export function mockPrompt(generator: Generator, answers: Generator.Answers): void; /** * Restore defaults prompts on a generator. @@ -105,7 +112,7 @@ export function createGenerator(name: string, dependencies: Dependency[], args?: * * @param dependencies - paths to the generators dependencies */ -export function registerDependencies(env: any, dependencies: Dependency[]): void; +export function registerDependencies(env: Env, dependencies: Dependency[]): void; /** * Run the provided Generator @@ -118,7 +125,18 @@ export interface RunContextSettings { * Automatically run this generator in a tmp dir * @default true */ - tmpdir: boolean; + tmpdir?: boolean; + + /** + * File path to the generator (only used if Generator is a constructor) + */ + resolved?: string; + + /** + * Namespace (only used if Generator is a constructor) + * @default 'gen:test' + */ + namespace?: string; } export interface RunContextConstructor { @@ -132,7 +150,15 @@ export interface RunContextConstructor { new (Generator: string | Constructor, settings?: RunContextSettings): RunContext; } -export interface RunContext extends EventEmitter { +export interface RunContext extends RunContextConstructor, EventEmitter { + ran: boolean; + inDirSet: boolean; + args: string[]; + options: {}; + answers: Generator.Answers; + localConfig: {}; + dependencies: Dependency[]; + /** * Hold the execution until the returned callback is triggered * @return Callback to notify the normal execution can resume @@ -162,7 +188,7 @@ export interface RunContext extends EventEmitter { * @param [cb] - callback who'll receive the folder path as argument * @return run context instance */ - inDir(dirPath: string, cb: (folderPath: string) => void): this; + inDir(dirPath: string, cb?: (folderPath: string) => void): this; /** * Change directory without deleting directory content. @@ -204,7 +230,7 @@ export interface RunContext extends EventEmitter { * Mock the prompt with dummy answers * @param answers - Answers to the prompt questions */ - withPrompts(answers: Dictionary): this; + withPrompts(answers: Generator.Answers): this; /** * Provide dependent generators diff --git a/types/yeoman-test/yeoman-test-tests.ts b/types/yeoman-test/yeoman-test-tests.ts index c5136c6089..2dba4923a2 100644 --- a/types/yeoman-test/yeoman-test-tests.ts +++ b/types/yeoman-test/yeoman-test-tests.ts @@ -57,6 +57,11 @@ helpers.run(path.join(__dirname, '../app')).withGenerators([ [helpers.createDummyGenerator(), 'karma:app'], ]); +helpers.run(Generator, { + resolved: '../app', + namespace: 'custom:generator' +}); + before(done => { helpers.run(path.join(__dirname, '../app')) .on('error', error => { /* ... */ }) diff --git a/types/yup/index.d.ts b/types/yup/index.d.ts index 821b0e3526..924f6f5019 100644 --- a/types/yup/index.d.ts +++ b/types/yup/index.d.ts @@ -5,6 +5,7 @@ // Moreton Bay Regional Council , // Sindre Seppola // Yash Kulshrestha +// Vincent Pizzo // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -47,6 +48,9 @@ export type AnySchemaConstructor = | ArraySchemaConstructor | ObjectSchemaConstructor; +export type TestOptionsMessage = string + | ((params: object & Partial) => string); + export interface Schema { clone(): this; label(label: string): this; @@ -67,11 +71,11 @@ export interface Schema { withMutation(fn: (current: this) => void): void; default(value?: any): this; nullable(isNullable: boolean): this; - required(message?: string): this; + required(message?: TestOptionsMessage): this; notRequired(): this; - typeError(message?: string): this; - oneOf(arrayOfValues: any[], message?: string): this; - notOneOf(arrayOfValues: any[], message?: string): this; + typeError(message?: TestOptionsMessage): this; + oneOf(arrayOfValues: any[], message?: TestOptionsMessage): this; + notOneOf(arrayOfValues: any[], message?: TestOptionsMessage): this; when(keys: string | any[], builder: WhenOptions): this; test( name: string, @@ -102,20 +106,20 @@ export interface StringSchemaConstructor { } export interface StringSchema extends Schema { - min(limit: number | Ref, message?: string): StringSchema; - max(limit: number | Ref, message?: string): StringSchema; + min(limit: number | Ref, message?: TestOptionsMessage): StringSchema; + max(limit: number | Ref, message?: TestOptionsMessage): StringSchema; matches( regex: RegExp, messageOrOptions?: - | string - | { message?: string; excludeEmptyString?: boolean } + | TestOptionsMessage + | { message?: TestOptionsMessage; excludeEmptyString?: boolean } ): StringSchema; - email(message?: string): StringSchema; - url(message?: string): StringSchema; + email(message?: TestOptionsMessage): StringSchema; + url(message?: TestOptionsMessage): StringSchema; ensure(): StringSchema; - trim(message?: string): StringSchema; - lowercase(message?: string): StringSchema; - uppercase(message?: string): StringSchema; + trim(message?: TestOptionsMessage): StringSchema; + lowercase(message?: TestOptionsMessage): StringSchema; + uppercase(message?: TestOptionsMessage): StringSchema; } export interface NumberSchemaConstructor { @@ -124,13 +128,13 @@ export interface NumberSchemaConstructor { } export interface NumberSchema extends Schema { - min(limit: number | Ref, message?: string): NumberSchema; - max(limit: number | Ref, message?: string): NumberSchema; - lessThan(limit: number | Ref, message?: string): NumberSchema; - moreThan(limit: number | Ref, message?: string): NumberSchema; - positive(message?: string): NumberSchema; - negative(message?: string): NumberSchema; - integer(message?: string): NumberSchema; + min(limit: number | Ref, message?: TestOptionsMessage): NumberSchema; + max(limit: number | Ref, message?: TestOptionsMessage): NumberSchema; + lessThan(limit: number | Ref, message?: TestOptionsMessage): NumberSchema; + moreThan(limit: number | Ref, message?: TestOptionsMessage): NumberSchema; + positive(message?: TestOptionsMessage): NumberSchema; + negative(message?: TestOptionsMessage): NumberSchema; + integer(message?: TestOptionsMessage): NumberSchema; truncate(): NumberSchema; round(type: "floor" | "ceil" | "trunc" | "round"): NumberSchema; } @@ -149,8 +153,8 @@ export interface DateSchemaConstructor { } export interface DateSchema extends Schema { - min(limit: Date | string | Ref, message?: string): DateSchema; - max(limit: Date | string | Ref, message?: string): DateSchema; + min(limit: Date | string | Ref, message?: TestOptionsMessage): DateSchema; + max(limit: Date | string | Ref, message?: TestOptionsMessage): DateSchema; } export interface ArraySchemaConstructor { @@ -160,8 +164,8 @@ export interface ArraySchemaConstructor { export interface ArraySchema extends Schema { of(type: Schema): ArraySchema; - min(limit: number | Ref, message?: string): ArraySchema; - max(limit: number | Ref, message?: string): ArraySchema; + min(limit: number | Ref, message?: TestOptionsMessage): ArraySchema; + max(limit: number | Ref, message?: TestOptionsMessage): ArraySchema; ensure(): ArraySchema; compact(rejector?: (value: any) => boolean): ArraySchema; } @@ -177,7 +181,7 @@ export interface ObjectSchema extends Schema { noSortEdges?: Array<[string, string]> ): ObjectSchema; from(fromKey: string, toKey: string, alias?: boolean): ObjectSchema; - noUnknown(onlyKnownKeys?: boolean, message?: string): ObjectSchema; + noUnknown(onlyKnownKeys?: boolean, message?: TestOptionsMessage): ObjectSchema; transformKeys(callback: (key: any) => any): void; camelCase(): ObjectSchema; constantCase(): ObjectSchema; @@ -206,6 +210,7 @@ export interface TestContext { options: ValidateOptions; parent: any; schema: Schema; + resolve: (value: any) => any; createError: (params: { path: string; message: string }) => ValidationError; } @@ -256,9 +261,7 @@ export interface TestOptions { /** * The validation error message */ - message?: - | string - | ((params: object & Partial) => string); + message?: TestOptionsMessage; /** * Values passed to message for interpolation diff --git a/types/yup/yup-tests.ts b/types/yup/yup-tests.ts index efef78d319..1c13d6566f 100644 --- a/types/yup/yup-tests.ts +++ b/types/yup/yup-tests.ts @@ -126,10 +126,15 @@ mixed.default(() => ({ number: 5 })); mixed.default(); mixed.nullable(true); mixed.required(); +mixed.required('Foo'); +mixed.required(() => 'Foo'); mixed.notRequired(); // $ExpectType MixedSchema mixed.typeError("type error"); +mixed.typeError(() => "type error"); mixed.oneOf(["hello", "world"], "message"); +mixed.oneOf(["hello", "world"], () => "message"); mixed.notOneOf(["hello", "world"], "message"); +mixed.notOneOf(["hello", "world"], () => "message"); mixed.when("isBig", { is: value => true, then: yup.number().min(5), @@ -174,6 +179,8 @@ const testContext = function(this: TestContext) { this.parent; // $ExpectType Schema this.schema; + // $ExpectType (value: any) => any + this.resolve; // $ExpectType ValidationError this.createError({ path: "1", message: "1" }); return true; @@ -255,26 +262,56 @@ yup.object() const strSchema = yup.string(); // $ExpectType StringSchema strSchema.isValid("hello"); // => true strSchema.required(); +strSchema.required("req"); +strSchema.required(() => "req"); strSchema.min(5, "message"); +strSchema.min(5, () => "message"); strSchema.max(5, "message"); +strSchema.max(5, () => "message"); strSchema.matches(/(hi|bye)/); +strSchema.matches(/(hi|bye)/, "invalid"); +strSchema.matches(/(hi|bye)/, () => "invalid"); strSchema.email(); +strSchema.email("invalid"); +strSchema.email(() => "invalid"); strSchema.url(); +strSchema.url("bad url"); +strSchema.url(() => "bad url"); strSchema.ensure(); strSchema.trim(); +strSchema.trim("trimmed"); +strSchema.trim(() => "trimmed"); strSchema.lowercase(); +strSchema.lowercase("lower"); +strSchema.lowercase(() => "lower"); strSchema.uppercase(); +strSchema.uppercase("upper"); +strSchema.uppercase(() => "upper"); // Number schema const numSchema = yup.number(); // $ExpectType NumberSchema numSchema.isValid(10); // => true +numSchema.min(5); numSchema.min(5, "message"); +numSchema.min(5, () => "message"); +numSchema.max(5); numSchema.max(5, "message"); +numSchema.max(5, () => "message"); numSchema.positive(); +numSchema.positive("pos"); +numSchema.positive(() => "pos"); numSchema.negative(); +numSchema.negative("neg"); +numSchema.negative(() => "neg"); numSchema.lessThan(5); +numSchema.lessThan(5, "lt"); +numSchema.lessThan(5, () => "lt"); numSchema.moreThan(5); +numSchema.moreThan(5, "mt"); +numSchema.moreThan(5, () => "mt"); numSchema.integer(); +numSchema.integer("int"); +numSchema.integer(() => "int"); numSchema.truncate(); numSchema.round("floor"); numSchema @@ -293,17 +330,27 @@ dateSchema.min(new Date()); dateSchema.min("2017-11-12"); dateSchema.min(new Date(), "message"); dateSchema.min("2017-11-12", "message"); +dateSchema.min("2017-11-12", () => "message"); dateSchema.max(new Date()); dateSchema.max("2017-11-12"); dateSchema.max(new Date(), "message"); dateSchema.max("2017-11-12", "message"); +dateSchema.max("2017-11-12", () => "message"); // Array Schema const arrSchema = yup.array().of(yup.number().min(2)); arrSchema.isValid([2, 3]); // => true arrSchema.isValid([1, -24]); // => false arrSchema.required(); +arrSchema.required("req"); +arrSchema.required(() => "req"); arrSchema.ensure(); +arrSchema.max(5); +arrSchema.max(5, "max"); +arrSchema.max(5, () => "max"); +arrSchema.min(5); +arrSchema.min(5, "min"); +arrSchema.min(5, () => "min"); arrSchema.compact(value => value === null); yup.array(); // $ExpectType ArraySchema<{}> @@ -334,6 +381,7 @@ objSchema.from("prop", "myProp", true); objSchema.noUnknown(); objSchema.noUnknown(true); objSchema.noUnknown(true, "message"); +objSchema.noUnknown(true, () => "message"); objSchema.transformKeys(key => key.toUpperCase()); objSchema.camelCase(); objSchema.constantCase();